@lunora/do 1.0.0-alpha.295 → 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.ts CHANGED
@@ -1558,7 +1558,14 @@ declare abstract class ShardDO {
1558
1558
  private readonly deliveryRequestPermits;
1559
1559
  private currentDeliveryPermit;
1560
1560
  private transactionRequestScope;
1561
- private readonly deliveryRegistrations;
1561
+ /**
1562
+ * Per socket, the identity of each subscription id's current registration: `subscribe` mints a
1563
+ * new one when it (re)registers an id, `unsubscribe` drops it. A path that awaits between reading
1564
+ * a subscription and acting on it compares identities so it never acts on a replacement. Memory
1565
+ * only, so a subscription restored from hibernation gets one lazily — see
1566
+ * {@link ShardDO.subscriptionRegistration}.
1567
+ */
1568
+ private readonly subscriptionRegistrations;
1562
1569
  /** ctx-db relation knobs from {@link ShardDOOptions}, handed on by {@link ShardDO.ctxDbTuning}. */
1563
1570
  private readonly ctxDbRelationOptions;
1564
1571
  /**
@@ -1869,6 +1876,12 @@ declare abstract class ShardDO {
1869
1876
  * requirement it places on the `ShardHost`.
1870
1877
  */
1871
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;
1872
1885
  /**
1873
1886
  * Changelog retention: the throttled sweep that bounds `__cdc_log` and the
1874
1887
  * archive-backed read that serves a consumer once it can no longer be
@@ -2099,6 +2112,8 @@ declare abstract class ShardDO {
2099
2112
  private readonly queuedSocketEvents;
2100
2113
  /** Sockets whose close is in progress: their room membership is being torn down, so nothing new may join or leave. */
2101
2114
  private readonly closingSockets;
2115
+ /** Per socket, the subscribe ids waiting on their function's load; see {@link ShardDO.subscribeOutlivedLoad}. */
2116
+ private readonly loadingSubscribes;
2102
2117
  /**
2103
2118
  * Sockets holding at least one live grant, so a publish visits only grant holders. Kept as a
2104
2119
  * superset of the truth: `deliverLiveLocal` re-checks each socket's attachment, and drops an
@@ -2203,13 +2218,6 @@ declare abstract class ShardDO {
2203
2218
  * for why a shared cursor leaves no cheaper recovery.
2204
2219
  */
2205
2220
  private globalResyncRequested;
2206
- /**
2207
- * Whether this wake has already re-minted the epoch to seal a rolled-back
2208
- * timeline. In-memory on purpose — see {@link ShardDO.sealForkedTimeline} for
2209
- * why the seal is capped at one per wake, and why losing the flag on eviction
2210
- * is the correct direction.
2211
- */
2212
- private forkSealed;
2213
2221
  /**
2214
2222
  * Wall-clock millis of the last unconditional `.global()` membership pass.
2215
2223
  * Bounds how long a write this deployment cannot see in its own changelog —
@@ -2232,53 +2240,11 @@ declare abstract class ShardDO {
2232
2240
  */
2233
2241
  private shardBinding;
2234
2242
  /**
2235
- * The `.shardBy()` tables this instance has registered with the shard
2236
- * registry, or is registering right now — claimed before the round trip so
2237
- * two concurrent first writes send one. Registration is idempotent, so this
2238
- * only saves round trips; it resets with the instance.
2239
- */
2240
- private readonly registeredTables;
2241
- /**
2242
- * The hand-offs awaiting the scheduler, per outbox id. `retryOutboxEntry` makes them `stale`
2243
- * (their failure must not overwrite the reset). Whether one was dropped is read from
2244
- * {@link ShardDO.scheduleOutboxDroppedThrough} by its token, not inferred from the row, because a
2245
- * row can also vanish for an innocent reason. In memory is enough: an attempt never outlives the
2246
- * instance that started it.
2247
- */
2248
- private readonly scheduleOutboxAttempts;
2249
- /**
2250
- * Outbox entries an operator is dropping right now. The drop first asks the
2251
- * scheduler to cancel the job (it may already hold it), and the retry loop must
2252
- * not hand the entry over again while that is awaiting.
2253
- */
2254
- private readonly scheduleOutboxDrops;
2255
- /**
2256
- * Per id, the newest recording an operator dropped: a drop covers every call recorded up to the
2257
- * row it acted on (including calls of one mutation that a later same-id record replaced), and
2258
- * no call recorded after it. A missing row alone cannot say "dropped": two calls of one mutation
2259
- * that share an explicit id share one row, and the first hand-off releases it. Pruned by
2260
- * {@link ShardDO.pruneScheduleOutboxDropMarker} once no call or attempt it could affect is left.
2261
- */
2262
- private readonly scheduleOutboxDroppedThrough;
2263
- /**
2264
- * Calls recorded for an id whose hand-off has not finished (or whose window has not rolled back).
2265
- * A drop marker is needed exactly that long, so it is pruned when this reaches zero instead of by
2266
- * count: evicting a marker early would let a queued call of a dropped job run.
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.
2267
2246
  */
2268
- private readonly scheduleOutboxPendingHandOffs;
2269
- /** The `created_at` last handed to `recordScheduleOutbox`; see {@link ShardDO.scheduleOutbox}. */
2270
- private lastScheduleOutboxRecordAt;
2271
- /**
2272
- * Epoch millis before which registration is not retried, set when one
2273
- * fails: a registry outage costs one attempt per window rather than one per
2274
- * write, against the single DO that has to recover.
2275
- */
2276
- private registryRetryAt;
2277
- /**
2278
- * Every registry round trip this shard makes, in order — see
2279
- * {@link ShardDO.serializeRegistry}. Never rejects.
2280
- */
2281
- private registryTail;
2247
+ private readonly shardRegistration;
2282
2248
  /**
2283
2249
  * Memoised {@link ShardDO.currentAdminBinding} result, keyed by the token it
2284
2250
  * was derived from so a rotation within one isolate re-derives rather than
@@ -2312,19 +2278,11 @@ declare abstract class ShardDO {
2312
2278
  */
2313
2279
  private readonly usedIndexes;
2314
2280
  /**
2315
- * Per-function execution counters surfaced by the
2316
- * `__lunora_admin__:getFunctionStats` RPC, keyed by `<file>:<function>`
2317
- * path. Shares the `metrics` lifecycle: in-memory, reset on
2318
- * hibernation/restart. `functionPath` is caller-controlled (the runtime
2319
- * forwards it unchecked), so the map is NOT bounded by the app's registered
2320
- * function count — every path that reaches a metrics-recording dispatch
2321
- * lands here, including one that resolves to nothing. `recordFunctionCall`
2322
- * therefore caps it at {@link FUNCTION_METRICS_MAX_PATHS} the same way the
2323
- * durable `__lunora_metrics` twin caps its table. Maintained by
2324
- * `recordFunctionCall` at the one dispatch site that also bumps the
2325
- * 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`.
2326
2284
  */
2327
- private readonly functionStats;
2285
+ private readonly functionMetrics;
2328
2286
  /**
2329
2287
  * Recent RPC errors on this shard instance, surfaced by the
2330
2288
  * `__lunora_admin__:getLogs` RPC. In-memory only and bounded — like
@@ -2334,6 +2292,12 @@ declare abstract class ShardDO {
2334
2292
  * "recent RPC errors on this instance" feed, not a general application log.
2335
2293
  */
2336
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;
2337
2301
  /**
2338
2302
  * Recent `ctx.trace` spans (plus the synthetic per-dispatch root), powering
2339
2303
  * the studio's Traces panel. In-memory and hibernation-volatile like
@@ -2380,7 +2344,7 @@ declare abstract class ShardDO {
2380
2344
  * that queries in a loop reuses the SAME prepared-statement text on every
2381
2345
  * iteration (bind parameters travel separately via `...params`, never
2382
2346
  * inlined into `query`), so folding each call into its entry as it lands
2383
- * collapses the loop to one entry — {@link ShardDO.foldStmtSamples} then
2347
+ * collapses the loop to one entry — {@link FunctionMetrics.foldStmtSamples} then
2384
2348
  * pays one upsert per DISTINCT statement instead of one per raw execution.
2385
2349
  * Bounded at {@link MAX_STMT_SAMPLES_PER_DISPATCH} distinct entries; past
2386
2350
  * that, a brand-new statement shape (ad-hoc SQL built per iteration) is
@@ -2392,30 +2356,6 @@ declare abstract class ShardDO {
2392
2356
  * result-set size only on a host that doesn't expose them.
2393
2357
  */
2394
2358
  private currentStmtSamples;
2395
- /**
2396
- * Exact per-path metric deltas not yet written to `__lunora_metrics*`. Every
2397
- * dispatch folds in here; {@link ShardDO.maybeFlushMetrics} writes the sum once
2398
- * every N dispatches ({@link ShardDO.metricsFlushEvery}, default 8), so rates stay exact
2399
- * and only write frequency drops. In memory only: an evicted DO loses at most
2400
- * N-1 dispatches of counters (no alarm flush).
2401
- */
2402
- private pendingFunctionMetrics;
2403
- /**
2404
- * Per-statement samples folded from `currentStmtSamples`, written with
2405
- * {@link ShardDO.pendingFunctionMetrics}. Keyed by statement AND the latency
2406
- * bucket of each dispatch's own average: `recordQueryMetric` places an entry in the
2407
- * histogram by its average, so only dispatches in the same bucket may merge (summing 19
2408
- * fast and 1 slow dispatch would flatten the tail percentiles). The key count also
2409
- * drives the width-based flush.
2410
- */
2411
- private pendingStmtSamples;
2412
- /** Dispatches folded since the last flush. */
2413
- private dispatchesSinceFlush;
2414
- /** Whether an errored/conflicted dispatch is pending (forces the next flush). */
2415
- private pendingForceFlush;
2416
- /** Time of the first / latest dispatch in the pending delta; `undefined` when empty. */
2417
- private pendingStartedAt;
2418
- private pendingLastAt;
2419
2359
  /**
2420
2360
  * The instrumented `sql` proxy built for {@link ShardDO.currentStmtSamples},
2421
2361
  * and the samples map it was built for.
@@ -2428,19 +2368,6 @@ declare abstract class ShardDO {
2428
2368
  * exists to remove.
2429
2369
  */
2430
2370
  private instrumentedSql;
2431
- /**
2432
- * Memos for {@link ShardDO.cdcEnabled} and {@link ShardDO.cachedCdcEpoch},
2433
- * which every flush and resume consults.
2434
- *
2435
- * Instance fields, never module state: a native PITR restore reverts
2436
- * `__cdc_meta` but only takes effect when the object restarts, so a fresh
2437
- * instance is what guarantees the restored row is read. Presence is
2438
- * remembered only once TRUE — a migration creates `__cdc_log` mid-instance,
2439
- * and nothing outside a restore drops it, so a cached `false` is the one
2440
- * answer that can go stale.
2441
- */
2442
- private cdcLogPresent;
2443
- private cdcEpochCache;
2444
2371
  /**
2445
2372
  * Set when `currentStmtSamples` hit {@link MAX_STMT_SAMPLES_PER_DISPATCH}
2446
2373
  * distinct statements and a brand-new shape was dropped this dispatch.
@@ -3341,49 +3268,7 @@ declare abstract class ShardDO {
3341
3268
  /**
3342
3269
  * Mint a fresh CDC epoch because a resume claim just proved this shard's
3343
3270
  * changelog forked under it, and return the new value for the outgoing frame.
3344
- *
3345
- * The trigger is a client presenting `sinceEpoch === epoch` with `sinceSeq >
3346
- * cursor`: it holds a cursor this shard once issued on THIS timeline and can
3347
- * no longer account for. Only a rollback produces that — in practice a native
3348
- * PITR restore, which is armed in {@link handlePitrAdminOp}.
3349
- *
3350
- * **Why the signal has to come from outside SQLite.** A restore reverts the
3351
- * whole SQLite database, `__cdc_meta` included, so the proactive bump
3352
- * `pitrRestore` performs is rolled back along with everything else — the
3353
- * epoch cannot detect the one event it exists for. Nothing durable inside a
3354
- * SQLite-backed Durable Object escapes that: the KV half of `state.storage`
3355
- * is the same database, and an alarm is a row in it. So every record of the
3356
- * pre-restore timeline that survives is somewhere the restore could not
3357
- * reach, and this shard has exactly two: the cursor a CONSUMER cached (a
3358
- * subscriber's `sinceSeq` here, a connector's in
3359
- * {@link ShardDO.runShardCdcSync}, a follower's in `replica.ts`), and the
3360
- * changelog ARCHIVE's own segments, which R2 keeps while the watermark
3361
- * naming them rolls back (`cdcArchiveRewound`, consulted by the retention
3362
- * sweep). Either one calls this, and turning one witness into a shard-wide
3363
- * epoch bump is what extends the protection to clients that reconnect later,
3364
- * after post-restore writes have climbed the AUTOINCREMENT back past their
3365
- * own `sinceSeq` and the `sinceSeq > cursor` guard no longer fires for them.
3366
- *
3367
- * **What it detects.** Any rollback under a live subscriber base, promptly: a
3368
- * restore restarts the object (`ctx.abort()`, or the eviction that lets a
3369
- * deferred restore apply), which drops every hibernated socket, so the whole
3370
- * subscriber set reconnects with pre-restore cursors while the restored
3371
- * cursor is still low. The first of them seals the fork for the rest.
3372
- *
3373
- * **What it cannot detect.** A rollback on a shard whose consumers ALL stay
3374
- * offline until the cursor has climbed back past their cursors, and which
3375
- * archives nothing — nobody is left to present the proof. A shard with no
3376
- * subscribers, no connector, no follower and no archive bucket is the
3377
- * degenerate case of that, and is also the case where nothing is stale.
3378
- *
3379
- * **On trusting `sinceSeq`.** It is client-supplied, so a caller that already
3380
- * knows this shard's epoch can force a bump, and a bump is shard-wide: every
3381
- * subscriber takes a full snapshot instead of a resume on its NEXT reconnect.
3382
- * The cost is bounded (the once-per-wake latch below) and deferred — nothing
3383
- * is pushed and no live subscription is interrupted — and it stays strictly
3384
- * less than what the same caller can already spend by subscribing without a
3385
- * `sinceSeq` at all.
3386
- * @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.
3387
3272
  */
3388
3273
  protected sealForkedTimeline(): string;
3389
3274
  /**
@@ -3672,6 +3557,15 @@ declare abstract class ShardDO {
3672
3557
  * nothing — and this is the only place left that still knows the call is paid.
3673
3558
  */
3674
3559
  protected isPaidFunction(_functionPath: string): boolean;
3560
+ /**
3561
+ * Whether `functionPath`'s `.use()` chain carries a per-dispatch middleware
3562
+ * (`perDispatch` on the registered function). `subscribe` refuses such a
3563
+ * query: a live query re-runs the chain on every refresh, and the effect —
3564
+ * limiter budget, a single-use token — must happen once per request. The
3565
+ * base class has no function registry, so the default is `false`; the
3566
+ * codegen-generated subclass answers from `LUNORA_FUNCTIONS`.
3567
+ */
3568
+ protected isPerDispatchFunction(_functionPath: string): boolean;
3675
3569
  /**
3676
3570
  * The argument names of `functionPath` whose validators carry a `v.sensitive`
3677
3571
  * marker. The request log replaces them before anything is persisted, logged or
@@ -3725,10 +3619,11 @@ declare abstract class ShardDO {
3725
3619
  * serialize. We never throw out of this path — the WS hibernation API
3726
3620
  * treats a thrown `webSocketMessage` as a fatal-channel error.
3727
3621
  *
3728
- * The `paid` refusal sits here rather than at the envelope so every
3729
- * registration path — not only the `subscribe` frame — goes through it.
3622
+ * The `paid` and `per_dispatch` refusals sit here rather than at the
3623
+ * envelope so every registration path — not only the `subscribe` frame —
3624
+ * goes through them.
3730
3625
  */
3731
- protected subscribe(ws: ShardSocketLike, subId: string, query: SubscriptionQuery): "ok" | "paid" | "serialize_failed" | "too_many";
3626
+ protected subscribe(ws: ShardSocketLike, subId: string, query: SubscriptionQuery): "ok" | "paid" | "per_dispatch" | "serialize_failed" | "too_many";
3732
3627
  protected unsubscribe(ws: ShardSocketLike, subId: string): void;
3733
3628
  /**
3734
3629
  * Register a live shape subscription on a socket — the partial-replication
@@ -3915,25 +3810,9 @@ declare abstract class ShardDO {
3915
3810
  protected scheduleTtlSweep(): Promise<void>;
3916
3811
  /**
3917
3812
  * Durable custody for this shard's deferred `ctx.scheduler` calls — the
3918
- * `ScheduleOutbox` the generated `buildCtx` hands to
3919
- * `withDeferredSchedules`.
3920
- *
3921
- * The two halves land on opposite sides of the COMMIT on purpose:
3922
- *
3923
- * - `record` runs while the handler is still inside its transaction, so the
3924
- * entry is durable exactly when the writes are and rolls back with them.
3925
- * It deliberately does NOT swallow: a failure here is still inside the span,
3926
- * so letting it throw rolls the mutation back — the one moment at which
3927
- * failing is free. Swallowing would put us back where we started, committing
3928
- * writes whose job nothing is holding.
3929
- * - `forget` runs after the dispatch, so it must never fail the response. A
3930
- * delete that does not land leaves an entry the retry loop re-offers, which
3931
- * the scheduler refuses as a duplicate and which is then dropped — the error
3932
- * self-heals into one wasted RPC.
3933
- *
3934
- * What survives a settle is therefore exactly the set of jobs that were
3935
- * promised and not enqueued, which is what {@link ShardDO.pollScheduleOutbox}
3936
- * 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.
3937
3816
  */
3938
3817
  protected scheduleOutbox(): ScheduleOutbox;
3939
3818
  /**
@@ -3951,29 +3830,8 @@ declare abstract class ShardDO {
3951
3830
  protected scheduleOutboxScheduler(): SchedulerLike | undefined;
3952
3831
  /**
3953
3832
  * Re-offer the deferred schedules that were promised to a caller and never
3954
- * reached the scheduler — the retry half of {@link ShardDO.scheduleOutbox}.
3955
- * Shares the poll alarm with the source-ingest and TTL tiers, and reports the
3956
- * earliest next-due time the same way, so a shard with an empty outbox (the
3957
- * steady state — an entry lives only between a COMMIT and its dispatch) arms
3958
- * nothing.
3959
- *
3960
- * Each attempt reuses the id the caller was already handed, so an entry whose
3961
- * original dispatch DID land — the failure was the `forget`, or the isolate
3962
- * died between the two — is refused as a duplicate rather than scheduled
3963
- * twice. A refusal and an acceptance are therefore both "the scheduler has
3964
- * it", and both end custody.
3965
- *
3966
- * The default bound is {@link SCHEDULE_OUTBOX_MAX_ATTEMPTS}: a job the
3967
- * scheduler will never accept stops costing alarms and becomes a reported
3968
- * fact instead — parked, logged at `error` with its id and target, and kept
3969
- * for {@link SCHEDULE_OUTBOX_RETENTION_MS} so an operator can see what was
3970
- * promised and never enqueued. A call made with `retry.forever` opts out of
3971
- * that ceiling: it stays live, paced by the ladder's last rung, until the
3972
- * scheduler accepts it or refuses it as invalid. The retention sweep only
3973
- * ever drops parked rows. The sweep rides whatever tick reaches this tier, so a shard
3974
- * holding ONLY parked entries keeps them until something else wakes it —
3975
- * which is the right trade: they are one row per genuinely lost job, not a
3976
- * 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.
3977
3835
  */
3978
3836
  protected pollScheduleOutbox(trace?: TraceRefLike): Promise<number | undefined>;
3979
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. */
@@ -4500,6 +4358,24 @@ declare abstract class ShardDO {
4500
4358
  * trace ids to needs a way to say so.
4501
4359
  */
4502
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
+ */
4503
4379
  protected makeDispatchSpan(anchor: TraceAnchor, sink?: TelemetrySink, scope?: SensitiveScope): SpanHandle;
4504
4380
  /**
4505
4381
  * Build the `ctx.metrics` recorder for one dispatched function. Thin wiring
@@ -4533,24 +4409,6 @@ declare abstract class ShardDO {
4533
4409
  * as the host-specific handler while the engine is progressively extracted.
4534
4410
  */
4535
4411
  protected handleAlarmCloudflare(): Promise<void>;
4536
- /**
4537
- * Build `ctx.span` — the handle onto the **dispatch's own span**, and with it
4538
- * the wide-event surface.
4539
- *
4540
- * `ctx.trace(...)` creates a *new* child span for a sub-operation; this
4541
- * attaches to the one that already exists for the request. That is the
4542
- * distinction between "time this thing" and "record a fact about this
4543
- * request", and conflating them is why instrumentation usually degrades into
4544
- * log spam: with nowhere to put a fact, people reach for `ctx.log.info`.
4545
- *
4546
- * Attributes accumulate across the whole dispatch and are folded into the
4547
- * root span in `recordDispatchRootSpan` — the OTel-native form of a
4548
- * wide event, needing no non-standard "canonical log line" convention on the
4549
- * collector side.
4550
- *
4551
- * Keyed by `dispatchSpanKey` — trace id AND root span id — so two concurrent
4552
- * dispatches forwarded under the same client trace accumulate separately.
4553
- */
4554
4412
  /**
4555
4413
  * Snapshot the per-request identity/replay fields into a {@link RequestScope}.
4556
4414
  * Paired with {@link ShardDO.restoreRequestScope}; see that type's docstring
@@ -4566,6 +4424,51 @@ declare abstract class ShardDO {
4566
4424
  * as this request's. The dispatch path re-pins its own afterwards.
4567
4425
  */
4568
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;
4443
+ /**
4444
+ * Load `functionPath`'s module before a live-query gate reads its registry entry: a lazy
4445
+ * registry's stub carries no `perDispatch` until then, so the gate would wave a cold per-dispatch
4446
+ * query through and run it once. A failed load is left to the run that follows, which reports it.
4447
+ *
4448
+ * The per-request fields are left alone: a socket path pins its identity around each run it
4449
+ * makes, so it holds no scope here, and putting a snapshot back after the wait would overwrite
4450
+ * those of a dispatch that ran meanwhile.
4451
+ */
4452
+ private prepareForLiveQueryGate;
4453
+ /**
4454
+ * Wait out a subscribe's function load, answering whether the subscribe may still register: an
4455
+ * unsubscribe for the same id, or the socket closing, during the wait makes it moot.
4456
+ */
4457
+ private subscribeOutlivedLoad;
4458
+ /** The identity of `subId`'s current registration on `ws`, minted for one restored from hibernation. */
4459
+ private subscriptionRegistration;
4460
+ /** Whether `subId` on `ws` is still the registration a caller read before awaiting. */
4461
+ private holdsRegistration;
4462
+ /**
4463
+ * The refresh sweep's gate: drop `subId` (and tell the client) when its function may not be held
4464
+ * live, once that function is loaded. `undefined` keeps it, decided without a yield; a promise
4465
+ * answers whether the sweep must skip it — dropped, or replaced or unsubscribed during the load,
4466
+ * in which case `functionPath` names a query the id no longer holds — and is only pending while
4467
+ * a cold function loads.
4468
+ */
4469
+ private dropIfNotLive;
4470
+ /** Why `functionPath` may not be held as a live subscription, or `undefined` when it may; shared by `subscribe` and the refresh sweep. */
4471
+ private liveQueryRefusal;
4569
4472
  /**
4570
4473
  * Whether a subscription gets its updates by re-execution, which diffs the
4571
4474
  * query's own result. A broadcast row would bypass that diff baseline (no
@@ -4799,106 +4702,6 @@ declare abstract class ShardDO {
4799
4702
  * the close path.
4800
4703
  */
4801
4704
  private purgeDurableSocketBaselines;
4802
- /**
4803
- * Fold one dispatch into the per-function counters keyed by `functionPath`,
4804
- * creating the entry on first sight. `errorMessage` is supplied only when
4805
- * the handler threw, in which case the failure counters advance too. The
4806
- * caller is expected to have already redacted `errorMessage` (via
4807
- * `redactArgs`, the same `standardRules` treatment the request-log sinks
4808
- * use) — this method persists/caches it verbatim into BOTH the durable
4809
- * `__lunora_metrics.last_error_message` column and the in-memory
4810
- * `functionStats.lastErrorMessage` served by `getFunctionStats`, so an
4811
- * un-redacted message reaching here leaks into the Studio.
4812
- * `scannedTables` carries the tables the dispatch full-scanned (collected by
4813
- * `getCtxDbReadHook`), which advance the causal scan attribution.
4814
- * `indexHits` carries the declared indexes it exercised (collected by
4815
- * `getCtxDbIndexUseHook`, NUL-free `JSON.stringify([table, index])` keys),
4816
- * which advance the durable `__lunora_metrics_index` hit counter behind the
4817
- * dead-index lint. Called once per `/rpc` dispatch alongside the aggregate
4818
- * `metrics` update.
4819
- *
4820
- * Two writes happen here. The in-memory {@link functionStats} map is kept
4821
- * for the fast warm-instance path, and the durable `__lunora_metrics`
4822
- * table is upserted so the counters survive hibernation/restart — the
4823
- * persisted table is the source of truth the admin RPCs read from. The
4824
- * persist is best-effort: a SQL failure (e.g. a test double without a
4825
- * `sql` handle) must never turn a successful dispatch into a failed one,
4826
- * so it is swallowed and the in-memory counters still advance.
4827
- *
4828
- * The durable write is COALESCED, not per-dispatch: the call is folded into
4829
- * {@link ShardDO.pendingFunctionMetrics} (exact counts, durations, scans and
4830
- * index hits) and {@link ShardDO.maybeFlushMetrics} writes the whole delta once
4831
- * every N dispatches ({@link ShardDO.metricsFlushEvery}; default 8; 1 = every dispatch),
4832
- * so the durable counters stay exact and only the write frequency drops.
4833
- */
4834
- private recordFunctionCall;
4835
- /**
4836
- * Fold the per-DISTINCT-statement SQL samples accumulated during the current
4837
- * dispatch into {@link ShardDO.pendingStmtSamples}. Called after
4838
- * `recordFunctionCall` on both the success and error paths, followed by
4839
- * {@link ShardDO.maybeFlushMetrics}.
4840
- *
4841
- * Already folded by the instrumented `sql` getter (see `currentStmtSamples`);
4842
- * `count` carries the real execution count so the durable
4843
- * `exec_count`/`total_duration_ms` still reflect every execution. Pure
4844
- * in-memory; nothing is written until the flush. Clearing `currentStmtSamples`
4845
- * happens in the `finally` block of the dispatch path, not here.
4846
- */
4847
- private foldStmtSamples;
4848
- /** Fold one completed dispatch into {@link ShardDO.pendingFunctionMetrics}. */
4849
- private foldFunctionMetric;
4850
- /**
4851
- * Write the pending metric delta when this dispatch is due: every
4852
- * N dispatches ({@link ShardDO.metricsFlushEvery}), immediately after an errored or
4853
- * conflicted one, or when the pending statement set is as wide as one
4854
- * dispatch may be. (A minute-boundary crossing flushes earlier, inside
4855
- * {@link ShardDO.foldFunctionMetric}.) Counts are exact either way; at most
4856
- * N-1 dispatches of counters are lost if the DO is evicted before a flush.
4857
- */
4858
- private maybeFlushMetrics;
4859
- /**
4860
- * Persist the pending delta: one `recordFunctionMetric` per path and one
4861
- * `recordQueryMetric` per (statement, latency bucket) key, so the
4862
- * histogram still sees each dispatch's own average. The accumulators are swapped out
4863
- * first, so a write that throws DROPS that path's (or entry's) delta and the rest
4864
- * of the batch is still written. There is deliberately no retry: metrics are
4865
- * best-effort, `recordFunctionMetric` is several statements per path and the host
4866
- * exposes no synchronous transaction, so a retry after a partial write would double
4867
- * count, and a persistent failure would grow the pending set without bound. One
4868
- * warning per flush reports what was dropped. Never fails the request.
4869
- */
4870
- private flushPendingMetrics;
4871
- /** Write any coalesced delta so an admin read of the durable metric tables is never stale. */
4872
- private flushUnwrittenMetrics;
4873
- /**
4874
- * Dispatches per durable metric write (env `LUNORA_METRICS_FLUSH_EVERY`): a positive
4875
- * integer, default {@link DEFAULT_METRICS_FLUSH_EVERY} (8). Unset, blank, fractional,
4876
- * non-numeric or < 1 values fall back to the default. An evicted DO loses at most N-1
4877
- * dispatches of un-flushed counters (7 by default); errored or conflicted dispatches
4878
- * and minute-boundary crossings still flush immediately. Set 1 to write every dispatch.
4879
- */
4880
- private metricsFlushEvery;
4881
- /**
4882
- * Assemble the per-function readout served by
4883
- * `__lunora_admin__:getFunctionStats`, sorted most-recently-called first so
4884
- * the busiest functions surface at the top of the studio table.
4885
- *
4886
- * Reads from the durable `__lunora_metrics` table — the source of truth —
4887
- * so the counts reflect the function's lifetime, not just calls since this
4888
- * instance woke. Falls back to the in-memory map only if the durable read
4889
- * throws (e.g. a test double without a usable `sql` handle), keeping the
4890
- * warm-instance counters available even then. The wire shape is unchanged
4891
- * (`{ functions, sinceMs }`), so existing studio/runtime consumers keep
4892
- * working; the rows are now backed by persisted data.
4893
- */
4894
- private collectFunctionStats;
4895
- /**
4896
- * Per-function coarse time-series served additively by the metrics RPC, so
4897
- * the studio can chart call/error history. Reads the durable
4898
- * `__lunora_metrics_buckets` table; returns an empty, non-truncated result
4899
- * when persistence is unavailable so the response stays well-formed.
4900
- */
4901
- private collectFunctionMetricBuckets;
4902
4705
  private maybeWarnRootSize;
4903
4706
  /**
4904
4707
  * Map a thrown value to a JSON response. `ValidationError` from
@@ -5306,38 +5109,14 @@ declare abstract class ShardDO {
5306
5109
  private handleRecordQueueMessage;
5307
5110
  /**
5308
5111
  * Serve `dropOutboxEntry` — cancel a deferred schedule the scheduler never
5309
- * confirmed, live or parked. `ctx.scheduler.cancel` only reaches jobs the
5310
- * SchedulerDO holds, so this is the only way to stop a `retry.forever` entry
5311
- * that is still waiting.
5312
- *
5313
- * The shard cannot always tell that the scheduler never got the job: the accept
5314
- * may have been lost on the way back, or an attempt may be awaiting it right now.
5315
- * So the drop cancels the id at the scheduler FIRST and deletes the row only once
5316
- * that settled. A cancel that fails (the scheduler is often the very thing that is down)
5317
- * parks the entry so it can never be handed over, and the error goes to the operator;
5318
- * dropping again completes it. And an attempt that was already in the air takes the job back out
5319
- * when it lands, see {@link ShardDO.retryScheduleOutboxEntry}. Admin-gated by the caller.
5112
+ * confirmed; see {@link ScheduleOutboxRunner.drop}. Admin-gated by the caller.
5320
5113
  */
5321
5114
  private handleDropOutboxEntry;
5322
5115
  /**
5323
- * Audit a drop that applied. "Not found" is the usual answer for a job the scheduler never
5324
- * accepted, and the same answer it gives once an accepted job has run: an earlier hand-off whose
5325
- * accept was lost on the way back. The drop cannot tell the two apart, so the operator is told the
5326
- * job may have run.
5327
- */
5328
- private auditAppliedScheduleOutboxDrop;
5329
- /**
5330
- * With no scheduler to ask, waiting never confirms the cancel. The first drop parked the row (a
5331
- * job may have been accepted under a binding that has since gone); dropping a row that was already
5332
- * parked, with nothing in flight, is the operator accepting that, and removes it.
5333
- * @returns whether the row was removed
5334
- */
5335
- private removeUnconfirmableScheduleOutboxDrop;
5336
- /**
5337
- * Serve `retryOutboxEntry` — put an entry back on the retry ladder, due now:
5338
- * the way back for a parked entry, and a way to skip a long backoff once the
5339
- * scheduler is healthy. Arms the poll alarm for now, because nothing else is
5340
- * 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.
5341
5120
  */
5342
5121
  private handleRetryOutboxEntry;
5343
5122
  /** Empty the dev queue consumed-message log (studio "clear log" action). Admin-gated by the caller. */
@@ -5835,51 +5614,13 @@ declare abstract class ShardDO {
5835
5614
  * middleware. Identity-scoping the key is what keeps that impossible.
5836
5615
  */
5837
5616
  private attachDurableStream;
5838
- /**
5839
- * Run one registry step after every step before it. Registration and release
5840
- * both go through here, so a release's emptiness check and unregister can
5841
- * never interleave with a registration: a write that lands mid-release
5842
- * registers AFTER the unregister, not before it.
5843
- */
5844
- private serializeRegistry;
5845
- /** The registry stub, pinned to this DO's own jurisdiction — the subnamespace the worker pins the registry it reads. */
5846
- private registryStub;
5847
- /**
5848
- * Where this shard's registry writes go. A Durable Object namespace is this app's own
5849
- * registry: signed directly with this worker's secret. Anything else is the RPC surface of
5850
- * the worker that hosts the registry, reached through its service binding, so the binding
5851
- * itself is the capability and no secret is needed. `undefined` when a namespace is not in
5852
- * this shard's jurisdiction.
5853
- */
5854
- private registryWriter;
5855
- /**
5856
- * Tell the shard registry this shard holds rows of each `.shardBy()` table
5857
- * the flushed write touched, once per table per instance. The cross-shard
5858
- * fan-outs (export, CDC sync, migrations) only reach the shards the registry
5859
- * lists, so a shard that never registers is left out of every one of them.
5860
- *
5861
- * Runs past the response (see `flushChangedTables`) and never rejects: the
5862
- * write has already committed, so a failure is logged, the table's claim
5863
- * released, and the first write after {@link SHARD_REGISTRY_RETRY_MS} retries.
5864
- */
5865
- private registerWrittenShard;
5866
5617
  /**
5867
5618
  * `__lunora_admin__:releaseShardRegistration`: drop this shard from the
5868
5619
  * registry for each named table it holds no rows of, and keep it for the rest.
5869
- *
5870
- * The shard decides rather than the caller because only here can the check
5871
- * be ordered against this shard's own writes. It runs on the registry chain
5872
- * (see {@link ShardDO.serializeRegistry}) and clears the table's claim, so a
5873
- * row written before the check is seen by it and keeps the table, and one
5874
- * written after re-registers once the unregister has landed. A caller that
5875
- * probed first and unregistered second could hide a shard written in between:
5876
- * its claim would say "registered" while the registry said otherwise.
5877
- *
5878
- * 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.
5879
5622
  */
5880
5623
  private handleReleaseShardRegistration;
5881
- /** Whether this shard's SQLite holds at least one row of `table` — `false` for a table it never created. */
5882
- private tableHasRows;
5883
5624
  /**
5884
5625
  * Drain the tables written during the in-flight RPC and re-run every
5885
5626
  * subscription that depends on one of them. Called after `handleRpc`
@@ -5984,6 +5725,8 @@ declare abstract class ShardDO {
5984
5725
  * persist failure. A subscription hitting one ends rather than latching for backoff.
5985
5726
  */
5986
5727
  private isDeterministicSubscriptionFailure;
5728
+ /** The refresh sweep's answer to a subscription run that threw. */
5729
+ private failRefresh;
5987
5730
  /**
5988
5731
  * A subscription's refresh threw: count and log it, latch it for backoff, and
5989
5732
  * tell the client the first time of a streak. The subscription stays
@@ -6373,74 +6116,6 @@ declare abstract class ShardDO {
6373
6116
  * deferral itself is the caller's job: this only reports it.
6374
6117
  */
6375
6118
  private recordScheduleRateDeferral;
6376
- /**
6377
- * One outbox attempt: replay the stored call, then either end custody or push
6378
- * the entry out along {@link SCHEDULE_OUTBOX_BACKOFF_MS}. The default policy
6379
- * parks once the ladder runs out; `retry.forever` keeps a valid call live.
6380
- *
6381
- * An envelope that will not parse is parked immediately rather than retried:
6382
- * no number of attempts turns malformed JSON into a job, and the log line is
6383
- * the only useful output left.
6384
- */
6385
- private retryScheduleOutboxEntry;
6386
- /**
6387
- * The post-commit hand-off of a deferred schedule, run as a recorded attempt like every retry:
6388
- * a drop that arrives while the call awaits the scheduler is seen here and the job is cancelled
6389
- * when it lands (the row stays parked if that cancel fails). A failure leaves the row for the
6390
- * retry loop, unless a drop already ended the entry, in which case the row goes.
6391
- */
6392
- private runScheduleOutboxHandOff;
6393
- private handOffRecordedScheduleOutboxCall;
6394
- private markScheduleOutboxDropped;
6395
- private isScheduleOutboxBeingDropped;
6396
- /** One recorded call is done with: handed off, skipped, or rolled back with its window. */
6397
- private finishScheduleOutboxHandOff;
6398
- /**
6399
- * Forget the drop marker of `id` once nothing it could still decide is left: no recorded call
6400
- * waiting for its hand-off, no attempt awaiting the scheduler, no drop in flight. Pruned by that
6401
- * condition rather than by count, because evicting a marker early would let a queued call of a
6402
- * dropped job go out.
6403
- */
6404
- private pruneScheduleOutboxDropMarker;
6405
- /** Whether a drop covers the recording `token` names: recorded no later than the row it acted on. */
6406
- private isScheduleOutboxTokenDropped;
6407
- /** Whether the entry this attempt was made for has been dropped, now or while it was in the air. */
6408
- private wasScheduleOutboxDropped;
6409
- private releaseScheduleOutboxAttempt;
6410
- /** A hand-off that threw: end custody if the scheduler turns out to hold the job, else defer or park the entry. */
6411
- private settleFailedScheduleOutboxAttempt;
6412
- /**
6413
- * The scheduler holds the job: end custody. If the entry was dropped while the
6414
- * hand-off was awaiting (or a drop is cancelling it right now), the operator asked
6415
- * for the job NOT to run, so take it back out of the scheduler. `landed` says the scheduler
6416
- * is known to hold (or to have held) the job, which is what makes a "not found" cancel a failure.
6417
- */
6418
- private settleScheduleOutboxHandOff;
6419
- /** Park `id` if it is still live, keeping its attempt count; a parked or absent row is left as it is. */
6420
- private parkLiveScheduleOutboxEntry;
6421
- /**
6422
- * Push one entry out along the ladder. A `retry.forever` entry that reaches
6423
- * the attempts a default entry would have parked at says so once, at `warn`:
6424
- * past that point nothing else reports that the job is still not enqueued.
6425
- */
6426
- private deferScheduleOutboxEntry;
6427
- /** Park one entry and say so at `error` — a job was promised to a caller and will not be enqueued. */
6428
- private parkScheduleOutboxEntry;
6429
- /**
6430
- * Arm the poll alarm once per warm instance if this shard is holding deferred
6431
- * schedules nobody has enqueued.
6432
- *
6433
- * The settle asks for a wake when its own dispatch fails, but the window that
6434
- * loses a job most quietly is the one where no settle ran at all: the DO is
6435
- * evicted between the COMMIT and the dispatch, and the entry sits with nothing
6436
- * pointing at it. Every entry point into this object goes through shard init,
6437
- * so hooking it here means the next time anything wakes this shard the retry
6438
- * loop starts — for the cost of one indexed read per cold start.
6439
- *
6440
- * Swallows: a shard whose store predates the table (or a harness with a stub
6441
- * handle) simply has no custody to resume, and init must not fail for it.
6442
- */
6443
- private armScheduleOutboxRetry;
6444
6119
  /**
6445
6120
  * When the TTL tier should next wake for `specs`: 1 ms past the earliest live
6446
6121
  * expiry (the sweep's `expiry < now` is strict), but never before `now +`
@@ -6957,27 +6632,6 @@ declare abstract class ShardDO {
6957
6632
  private reauthenticateSocket;
6958
6633
  private routeNonRpc;
6959
6634
  private handleWebSocketUpgrade;
6960
- /**
6961
- * Whether this shard has a `__cdc_log` table. The single source of the
6962
- * "is CDC on here?" probe shared by {@link currentCdcCursor},
6963
- * {@link currentCdcEpoch}, {@link evaluateResume}, and the PITR-restore epoch
6964
- * bump. Returns `false` (rather than throwing) on a stub `sql` handle (unit
6965
- * harness double) or a pre-CDC shard, so callers degrade to the no-CDC path.
6966
- */
6967
- private cdcEnabled;
6968
- /**
6969
- * The `__cdc_meta` epoch, read from SQLite at most once until
6970
- * {@link invalidateCdcMetaCache} runs. Callers gate on {@link cdcEnabled}
6971
- * first, except {@link sealForkedTimeline}, whose callers already proved it.
6972
- */
6973
- private cachedCdcEpoch;
6974
- /** Bump the CDC epoch and drop the CDC memos in one step, so no caller can bump without invalidating. */
6975
- private bumpCdcEpochUncached;
6976
- /**
6977
- * Drop both CDC memos — the single exit for every path that can change
6978
- * `__cdc_log`'s presence or the `__cdc_meta` row behind this instance's back.
6979
- */
6980
- private invalidateCdcMetaCache;
6981
6635
  /**
6982
6636
  * A route upgrade refused before anything it would run is registered. A route that requires a verified session
6983
6637
  * refuses an anonymous caller with a plain 401 (the default route allows anonymous sockets, like every other