@pgxsinkit/client 0.2.5 → 0.2.6

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/src/index.ts CHANGED
@@ -38,6 +38,17 @@ import { type BootReport, type BootReportBuilder, createBootReportBuilder } from
38
38
  import { type ConvergenceDriver, type ConvergenceTrigger, createConvergenceDriver } from "./convergence";
39
39
  import { syncDebug, timeAsync } from "./debug";
40
40
  import { describeErrorChain } from "./error-chain";
41
+ import {
42
+ createEventFlushDriver,
43
+ createEventLaneRuntime,
44
+ deriveBatchEventUrl,
45
+ type EventAppendResult,
46
+ type EventFlushDriver,
47
+ type EventLaneOptions,
48
+ type EventLaneReport,
49
+ type EventLaneRuntime,
50
+ type OutboxStatus,
51
+ } from "./event-lane";
41
52
  import { type DataExportOptions, type DataExportResult, performDataExport } from "./export-data";
42
53
  import { type DiagnosticExportOptions, type DiagnosticExportResult, performDiagnosticExport } from "./export-dump";
43
54
  import { performStoreExport, type StoreExportOptions, type StoreExportResult } from "./export-store";
@@ -152,6 +163,39 @@ export {
152
163
  type StoreExportResult,
153
164
  } from "./export-store";
154
165
  export { createLifecycleSlot, LifecycleBusyError, type LifecycleSlot } from "./lifecycle-slot";
166
+ // The Event lane's client half (ADR-0053). The runtime/driver factories are exported alongside the types
167
+ // because the lane is composable the same way the mutation runtime is (the harness and tests drive them
168
+ // directly); app code reaches it through `client.appendEvent` / `onOutboxStatus` / `onEventLaneReport`.
169
+ export {
170
+ classifyEventBatchFailure,
171
+ computeEventBackoffMs,
172
+ createEventFlushDriver,
173
+ createEventLaneRuntime,
174
+ DEFAULT_EVENT_BACKOFF_BASE_MS,
175
+ DEFAULT_EVENT_BACKOFF_CEILING_MS,
176
+ DEFAULT_EVENT_BATCH_SIZE,
177
+ DEFAULT_EVENT_FLUSH_INTERVAL_MS,
178
+ deriveBatchEventUrl,
179
+ type EventAppendResult,
180
+ type EventBackoffOptions,
181
+ type EventFlushDriver,
182
+ type EventFlushDriverOptions,
183
+ type EventFlushGate,
184
+ type EventLaneBackoffTransition,
185
+ type EventLaneDb,
186
+ type EventLaneOptions,
187
+ type EventLaneReport,
188
+ type EventLaneRuntime,
189
+ type EventLaneVerdict,
190
+ EventPayloadInvalidError,
191
+ EventPayloadTooLargeError,
192
+ type EventStreamFlushOptions,
193
+ EventStreamsNotRegisteredError,
194
+ type OutboxStatus,
195
+ parseRetryAfterMs,
196
+ resolveBatchEventUrl,
197
+ UnknownEventStreamError,
198
+ } from "./event-lane";
155
199
  export {
156
200
  destroyStoreArtifacts,
157
201
  type ElectedEngineWorker,
@@ -254,17 +298,22 @@ export {
254
298
  type LazyGuardIndex,
255
299
  LazyRelationNotActivatedError,
256
300
  } from "./lazy-guard";
301
+ // The Outbox's object NAMES are public contract like its shape (ADR-0053 decision 2) — inspection
302
+ // surfaces (the board's schema map, debug tooling) need them without re-deriving DDL internals.
303
+ export { OUTBOX_SEQUENCE, OUTBOX_TABLE } from "./schema";
257
304
  export {
258
305
  type AllMutationsView,
259
306
  getAllMutationsView,
260
307
  getJournalTable,
261
308
  getLocalMetaTable,
309
+ getOutboxTable,
262
310
  getOverlayTable,
263
311
  getReadModelView,
264
312
  getSyncedLocalTable,
265
313
  getSyncStateView,
266
314
  type JournalTable,
267
315
  type LocalMetaTable,
316
+ type OutboxTable,
268
317
  type OverlayTable,
269
318
  type ReadModelView,
270
319
  type SyncStateView,
@@ -1065,6 +1114,21 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
1065
1114
  autoSync?: ConvergenceTrigger;
1066
1115
  /** Invoked after each automatic convergence pass with its error, or `null` on success (only when `autoSync` is set). */
1067
1116
  onConvergencePass?: (error: unknown) => void;
1117
+ /**
1118
+ * The **Event lane**'s ingestion endpoint (ADR-0053 decision 3) — `"/api/events"`, or an absolute
1119
+ * deployment URL ending in it, under the same hard-required-path rule as {@link batchWriteUrl}. Omit it and
1120
+ * the client DERIVES it from `batchWriteUrl` (`…/api/mutations` → `…/api/events`), which is correct for the
1121
+ * ordinary deployment where one `createSyncServer` mounts both; set it explicitly when the two endpoints
1122
+ * are not siblings.
1123
+ */
1124
+ batchEventUrl?: string;
1125
+ /**
1126
+ * The Event lane's client-level flush policy (ADR-0053): batch caps, the fallback interval, backoff
1127
+ * tuning, and per-Event-stream overrides. NEVER on the registry — the registry is the contract, cadence is
1128
+ * deployment tuning, and a batch-size tweak must not surface as a registry diff. Client batching is
1129
+ * additionally clamped by the contracts-level request-shape limits the server enforces independently.
1130
+ */
1131
+ events?: EventLaneOptions;
1068
1132
  /**
1069
1133
  * Invoked when a read-path sync commit fails after exhausting its retries (ADR-0009 decision 5).
1070
1134
  * The runtime enters the `degraded` phase and holds the read cache at the last applied commit
@@ -1335,23 +1399,86 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
1335
1399
  haltActivity: () => void;
1336
1400
  stop: () => Promise<void>;
1337
1401
  /**
1338
- * Wipe the entire local store (synced cache + overlay + journal) and close the handle
1339
- * (ADR-0005). Refuses if mutations are still owed to the server unless `force` is set, so
1340
- * it never silently drops un-flushed writes. Distinct from `stop()`, which only halts sync.
1402
+ * Wipe the entire local store (synced cache + overlay + journal + Outbox) and close the handle
1403
+ * (ADR-0005). Refuses if mutations are still owed to the server — OR if the Outbox still holds staged
1404
+ * events (ADR-0053 decision 8: the same "never discard without a server verdict" rule the owed-mutations
1405
+ * refusal upholds) — unless `force` is set, so it never silently drops un-flushed writes or un-delivered
1406
+ * events. The refusal names which of the two blocked it. Distinct from `stop()`, which only halts sync.
1341
1407
  * Runs under the single lifecycle slot (ADR-0035 decision 4): a concurrent export — or another
1342
1408
  * `destroy`/`discardEphemeral`/`dropReadCache` — rejects with a {@link LifecycleBusyError} rather
1343
1409
  * than interleaving the wipe with a running export.
1344
1410
  */
1345
1411
  destroy: (options?: { force?: boolean }) => Promise<void>;
1346
1412
  /**
1347
- * Drop and rebuild the reconstructible synced read cache, preserving the overlay and
1348
- * mutation journal (ADR-0006). The next sync refills it. Use to recover from a corrupt or
1413
+ * Drop and rebuild the reconstructible synced read cache, preserving the overlay, the
1414
+ * mutation journal, and the Outbox (ADR-0006; ADR-0053 decision 8 — the Outbox is not read cache, so this
1415
+ * never touches it). The next sync refills it. Use to recover from a corrupt or
1349
1416
  * stale read cache without losing un-flushed writes. Runs under the single lifecycle slot
1350
1417
  * (ADR-0035 decision 4) — it drops and rebuilds the synced tables, so an export must not capture a
1351
1418
  * half-rebuilt cache; a concurrent export (or `destroy`/`discardEphemeral`) rejects with a
1352
1419
  * {@link LifecycleBusyError}.
1353
1420
  */
1354
1421
  dropReadCache: () => Promise<void>;
1422
+ /**
1423
+ * Append one client event to the **Outbox** (ADR-0053 decision 2) — the Event lane's entry point, and the
1424
+ * only way an app produces an event. Fire-and-forget by design: nothing echoes back, nothing is overlaid,
1425
+ * nothing converges. The promise resolves on DURABLE local enqueue under the store's declared durability,
1426
+ * NOT on delivery; the flush loop drains the Outbox in the background (and after reconnect/boot), and the
1427
+ * server's per-event verdicts surface on {@link onEventLaneReport}.
1428
+ *
1429
+ * Four refusals, all synchronous call-site failures rather than runtime conditions — the invariant
1430
+ * "everything in the Outbox is well-formed" is what the flush loop and any best-guess view lean on:
1431
+ *
1432
+ * - no Event stream registered at all → {@link EventStreamsNotRegisteredError};
1433
+ * - an unregistered Event-stream name → {@link UnknownEventStreamError};
1434
+ * - a payload failing the stream's registered zod schema → {@link EventPayloadInvalidError};
1435
+ * - a serialized payload over the contracts-level per-event cap → {@link EventPayloadTooLargeError}.
1436
+ *
1437
+ * The library stamps `eventId` (uuid — the server's dedupe key, which is what makes at-least-once delivery
1438
+ * idempotent end-to-end) and `occurredAtUs`, and returns both plus the local append ordinal.
1439
+ *
1440
+ * `stream`/`payload` are typed as `string`/`unknown`: a registry's Event streams ride a symbol and are
1441
+ * type-erased by `defineSyncRegistry`'s return type, so the REGISTERED ZOD SCHEMA is the enforced contract
1442
+ * (at append, and again at ingest for non-library callers).
1443
+ */
1444
+ appendEvent: (stream: string, payload: unknown) => Promise<EventAppendResult>;
1445
+ /**
1446
+ * Drain the Outbox now — the Event lane's manual primitive, the twin of {@link flush}. Assembles batches
1447
+ * in append (`seq`) order across every Event stream, POSTs them, and applies the per-event verdicts, until
1448
+ * nothing more is eligible this pass. A no-op while the lane is in batch-level backoff, and a no-op for a
1449
+ * registry with no Event streams. With `autoSync` installed the lane drives itself (appends nudge a pass,
1450
+ * an interval is the fallback, and boot/reconnect drain what was written offline); this is the escape
1451
+ * hatch for a fully-manual host.
1452
+ */
1453
+ flushEvents: () => Promise<void>;
1454
+ /**
1455
+ * The **drain signal** (ADR-0053 decision 2): subscribe to the Outbox's empty ↔ non-empty transitions, with
1456
+ * the CURRENT state delivered on subscribe. Returns an unsubscribe.
1457
+ *
1458
+ * The invalidation hook for a best-guess view that composes pending events with down-synced aggregates:
1459
+ * when the Outbox drains, the aggregate is authoritative again. Deliberately carries no count — a count
1460
+ * that updates only on transitions is stale by construction, and one that updates per append is a worse
1461
+ * live query; for richer detail, query the Outbox table (`getOutboxTable(registry)`).
1462
+ */
1463
+ onOutboxStatus: (listener: (status: OutboxStatus) => void) => () => void;
1464
+ /**
1465
+ * The drain signal as a one-shot READ — the pull twin of {@link onOutboxStatus}'s push (the
1466
+ * {@link bootReport} pattern). Reads the store, so it is always current: a tab attaching long after the
1467
+ * engine's last transition folds its initial state from here rather than waiting for the next one.
1468
+ */
1469
+ outboxStatus: () => Promise<OutboxStatus>;
1470
+ /**
1471
+ * The Event lane's verdict/report surface (ADR-0053 decision 2): per flush pass, the TERMINAL non-`acked`
1472
+ * verdicts (`refused` — the server's gating hook said no; `rejected` — a schema-invalid or oversized
1473
+ * payload for a KNOWN stream), the `deferred` ones (an Event stream the server does not yet know — ordinary
1474
+ * rollout skew; the rows stay and retry), and the batch-level backoff transitions. `acked` is not reported:
1475
+ * a high-volume append-only lane would drown the app in its own success.
1476
+ *
1477
+ * An EPHEMERAL subscription, deliberately — a durable client-side verdict table would be retention-bearing
1478
+ * state for a debugging need. With nothing subscribed the library logs each report at warn level rather
1479
+ * than dropping it, because once a terminal row is deleted the Outbox cannot answer what happened to it.
1480
+ */
1481
+ onEventLaneReport: (listener: (report: EventLaneReport) => void) => () => void;
1355
1482
  flush: (table?: SyncTableName<TRegistry>) => Promise<void>;
1356
1483
  reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;
1357
1484
  retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;
@@ -1391,7 +1518,16 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
1391
1518
  table: TKey,
1392
1519
  entityKey: Record<string, string>,
1393
1520
  ) => Promise<void>;
1394
- diagnostics: (table?: SyncTableName<TRegistry>) => Promise<{ mutation: MutationDiagnostics }>;
1521
+ /**
1522
+ * The store's owed-state diagnostics: the mutation journal's per-status counts, plus — when this client has
1523
+ * an Event lane — the Outbox's drain signal (ADR-0053 decision 8: the Event lane's durable state takes a
1524
+ * position on every lifecycle surface). `outbox` is the boolean signal rather than a count, for the reason
1525
+ * {@link onOutboxStatus} carries none; it is absent on a client with no lane.
1526
+ */
1527
+ diagnostics: (table?: SyncTableName<TRegistry>) => Promise<{
1528
+ mutation: MutationDiagnostics;
1529
+ outbox?: OutboxStatus;
1530
+ }>;
1395
1531
  /**
1396
1532
  * The registry-wide reactive mutation-status surface: a global per-status summary and a
1397
1533
  * filtered normalized detail list over EVERY writable journal, each available one-shot or as a live
@@ -2286,6 +2422,35 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2286
2422
  ...(options.onReject ? { onReject: options.onReject } : {}),
2287
2423
  });
2288
2424
 
2425
+ // The Event lane (ADR-0053). Constructed on EVERY boot, registry streams or not: the Outbox DDL is
2426
+ // stream-independent and the runtime is inert without streams (`appendEvent` throws, `flushEvents` no-ops,
2427
+ // no driver is stood up), so there is no conditional to get wrong when a registry gains its first stream.
2428
+ // The ingestion endpoint is the mutation endpoint's sibling — derived from `batchWriteUrl` unless the
2429
+ // consumer names it — and it shares the write path's headers (same ingress, same gateway credentials).
2430
+ // A caller-owned PGlite (`pgliteInstance`) never had the toolkit's schema applied, so the Outbox table may
2431
+ // not exist: the lane stays unconstructed there, exactly as the meta-table marker is left alone.
2432
+ const eventLaneUrl = options.batchEventUrl ?? deriveBatchEventUrl(options.batchWriteUrl);
2433
+ const eventLane: EventLaneRuntime | null =
2434
+ eventLaneUrl != null && !options.pgliteInstance
2435
+ ? createEventLaneRuntime({
2436
+ db: pglite,
2437
+ registry: options.registry,
2438
+ batchEventUrl: eventLaneUrl,
2439
+ ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
2440
+ ...(writePathHeaders ? { requestHeaders: writePathHeaders } : {}),
2441
+ ...(options.events ? { events: options.events } : {}),
2442
+ })
2443
+ : null;
2444
+ /** The refusal a lane-less client gives, naming the two ways a lane can be absent. */
2445
+ const requireEventLane = (): EventLaneRuntime => {
2446
+ if (eventLane) return eventLane;
2447
+ throw new Error(
2448
+ "pgxsinkit: the Event lane is not available on this client — either `batchWriteUrl` is not the canonical " +
2449
+ '"…/api/mutations" shape (pass `batchEventUrl` explicitly), or this client adopted a caller-owned ' +
2450
+ "`pgliteInstance` (whose store pgxsinkit never provisioned, so it has no Outbox).",
2451
+ );
2452
+ };
2453
+
2289
2454
  // Activation buffer (ADR-0041): a read (`ensureSynced`) OR a write (`onOrdinaryEnqueue`) can reference a
2290
2455
  // lazy group after `localReadReady` but BEFORE `sync` is wired (the Option B window). With a null `sync` the
2291
2456
  // seams cannot start a group, so BOTH feed this one buffer; the tail replays it once sync is wired, so the
@@ -2351,6 +2516,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2351
2516
 
2352
2517
  let sync: Awaited<ReturnType<typeof startConfiguredSync>> | null = null;
2353
2518
  let convergenceDriver: ConvergenceDriver | null = null;
2519
+ let eventFlushDriver: EventFlushDriver | null = null;
2354
2520
 
2355
2521
  // Lifecycle guard (ADR-0041): `stop()`/`destroy()` can now be called while the background write/sync tail is
2356
2522
  // still in flight (React StrictMode mount/unmount is the canonical case). `disposed` lets the tail bail at
@@ -2407,8 +2573,12 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2407
2573
  disposed = true;
2408
2574
  clearReadSilenceWatchdog();
2409
2575
  mutationRuntime.abortInFlight();
2576
+ // The Event lane's in-flight POST is aborted on the same synchronous edge as the write path's: a flush
2577
+ // must not still be settling verdicts into a store the teardown is about to close.
2578
+ eventLane?.abortInFlight();
2410
2579
  void engine.close();
2411
2580
  void convergenceDriver?.stop();
2581
+ void eventFlushDriver?.stop();
2412
2582
  };
2413
2583
 
2414
2584
  // The write/sync activation tail (ADR-0041 decision 3). On a NORMAL boot this runs in the BACKGROUND after
@@ -2530,6 +2700,30 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2530
2700
  );
2531
2701
  }
2532
2702
 
2703
+ // The Event-lane flush driver (ADR-0053 decision 3), standing on the SAME scheduling seam as convergence:
2704
+ // one `autoSync` trigger answers both "is the app online/foregrounded?" (the offline pause) and "something
2705
+ // changed, try now" (online/visibility signals). It keeps its own, slower interval — an append nudges a
2706
+ // pass, so the interval only has to catch retries and recovery — and `start()` runs a pass immediately,
2707
+ // which is what drains events written offline after a boot or reconnect with no new append.
2708
+ //
2709
+ // Gated exactly like convergence on a restore boot that stays OFFLINE, for the mirrored reason: recovered
2710
+ // Outbox rows are NOT quarantined (ADR-0053 decision 8), but a store whose recovered JOURNAL is parked is
2711
+ // being held for human inspection, and starting network activity under it would contradict that.
2712
+ if (eventLane?.hasStreams && options.autoSync && (!restoreBoot || syncEnabled)) {
2713
+ const autoSync = options.autoSync;
2714
+ eventFlushDriver = createEventFlushDriver({
2715
+ flush: () => eventLane.flush(),
2716
+ gate: { subscribe: autoSync.subscribe, shouldFlush: () => autoSync.shouldConverge() },
2717
+ ...(options.events?.intervalMs != null ? { intervalMs: options.events.intervalMs } : {}),
2718
+ });
2719
+ // Start once initial sync is ready, mirroring convergence: the first pass never races the first shape
2720
+ // load, and a rejected `ready` (a failed background tail) leaves the driver un-started.
2721
+ void ready.then(
2722
+ () => eventFlushDriver?.start(),
2723
+ () => undefined,
2724
+ );
2725
+ }
2726
+
2533
2727
  // Event-driven convergence: the moment a mutation is enqueued, ask the driver to run a pass so the
2534
2728
  // write flushes immediately rather than waiting for the trigger's next interval tick. This is what
2535
2729
  // lets the interval be a rare fallback (and so run far less often). No-op when `autoSync` is off — the
@@ -2981,8 +3175,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2981
3175
  // PGlite. Any sync the tail started before disposal is now in `sync` for the unsubscribe below.
2982
3176
  await quiesceTailForTeardown();
2983
3177
  // Await any in-flight convergence pass before closing PGlite, so a pass never queries a
2984
- // closed handle.
3178
+ // closed handle. The Event-lane flush pass is awaited on the same rule, for the same reason.
2985
3179
  await convergenceDriver?.stop();
3180
+ await eventFlushDriver?.stop();
2986
3181
  sync?.unsubscribe();
2987
3182
  status.isRunning = false;
2988
3183
  options.onStatusChange?.(status);
@@ -3020,11 +3215,23 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3020
3215
  `destroy() refused: ${owed} mutation(s) still owed to the server. Flush them first or call destroy({ force: true }).`,
3021
3216
  );
3022
3217
  }
3218
+
3219
+ // ADR-0053 decision 8: the same refusal, for the Event lane's durable state. A non-empty Outbox
3220
+ // holds events the SERVER has not yet ruled on, and "never discard without a server verdict" is
3221
+ // exactly what at-least-once means on this edge — so a non-forced destroy refuses here too,
3222
+ // naming the Outbox so the two causes are never confused.
3223
+ if (eventLane && !(await eventLane.outboxStatus()).empty) {
3224
+ throw new Error(
3225
+ "destroy() refused: the Outbox still holds staged event(s) awaiting a server verdict. " +
3226
+ "Flush them first (`flushEvents()`) or call destroy({ force: true }).",
3227
+ );
3228
+ }
3023
3229
  }
3024
3230
 
3025
3231
  // Drain any in-flight convergence pass before wiping, so a pass never writes into a store
3026
- // being torn down underneath it.
3232
+ // being torn down underneath it. Same for the Event lane's flush pass.
3027
3233
  await convergenceDriver?.stop();
3234
+ await eventFlushDriver?.stop();
3028
3235
  sync?.unsubscribe();
3029
3236
  status.isRunning = false;
3030
3237
  options.onStatusChange?.(status);
@@ -3082,6 +3289,31 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3082
3289
  })
3083
3290
  );
3084
3291
  },
3292
+ // The Event lane (ADR-0053). An append touches only the Outbox — no journal, no overlay, no recovery
3293
+ // pass — so it gates on `localReadReady` (the store is open and its durable schema, Outbox included, is
3294
+ // provisioned), NOT on `writeReady`. That is deliberate: an app that instruments its very first paint
3295
+ // should not have its telemetry blocked behind the mutation runtime's boot recovery.
3296
+ appendEvent: async (stream, payload) => {
3297
+ const lane = requireEventLane();
3298
+ await localReadReady;
3299
+ const result = await lane.appendEvent(stream, payload);
3300
+ // Nudge the driver so a fresh event flushes now rather than at the next interval tick — the
3301
+ // event-driven path, coalesced exactly like an interval signal (and a no-op when no driver runs).
3302
+ eventFlushDriver?.requestPass();
3303
+ return result;
3304
+ },
3305
+ flushEvents: async () => {
3306
+ const lane = requireEventLane();
3307
+ await localReadReady;
3308
+ return lane.flush();
3309
+ },
3310
+ onOutboxStatus: (listener) => requireEventLane().onOutboxStatus(listener),
3311
+ outboxStatus: async () => {
3312
+ const lane = requireEventLane();
3313
+ await localReadReady;
3314
+ return lane.outboxStatus();
3315
+ },
3316
+ onEventLaneReport: (listener) => requireEventLane().onEventLaneReport(listener),
3085
3317
  // Write-path methods gate on `writeReady` (ADR-0041): each enqueues, drains, or mutates a journal, so
3086
3318
  // none may run before the write runtime + boot recovery have completed. `writeReady` is already resolved
3087
3319
  // on the steady-state client, so these are settled-promise awaits.
@@ -3117,6 +3349,10 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3117
3349
  // See the `readMutationDetails` note: a read, ungated, so pre-`writeReady` it may show pre-recovery counts.
3118
3350
  diagnostics: async (table) => ({
3119
3351
  mutation: await mutationRuntime.readMutationStats(table),
3352
+ // The Event lane's durable state belongs in the store's diagnostics too (ADR-0053 decision 8). It is
3353
+ // the BOOLEAN drain signal, not a count: the read is a `LIMIT 1`, so adding it costs nothing even on
3354
+ // the export drain's polling loop. Absent when this client has no lane at all.
3355
+ ...(eventLane ? { outbox: await eventLane.outboxStatus() } : {}),
3120
3356
  }),
3121
3357
  // The registry-wide mutation-status API (slice 4). Assigned just below the object so it can close over
3122
3358
  // this client's own `subscribeLiveRows` + `pglite.query` seams — the SAME factory the worker facade uses.
@@ -6,6 +6,7 @@ import {
6
6
  customType,
7
7
  getTableConfig,
8
8
  integer,
9
+ jsonb,
9
10
  pgSchema,
10
11
  pgTable,
11
12
  pgView,
@@ -27,7 +28,7 @@ import {
27
28
  type SyncTableRegistry,
28
29
  } from "@pgxsinkit/contracts";
29
30
 
30
- import { ALL_MUTATIONS_VIEW, LOCAL_META_TABLE } from "./schema";
31
+ import { ALL_MUTATIONS_VIEW, LOCAL_META_TABLE, OUTBOX_TABLE } from "./schema";
31
32
 
32
33
  /**
33
34
  * Runtime Drizzle objects for the GENERATED local-store relations (ADR-0004): the per-writable-table
@@ -146,6 +147,29 @@ const localMetaShape = pgTable(LOCAL_META_TABLE, {
146
147
  value: text("value").notNull(),
147
148
  });
148
149
 
150
+ /**
151
+ * The **Outbox**'s columns (ADR-0053 decision 2), mirroring the DDL in `schema.ts` — see {@link OUTBOX_TABLE}
152
+ * there for the column-by-column public contract. The `_us` bigints and `seq` are the same `bigintText`
153
+ * passthrough the journal object uses (rows come back through the raw seam UNMAPPED, so the runtime reads
154
+ * them as strings); `payload` is real `jsonb` (PGlite parses it, so the flush loop gets the object back).
155
+ * `seq` is DEFAULTed by the sequence, so an insert omits it — hence no `.notNull()` footgun on `$inferInsert`.
156
+ */
157
+ function buildOutboxColumns() {
158
+ return {
159
+ seq: bigintText("seq"),
160
+ eventId: uuid("event_id").notNull(),
161
+ stream: text("stream").notNull(),
162
+ occurredAtUs: bigintText("occurred_at_us").notNull(),
163
+ payload: jsonb("payload").notNull(),
164
+ enqueuedAtUs: bigintText("enqueued_at_us").notNull(),
165
+ attemptCount: integer("attempt_count").notNull().default(0),
166
+ nextRetryAtUs: bigintText("next_retry_at_us"),
167
+ lastReason: text("last_reason"),
168
+ };
169
+ }
170
+
171
+ const outboxShape = pgTable(OUTBOX_TABLE, buildOutboxColumns());
172
+
149
173
  /**
150
174
  * The entry's PROJECTED local table type — its server columns minus `clientProjection.omitColumns`,
151
175
  * exactly the shape `defineSyncTable` stamped onto `entry.localTable`. When `TEntry` is a concrete
@@ -212,6 +236,8 @@ export type JournalTable = typeof journalShape & { [columnName: string]: PgColum
212
236
  export type SyncStateView = typeof syncStateShape & { [columnName: string]: PgColumn };
213
237
  /** The `pgxsinkit_local_meta` key/value table (ADR-0006). */
214
238
  export type LocalMetaTable = typeof localMetaShape;
239
+ /** The `pgxsinkit_outbox` Event-lane staging table (ADR-0053). */
240
+ export type OutboxTable = typeof outboxShape;
215
241
 
216
242
  /**
217
243
  * Build a runtime `pgTable` for a local-store relation. An `ephemeral`-lifecycle entry (ADR-0021 §3)
@@ -280,6 +306,7 @@ interface EntryLocalTables {
280
306
 
281
307
  const localTablesCache = new WeakMap<SyncTableRegistry, Map<string, EntryLocalTables>>();
282
308
  const localMetaCache = new Map<string, LocalMetaTable>();
309
+ const outboxCache = new Map<string, OutboxTable>();
283
310
 
284
311
  function cacheFor(registry: SyncTableRegistry, tableKey: string): EntryLocalTables {
285
312
  let byKey = localTablesCache.get(registry);
@@ -585,6 +612,26 @@ export function getAllMutationsView(_registry: SyncTableRegistry): AllMutationsV
585
612
  return allMutationsShape;
586
613
  }
587
614
 
615
+ /**
616
+ * The **Outbox** (ADR-0053 decision 2) under the registry's local schema, as a runtime Drizzle object — the
617
+ * one relation the Event lane stages into. Registry-WIDE (one table, a `stream` column) and memoized per
618
+ * local schema, exactly like {@link getLocalMetaTable}; it takes the registry only to resolve that schema.
619
+ *
620
+ * Public on purpose: the table's shape is contract, so an app composing a best-guess view (pending events
621
+ * over down-synced aggregates) authors it as tier-① Drizzle instead of hand-written SQL —
622
+ * `client.query((c) => c.drizzle.select().from(getOutboxTable(registry)).where(eq(outbox.stream, "…")))`.
623
+ */
624
+ export function getOutboxTable(registry: SyncTableRegistry): OutboxTable {
625
+ const localSchema = getSyncRegistrySchema(registry);
626
+ const cached = outboxCache.get(localSchema);
627
+ if (cached) {
628
+ return cached;
629
+ }
630
+ const table = makeTable(localSchema, OUTBOX_TABLE, buildOutboxColumns()) as OutboxTable;
631
+ outboxCache.set(localSchema, table);
632
+ return table;
633
+ }
634
+
588
635
  /** The `pgxsinkit_local_meta` key/value table (ADR-0006) under the registry's local schema. */
589
636
  export function getLocalMetaTable(registry: SyncTableRegistry): LocalMetaTable {
590
637
  const localSchema = getSyncRegistrySchema(registry);
package/src/mutation.ts CHANGED
@@ -96,6 +96,7 @@ import {
96
96
  fingerprintRegistry,
97
97
  getProjectedColumns as getProjectedTableColumns,
98
98
  getSyncRegistrySchema,
99
+ isManagedFieldGuarded,
99
100
  maybeQuoteIdentifier,
100
101
  quoteIdentifier,
101
102
  resolveServerVersionColumnName,
@@ -3006,6 +3007,17 @@ function resolveMutationUrls(batchWriteUrl: string): { batch: string; authoritat
3006
3007
  return { batch: batchWriteUrl, authoritative: `${batchWriteUrl}/unit` };
3007
3008
  }
3008
3009
 
3010
+ /**
3011
+ * Drop the server-owned keys from an outgoing payload. What counts as server-owned is decided by
3012
+ * contracts' {@link isManagedFieldGuarded} — the single definition of the guard rule, shared with the
3013
+ * write route's `getGuardedManagedFields` and the apply-function generator, so this strip and the
3014
+ * server's rejection can never disagree (notably: an update strips **every** managed field, a create-only
3015
+ * one included, because it is inert on update and the server 400-rejects a payload carrying it — so
3016
+ * stripping keeps a locally-authored patch from round-tripping to that rejection).
3017
+ *
3018
+ * `SyncTableUpdateInput` already omits every managed key at the type level, so this is the runtime half;
3019
+ * a payload reaching here with a managed key came through an untyped path.
3020
+ */
3009
3021
  function stripManagedFields(
3010
3022
  context: TableContext,
3011
3023
  payload: Record<string, unknown>,
@@ -3014,7 +3026,7 @@ function stripManagedFields(
3014
3026
  const managedColumns = new Set<string>();
3015
3027
 
3016
3028
  for (const mf of context.entry.governance?.managedFields ?? []) {
3017
- if (mf.applyOn.includes(operation)) {
3029
+ if (isManagedFieldGuarded(mf, operation)) {
3018
3030
  managedColumns.add(mf.column);
3019
3031
  }
3020
3032
  }
package/src/schema.ts CHANGED
@@ -39,6 +39,45 @@ interface ResolvedProjection {
39
39
 
40
40
  /** Local key/value metadata table for current-store safety, boot state, and registry identity. */
41
41
  export const LOCAL_META_TABLE = "pgxsinkit_local_meta";
42
+
43
+ /**
44
+ * The **Outbox** (ADR-0053 decision 2) — the local-only, append-only table where client events are staged
45
+ * until a flush is acknowledged. ONE table for every Event stream (a `stream` column, not a table per
46
+ * stream), library-owned, never in the sync registry and never replicated, and **stream-independent**:
47
+ * registering an Event stream changes nothing about this DDL, so it is emitted unconditionally beside the
48
+ * engine's other internal relations rather than derived from `registry.streams`.
49
+ *
50
+ * Its SHAPE IS PUBLIC CONTRACT, because apps compose pending rows with down-synced aggregates into
51
+ * best-guess views. The columns:
52
+ *
53
+ * - `seq` — the durable, monotonically increasing local **append ordinal**, the ONE ordering key for
54
+ * Outbox selection and batch assembly (UUIDs do not order, `occurred_at_us` collides at these volumes,
55
+ * and SQL row order is undefined). Local machinery: it is never transmitted. Assigned from
56
+ * {@link OUTBOX_SEQUENCE} exactly as the mutation journal's `mutation_seq` is.
57
+ * - `event_id` — the library-stamped uuid carried on the wire; the server-side dedupe key that makes
58
+ * at-least-once delivery idempotent end-to-end. UNIQUE: a duplicate would be a library bug.
59
+ * - `stream` — the registered Event-stream name.
60
+ * - `occurred_at_us` — the library-stamped append time (microseconds), carried on the wire. Consumers
61
+ * needing temporal order re-sort on it (ADR-0053 decision 6).
62
+ * - `payload` — the event body as `jsonb`, validated against the Event stream's zod schema AT APPEND, so
63
+ * "everything in the Outbox is well-formed" holds for the flush loop and for best-guess views. It is
64
+ * EXACTLY the value the caller passed to `appendEvent` — never the schema's `parsed.data`. The schema is
65
+ * used at append only to VALIDATE (its output is discarded); the one AUTHORITATIVE parse is at ingest, and
66
+ * that output's JSON-NORMALIZED form is what the consumer receives (a `Date` becomes its ISO string; a
67
+ * nested `undefined` property is dropped). The schema therefore executes at both boundaries — so
68
+ * transforms must be pure and deterministic — while a best-guess view here reads back precisely what the
69
+ * app appended.
70
+ * - `enqueued_at_us` — when the row was durably enqueued locally (never transmitted; observability).
71
+ * - `attempt_count` / `next_retry_at_us` — the per-row DEFERRED backoff (ADR-0053 decision 3): an Event
72
+ * stream the server does not yet know parks its rows here rather than deleting them. A row whose
73
+ * `next_retry_at_us` is in the future is skipped by batch assembly. NULL = eligible now.
74
+ * - `last_reason` — the most recent server `deferred` reason, kept on the row it belongs to (never a
75
+ * second, retention-bearing verdict table — ADR-0053 rejects that).
76
+ */
77
+ export const OUTBOX_TABLE = "pgxsinkit_outbox";
78
+
79
+ /** The sequence backing {@link OUTBOX_TABLE}'s `seq` append ordinal (the journal's `mutation_seq` precedent). */
80
+ export const OUTBOX_SEQUENCE = `${OUTBOX_TABLE}_seq`;
42
81
  export const REGISTRY_FINGERPRINT_KEY = "registry_fingerprint";
43
82
  /**
44
83
  * The `pgxsinkit_local_meta` key holding the DURABLE-schema fingerprint the local store was last
@@ -121,6 +160,39 @@ function localMetaBootstrapStatements(localSchema: string): string[] {
121
160
  return statements;
122
161
  }
123
162
 
163
+ /**
164
+ * The **Outbox** DDL (ADR-0053 decision 2) — its sequence, table, and the two indexes that serve it. Emitted
165
+ * unconditionally in the durable stream (never gated on `registry.streams`): the shape is stream-independent
166
+ * and the table must exist before the first `appendEvent`, which may be the first thing an app does after a
167
+ * registry gains its first Event stream. See {@link OUTBOX_TABLE} for the column contract.
168
+ *
169
+ * Two indexes, one per access pattern:
170
+ * - `(stream, seq)` serves the APP's `WHERE stream = ?` best-guess-view queries in append order;
171
+ * - `(next_retry_at_us, seq)` serves BATCH ASSEMBLY — ordered by `seq` across all streams, skipping rows
172
+ * whose deferred backoff has not elapsed.
173
+ */
174
+ function outboxStatements(localSchema: string): string[] {
175
+ const outboxTable = qualifyIdentifier(localSchema, OUTBOX_TABLE);
176
+ const outboxSequence = qualifyIdentifier(localSchema, OUTBOX_SEQUENCE);
177
+
178
+ return [
179
+ `CREATE SEQUENCE IF NOT EXISTS ${outboxSequence} AS bigint START WITH 1 INCREMENT BY 1;`,
180
+ `CREATE TABLE IF NOT EXISTS ${outboxTable} (\n ${[
181
+ `seq BIGINT PRIMARY KEY DEFAULT nextval(${quoteSqlStringLiteral(outboxSequence)})`,
182
+ "event_id UUID NOT NULL UNIQUE",
183
+ "stream TEXT NOT NULL",
184
+ "occurred_at_us BIGINT NOT NULL",
185
+ "payload JSONB NOT NULL",
186
+ "enqueued_at_us BIGINT NOT NULL",
187
+ "attempt_count INTEGER NOT NULL DEFAULT 0",
188
+ "next_retry_at_us BIGINT",
189
+ "last_reason TEXT",
190
+ ].join(",\n ")}\n);`,
191
+ renderCreateIndexStatement(outboxTable, `${OUTBOX_TABLE}_stream_seq_idx`, ["stream", "seq"]),
192
+ renderCreateIndexStatement(outboxTable, `${OUTBOX_TABLE}_retry_seq_idx`, ["next_retry_at_us", "seq"]),
193
+ ];
194
+ }
195
+
124
196
  /**
125
197
  * The minimal durable bootstrap (schema + meta table) as an executable script (slice 3). Run as the first,
126
198
  * tiny crossing on every client-owned boot so the `local_schema_fingerprint` read/write has its table before
@@ -356,7 +428,10 @@ function buildEntryClusterStatements(entry: SyncTableEntry, tableKey: string, lo
356
428
  */
357
429
  function durableSchemaStatements<TRegistry extends SyncTableRegistry>(registry: TRegistry): string[] {
358
430
  const localSchema = getSyncRegistrySchema(registry);
359
- const statements: string[] = [...localMetaBootstrapStatements(localSchema)];
431
+ // The Outbox (ADR-0053) joins the durable stream right after the meta bootstrap: library-owned engine
432
+ // state, stream-independent, and durable (events survive reload/offline weeks). It is deliberately NOT in
433
+ // the ephemeral portion and NOT in the read cache.
434
+ const statements: string[] = [...localMetaBootstrapStatements(localSchema), ...outboxStatements(localSchema)];
360
435
 
361
436
  for (const enumDefinition of collectEnumDefinitions(registry, localSchema)) {
362
437
  statements.push(buildCreateEnumTypeSql(enumDefinition));
@@ -1012,6 +1087,11 @@ export function buildWipeLocalStoreSql<TRegistry extends SyncTableRegistry>(regi
1012
1087
  statements.push(`DROP TYPE IF EXISTS ${qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName)};`);
1013
1088
  }
1014
1089
 
1090
+ // The Outbox is durable library-owned state, so the FULL teardown drops it (ADR-0053 decision 8) — and
1091
+ // only the full teardown: `buildDropReadCacheSql` above never names it (the Outbox is not read cache), so
1092
+ // a cache rebuild leaves staged events untouched.
1093
+ statements.push(`DROP TABLE IF EXISTS ${qualifyIdentifier(localSchema, OUTBOX_TABLE)} CASCADE;`);
1094
+ statements.push(`DROP SEQUENCE IF EXISTS ${qualifyIdentifier(localSchema, OUTBOX_SEQUENCE)};`);
1015
1095
  statements.push(`DROP TABLE IF EXISTS ${qualifyIdentifier(localSchema, LOCAL_META_TABLE)} CASCADE;`);
1016
1096
 
1017
1097
  return `${statements.join("\n")}\n`;