@lunora/do 1.0.0-alpha.274 → 1.0.0-alpha.275

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
@@ -1765,6 +1765,14 @@ declare abstract class ShardDO {
1765
1765
  * the first ctx is.
1766
1766
  */
1767
1767
  private lastTelemetrySink;
1768
+ /**
1769
+ * `functionPath` + limit kind of every live-query re-run that already warned
1770
+ * near a limit. Each re-run gets a fresh tracker, so without this a query that
1771
+ * sits past 80% would warn once per subscriber per write. Bounded by the
1772
+ * app's query paths; it clears when the instance hibernates, so a query that
1773
+ * stays near a limit warns again after a wake.
1774
+ */
1775
+ private readonly rerunNearLimitWarned;
1768
1776
  /**
1769
1777
  * Client-issued idempotency key for the in-flight mutation, forwarded via the
1770
1778
  * `x-lunora-mutation-id` header. When set, the dispatch path dedups the call
@@ -2178,6 +2186,36 @@ declare abstract class ShardDO {
2178
2186
  * only saves round trips; it resets with the instance.
2179
2187
  */
2180
2188
  private readonly registeredTables;
2189
+ /**
2190
+ * The hand-offs awaiting the scheduler, per outbox id. `retryOutboxEntry` makes them `stale`
2191
+ * (their failure must not overwrite the reset). Whether one was dropped is read from
2192
+ * {@link ShardDO.scheduleOutboxDroppedThrough} by its token, not inferred from the row, because a
2193
+ * row can also vanish for an innocent reason. In memory is enough: an attempt never outlives the
2194
+ * instance that started it.
2195
+ */
2196
+ private readonly scheduleOutboxAttempts;
2197
+ /**
2198
+ * Outbox entries an operator is dropping right now. The drop first asks the
2199
+ * scheduler to cancel the job (it may already hold it), and the retry loop must
2200
+ * not hand the entry over again while that is awaiting.
2201
+ */
2202
+ private readonly scheduleOutboxDrops;
2203
+ /**
2204
+ * Per id, the newest recording an operator dropped: a drop covers every call recorded up to the
2205
+ * row it acted on (including calls of one mutation that a later same-id record replaced), and
2206
+ * no call recorded after it. A missing row alone cannot say "dropped": two calls of one mutation
2207
+ * that share an explicit id share one row, and the first hand-off releases it. Pruned by
2208
+ * {@link ShardDO.pruneScheduleOutboxDropMarker} once no call or attempt it could affect is left.
2209
+ */
2210
+ private readonly scheduleOutboxDroppedThrough;
2211
+ /**
2212
+ * Calls recorded for an id whose hand-off has not finished (or whose window has not rolled back).
2213
+ * A drop marker is needed exactly that long, so it is pruned when this reaches zero instead of by
2214
+ * count: evicting a marker early would let a queued call of a dropped job run.
2215
+ */
2216
+ private readonly scheduleOutboxPendingHandOffs;
2217
+ /** The `created_at` last handed to `recordScheduleOutbox`; see {@link ShardDO.scheduleOutbox}. */
2218
+ private lastScheduleOutboxRecordAt;
2181
2219
  /**
2182
2220
  * Epoch millis before which registration is not retried, set when one
2183
2221
  * fails: a registry outage costs one attempt per window rather than one per
@@ -3773,7 +3811,7 @@ declare abstract class ShardDO {
3773
3811
  * TTL, so an idle TTL table does not wake the shard. A write that adds an
3774
3812
  * expiring row re-arms through {@link ShardDO.armTtlSweepAfterWrite}.
3775
3813
  *
3776
- * One {@link ShardDO.alarmHeadroom} tracker covers the WHOLE sweep pass (every
3814
+ * One tracker (built like {@link ShardDO.alarmHeadroom}, minus its warning) covers the WHOLE sweep pass (every
3777
3815
  * spec, every batch) — not per-row or per-spec — because the ceiling exists to
3778
3816
  * bound one alarm tick's total isolate cost, not any single table's. A
3779
3817
  * `TRANSACTION_LIMIT_EXCEEDED` mid-batch is "batch full", not a genuine
@@ -3822,7 +3860,9 @@ declare abstract class ShardDO {
3822
3860
  * config to read, so it reports `undefined` and the tier stays dormant. The
3823
3861
  * generated subclass overrides it with the app's configured scheduler —
3824
3862
  * and only when one is configured, so a shard whose `ctx.scheduler` is the
3825
- * throwing stub does not retry against a stub eight times before parking.
3863
+ * throwing stub does not retry against a stub eight times before parking. A
3864
+ * `retry.forever` entry stays in custody with backoff while no scheduler is
3865
+ * configured, so a deploy that restores one picks it up.
3826
3866
  * @returns the scheduler to retry through, or `undefined` when this shard has none
3827
3867
  */
3828
3868
  protected scheduleOutboxScheduler(): SchedulerLike | undefined;
@@ -3840,13 +3880,14 @@ declare abstract class ShardDO {
3840
3880
  * twice. A refusal and an acceptance are therefore both "the scheduler has
3841
3881
  * it", and both end custody.
3842
3882
  *
3843
- * The bound is {@link SCHEDULE_OUTBOX_MAX_ATTEMPTS}: a job the scheduler will
3844
- * never accept stops costing alarms and becomes a reported fact instead —
3845
- * parked, logged at `error` with its id and target, and kept for
3846
- * {@link SCHEDULE_OUTBOX_RETENTION_MS} so an operator can see what was
3847
- * promised and never enqueued. The queue is bounded on both sides: the
3848
- * ceiling stops live entries accumulating, the retention sweep stops parked
3849
- * ones doing so. The sweep rides whatever tick reaches this tier, so a shard
3883
+ * The default bound is {@link SCHEDULE_OUTBOX_MAX_ATTEMPTS}: a job the
3884
+ * scheduler will never accept stops costing alarms and becomes a reported
3885
+ * fact instead — parked, logged at `error` with its id and target, and kept
3886
+ * for {@link SCHEDULE_OUTBOX_RETENTION_MS} so an operator can see what was
3887
+ * promised and never enqueued. A call made with `retry.forever` opts out of
3888
+ * that ceiling: it stays live, paced by the ladder's last rung, until the
3889
+ * scheduler accepts it or refuses it as invalid. The retention sweep only
3890
+ * ever drops parked rows. The sweep rides whatever tick reaches this tier, so a shard
3850
3891
  * holding ONLY parked entries keeps them until something else wakes it —
3851
3892
  * which is the right trade: they are one row per genuinely lost job, not a
3852
3893
  * loop that grows on its own.
@@ -4201,7 +4242,7 @@ declare abstract class ShardDO {
4201
4242
  * for the same reason — an ambient field says "a dispatch is in flight", not
4202
4243
  * "this caller is that dispatch".
4203
4244
  */
4204
- protected transactionHeadroom(): TransactionHeadroomTracker;
4245
+ protected transactionHeadroom(functionPath?: string): TransactionHeadroomTracker;
4205
4246
  /**
4206
4247
  * A fresh budget for one deferred subscription re-run.
4207
4248
  *
@@ -4218,19 +4259,27 @@ declare abstract class ShardDO {
4218
4259
  * background: a concurrent `/rpc` dispatch building its `ctx.db` during the
4219
4260
  * drain would take the refresh branch and lose its own ceiling entirely.
4220
4261
  */
4221
- protected subscriptionHeadroom(): TransactionHeadroomTracker;
4262
+ protected subscriptionHeadroom(functionPath: string, identity?: SubscriptionIdentity): TransactionHeadroomTracker;
4263
+ /**
4264
+ * A stream's budget, held for its whole life. Rows stay capped over the life,
4265
+ * as before; bytes are capped per frame by {@link ShardDO.windowStreamReads}.
4266
+ */
4267
+ protected streamHeadroom(functionPath: string, identity?: SubscriptionIdentity): TransactionHeadroomTracker;
4268
+ /** Pass `frames` through, opening a fresh read-byte window after each one. */
4269
+ protected windowStreamReads(headroom: TransactionHeadroomTracker, frames: AsyncIterable<unknown>): AsyncIterable<unknown>;
4222
4270
  /**
4223
4271
  * A fresh budget for one alarm-driven work item — one external-source
4224
- * table's tick, or one TTL sweep pass.
4272
+ * table's tick.
4225
4273
  *
4226
4274
  * Alarm work runs with no client waiting and no `/rpc` dispatch in flight,
4227
4275
  * so `transactionHeadroom()`'s per-dispatch tracker is `undefined` there —
4228
- * leaving external-source ingest and TTL sweeps completely unmetered, the
4229
- * exact isolate-exhaustion class the meter exists to bound. Handed to the
4276
+ * leaving external-source ingest completely unmetered, the exact
4277
+ * isolate-exhaustion class the meter exists to bound. Handed to the
4230
4278
  * writer BY VALUE, the same pattern as `subscriptionHeadroom()` and for the
4231
4279
  * same reason: an ambient instance-field flag would race a concurrently
4232
4280
  * in-flight `/rpc` dispatch, or a sibling alarm work item, clearing or
4233
- * substituting the wrong tracker mid-flight.
4281
+ * substituting the wrong tracker mid-flight. A TTL sweep builds its own
4282
+ * tracker instead, without the near-limit warning (see `pollTtlSweeps`).
4234
4283
  */
4235
4284
  protected alarmHeadroom(): TransactionHeadroomTracker;
4236
4285
  /**
@@ -4266,7 +4315,10 @@ declare abstract class ShardDO {
4266
4315
  * Unlike request-log args, `ctx.log` args are NOT redacted: the developer
4267
4316
  * chose to log them, exactly like a raw `console.log`.
4268
4317
  */
4269
- protected recordUserLog(functionPath: string, level: ContextLogLevel, args: unknown[], message: string, fields: Record<string, unknown> | undefined, sink?: TelemetrySink, eventName?: string, anchor?: TraceAnchor, error?: ErrorDetail | undefined): void;
4318
+ protected recordUserLog(functionPath: string, level: ContextLogLevel, args: unknown[], message: string, fields: Record<string, unknown> | undefined, sink?: TelemetrySink, eventName?: string, anchor?: TraceAnchor, error?: ErrorDetail | undefined, pinned?: {
4319
+ trace: TraceAnchor | undefined;
4320
+ userId: string | undefined;
4321
+ }): void;
4270
4322
  /**
4271
4323
  * Build the `ctx.log` logger for one dispatched function. Each severity method
4272
4324
  * accepts either the structured form (`(message, fields)`) or console-style
@@ -4328,6 +4380,14 @@ declare abstract class ShardDO {
4328
4380
  * span through the root-span mirroring in `recordDispatchRootSpan`.
4329
4381
  */
4330
4382
  protected instrumentSql<T extends SqlClientLike>(client: T, functionPath: string, anchor: TraceAnchor, sink?: TelemetrySink, scope?: SensitiveScope): T;
4383
+ /**
4384
+ * Count the I/O an action starts through `ctx`. The returned function, called
4385
+ * once the handler has returned, restores `ctx` and logs one `warn` line
4386
+ * naming every call still in flight. On Workers that work can be cancelled
4387
+ * silently after the response; the line is how a developer finds out before
4388
+ * production does. Nothing is awaited on the handler's behalf.
4389
+ */
4390
+ protected watchActionWork(functionPath: string, context: unknown): () => void;
4331
4391
  /**
4332
4392
  * Build `ctx.fetch` — the platform `fetch`, instrumented.
4333
4393
  *
@@ -5097,6 +5157,42 @@ declare abstract class ShardDO {
5097
5157
  * already mutate the shard, so a token-gated capture insert adds no privilege.
5098
5158
  */
5099
5159
  private handleRecordQueueMessage;
5160
+ /**
5161
+ * Serve `dropOutboxEntry` — cancel a deferred schedule the scheduler never
5162
+ * confirmed, live or parked. `ctx.scheduler.cancel` only reaches jobs the
5163
+ * SchedulerDO holds, so this is the only way to stop a `retry.forever` entry
5164
+ * that is still waiting.
5165
+ *
5166
+ * The shard cannot always tell that the scheduler never got the job: the accept
5167
+ * may have been lost on the way back, or an attempt may be awaiting it right now.
5168
+ * So the drop cancels the id at the scheduler FIRST and deletes the row only once
5169
+ * that settled. A cancel that fails (the scheduler is often the very thing that is down)
5170
+ * parks the entry so it can never be handed over, and the error goes to the operator;
5171
+ * dropping again completes it. And an attempt that was already in the air takes the job back out
5172
+ * when it lands, see {@link ShardDO.retryScheduleOutboxEntry}. Admin-gated by the caller.
5173
+ */
5174
+ private handleDropOutboxEntry;
5175
+ /**
5176
+ * Audit a drop that applied. "Not found" is the usual answer for a job the scheduler never
5177
+ * accepted, and the same answer it gives once an accepted job has run: an earlier hand-off whose
5178
+ * accept was lost on the way back. The drop cannot tell the two apart, so the operator is told the
5179
+ * job may have run.
5180
+ */
5181
+ private auditAppliedScheduleOutboxDrop;
5182
+ /**
5183
+ * With no scheduler to ask, waiting never confirms the cancel. The first drop parked the row (a
5184
+ * job may have been accepted under a binding that has since gone); dropping a row that was already
5185
+ * parked, with nothing in flight, is the operator accepting that, and removes it.
5186
+ * @returns whether the row was removed
5187
+ */
5188
+ private removeUnconfirmableScheduleOutboxDrop;
5189
+ /**
5190
+ * Serve `retryOutboxEntry` — put an entry back on the retry ladder, due now:
5191
+ * the way back for a parked entry, and a way to skip a long backoff once the
5192
+ * scheduler is healthy. Arms the poll alarm for now, because nothing else is
5193
+ * due to wake a shard whose entries were all parked. Admin-gated by the caller.
5194
+ */
5195
+ private handleRetryOutboxEntry;
5100
5196
  /** Empty the dev queue consumed-message log (studio "clear log" action). Admin-gated by the caller. */
5101
5197
  private handleClearQueueMessages;
5102
5198
  /**
@@ -6097,14 +6193,55 @@ declare abstract class ShardDO {
6097
6193
  private recordScheduleRateDeferral;
6098
6194
  /**
6099
6195
  * One outbox attempt: replay the stored call, then either end custody or push
6100
- * the entry out along {@link SCHEDULE_OUTBOX_BACKOFF_MS} — parking it once the
6101
- * ladder runs out.
6196
+ * the entry out along {@link SCHEDULE_OUTBOX_BACKOFF_MS}. The default policy
6197
+ * parks once the ladder runs out; `retry.forever` keeps a valid call live.
6102
6198
  *
6103
6199
  * An envelope that will not parse is parked immediately rather than retried:
6104
6200
  * no number of attempts turns malformed JSON into a job, and the log line is
6105
6201
  * the only useful output left.
6106
6202
  */
6107
6203
  private retryScheduleOutboxEntry;
6204
+ /**
6205
+ * The post-commit hand-off of a deferred schedule, run as a recorded attempt like every retry:
6206
+ * a drop that arrives while the call awaits the scheduler is seen here and the job is cancelled
6207
+ * when it lands (the row stays parked if that cancel fails). A failure leaves the row for the
6208
+ * retry loop, unless a drop already ended the entry, in which case the row goes.
6209
+ */
6210
+ private runScheduleOutboxHandOff;
6211
+ private handOffRecordedScheduleOutboxCall;
6212
+ private markScheduleOutboxDropped;
6213
+ private isScheduleOutboxBeingDropped;
6214
+ /** One recorded call is done with: handed off, skipped, or rolled back with its window. */
6215
+ private finishScheduleOutboxHandOff;
6216
+ /**
6217
+ * Forget the drop marker of `id` once nothing it could still decide is left: no recorded call
6218
+ * waiting for its hand-off, no attempt awaiting the scheduler, no drop in flight. Pruned by that
6219
+ * condition rather than by count, because evicting a marker early would let a queued call of a
6220
+ * dropped job go out.
6221
+ */
6222
+ private pruneScheduleOutboxDropMarker;
6223
+ /** Whether a drop covers the recording `token` names: recorded no later than the row it acted on. */
6224
+ private isScheduleOutboxTokenDropped;
6225
+ /** Whether the entry this attempt was made for has been dropped, now or while it was in the air. */
6226
+ private wasScheduleOutboxDropped;
6227
+ private releaseScheduleOutboxAttempt;
6228
+ /** A hand-off that threw: end custody if the scheduler turns out to hold the job, else defer or park the entry. */
6229
+ private settleFailedScheduleOutboxAttempt;
6230
+ /**
6231
+ * The scheduler holds the job: end custody. If the entry was dropped while the
6232
+ * hand-off was awaiting (or a drop is cancelling it right now), the operator asked
6233
+ * for the job NOT to run, so take it back out of the scheduler. `landed` says the scheduler
6234
+ * is known to hold (or to have held) the job, which is what makes a "not found" cancel a failure.
6235
+ */
6236
+ private settleScheduleOutboxHandOff;
6237
+ /** Park `id` if it is still live, keeping its attempt count; a parked or absent row is left as it is. */
6238
+ private parkLiveScheduleOutboxEntry;
6239
+ /**
6240
+ * Push one entry out along the ladder. A `retry.forever` entry that reaches
6241
+ * the attempts a default entry would have parked at says so once, at `warn`:
6242
+ * past that point nothing else reports that the job is still not enqueued.
6243
+ */
6244
+ private deferScheduleOutboxEntry;
6108
6245
  /** Park one entry and say so at `error` — a job was promised to a caller and will not be enqueued. */
6109
6246
  private parkScheduleOutboxEntry;
6110
6247
  /**
@@ -6235,6 +6372,26 @@ declare abstract class ShardDO {
6235
6372
  * @returns The response to return, or `undefined` to continue into dispatch.
6236
6373
  */
6237
6374
  private preDispatchAnswer;
6375
+ /**
6376
+ * Record how late a scheduled job started: `scheduler.lag_ms` is the gap
6377
+ * between its due time and this dispatch. A queue that cannot keep up shows
6378
+ * as a climbing lag long before jobs fail, and nothing else measures it.
6379
+ * Only a system dispatch may carry the due time; a client-sent header is
6380
+ * ignored rather than trusted to write the operator's metrics.
6381
+ */
6382
+ private recordSchedulerLag;
6383
+ /**
6384
+ * A fresh budget that reports crossing 80% of any ceiling as a `warn` line.
6385
+ * Local data is usually a fraction of production's, so the transaction that
6386
+ * fails after deploy is the one that only ever got close here — the line is
6387
+ * how a developer sees it coming. `functionPath` names the work; callers
6388
+ * without one pass the kind of work instead.
6389
+ *
6390
+ * The warning fires mid-handler, after awaits an interleaved dispatch can
6391
+ * use to re-set the shared trace and user, so both are pinned here. A `trace` of `undefined` files the line under no trace rather than
6392
+ * borrowing an unrelated one.
6393
+ */
6394
+ private mintHeadroom;
6238
6395
  /**
6239
6396
  * Stamp everything one RPC dispatch needs off its request, and reset every
6240
6397
  * per-request capture the handler will fill.
package/dist/index.d.ts CHANGED
@@ -1765,6 +1765,14 @@ declare abstract class ShardDO {
1765
1765
  * the first ctx is.
1766
1766
  */
1767
1767
  private lastTelemetrySink;
1768
+ /**
1769
+ * `functionPath` + limit kind of every live-query re-run that already warned
1770
+ * near a limit. Each re-run gets a fresh tracker, so without this a query that
1771
+ * sits past 80% would warn once per subscriber per write. Bounded by the
1772
+ * app's query paths; it clears when the instance hibernates, so a query that
1773
+ * stays near a limit warns again after a wake.
1774
+ */
1775
+ private readonly rerunNearLimitWarned;
1768
1776
  /**
1769
1777
  * Client-issued idempotency key for the in-flight mutation, forwarded via the
1770
1778
  * `x-lunora-mutation-id` header. When set, the dispatch path dedups the call
@@ -2178,6 +2186,36 @@ declare abstract class ShardDO {
2178
2186
  * only saves round trips; it resets with the instance.
2179
2187
  */
2180
2188
  private readonly registeredTables;
2189
+ /**
2190
+ * The hand-offs awaiting the scheduler, per outbox id. `retryOutboxEntry` makes them `stale`
2191
+ * (their failure must not overwrite the reset). Whether one was dropped is read from
2192
+ * {@link ShardDO.scheduleOutboxDroppedThrough} by its token, not inferred from the row, because a
2193
+ * row can also vanish for an innocent reason. In memory is enough: an attempt never outlives the
2194
+ * instance that started it.
2195
+ */
2196
+ private readonly scheduleOutboxAttempts;
2197
+ /**
2198
+ * Outbox entries an operator is dropping right now. The drop first asks the
2199
+ * scheduler to cancel the job (it may already hold it), and the retry loop must
2200
+ * not hand the entry over again while that is awaiting.
2201
+ */
2202
+ private readonly scheduleOutboxDrops;
2203
+ /**
2204
+ * Per id, the newest recording an operator dropped: a drop covers every call recorded up to the
2205
+ * row it acted on (including calls of one mutation that a later same-id record replaced), and
2206
+ * no call recorded after it. A missing row alone cannot say "dropped": two calls of one mutation
2207
+ * that share an explicit id share one row, and the first hand-off releases it. Pruned by
2208
+ * {@link ShardDO.pruneScheduleOutboxDropMarker} once no call or attempt it could affect is left.
2209
+ */
2210
+ private readonly scheduleOutboxDroppedThrough;
2211
+ /**
2212
+ * Calls recorded for an id whose hand-off has not finished (or whose window has not rolled back).
2213
+ * A drop marker is needed exactly that long, so it is pruned when this reaches zero instead of by
2214
+ * count: evicting a marker early would let a queued call of a dropped job run.
2215
+ */
2216
+ private readonly scheduleOutboxPendingHandOffs;
2217
+ /** The `created_at` last handed to `recordScheduleOutbox`; see {@link ShardDO.scheduleOutbox}. */
2218
+ private lastScheduleOutboxRecordAt;
2181
2219
  /**
2182
2220
  * Epoch millis before which registration is not retried, set when one
2183
2221
  * fails: a registry outage costs one attempt per window rather than one per
@@ -3773,7 +3811,7 @@ declare abstract class ShardDO {
3773
3811
  * TTL, so an idle TTL table does not wake the shard. A write that adds an
3774
3812
  * expiring row re-arms through {@link ShardDO.armTtlSweepAfterWrite}.
3775
3813
  *
3776
- * One {@link ShardDO.alarmHeadroom} tracker covers the WHOLE sweep pass (every
3814
+ * One tracker (built like {@link ShardDO.alarmHeadroom}, minus its warning) covers the WHOLE sweep pass (every
3777
3815
  * spec, every batch) — not per-row or per-spec — because the ceiling exists to
3778
3816
  * bound one alarm tick's total isolate cost, not any single table's. A
3779
3817
  * `TRANSACTION_LIMIT_EXCEEDED` mid-batch is "batch full", not a genuine
@@ -3822,7 +3860,9 @@ declare abstract class ShardDO {
3822
3860
  * config to read, so it reports `undefined` and the tier stays dormant. The
3823
3861
  * generated subclass overrides it with the app's configured scheduler —
3824
3862
  * and only when one is configured, so a shard whose `ctx.scheduler` is the
3825
- * throwing stub does not retry against a stub eight times before parking.
3863
+ * throwing stub does not retry against a stub eight times before parking. A
3864
+ * `retry.forever` entry stays in custody with backoff while no scheduler is
3865
+ * configured, so a deploy that restores one picks it up.
3826
3866
  * @returns the scheduler to retry through, or `undefined` when this shard has none
3827
3867
  */
3828
3868
  protected scheduleOutboxScheduler(): SchedulerLike | undefined;
@@ -3840,13 +3880,14 @@ declare abstract class ShardDO {
3840
3880
  * twice. A refusal and an acceptance are therefore both "the scheduler has
3841
3881
  * it", and both end custody.
3842
3882
  *
3843
- * The bound is {@link SCHEDULE_OUTBOX_MAX_ATTEMPTS}: a job the scheduler will
3844
- * never accept stops costing alarms and becomes a reported fact instead —
3845
- * parked, logged at `error` with its id and target, and kept for
3846
- * {@link SCHEDULE_OUTBOX_RETENTION_MS} so an operator can see what was
3847
- * promised and never enqueued. The queue is bounded on both sides: the
3848
- * ceiling stops live entries accumulating, the retention sweep stops parked
3849
- * ones doing so. The sweep rides whatever tick reaches this tier, so a shard
3883
+ * The default bound is {@link SCHEDULE_OUTBOX_MAX_ATTEMPTS}: a job the
3884
+ * scheduler will never accept stops costing alarms and becomes a reported
3885
+ * fact instead — parked, logged at `error` with its id and target, and kept
3886
+ * for {@link SCHEDULE_OUTBOX_RETENTION_MS} so an operator can see what was
3887
+ * promised and never enqueued. A call made with `retry.forever` opts out of
3888
+ * that ceiling: it stays live, paced by the ladder's last rung, until the
3889
+ * scheduler accepts it or refuses it as invalid. The retention sweep only
3890
+ * ever drops parked rows. The sweep rides whatever tick reaches this tier, so a shard
3850
3891
  * holding ONLY parked entries keeps them until something else wakes it —
3851
3892
  * which is the right trade: they are one row per genuinely lost job, not a
3852
3893
  * loop that grows on its own.
@@ -4201,7 +4242,7 @@ declare abstract class ShardDO {
4201
4242
  * for the same reason — an ambient field says "a dispatch is in flight", not
4202
4243
  * "this caller is that dispatch".
4203
4244
  */
4204
- protected transactionHeadroom(): TransactionHeadroomTracker;
4245
+ protected transactionHeadroom(functionPath?: string): TransactionHeadroomTracker;
4205
4246
  /**
4206
4247
  * A fresh budget for one deferred subscription re-run.
4207
4248
  *
@@ -4218,19 +4259,27 @@ declare abstract class ShardDO {
4218
4259
  * background: a concurrent `/rpc` dispatch building its `ctx.db` during the
4219
4260
  * drain would take the refresh branch and lose its own ceiling entirely.
4220
4261
  */
4221
- protected subscriptionHeadroom(): TransactionHeadroomTracker;
4262
+ protected subscriptionHeadroom(functionPath: string, identity?: SubscriptionIdentity): TransactionHeadroomTracker;
4263
+ /**
4264
+ * A stream's budget, held for its whole life. Rows stay capped over the life,
4265
+ * as before; bytes are capped per frame by {@link ShardDO.windowStreamReads}.
4266
+ */
4267
+ protected streamHeadroom(functionPath: string, identity?: SubscriptionIdentity): TransactionHeadroomTracker;
4268
+ /** Pass `frames` through, opening a fresh read-byte window after each one. */
4269
+ protected windowStreamReads(headroom: TransactionHeadroomTracker, frames: AsyncIterable<unknown>): AsyncIterable<unknown>;
4222
4270
  /**
4223
4271
  * A fresh budget for one alarm-driven work item — one external-source
4224
- * table's tick, or one TTL sweep pass.
4272
+ * table's tick.
4225
4273
  *
4226
4274
  * Alarm work runs with no client waiting and no `/rpc` dispatch in flight,
4227
4275
  * so `transactionHeadroom()`'s per-dispatch tracker is `undefined` there —
4228
- * leaving external-source ingest and TTL sweeps completely unmetered, the
4229
- * exact isolate-exhaustion class the meter exists to bound. Handed to the
4276
+ * leaving external-source ingest completely unmetered, the exact
4277
+ * isolate-exhaustion class the meter exists to bound. Handed to the
4230
4278
  * writer BY VALUE, the same pattern as `subscriptionHeadroom()` and for the
4231
4279
  * same reason: an ambient instance-field flag would race a concurrently
4232
4280
  * in-flight `/rpc` dispatch, or a sibling alarm work item, clearing or
4233
- * substituting the wrong tracker mid-flight.
4281
+ * substituting the wrong tracker mid-flight. A TTL sweep builds its own
4282
+ * tracker instead, without the near-limit warning (see `pollTtlSweeps`).
4234
4283
  */
4235
4284
  protected alarmHeadroom(): TransactionHeadroomTracker;
4236
4285
  /**
@@ -4266,7 +4315,10 @@ declare abstract class ShardDO {
4266
4315
  * Unlike request-log args, `ctx.log` args are NOT redacted: the developer
4267
4316
  * chose to log them, exactly like a raw `console.log`.
4268
4317
  */
4269
- protected recordUserLog(functionPath: string, level: ContextLogLevel, args: unknown[], message: string, fields: Record<string, unknown> | undefined, sink?: TelemetrySink, eventName?: string, anchor?: TraceAnchor, error?: ErrorDetail | undefined): void;
4318
+ protected recordUserLog(functionPath: string, level: ContextLogLevel, args: unknown[], message: string, fields: Record<string, unknown> | undefined, sink?: TelemetrySink, eventName?: string, anchor?: TraceAnchor, error?: ErrorDetail | undefined, pinned?: {
4319
+ trace: TraceAnchor | undefined;
4320
+ userId: string | undefined;
4321
+ }): void;
4270
4322
  /**
4271
4323
  * Build the `ctx.log` logger for one dispatched function. Each severity method
4272
4324
  * accepts either the structured form (`(message, fields)`) or console-style
@@ -4328,6 +4380,14 @@ declare abstract class ShardDO {
4328
4380
  * span through the root-span mirroring in `recordDispatchRootSpan`.
4329
4381
  */
4330
4382
  protected instrumentSql<T extends SqlClientLike>(client: T, functionPath: string, anchor: TraceAnchor, sink?: TelemetrySink, scope?: SensitiveScope): T;
4383
+ /**
4384
+ * Count the I/O an action starts through `ctx`. The returned function, called
4385
+ * once the handler has returned, restores `ctx` and logs one `warn` line
4386
+ * naming every call still in flight. On Workers that work can be cancelled
4387
+ * silently after the response; the line is how a developer finds out before
4388
+ * production does. Nothing is awaited on the handler's behalf.
4389
+ */
4390
+ protected watchActionWork(functionPath: string, context: unknown): () => void;
4331
4391
  /**
4332
4392
  * Build `ctx.fetch` — the platform `fetch`, instrumented.
4333
4393
  *
@@ -5097,6 +5157,42 @@ declare abstract class ShardDO {
5097
5157
  * already mutate the shard, so a token-gated capture insert adds no privilege.
5098
5158
  */
5099
5159
  private handleRecordQueueMessage;
5160
+ /**
5161
+ * Serve `dropOutboxEntry` — cancel a deferred schedule the scheduler never
5162
+ * confirmed, live or parked. `ctx.scheduler.cancel` only reaches jobs the
5163
+ * SchedulerDO holds, so this is the only way to stop a `retry.forever` entry
5164
+ * that is still waiting.
5165
+ *
5166
+ * The shard cannot always tell that the scheduler never got the job: the accept
5167
+ * may have been lost on the way back, or an attempt may be awaiting it right now.
5168
+ * So the drop cancels the id at the scheduler FIRST and deletes the row only once
5169
+ * that settled. A cancel that fails (the scheduler is often the very thing that is down)
5170
+ * parks the entry so it can never be handed over, and the error goes to the operator;
5171
+ * dropping again completes it. And an attempt that was already in the air takes the job back out
5172
+ * when it lands, see {@link ShardDO.retryScheduleOutboxEntry}. Admin-gated by the caller.
5173
+ */
5174
+ private handleDropOutboxEntry;
5175
+ /**
5176
+ * Audit a drop that applied. "Not found" is the usual answer for a job the scheduler never
5177
+ * accepted, and the same answer it gives once an accepted job has run: an earlier hand-off whose
5178
+ * accept was lost on the way back. The drop cannot tell the two apart, so the operator is told the
5179
+ * job may have run.
5180
+ */
5181
+ private auditAppliedScheduleOutboxDrop;
5182
+ /**
5183
+ * With no scheduler to ask, waiting never confirms the cancel. The first drop parked the row (a
5184
+ * job may have been accepted under a binding that has since gone); dropping a row that was already
5185
+ * parked, with nothing in flight, is the operator accepting that, and removes it.
5186
+ * @returns whether the row was removed
5187
+ */
5188
+ private removeUnconfirmableScheduleOutboxDrop;
5189
+ /**
5190
+ * Serve `retryOutboxEntry` — put an entry back on the retry ladder, due now:
5191
+ * the way back for a parked entry, and a way to skip a long backoff once the
5192
+ * scheduler is healthy. Arms the poll alarm for now, because nothing else is
5193
+ * due to wake a shard whose entries were all parked. Admin-gated by the caller.
5194
+ */
5195
+ private handleRetryOutboxEntry;
5100
5196
  /** Empty the dev queue consumed-message log (studio "clear log" action). Admin-gated by the caller. */
5101
5197
  private handleClearQueueMessages;
5102
5198
  /**
@@ -6097,14 +6193,55 @@ declare abstract class ShardDO {
6097
6193
  private recordScheduleRateDeferral;
6098
6194
  /**
6099
6195
  * One outbox attempt: replay the stored call, then either end custody or push
6100
- * the entry out along {@link SCHEDULE_OUTBOX_BACKOFF_MS} — parking it once the
6101
- * ladder runs out.
6196
+ * the entry out along {@link SCHEDULE_OUTBOX_BACKOFF_MS}. The default policy
6197
+ * parks once the ladder runs out; `retry.forever` keeps a valid call live.
6102
6198
  *
6103
6199
  * An envelope that will not parse is parked immediately rather than retried:
6104
6200
  * no number of attempts turns malformed JSON into a job, and the log line is
6105
6201
  * the only useful output left.
6106
6202
  */
6107
6203
  private retryScheduleOutboxEntry;
6204
+ /**
6205
+ * The post-commit hand-off of a deferred schedule, run as a recorded attempt like every retry:
6206
+ * a drop that arrives while the call awaits the scheduler is seen here and the job is cancelled
6207
+ * when it lands (the row stays parked if that cancel fails). A failure leaves the row for the
6208
+ * retry loop, unless a drop already ended the entry, in which case the row goes.
6209
+ */
6210
+ private runScheduleOutboxHandOff;
6211
+ private handOffRecordedScheduleOutboxCall;
6212
+ private markScheduleOutboxDropped;
6213
+ private isScheduleOutboxBeingDropped;
6214
+ /** One recorded call is done with: handed off, skipped, or rolled back with its window. */
6215
+ private finishScheduleOutboxHandOff;
6216
+ /**
6217
+ * Forget the drop marker of `id` once nothing it could still decide is left: no recorded call
6218
+ * waiting for its hand-off, no attempt awaiting the scheduler, no drop in flight. Pruned by that
6219
+ * condition rather than by count, because evicting a marker early would let a queued call of a
6220
+ * dropped job go out.
6221
+ */
6222
+ private pruneScheduleOutboxDropMarker;
6223
+ /** Whether a drop covers the recording `token` names: recorded no later than the row it acted on. */
6224
+ private isScheduleOutboxTokenDropped;
6225
+ /** Whether the entry this attempt was made for has been dropped, now or while it was in the air. */
6226
+ private wasScheduleOutboxDropped;
6227
+ private releaseScheduleOutboxAttempt;
6228
+ /** A hand-off that threw: end custody if the scheduler turns out to hold the job, else defer or park the entry. */
6229
+ private settleFailedScheduleOutboxAttempt;
6230
+ /**
6231
+ * The scheduler holds the job: end custody. If the entry was dropped while the
6232
+ * hand-off was awaiting (or a drop is cancelling it right now), the operator asked
6233
+ * for the job NOT to run, so take it back out of the scheduler. `landed` says the scheduler
6234
+ * is known to hold (or to have held) the job, which is what makes a "not found" cancel a failure.
6235
+ */
6236
+ private settleScheduleOutboxHandOff;
6237
+ /** Park `id` if it is still live, keeping its attempt count; a parked or absent row is left as it is. */
6238
+ private parkLiveScheduleOutboxEntry;
6239
+ /**
6240
+ * Push one entry out along the ladder. A `retry.forever` entry that reaches
6241
+ * the attempts a default entry would have parked at says so once, at `warn`:
6242
+ * past that point nothing else reports that the job is still not enqueued.
6243
+ */
6244
+ private deferScheduleOutboxEntry;
6108
6245
  /** Park one entry and say so at `error` — a job was promised to a caller and will not be enqueued. */
6109
6246
  private parkScheduleOutboxEntry;
6110
6247
  /**
@@ -6235,6 +6372,26 @@ declare abstract class ShardDO {
6235
6372
  * @returns The response to return, or `undefined` to continue into dispatch.
6236
6373
  */
6237
6374
  private preDispatchAnswer;
6375
+ /**
6376
+ * Record how late a scheduled job started: `scheduler.lag_ms` is the gap
6377
+ * between its due time and this dispatch. A queue that cannot keep up shows
6378
+ * as a climbing lag long before jobs fail, and nothing else measures it.
6379
+ * Only a system dispatch may carry the due time; a client-sent header is
6380
+ * ignored rather than trusted to write the operator's metrics.
6381
+ */
6382
+ private recordSchedulerLag;
6383
+ /**
6384
+ * A fresh budget that reports crossing 80% of any ceiling as a `warn` line.
6385
+ * Local data is usually a fraction of production's, so the transaction that
6386
+ * fails after deploy is the one that only ever got close here — the line is
6387
+ * how a developer sees it coming. `functionPath` names the work; callers
6388
+ * without one pass the kind of work instead.
6389
+ *
6390
+ * The warning fires mid-handler, after awaits an interleaved dispatch can
6391
+ * use to re-set the shared trace and user, so both are pinned here. A `trace` of `undefined` files the line under no trace rather than
6392
+ * borrowing an unrelated one.
6393
+ */
6394
+ private mintHeadroom;
6238
6395
  /**
6239
6396
  * Stamp everything one RPC dispatch needs off its request, and reset every
6240
6397
  * per-request capture the handler will fill.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{installDeliveryFence as a}from"./packem_shared/installDeliveryFence-B6M9KOnb.mjs";import{MERGED_ROLES as o,mergeDurableObjects as c,roleNamespace as S}from"./packem_shared/MERGED_ROLES-C4RToZ16.mjs";import{serveRelationFanout as i}from"./packem_shared/serveRelationFanout-DcSjzAZv.mjs";import{SESSION_DO_TTL_DEFAULT as n,SessionDO as d}from"./packem_shared/SESSION_DO_TTL_DEFAULT-DSvTwRjc.mjs";import{ROOT_DO_SIZE_WARN_BYTES as p,ROOT_SHARD_NAME as m,ShardDO as h}from"./packem_shared/ROOT_DO_SIZE_WARN_BYTES-467RfpXt.mjs";import{SHARD_REGISTRY_DO_NAME as E,ShardRegistryDO as O,hostedShardRegistry as _}from"./packem_shared/SHARD_REGISTRY_DO_NAME-YZZk79QR.mjs";import{createStableIdFactory as u,createStableRandomFactory as b}from"./packem_shared/createStableIdFactory-DPDT_chw.mjs";import{createShardAlarms as T,createShardDirectory as I,createShardHost as g,createShardKvStore as y,createShardPlatform as A,createSocketHost as M,createWorkerPlatform as N}from"@lunora/platform-cloudflare";import{REPROJECTION_MIGRATION_PREFIX as F,UNVOUCHABLE_DEP as L,applyCdcChanges as C,assertShapeShardable as H,backfillSearchIndexes as P,backfillVectorIndexes as j,buildReprojectionMigration as v,clearMemoryTables as U,countLegacyRows as w,createReadFootprint as G,createShardCtxDb as B,exportShardRows as V,importShardRows as W,isSourceDue as Y,markUnvouchableReads as J,pullExternalSourceIncrementalTick as K,pullExternalSourceTick as X,reprojectionMigrationId as Z,reprojectionTables as q,runDataMigration as z,runShardMigrations as Q,subscriptionListDeltas as $}from"@lunora/shard-engine";export{o as MERGED_ROLES,F as REPROJECTION_MIGRATION_PREFIX,p as ROOT_DO_SIZE_WARN_BYTES,m as ROOT_SHARD_NAME,n as SESSION_DO_TTL_DEFAULT,E as SHARD_REGISTRY_DO_NAME,d as SessionDO,h as ShardDO,O as ShardRegistryDO,L as UNVOUCHABLE_DEP,C as applyCdcChanges,H as assertShapeShardable,P as backfillSearchIndexes,j as backfillVectorIndexes,v as buildReprojectionMigration,U as clearMemoryTables,w as countLegacyRows,G as createReadFootprint,T as createShardAlarms,B as createShardCtxDb,I as createShardDirectory,g as createShardHost,y as createShardKvStore,A as createShardPlatform,M as createSocketHost,u as createStableIdFactory,b as createStableRandomFactory,N as createWorkerPlatform,V as exportShardRows,_ as hostedShardRegistry,W as importShardRows,a as installDeliveryFence,Y as isSourceDue,J as markUnvouchableReads,c as mergeDurableObjects,K as pullExternalSourceIncrementalTick,X as pullExternalSourceTick,Z as reprojectionMigrationId,q as reprojectionTables,S as roleNamespace,z as runDataMigration,Q as runShardMigrations,i as serveRelationFanout,$ as subscriptionListDeltas};
1
+ import{installDeliveryFence as a}from"./packem_shared/installDeliveryFence-B6M9KOnb.mjs";import{MERGED_ROLES as o,mergeDurableObjects as c,roleNamespace as S}from"./packem_shared/MERGED_ROLES-C4RToZ16.mjs";import{serveRelationFanout as i}from"./packem_shared/serveRelationFanout-DcSjzAZv.mjs";import{SESSION_DO_TTL_DEFAULT as n,SessionDO as d}from"./packem_shared/SESSION_DO_TTL_DEFAULT-DSvTwRjc.mjs";import{ROOT_DO_SIZE_WARN_BYTES as p,ROOT_SHARD_NAME as m,ShardDO as h}from"./packem_shared/ROOT_DO_SIZE_WARN_BYTES-D5nWTd3i.mjs";import{SHARD_REGISTRY_DO_NAME as E,ShardRegistryDO as O,hostedShardRegistry as _}from"./packem_shared/SHARD_REGISTRY_DO_NAME-YZZk79QR.mjs";import{createStableIdFactory as u,createStableRandomFactory as b}from"./packem_shared/createStableIdFactory-DPDT_chw.mjs";import{createShardAlarms as T,createShardDirectory as I,createShardHost as g,createShardKvStore as y,createShardPlatform as A,createSocketHost as M,createWorkerPlatform as N}from"@lunora/platform-cloudflare";import{REPROJECTION_MIGRATION_PREFIX as F,UNVOUCHABLE_DEP as L,applyCdcChanges as C,assertShapeShardable as H,backfillSearchIndexes as P,backfillVectorIndexes as j,buildReprojectionMigration as v,clearMemoryTables as U,countLegacyRows as w,createReadFootprint as G,createShardCtxDb as B,exportShardRows as V,importShardRows as W,isSourceDue as Y,markUnvouchableReads as J,pullExternalSourceIncrementalTick as K,pullExternalSourceTick as X,reprojectionMigrationId as Z,reprojectionTables as q,runDataMigration as z,runShardMigrations as Q,subscriptionListDeltas as $}from"@lunora/shard-engine";export{o as MERGED_ROLES,F as REPROJECTION_MIGRATION_PREFIX,p as ROOT_DO_SIZE_WARN_BYTES,m as ROOT_SHARD_NAME,n as SESSION_DO_TTL_DEFAULT,E as SHARD_REGISTRY_DO_NAME,d as SessionDO,h as ShardDO,O as ShardRegistryDO,L as UNVOUCHABLE_DEP,C as applyCdcChanges,H as assertShapeShardable,P as backfillSearchIndexes,j as backfillVectorIndexes,v as buildReprojectionMigration,U as clearMemoryTables,w as countLegacyRows,G as createReadFootprint,T as createShardAlarms,B as createShardCtxDb,I as createShardDirectory,g as createShardHost,y as createShardKvStore,A as createShardPlatform,M as createSocketHost,u as createStableIdFactory,b as createStableRandomFactory,N as createWorkerPlatform,V as exportShardRows,_ as hostedShardRegistry,W as importShardRows,a as installDeliveryFence,Y as isSourceDue,J as markUnvouchableReads,c as mergeDurableObjects,K as pullExternalSourceIncrementalTick,X as pullExternalSourceTick,Z as reprojectionMigrationId,q as reprojectionTables,S as roleNamespace,z as runDataMigration,Q as runShardMigrations,i as serveRelationFanout,$ as subscriptionListDeltas};