@lunora/do 1.0.0-alpha.296 → 1.0.0-alpha.297

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1876,6 +1876,12 @@ declare abstract class ShardDO {
1876
1876
  * requirement it places on the `ShardHost`.
1877
1877
  */
1878
1878
  private readonly inFlightClaims;
1879
+ /**
1880
+ * The CDC presence and epoch memos, and the once-per-wake fork seal. Built
1881
+ * from a `sql` thunk, so this field initializer can run before the
1882
+ * constructor assigns the storage it reads.
1883
+ */
1884
+ private readonly cdcMeta;
1879
1885
  /**
1880
1886
  * Changelog retention: the throttled sweep that bounds `__cdc_log` and the
1881
1887
  * archive-backed read that serves a consumer once it can no longer be
@@ -2212,13 +2218,6 @@ declare abstract class ShardDO {
2212
2218
  * for why a shared cursor leaves no cheaper recovery.
2213
2219
  */
2214
2220
  private globalResyncRequested;
2215
- /**
2216
- * Whether this wake has already re-minted the epoch to seal a rolled-back
2217
- * timeline. In-memory on purpose — see {@link ShardDO.sealForkedTimeline} for
2218
- * why the seal is capped at one per wake, and why losing the flag on eviction
2219
- * is the correct direction.
2220
- */
2221
- private forkSealed;
2222
2221
  /**
2223
2222
  * Wall-clock millis of the last unconditional `.global()` membership pass.
2224
2223
  * Bounds how long a write this deployment cannot see in its own changelog —
@@ -2241,53 +2240,11 @@ declare abstract class ShardDO {
2241
2240
  */
2242
2241
  private shardBinding;
2243
2242
  /**
2244
- * The `.shardBy()` tables this instance has registered with the shard
2245
- * registry, or is registering right now — claimed before the round trip so
2246
- * two concurrent first writes send one. Registration is idempotent, so this
2247
- * only saves round trips; it resets with the instance.
2248
- */
2249
- private readonly registeredTables;
2250
- /**
2251
- * The hand-offs awaiting the scheduler, per outbox id. `retryOutboxEntry` makes them `stale`
2252
- * (their failure must not overwrite the reset). Whether one was dropped is read from
2253
- * {@link ShardDO.scheduleOutboxDroppedThrough} by its token, not inferred from the row, because a
2254
- * row can also vanish for an innocent reason. In memory is enough: an attempt never outlives the
2255
- * instance that started it.
2243
+ * This shard's registrations with the shard registry. Built from thunks, so
2244
+ * this field initializer can run before the constructor assigns `state` and
2245
+ * `env`, and `shardRegistry` stays the subclass's hook, asked per write.
2256
2246
  */
2257
- private readonly scheduleOutboxAttempts;
2258
- /**
2259
- * Outbox entries an operator is dropping right now. The drop first asks the
2260
- * scheduler to cancel the job (it may already hold it), and the retry loop must
2261
- * not hand the entry over again while that is awaiting.
2262
- */
2263
- private readonly scheduleOutboxDrops;
2264
- /**
2265
- * Per id, the newest recording an operator dropped: a drop covers every call recorded up to the
2266
- * row it acted on (including calls of one mutation that a later same-id record replaced), and
2267
- * no call recorded after it. A missing row alone cannot say "dropped": two calls of one mutation
2268
- * that share an explicit id share one row, and the first hand-off releases it. Pruned by
2269
- * {@link ShardDO.pruneScheduleOutboxDropMarker} once no call or attempt it could affect is left.
2270
- */
2271
- private readonly scheduleOutboxDroppedThrough;
2272
- /**
2273
- * Calls recorded for an id whose hand-off has not finished (or whose window has not rolled back).
2274
- * A drop marker is needed exactly that long, so it is pruned when this reaches zero instead of by
2275
- * count: evicting a marker early would let a queued call of a dropped job run.
2276
- */
2277
- private readonly scheduleOutboxPendingHandOffs;
2278
- /** The `created_at` last handed to `recordScheduleOutbox`; see {@link ShardDO.scheduleOutbox}. */
2279
- private lastScheduleOutboxRecordAt;
2280
- /**
2281
- * Epoch millis before which registration is not retried, set when one
2282
- * fails: a registry outage costs one attempt per window rather than one per
2283
- * write, against the single DO that has to recover.
2284
- */
2285
- private registryRetryAt;
2286
- /**
2287
- * Every registry round trip this shard makes, in order — see
2288
- * {@link ShardDO.serializeRegistry}. Never rejects.
2289
- */
2290
- private registryTail;
2247
+ private readonly shardRegistration;
2291
2248
  /**
2292
2249
  * Memoised {@link ShardDO.currentAdminBinding} result, keyed by the token it
2293
2250
  * was derived from so a rotation within one isolate re-derives rather than
@@ -2321,19 +2278,11 @@ declare abstract class ShardDO {
2321
2278
  */
2322
2279
  private readonly usedIndexes;
2323
2280
  /**
2324
- * Per-function execution counters surfaced by the
2325
- * `__lunora_admin__:getFunctionStats` RPC, keyed by `<file>:<function>`
2326
- * path. Shares the `metrics` lifecycle: in-memory, reset on
2327
- * hibernation/restart. `functionPath` is caller-controlled (the runtime
2328
- * forwards it unchecked), so the map is NOT bounded by the app's registered
2329
- * function count — every path that reaches a metrics-recording dispatch
2330
- * lands here, including one that resolves to nothing. `recordFunctionCall`
2331
- * therefore caps it at {@link FUNCTION_METRICS_MAX_PATHS} the same way the
2332
- * durable `__lunora_metrics` twin caps its table. Maintained by
2333
- * `recordFunctionCall` at the one dispatch site that also bumps the
2334
- * aggregate `metrics` counters.
2281
+ * Per-function counters and the coalesced durable delta. Built from thunks,
2282
+ * so this field initializer can run before the constructor assigns `env`
2283
+ * and `shardHost`.
2335
2284
  */
2336
- private readonly functionStats;
2285
+ private readonly functionMetrics;
2337
2286
  /**
2338
2287
  * Recent RPC errors on this shard instance, surfaced by the
2339
2288
  * `__lunora_admin__:getLogs` RPC. In-memory only and bounded — like
@@ -2343,6 +2292,12 @@ declare abstract class ShardDO {
2343
2292
  * "recent RPC errors on this instance" feed, not a general application log.
2344
2293
  */
2345
2294
  private readonly logs;
2295
+ /**
2296
+ * Custody for deferred `ctx.scheduler` calls. Built from thunks, so this field
2297
+ * initializer can run before the constructor assigns the hosts, and the
2298
+ * `scheduleOutboxScheduler` hook stays the subclass's, asked per attempt.
2299
+ */
2300
+ private readonly scheduleOutboxRunner;
2346
2301
  /**
2347
2302
  * Recent `ctx.trace` spans (plus the synthetic per-dispatch root), powering
2348
2303
  * the studio's Traces panel. In-memory and hibernation-volatile like
@@ -2389,7 +2344,7 @@ declare abstract class ShardDO {
2389
2344
  * that queries in a loop reuses the SAME prepared-statement text on every
2390
2345
  * iteration (bind parameters travel separately via `...params`, never
2391
2346
  * inlined into `query`), so folding each call into its entry as it lands
2392
- * collapses the loop to one entry — {@link ShardDO.foldStmtSamples} then
2347
+ * collapses the loop to one entry — {@link FunctionMetrics.foldStmtSamples} then
2393
2348
  * pays one upsert per DISTINCT statement instead of one per raw execution.
2394
2349
  * Bounded at {@link MAX_STMT_SAMPLES_PER_DISPATCH} distinct entries; past
2395
2350
  * that, a brand-new statement shape (ad-hoc SQL built per iteration) is
@@ -2401,30 +2356,6 @@ declare abstract class ShardDO {
2401
2356
  * result-set size only on a host that doesn't expose them.
2402
2357
  */
2403
2358
  private currentStmtSamples;
2404
- /**
2405
- * Exact per-path metric deltas not yet written to `__lunora_metrics*`. Every
2406
- * dispatch folds in here; {@link ShardDO.maybeFlushMetrics} writes the sum once
2407
- * every N dispatches ({@link ShardDO.metricsFlushEvery}, default 8), so rates stay exact
2408
- * and only write frequency drops. In memory only: an evicted DO loses at most
2409
- * N-1 dispatches of counters (no alarm flush).
2410
- */
2411
- private pendingFunctionMetrics;
2412
- /**
2413
- * Per-statement samples folded from `currentStmtSamples`, written with
2414
- * {@link ShardDO.pendingFunctionMetrics}. Keyed by statement AND the latency
2415
- * bucket of each dispatch's own average: `recordQueryMetric` places an entry in the
2416
- * histogram by its average, so only dispatches in the same bucket may merge (summing 19
2417
- * fast and 1 slow dispatch would flatten the tail percentiles). The key count also
2418
- * drives the width-based flush.
2419
- */
2420
- private pendingStmtSamples;
2421
- /** Dispatches folded since the last flush. */
2422
- private dispatchesSinceFlush;
2423
- /** Whether an errored/conflicted dispatch is pending (forces the next flush). */
2424
- private pendingForceFlush;
2425
- /** Time of the first / latest dispatch in the pending delta; `undefined` when empty. */
2426
- private pendingStartedAt;
2427
- private pendingLastAt;
2428
2359
  /**
2429
2360
  * The instrumented `sql` proxy built for {@link ShardDO.currentStmtSamples},
2430
2361
  * and the samples map it was built for.
@@ -2437,19 +2368,6 @@ declare abstract class ShardDO {
2437
2368
  * exists to remove.
2438
2369
  */
2439
2370
  private instrumentedSql;
2440
- /**
2441
- * Memos for {@link ShardDO.cdcEnabled} and {@link ShardDO.cachedCdcEpoch},
2442
- * which every flush and resume consults.
2443
- *
2444
- * Instance fields, never module state: a native PITR restore reverts
2445
- * `__cdc_meta` but only takes effect when the object restarts, so a fresh
2446
- * instance is what guarantees the restored row is read. Presence is
2447
- * remembered only once TRUE — a migration creates `__cdc_log` mid-instance,
2448
- * and nothing outside a restore drops it, so a cached `false` is the one
2449
- * answer that can go stale.
2450
- */
2451
- private cdcLogPresent;
2452
- private cdcEpochCache;
2453
2371
  /**
2454
2372
  * Set when `currentStmtSamples` hit {@link MAX_STMT_SAMPLES_PER_DISPATCH}
2455
2373
  * distinct statements and a brand-new shape was dropped this dispatch.
@@ -3350,49 +3268,7 @@ declare abstract class ShardDO {
3350
3268
  /**
3351
3269
  * Mint a fresh CDC epoch because a resume claim just proved this shard's
3352
3270
  * changelog forked under it, and return the new value for the outgoing frame.
3353
- *
3354
- * The trigger is a client presenting `sinceEpoch === epoch` with `sinceSeq >
3355
- * cursor`: it holds a cursor this shard once issued on THIS timeline and can
3356
- * no longer account for. Only a rollback produces that — in practice a native
3357
- * PITR restore, which is armed in {@link handlePitrAdminOp}.
3358
- *
3359
- * **Why the signal has to come from outside SQLite.** A restore reverts the
3360
- * whole SQLite database, `__cdc_meta` included, so the proactive bump
3361
- * `pitrRestore` performs is rolled back along with everything else — the
3362
- * epoch cannot detect the one event it exists for. Nothing durable inside a
3363
- * SQLite-backed Durable Object escapes that: the KV half of `state.storage`
3364
- * is the same database, and an alarm is a row in it. So every record of the
3365
- * pre-restore timeline that survives is somewhere the restore could not
3366
- * reach, and this shard has exactly two: the cursor a CONSUMER cached (a
3367
- * subscriber's `sinceSeq` here, a connector's in
3368
- * {@link ShardDO.runShardCdcSync}, a follower's in `replica.ts`), and the
3369
- * changelog ARCHIVE's own segments, which R2 keeps while the watermark
3370
- * naming them rolls back (`cdcArchiveRewound`, consulted by the retention
3371
- * sweep). Either one calls this, and turning one witness into a shard-wide
3372
- * epoch bump is what extends the protection to clients that reconnect later,
3373
- * after post-restore writes have climbed the AUTOINCREMENT back past their
3374
- * own `sinceSeq` and the `sinceSeq > cursor` guard no longer fires for them.
3375
- *
3376
- * **What it detects.** Any rollback under a live subscriber base, promptly: a
3377
- * restore restarts the object (`ctx.abort()`, or the eviction that lets a
3378
- * deferred restore apply), which drops every hibernated socket, so the whole
3379
- * subscriber set reconnects with pre-restore cursors while the restored
3380
- * cursor is still low. The first of them seals the fork for the rest.
3381
- *
3382
- * **What it cannot detect.** A rollback on a shard whose consumers ALL stay
3383
- * offline until the cursor has climbed back past their cursors, and which
3384
- * archives nothing — nobody is left to present the proof. A shard with no
3385
- * subscribers, no connector, no follower and no archive bucket is the
3386
- * degenerate case of that, and is also the case where nothing is stale.
3387
- *
3388
- * **On trusting `sinceSeq`.** It is client-supplied, so a caller that already
3389
- * knows this shard's epoch can force a bump, and a bump is shard-wide: every
3390
- * subscriber takes a full snapshot instead of a resume on its NEXT reconnect.
3391
- * The cost is bounded (the once-per-wake latch below) and deferred — nothing
3392
- * is pushed and no live subscription is interrupted — and it stays strictly
3393
- * less than what the same caller can already spend by subscribing without a
3394
- * `sinceSeq` at all.
3395
- * @returns the freshly minted epoch, to stamp on the frame this verdict produces
3271
+ * At most once per wake; see {@link CdcMeta.sealForkedTimeline} for why.
3396
3272
  */
3397
3273
  protected sealForkedTimeline(): string;
3398
3274
  /**
@@ -3934,25 +3810,9 @@ declare abstract class ShardDO {
3934
3810
  protected scheduleTtlSweep(): Promise<void>;
3935
3811
  /**
3936
3812
  * Durable custody for this shard's deferred `ctx.scheduler` calls — the
3937
- * `ScheduleOutbox` the generated `buildCtx` hands to
3938
- * `withDeferredSchedules`.
3939
- *
3940
- * The two halves land on opposite sides of the COMMIT on purpose:
3941
- *
3942
- * - `record` runs while the handler is still inside its transaction, so the
3943
- * entry is durable exactly when the writes are and rolls back with them.
3944
- * It deliberately does NOT swallow: a failure here is still inside the span,
3945
- * so letting it throw rolls the mutation back — the one moment at which
3946
- * failing is free. Swallowing would put us back where we started, committing
3947
- * writes whose job nothing is holding.
3948
- * - `forget` runs after the dispatch, so it must never fail the response. A
3949
- * delete that does not land leaves an entry the retry loop re-offers, which
3950
- * the scheduler refuses as a duplicate and which is then dropped — the error
3951
- * self-heals into one wasted RPC.
3952
- *
3953
- * What survives a settle is therefore exactly the set of jobs that were
3954
- * promised and not enqueued, which is what {@link ShardDO.pollScheduleOutbox}
3955
- * drains.
3813
+ * `ScheduleOutbox` the generated `buildCtx` hands to `withDeferredSchedules`.
3814
+ * See {@link ScheduleOutboxRunner.scheduleOutbox} for why `record` and
3815
+ * `forget` land on opposite sides of the COMMIT.
3956
3816
  */
3957
3817
  protected scheduleOutbox(): ScheduleOutbox;
3958
3818
  /**
@@ -3970,29 +3830,8 @@ declare abstract class ShardDO {
3970
3830
  protected scheduleOutboxScheduler(): SchedulerLike | undefined;
3971
3831
  /**
3972
3832
  * Re-offer the deferred schedules that were promised to a caller and never
3973
- * reached the scheduler — the retry half of {@link ShardDO.scheduleOutbox}.
3974
- * Shares the poll alarm with the source-ingest and TTL tiers, and reports the
3975
- * earliest next-due time the same way, so a shard with an empty outbox (the
3976
- * steady state — an entry lives only between a COMMIT and its dispatch) arms
3977
- * nothing.
3978
- *
3979
- * Each attempt reuses the id the caller was already handed, so an entry whose
3980
- * original dispatch DID land — the failure was the `forget`, or the isolate
3981
- * died between the two — is refused as a duplicate rather than scheduled
3982
- * twice. A refusal and an acceptance are therefore both "the scheduler has
3983
- * it", and both end custody.
3984
- *
3985
- * The default bound is {@link SCHEDULE_OUTBOX_MAX_ATTEMPTS}: a job the
3986
- * scheduler will never accept stops costing alarms and becomes a reported
3987
- * fact instead — parked, logged at `error` with its id and target, and kept
3988
- * for {@link SCHEDULE_OUTBOX_RETENTION_MS} so an operator can see what was
3989
- * promised and never enqueued. A call made with `retry.forever` opts out of
3990
- * that ceiling: it stays live, paced by the ladder's last rung, until the
3991
- * scheduler accepts it or refuses it as invalid. The retention sweep only
3992
- * ever drops parked rows. The sweep rides whatever tick reaches this tier, so a shard
3993
- * holding ONLY parked entries keeps them until something else wakes it —
3994
- * which is the right trade: they are one row per genuinely lost job, not a
3995
- * loop that grows on its own.
3833
+ * reached the scheduler; see {@link ScheduleOutboxRunner.pollScheduleOutbox}.
3834
+ * Reports the earliest next-due time, like the other poll tiers.
3996
3835
  */
3997
3836
  protected pollScheduleOutbox(trace?: TraceRefLike): Promise<number | undefined>;
3998
3837
  /** This DO's shard key (its DO name), or `__root__` for the single-DO default. The `tenantBy` mapper binds it into the source query. */
@@ -4519,6 +4358,24 @@ declare abstract class ShardDO {
4519
4358
  * trace ids to needs a way to say so.
4520
4359
  */
4521
4360
  protected makeFetch(functionPath: string, anchor: TraceAnchor, sink?: TelemetrySink, scope?: SensitiveScope): ContextFetch;
4361
+ /**
4362
+ * Build `ctx.span` — the handle onto the **dispatch's own span**, and with it
4363
+ * the wide-event surface.
4364
+ *
4365
+ * `ctx.trace(...)` creates a *new* child span for a sub-operation; this
4366
+ * attaches to the one that already exists for the request. That is the
4367
+ * distinction between "time this thing" and "record a fact about this
4368
+ * request", and conflating them is why instrumentation usually degrades into
4369
+ * log spam: with nowhere to put a fact, people reach for `ctx.log.info`.
4370
+ *
4371
+ * Attributes accumulate across the whole dispatch and are folded into the
4372
+ * root span in `recordDispatchRootSpan` — the OTel-native form of a
4373
+ * wide event, needing no non-standard "canonical log line" convention on the
4374
+ * collector side.
4375
+ *
4376
+ * Keyed by `dispatchSpanKey` — trace id AND root span id — so two concurrent
4377
+ * dispatches forwarded under the same client trace accumulate separately.
4378
+ */
4522
4379
  protected makeDispatchSpan(anchor: TraceAnchor, sink?: TelemetrySink, scope?: SensitiveScope): SpanHandle;
4523
4380
  /**
4524
4381
  * Build the `ctx.metrics` recorder for one dispatched function. Thin wiring
@@ -4552,24 +4409,6 @@ declare abstract class ShardDO {
4552
4409
  * as the host-specific handler while the engine is progressively extracted.
4553
4410
  */
4554
4411
  protected handleAlarmCloudflare(): Promise<void>;
4555
- /**
4556
- * Build `ctx.span` — the handle onto the **dispatch's own span**, and with it
4557
- * the wide-event surface.
4558
- *
4559
- * `ctx.trace(...)` creates a *new* child span for a sub-operation; this
4560
- * attaches to the one that already exists for the request. That is the
4561
- * distinction between "time this thing" and "record a fact about this
4562
- * request", and conflating them is why instrumentation usually degrades into
4563
- * log spam: with nowhere to put a fact, people reach for `ctx.log.info`.
4564
- *
4565
- * Attributes accumulate across the whole dispatch and are folded into the
4566
- * root span in `recordDispatchRootSpan` — the OTel-native form of a
4567
- * wide event, needing no non-standard "canonical log line" convention on the
4568
- * collector side.
4569
- *
4570
- * Keyed by `dispatchSpanKey` — trace id AND root span id — so two concurrent
4571
- * dispatches forwarded under the same client trace accumulate separately.
4572
- */
4573
4412
  /**
4574
4413
  * Snapshot the per-request identity/replay fields into a {@link RequestScope}.
4575
4414
  * Paired with {@link ShardDO.restoreRequestScope}; see that type's docstring
@@ -4585,6 +4424,22 @@ declare abstract class ShardDO {
4585
4424
  * as this request's. The dispatch path re-pins its own afterwards.
4586
4425
  */
4587
4426
  protected restoreRequestScope(scope: RequestScope): void;
4427
+ /** The `connect` control frame: verify a pending socket, send its identity, and fire `onConnect` once. */
4428
+ private handleConnectFrame;
4429
+ /** A live-query `subscribe` frame: gate it, register it on the socket, and seed it. */
4430
+ private handleSubscribeFrame;
4431
+ /** A `shape_subscribe` frame: decode its args and hand it to {@link ShardDO.handleShapeSubscribe}. */
4432
+ private handleShapeSubscribeFrame;
4433
+ /** A `shape_unsubscribe` frame. */
4434
+ private handleShapeUnsubscribeFrame;
4435
+ /** A `stream` frame: refuse admin and paid functions, decode the args, and start the stream without awaiting it. */
4436
+ private handleStreamFrame;
4437
+ /** A `whisper_subscribe` / `whisper_unsubscribe` frame: join or leave a topic, running a room's `onJoin` / `onLeave`. */
4438
+ private handleWhisperMembershipFrame;
4439
+ /** A `whisper` frame: relay it to the topic, or dispatch a room's `onMessage`. */
4440
+ private handleWhisperFrame;
4441
+ /** An `unsubscribe` frame: cancel a stream with that id, if any, and drop the subscription. */
4442
+ private handleUnsubscribeFrame;
4588
4443
  /**
4589
4444
  * Load `functionPath`'s module before a live-query gate reads its registry entry: a lazy
4590
4445
  * registry's stub carries no `perDispatch` until then, so the gate would wave a cold per-dispatch
@@ -4847,106 +4702,6 @@ declare abstract class ShardDO {
4847
4702
  * the close path.
4848
4703
  */
4849
4704
  private purgeDurableSocketBaselines;
4850
- /**
4851
- * Fold one dispatch into the per-function counters keyed by `functionPath`,
4852
- * creating the entry on first sight. `errorMessage` is supplied only when
4853
- * the handler threw, in which case the failure counters advance too. The
4854
- * caller is expected to have already redacted `errorMessage` (via
4855
- * `redactArgs`, the same `standardRules` treatment the request-log sinks
4856
- * use) — this method persists/caches it verbatim into BOTH the durable
4857
- * `__lunora_metrics.last_error_message` column and the in-memory
4858
- * `functionStats.lastErrorMessage` served by `getFunctionStats`, so an
4859
- * un-redacted message reaching here leaks into the Studio.
4860
- * `scannedTables` carries the tables the dispatch full-scanned (collected by
4861
- * `getCtxDbReadHook`), which advance the causal scan attribution.
4862
- * `indexHits` carries the declared indexes it exercised (collected by
4863
- * `getCtxDbIndexUseHook`, NUL-free `JSON.stringify([table, index])` keys),
4864
- * which advance the durable `__lunora_metrics_index` hit counter behind the
4865
- * dead-index lint. Called once per `/rpc` dispatch alongside the aggregate
4866
- * `metrics` update.
4867
- *
4868
- * Two writes happen here. The in-memory {@link functionStats} map is kept
4869
- * for the fast warm-instance path, and the durable `__lunora_metrics`
4870
- * table is upserted so the counters survive hibernation/restart — the
4871
- * persisted table is the source of truth the admin RPCs read from. The
4872
- * persist is best-effort: a SQL failure (e.g. a test double without a
4873
- * `sql` handle) must never turn a successful dispatch into a failed one,
4874
- * so it is swallowed and the in-memory counters still advance.
4875
- *
4876
- * The durable write is COALESCED, not per-dispatch: the call is folded into
4877
- * {@link ShardDO.pendingFunctionMetrics} (exact counts, durations, scans and
4878
- * index hits) and {@link ShardDO.maybeFlushMetrics} writes the whole delta once
4879
- * every N dispatches ({@link ShardDO.metricsFlushEvery}; default 8; 1 = every dispatch),
4880
- * so the durable counters stay exact and only the write frequency drops.
4881
- */
4882
- private recordFunctionCall;
4883
- /**
4884
- * Fold the per-DISTINCT-statement SQL samples accumulated during the current
4885
- * dispatch into {@link ShardDO.pendingStmtSamples}. Called after
4886
- * `recordFunctionCall` on both the success and error paths, followed by
4887
- * {@link ShardDO.maybeFlushMetrics}.
4888
- *
4889
- * Already folded by the instrumented `sql` getter (see `currentStmtSamples`);
4890
- * `count` carries the real execution count so the durable
4891
- * `exec_count`/`total_duration_ms` still reflect every execution. Pure
4892
- * in-memory; nothing is written until the flush. Clearing `currentStmtSamples`
4893
- * happens in the `finally` block of the dispatch path, not here.
4894
- */
4895
- private foldStmtSamples;
4896
- /** Fold one completed dispatch into {@link ShardDO.pendingFunctionMetrics}. */
4897
- private foldFunctionMetric;
4898
- /**
4899
- * Write the pending metric delta when this dispatch is due: every
4900
- * N dispatches ({@link ShardDO.metricsFlushEvery}), immediately after an errored or
4901
- * conflicted one, or when the pending statement set is as wide as one
4902
- * dispatch may be. (A minute-boundary crossing flushes earlier, inside
4903
- * {@link ShardDO.foldFunctionMetric}.) Counts are exact either way; at most
4904
- * N-1 dispatches of counters are lost if the DO is evicted before a flush.
4905
- */
4906
- private maybeFlushMetrics;
4907
- /**
4908
- * Persist the pending delta: one `recordFunctionMetric` per path and one
4909
- * `recordQueryMetric` per (statement, latency bucket) key, so the
4910
- * histogram still sees each dispatch's own average. The accumulators are swapped out
4911
- * first, so a write that throws DROPS that path's (or entry's) delta and the rest
4912
- * of the batch is still written. There is deliberately no retry: metrics are
4913
- * best-effort, `recordFunctionMetric` is several statements per path and the host
4914
- * exposes no synchronous transaction, so a retry after a partial write would double
4915
- * count, and a persistent failure would grow the pending set without bound. One
4916
- * warning per flush reports what was dropped. Never fails the request.
4917
- */
4918
- private flushPendingMetrics;
4919
- /** Write any coalesced delta so an admin read of the durable metric tables is never stale. */
4920
- private flushUnwrittenMetrics;
4921
- /**
4922
- * Dispatches per durable metric write (env `LUNORA_METRICS_FLUSH_EVERY`): a positive
4923
- * integer, default {@link DEFAULT_METRICS_FLUSH_EVERY} (8). Unset, blank, fractional,
4924
- * non-numeric or < 1 values fall back to the default. An evicted DO loses at most N-1
4925
- * dispatches of un-flushed counters (7 by default); errored or conflicted dispatches
4926
- * and minute-boundary crossings still flush immediately. Set 1 to write every dispatch.
4927
- */
4928
- private metricsFlushEvery;
4929
- /**
4930
- * Assemble the per-function readout served by
4931
- * `__lunora_admin__:getFunctionStats`, sorted most-recently-called first so
4932
- * the busiest functions surface at the top of the studio table.
4933
- *
4934
- * Reads from the durable `__lunora_metrics` table — the source of truth —
4935
- * so the counts reflect the function's lifetime, not just calls since this
4936
- * instance woke. Falls back to the in-memory map only if the durable read
4937
- * throws (e.g. a test double without a usable `sql` handle), keeping the
4938
- * warm-instance counters available even then. The wire shape is unchanged
4939
- * (`{ functions, sinceMs }`), so existing studio/runtime consumers keep
4940
- * working; the rows are now backed by persisted data.
4941
- */
4942
- private collectFunctionStats;
4943
- /**
4944
- * Per-function coarse time-series served additively by the metrics RPC, so
4945
- * the studio can chart call/error history. Reads the durable
4946
- * `__lunora_metrics_buckets` table; returns an empty, non-truncated result
4947
- * when persistence is unavailable so the response stays well-formed.
4948
- */
4949
- private collectFunctionMetricBuckets;
4950
4705
  private maybeWarnRootSize;
4951
4706
  /**
4952
4707
  * Map a thrown value to a JSON response. `ValidationError` from
@@ -5354,38 +5109,14 @@ declare abstract class ShardDO {
5354
5109
  private handleRecordQueueMessage;
5355
5110
  /**
5356
5111
  * Serve `dropOutboxEntry` — cancel a deferred schedule the scheduler never
5357
- * confirmed, live or parked. `ctx.scheduler.cancel` only reaches jobs the
5358
- * SchedulerDO holds, so this is the only way to stop a `retry.forever` entry
5359
- * that is still waiting.
5360
- *
5361
- * The shard cannot always tell that the scheduler never got the job: the accept
5362
- * may have been lost on the way back, or an attempt may be awaiting it right now.
5363
- * So the drop cancels the id at the scheduler FIRST and deletes the row only once
5364
- * that settled. A cancel that fails (the scheduler is often the very thing that is down)
5365
- * parks the entry so it can never be handed over, and the error goes to the operator;
5366
- * dropping again completes it. And an attempt that was already in the air takes the job back out
5367
- * when it lands, see {@link ShardDO.retryScheduleOutboxEntry}. Admin-gated by the caller.
5112
+ * confirmed; see {@link ScheduleOutboxRunner.drop}. Admin-gated by the caller.
5368
5113
  */
5369
5114
  private handleDropOutboxEntry;
5370
5115
  /**
5371
- * Audit a drop that applied. "Not found" is the usual answer for a job the scheduler never
5372
- * accepted, and the same answer it gives once an accepted job has run: an earlier hand-off whose
5373
- * accept was lost on the way back. The drop cannot tell the two apart, so the operator is told the
5374
- * job may have run.
5375
- */
5376
- private auditAppliedScheduleOutboxDrop;
5377
- /**
5378
- * With no scheduler to ask, waiting never confirms the cancel. The first drop parked the row (a
5379
- * job may have been accepted under a binding that has since gone); dropping a row that was already
5380
- * parked, with nothing in flight, is the operator accepting that, and removes it.
5381
- * @returns whether the row was removed
5382
- */
5383
- private removeUnconfirmableScheduleOutboxDrop;
5384
- /**
5385
- * Serve `retryOutboxEntry` — put an entry back on the retry ladder, due now:
5386
- * the way back for a parked entry, and a way to skip a long backoff once the
5387
- * scheduler is healthy. Arms the poll alarm for now, because nothing else is
5388
- * due to wake a shard whose entries were all parked. Admin-gated by the caller.
5116
+ * Serve `retryOutboxEntry` — put an entry back on the retry ladder, due now
5117
+ * (see {@link ScheduleOutboxRunner.retry}), and arm the poll alarm for now,
5118
+ * because nothing else is due to wake a shard whose entries were all parked.
5119
+ * Admin-gated by the caller.
5389
5120
  */
5390
5121
  private handleRetryOutboxEntry;
5391
5122
  /** Empty the dev queue consumed-message log (studio "clear log" action). Admin-gated by the caller. */
@@ -5883,51 +5614,13 @@ declare abstract class ShardDO {
5883
5614
  * middleware. Identity-scoping the key is what keeps that impossible.
5884
5615
  */
5885
5616
  private attachDurableStream;
5886
- /**
5887
- * Run one registry step after every step before it. Registration and release
5888
- * both go through here, so a release's emptiness check and unregister can
5889
- * never interleave with a registration: a write that lands mid-release
5890
- * registers AFTER the unregister, not before it.
5891
- */
5892
- private serializeRegistry;
5893
- /** The registry stub, pinned to this DO's own jurisdiction — the subnamespace the worker pins the registry it reads. */
5894
- private registryStub;
5895
- /**
5896
- * Where this shard's registry writes go. A Durable Object namespace is this app's own
5897
- * registry: signed directly with this worker's secret. Anything else is the RPC surface of
5898
- * the worker that hosts the registry, reached through its service binding, so the binding
5899
- * itself is the capability and no secret is needed. `undefined` when a namespace is not in
5900
- * this shard's jurisdiction.
5901
- */
5902
- private registryWriter;
5903
- /**
5904
- * Tell the shard registry this shard holds rows of each `.shardBy()` table
5905
- * the flushed write touched, once per table per instance. The cross-shard
5906
- * fan-outs (export, CDC sync, migrations) only reach the shards the registry
5907
- * lists, so a shard that never registers is left out of every one of them.
5908
- *
5909
- * Runs past the response (see `flushChangedTables`) and never rejects: the
5910
- * write has already committed, so a failure is logged, the table's claim
5911
- * released, and the first write after {@link SHARD_REGISTRY_RETRY_MS} retries.
5912
- */
5913
- private registerWrittenShard;
5914
5617
  /**
5915
5618
  * `__lunora_admin__:releaseShardRegistration`: drop this shard from the
5916
5619
  * registry for each named table it holds no rows of, and keep it for the rest.
5917
- *
5918
- * The shard decides rather than the caller because only here can the check
5919
- * be ordered against this shard's own writes. It runs on the registry chain
5920
- * (see {@link ShardDO.serializeRegistry}) and clears the table's claim, so a
5921
- * row written before the check is seen by it and keeps the table, and one
5922
- * written after re-registers once the unregister has landed. A caller that
5923
- * probed first and unregistered second could hide a shard written in between:
5924
- * its claim would say "registered" while the registry said otherwise.
5925
- *
5926
- * A soft-deleted row still counts as a row — the shard is kept.
5620
+ * See {@link ShardRegistration.release} for why the shard, not the caller,
5621
+ * decides.
5927
5622
  */
5928
5623
  private handleReleaseShardRegistration;
5929
- /** Whether this shard's SQLite holds at least one row of `table` — `false` for a table it never created. */
5930
- private tableHasRows;
5931
5624
  /**
5932
5625
  * Drain the tables written during the in-flight RPC and re-run every
5933
5626
  * subscription that depends on one of them. Called after `handleRpc`
@@ -6423,74 +6116,6 @@ declare abstract class ShardDO {
6423
6116
  * deferral itself is the caller's job: this only reports it.
6424
6117
  */
6425
6118
  private recordScheduleRateDeferral;
6426
- /**
6427
- * One outbox attempt: replay the stored call, then either end custody or push
6428
- * the entry out along {@link SCHEDULE_OUTBOX_BACKOFF_MS}. The default policy
6429
- * parks once the ladder runs out; `retry.forever` keeps a valid call live.
6430
- *
6431
- * An envelope that will not parse is parked immediately rather than retried:
6432
- * no number of attempts turns malformed JSON into a job, and the log line is
6433
- * the only useful output left.
6434
- */
6435
- private retryScheduleOutboxEntry;
6436
- /**
6437
- * The post-commit hand-off of a deferred schedule, run as a recorded attempt like every retry:
6438
- * a drop that arrives while the call awaits the scheduler is seen here and the job is cancelled
6439
- * when it lands (the row stays parked if that cancel fails). A failure leaves the row for the
6440
- * retry loop, unless a drop already ended the entry, in which case the row goes.
6441
- */
6442
- private runScheduleOutboxHandOff;
6443
- private handOffRecordedScheduleOutboxCall;
6444
- private markScheduleOutboxDropped;
6445
- private isScheduleOutboxBeingDropped;
6446
- /** One recorded call is done with: handed off, skipped, or rolled back with its window. */
6447
- private finishScheduleOutboxHandOff;
6448
- /**
6449
- * Forget the drop marker of `id` once nothing it could still decide is left: no recorded call
6450
- * waiting for its hand-off, no attempt awaiting the scheduler, no drop in flight. Pruned by that
6451
- * condition rather than by count, because evicting a marker early would let a queued call of a
6452
- * dropped job go out.
6453
- */
6454
- private pruneScheduleOutboxDropMarker;
6455
- /** Whether a drop covers the recording `token` names: recorded no later than the row it acted on. */
6456
- private isScheduleOutboxTokenDropped;
6457
- /** Whether the entry this attempt was made for has been dropped, now or while it was in the air. */
6458
- private wasScheduleOutboxDropped;
6459
- private releaseScheduleOutboxAttempt;
6460
- /** A hand-off that threw: end custody if the scheduler turns out to hold the job, else defer or park the entry. */
6461
- private settleFailedScheduleOutboxAttempt;
6462
- /**
6463
- * The scheduler holds the job: end custody. If the entry was dropped while the
6464
- * hand-off was awaiting (or a drop is cancelling it right now), the operator asked
6465
- * for the job NOT to run, so take it back out of the scheduler. `landed` says the scheduler
6466
- * is known to hold (or to have held) the job, which is what makes a "not found" cancel a failure.
6467
- */
6468
- private settleScheduleOutboxHandOff;
6469
- /** Park `id` if it is still live, keeping its attempt count; a parked or absent row is left as it is. */
6470
- private parkLiveScheduleOutboxEntry;
6471
- /**
6472
- * Push one entry out along the ladder. A `retry.forever` entry that reaches
6473
- * the attempts a default entry would have parked at says so once, at `warn`:
6474
- * past that point nothing else reports that the job is still not enqueued.
6475
- */
6476
- private deferScheduleOutboxEntry;
6477
- /** Park one entry and say so at `error` — a job was promised to a caller and will not be enqueued. */
6478
- private parkScheduleOutboxEntry;
6479
- /**
6480
- * Arm the poll alarm once per warm instance if this shard is holding deferred
6481
- * schedules nobody has enqueued.
6482
- *
6483
- * The settle asks for a wake when its own dispatch fails, but the window that
6484
- * loses a job most quietly is the one where no settle ran at all: the DO is
6485
- * evicted between the COMMIT and the dispatch, and the entry sits with nothing
6486
- * pointing at it. Every entry point into this object goes through shard init,
6487
- * so hooking it here means the next time anything wakes this shard the retry
6488
- * loop starts — for the cost of one indexed read per cold start.
6489
- *
6490
- * Swallows: a shard whose store predates the table (or a harness with a stub
6491
- * handle) simply has no custody to resume, and init must not fail for it.
6492
- */
6493
- private armScheduleOutboxRetry;
6494
6119
  /**
6495
6120
  * When the TTL tier should next wake for `specs`: 1 ms past the earliest live
6496
6121
  * expiry (the sweep's `expiry < now` is strict), but never before `now +`
@@ -7007,27 +6632,6 @@ declare abstract class ShardDO {
7007
6632
  private reauthenticateSocket;
7008
6633
  private routeNonRpc;
7009
6634
  private handleWebSocketUpgrade;
7010
- /**
7011
- * Whether this shard has a `__cdc_log` table. The single source of the
7012
- * "is CDC on here?" probe shared by {@link currentCdcCursor},
7013
- * {@link currentCdcEpoch}, {@link evaluateResume}, and the PITR-restore epoch
7014
- * bump. Returns `false` (rather than throwing) on a stub `sql` handle (unit
7015
- * harness double) or a pre-CDC shard, so callers degrade to the no-CDC path.
7016
- */
7017
- private cdcEnabled;
7018
- /**
7019
- * The `__cdc_meta` epoch, read from SQLite at most once until
7020
- * {@link invalidateCdcMetaCache} runs. Callers gate on {@link cdcEnabled}
7021
- * first, except {@link sealForkedTimeline}, whose callers already proved it.
7022
- */
7023
- private cachedCdcEpoch;
7024
- /** Bump the CDC epoch and drop the CDC memos in one step, so no caller can bump without invalidating. */
7025
- private bumpCdcEpochUncached;
7026
- /**
7027
- * Drop both CDC memos — the single exit for every path that can change
7028
- * `__cdc_log`'s presence or the `__cdc_meta` row behind this instance's back.
7029
- */
7030
- private invalidateCdcMetaCache;
7031
6635
  /**
7032
6636
  * A route upgrade refused before anything it would run is registered. A route that requires a verified session
7033
6637
  * refuses an anonymous caller with a plain 401 (the default route allows anonymous sockets, like every other