@pgxsinkit/client 0.2.4 → 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.
@@ -0,0 +1,102 @@
1
+ import { BackoffDefaults, type BackoffOptions } from "@electric-sql/client";
2
+
3
+ /**
4
+ * The read path's OUTAGE seam (board ADR-0010 "offline return").
5
+ *
6
+ * Every shape fetch runs inside Electric's `createFetchWithBackoff`, which retries a failed attempt
7
+ * **forever** (`maxRetries: Infinity` — "clients may go offline and come back") and only re-throws a
8
+ * non-retryable 4xx. A network-level failure therefore never escapes that wrapper: `ShapeStream.onError`
9
+ * is never called, so neither is `onReadStreamError`, and a runtime keying off those alone reports
10
+ * `syncing` for as long as the machine stays offline. `backoffOptions.onFailedAttempt` is the ONLY signal
11
+ * Electric surfaces from inside the loop, and it is what this probe turns into a runtime status change.
12
+ *
13
+ * The two seams PARTITION the failures, they do not overlap:
14
+ *
15
+ * - **Retried inside the wrapper** (a rejected request — the offline case, with no HTTP status at all — a
16
+ * 5xx, or a 429) → nobody else will ever hear about it. This probe's `onStalled`.
17
+ * - **Escapes the wrapper** (any other 4xx: 401/403 auth, 404/409/… structural) → `ShapeStream.onError`,
18
+ * i.e. `createShapeErrorHandler` → `onAuthError` / `onReadStreamError`, which own it and carry a real
19
+ * error message. Deliberately NOT reported here, so a rejected token still surfaces as the more
20
+ * actionable `auth-needed` and an expired handle's 409 stays the recovery it is.
21
+ * - **A deliberate abort** — a stream teardown, a hidden tab (`PAUSE_STREAM`), a live-request timeout, a
22
+ * system wake, and the live-tail nudge's `forceDisconnectAndRefresh` all abort the in-flight request,
23
+ * and Electric calls `onFailedAttempt` for the resulting `AbortError` like any other. None is an
24
+ * outage; counting them would report "connection needed" for backgrounding a tab.
25
+ *
26
+ * `onFailedAttempt` carries no arguments, so the classification is made one layer down, in the
27
+ * `fetchClient` this probe supplies: it records how the attempt that just settled would be treated by the
28
+ * very next lines of Electric's own catch block. Recovery needs nothing here — the runtime clears a
29
+ * stream-degraded status on the next delivered batch (`onSyncActivity`), which a resumed stream produces
30
+ * on its first successful poll.
31
+ */
32
+ export interface ReadStreamStallProbe {
33
+ /** Pass as `ShapeStreamOptions.backoffOptions` — Electric's defaults plus the failed-attempt hook. */
34
+ backoffOptions: BackoffOptions;
35
+ /** Pass as `ShapeStreamOptions.fetchClient` — the innermost transport, wrapped to classify each attempt. */
36
+ fetchClient: typeof fetch;
37
+ }
38
+
39
+ /**
40
+ * The CALL signature of `fetch`, without the runtime-specific statics (Bun's global carries `preconnect`).
41
+ * A ShapeStream only ever invokes its `fetchClient` as a plain call, so this is the honest contract for a
42
+ * transport being wrapped — and it is what lets a test inject a failing one.
43
+ */
44
+ type FetchLike = (request: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => Promise<Response>;
45
+
46
+ /**
47
+ * Would Electric SWALLOW this response status and retry it inside the backoff loop? Mirrors the branch in
48
+ * `createFetchWithBackoff`: a 4xx is re-thrown (and reaches `onError`) unless it is the one retryable
49
+ * status, 429; everything else — 5xx above all — is retried where no other seam can see it.
50
+ */
51
+ function isRetriedInsideBackoff(status: number): boolean {
52
+ return status === 429 || status < 400 || status >= 500;
53
+ }
54
+
55
+ export function createReadStreamStallProbe(input: {
56
+ /**
57
+ * Notified per failed attempt that Electric will retry internally, never for an escaping 4xx and never
58
+ * for a deliberate abort. Fires repeatedly while an outage lasts — Electric retries forever — so the
59
+ * consumer owns the transition/dedup, not this probe.
60
+ */
61
+ onStalled: () => void;
62
+ /** The transport to wrap. Defaults to the global `fetch`; a test injects the failure here. */
63
+ fetchClient?: FetchLike;
64
+ }): ReadStreamStallProbe {
65
+ const transport = input.fetchClient;
66
+ // How the attempt that just settled will be treated by Electric's catch block. Written by the fetch
67
+ // wrapper and read by `onFailedAttempt`, which Electric invokes in the catch of the very call that just
68
+ // settled — no await sits between the two, so the pairing holds. Per-probe (one probe per shape), so a
69
+ // sibling shape's traffic can never answer for this one.
70
+ let lastAttemptRetried = false;
71
+ const fetchClient = (async (request: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
72
+ try {
73
+ const response = await (transport ? transport(request, init) : fetch(request, init));
74
+ // The server answered. `ok` means no failed attempt at all; otherwise the backoff wrapper turns it
75
+ // into a `FetchError` and either swallows it (5xx/429 — ours) or re-throws it (4xx — `onError`'s).
76
+ lastAttemptRetried = !response.ok && isRetriedInsideBackoff(response.status);
77
+ return response;
78
+ } catch (error) {
79
+ // A rejection: a transport fault (retried forever — the outage) unless the request was deliberately
80
+ // aborted, which Electric turns into a `FetchBackoffAbortError` rather than a retry.
81
+ lastAttemptRetried = init?.signal?.aborted !== true;
82
+ throw error;
83
+ }
84
+ // `typeof fetch` (Bun's global) carries a `preconnect` member the wrapper neither has nor needs — the
85
+ // ShapeStream only ever invokes fetchClient as a plain fetch — so the shape-compatible cast is safe.
86
+ }) as typeof fetch;
87
+
88
+ return {
89
+ fetchClient,
90
+ // `ShapeStream` uses `options.backoffOptions ?? BackoffDefaults` — it SPREADS, it does not merge — so
91
+ // a partial object would blank Electric's timings. Spreading `BackoffDefaults` keeps them (1000 /
92
+ // 32000 / 2, `maxRetries: Infinity`) and tracks upstream if they ever move: adding this callback is
93
+ // behaviour-neutral for retrying.
94
+ backoffOptions: {
95
+ ...BackoffDefaults,
96
+ onFailedAttempt: () => {
97
+ if (!lastAttemptRetried) return;
98
+ input.onStalled();
99
+ },
100
+ },
101
+ };
102
+ }
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`;
package/src/shape-sync.ts CHANGED
@@ -10,6 +10,7 @@ import {
10
10
  } from "@pgxsinkit/contracts";
11
11
 
12
12
  import type { BootStampCollector, GroupBootStamp } from "./boot-report";
13
+ import { createReadStreamStallProbe } from "./read-stream-stall";
13
14
  import type { SyncNamespaceObj } from "./sync";
14
15
  import { createShapeErrorHandler } from "./sync-auth";
15
16
 
@@ -79,6 +80,15 @@ export interface StartConfiguredSyncOptions {
79
80
  * never silently believes the read path is live while it has actually stalled.
80
81
  */
81
82
  onReadStreamError?: (error: Error) => void;
83
+ /**
84
+ * Notified when a shape's fetch ATTEMPT failed and Electric is retrying it inside its own backoff
85
+ * wrapper (board ADR-0010): a rejected request (the offline case — no HTTP status at all), a 5xx, or a
86
+ * 429. The complement of {@link onReadStreamError}, which only ever fires for an error that ESCAPED that
87
+ * wrapper (any other 4xx) — which a network outage never does, since Electric retries it forever. Fires
88
+ * per attempt for as long as the outage lasts, so the runtime owns the transition; a deliberate abort
89
+ * (teardown, hidden tab, nudge refresh) is not a failure and is filtered out. See `read-stream-stall.ts`.
90
+ */
91
+ onReadStreamStalled?: () => void;
82
92
  /**
83
93
  * Notified when a shape successfully delivers a batch — i.e. a fetch just succeeded (ADR-0013
84
94
  * Phase 3). The runtime uses this to clear an `auth-needed`/`degraded` status once sync resumes.
@@ -310,6 +320,7 @@ export async function startConfiguredSync(
310
320
  ...(input.onSyncError ? { onSyncError: input.onSyncError } : {}),
311
321
  ...(input.onAuthError ? { onAuthError: input.onAuthError } : {}),
312
322
  ...(input.onReadStreamError ? { onReadStreamError: input.onReadStreamError } : {}),
323
+ ...(input.onReadStreamStalled ? { onReadStreamStalled: input.onReadStreamStalled } : {}),
313
324
  ...(input.onSyncActivity ? { onSyncActivity: input.onSyncActivity } : {}),
314
325
  onGroupInitialSync: () => {
315
326
  // The group is up-to-date as a unit; signal each member table, mark the group ready (per-group
@@ -419,6 +430,8 @@ interface StartGroupSyncOptions {
419
430
  onSyncError?: (error: Error) => void;
420
431
  onAuthError?: () => void;
421
432
  onReadStreamError?: (error: Error) => void;
433
+ /** A failed fetch ATTEMPT inside Electric's backoff loop; see {@link StartConfiguredSyncOptions.onReadStreamStalled}. */
434
+ onReadStreamStalled?: () => void;
422
435
  onSyncActivity?: () => void;
423
436
  }
424
437
 
@@ -438,22 +451,33 @@ export async function startGroupSync(pg: SyncEnginePGlite, input: StartGroupSync
438
451
  ...(input.onReadStreamError ? { onReadStreamError: input.onReadStreamError } : {}),
439
452
  });
440
453
 
454
+ // The failed-attempt probe is `onError`'s complement and the reason it exists: `onError` sees only the
455
+ // failures that ESCAPE Electric's retry wrapper, which a network outage never does — it is retried in
456
+ // there forever (board ADR-0010). The two PARTITION the failure space; neither masks the other. One probe
457
+ // per shape — each classifies its own in-flight request — and none at all when no consumer wants the
458
+ // signal, so the off-path keeps Electric's untouched fetch/backoff wiring.
459
+ const onReadStreamStalled = input.onReadStreamStalled;
460
+
441
461
  const shapes = Object.fromEntries(
442
- input.specs.map((spec) => [
443
- spec.key,
444
- {
445
- shape: {
446
- // Ingress `table` = the unique `shapeKey` (proxy maps it to the physical table on egress).
447
- url: buildShapeUrl(spec.electricUrl, spec.shapeKey),
448
- ...(shapeHeaders ? { headers: shapeHeaders } : {}),
449
- onError,
462
+ input.specs.map((spec) => {
463
+ const stallProbe = onReadStreamStalled ? createReadStreamStallProbe({ onStalled: onReadStreamStalled }) : null;
464
+ return [
465
+ spec.key,
466
+ {
467
+ shape: {
468
+ // Ingress `table` = the unique `shapeKey` (proxy maps it to the physical table on egress).
469
+ url: buildShapeUrl(spec.electricUrl, spec.shapeKey),
470
+ ...(shapeHeaders ? { headers: shapeHeaders } : {}),
471
+ onError,
472
+ ...(stallProbe ? { backoffOptions: stallProbe.backoffOptions, fetchClient: stallProbe.fetchClient } : {}),
473
+ },
474
+ // ADR-0029 D1: the registry table key is the engine's sole per-table spec — the local apply
475
+ // target, PKs, strategy, and column types all derive from `(registry, tableKey)`. The
476
+ // `syncConfig` table key IS the registry key, so the spec's `key` is the `tableKey`.
477
+ tableKey: spec.key,
450
478
  },
451
- // ADR-0029 D1: the registry table key is the engine's sole per-table spec — the local apply
452
- // target, PKs, strategy, and column types all derive from `(registry, tableKey)`. The
453
- // `syncConfig` table key IS the registry key, so the spec's `key` is the `tableKey`.
454
- tableKey: spec.key,
455
- },
456
- ]),
479
+ ];
480
+ }),
457
481
  );
458
482
 
459
483
  return getElectricNamespace(pg).syncShapesToTables({
@@ -26,6 +26,8 @@ import type {
26
26
  import { StorageDeclarationRefusedError } from "@pgxsinkit/contracts";
27
27
 
28
28
  import type { BootReport } from "../boot-report";
29
+ import { syncDebug } from "../debug";
30
+ import type { EventAppendResult, EventLaneReport, OutboxStatus } from "../event-lane";
29
31
  import type { DataExportOptions, DataExportResult } from "../export-data";
30
32
  import type { DiagnosticExportOptions, DiagnosticExportResult } from "../export-dump";
31
33
  import type { StoreExportOptions, StoreExportResult } from "../export-store";
@@ -574,6 +576,12 @@ const MUTATION_RPC_OPS: ReadonlySet<RpcOp> = new Set<RpcOp>([
574
576
  "discardQuarantined",
575
577
  "desync",
576
578
  "discardEphemeral",
579
+ // The Event lane's two write-capable ops (ADR-0053). `appendEvent` STAGES a durable row, so a lost
580
+ // response is genuinely `"unknown"` — a blind repeat would stamp a FRESH `eventId` and append a second
581
+ // event (the server's dedupe keys on the id we never learned). `flushEvents` settles verdicts into the
582
+ // Outbox, so its outcome is likewise unknown on a lost response.
583
+ "appendEvent",
584
+ "flushEvents",
577
585
  // `rawExec` is WRITE-CAPABLE (its docstring: any write it issues stays local and will NOT converge), so a
578
586
  // dispatched rawExec with a lost response is `"unknown"` — retrying could double-apply a local write.
579
587
  "rawExec",
@@ -1094,6 +1102,13 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
1094
1102
  // `live-hydrated` on the same port as the diff stream, strictly after the catch-up rows — so
1095
1103
  // resolution here guarantees the rows have already been applied by the materializer.
1096
1104
  const hydratedPending = new Map<string, () => void>();
1105
+ // The Event lane's two tab-side subscriber sets (ADR-0053 decision 2). The worker holds ONE Outbox and
1106
+ // broadcasts its transitions/reports; each tab fans them out to its own observers. `lastOutboxStatus`
1107
+ // caches the most recent broadcast so a subscriber arriving between transitions is served without a
1108
+ // round trip (a tab that has seen NO broadcast pulls the current state instead).
1109
+ const outboxStatusListeners = new Set<(status: OutboxStatus) => void>();
1110
+ const eventLaneReportListeners = new Set<(report: EventLaneReport) => void>();
1111
+ let lastOutboxStatus: OutboxStatus | null = null;
1097
1112
  // Set once this tab detaches (explicit `stop()` OR a terminal `pagehide`). Guards NEW operations (they
1098
1113
  // reject at once) and lets `detachFromWorker` settle every outstanding promise — the port listener is torn
1099
1114
  // down on detach, so an unsettled `rpc`/`live-initial` waiter would otherwise hang forever (ADR-0040 P2).
@@ -1185,6 +1200,27 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
1185
1200
  case "reject":
1186
1201
  options.onReject?.(event.details as MutationDetail[]);
1187
1202
  break;
1203
+ case "outbox-status": {
1204
+ // The drain signal's transition push (ADR-0053 decision 2), fanned out to this tab's observers and
1205
+ // cached so a later subscriber is served without a pull.
1206
+ const status = event.status as OutboxStatus;
1207
+ lastOutboxStatus = status;
1208
+ for (const listener of outboxStatusListeners) listener(status);
1209
+ break;
1210
+ }
1211
+ case "event-lane-report": {
1212
+ const report = event.report as EventLaneReport;
1213
+ if (eventLaneReportListeners.size === 0) {
1214
+ // The default warn lives HERE, not in the worker: the engine always has the bridge as a
1215
+ // subscriber, and a SharedWorker's console is invisible anyway. Same `onDeadLetter` rule — a
1216
+ // terminal verdict must never be silent, because once the row is deleted the Outbox cannot
1217
+ // answer for it.
1218
+ console.warn("pgxsinkit: event-lane report (no `onEventLaneReport` subscriber)", report);
1219
+ break;
1220
+ }
1221
+ for (const listener of eventLaneReportListeners) listener(report);
1222
+ break;
1223
+ }
1188
1224
  case "schema-change":
1189
1225
  options.onSchemaChange?.(event.event as LocalStoreVersionEvent);
1190
1226
  break;
@@ -2069,6 +2105,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
2069
2105
  throw error;
2070
2106
  }
2071
2107
  const initialRows = materializer.seed(initial.rows as TRow[]);
2108
+ // Tab-side receipt on the rail: pairs with the worker's "live-initial post" — if that line fires and
2109
+ // this one never does, the loss is in the bridge; if both fire with 0 rows, the store was empty.
2110
+ syncDebug("live-initial received", { rows: initialRows.length });
2072
2111
  // Register the live query for ADR-0049 re-subscribe: on a pipe swap, re-issue the SAME subscribe (same
2073
2112
  // queryId → diffs still route to the same materializer/handler) and re-seed the materializer off the fresh
2074
2113
  // snapshot. This is the re-attach re-establishment of live queries (ADR-0041 staged readiness); its
@@ -2222,7 +2261,7 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
2222
2261
  const peers = await queryDestroyPeers();
2223
2262
  if (peers > 1) throw new StoreDestroyRefusedError(peers);
2224
2263
  if (!destroyOptions?.force) {
2225
- const { mutation } = await client.diagnostics();
2264
+ const { mutation, outbox } = await client.diagnostics();
2226
2265
  const owed =
2227
2266
  mutation.pendingCount +
2228
2267
  mutation.sendingCount +
@@ -2234,6 +2273,16 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
2234
2273
  `destroy() refused: ${owed} mutation(s) still owed to the server. Flush them first or call destroy({ force: true }).`,
2235
2274
  );
2236
2275
  }
2276
+ // ADR-0053 decision 8, the Event lane's half of the same refusal. It rides the diagnostics round
2277
+ // trip already taken above rather than a second one: the tab has no local Outbox (exactly as it has
2278
+ // no local journal), and a destroy must not add a network-shaped hop it can avoid. Absent `outbox`
2279
+ // means the engine has no Event lane, which is not a reason to block a destroy.
2280
+ if (outbox?.empty === false) {
2281
+ throw new Error(
2282
+ "destroy() refused: the Outbox still holds staged event(s) awaiting a server verdict. " +
2283
+ "Flush them first (`flushEvents()`) or call destroy({ force: true }).",
2284
+ );
2285
+ }
2237
2286
  }
2238
2287
  const storePath = resolveDestroyStorePath();
2239
2288
  // ADR-0049 D8 ordering (elected placement): RETIRE this tab's own elected engine and AWAIT its teardown —
@@ -2249,6 +2298,40 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
2249
2298
  await runStoreDestruction(effects);
2250
2299
  },
2251
2300
  dropReadCache: notSupported("client.dropReadCache"),
2301
+ // The Event lane (ADR-0053) over the bridge. `appendEvent` is ONE round trip — the validation, the
2302
+ // stamps, and the durable insert all run on the worker's engine, so both client forms share one
2303
+ // implementation and one Outbox; a refusal rebuilds tab-side as the same name-tagged error.
2304
+ appendEvent: (stream, payload) => rpc<EventAppendResult>("appendEvent", [stream, payload]),
2305
+ flushEvents: () => rpc<void>("flushEvents", []),
2306
+ outboxStatus: () => rpc<OutboxStatus>("outboxStatus", []),
2307
+ onOutboxStatus: (listener) => {
2308
+ outboxStatusListeners.add(listener);
2309
+ // Current state on subscribe, matching the in-process contract. The engine broadcasts TRANSITIONS
2310
+ // only, so a tab that attached after the last one has nothing to fold — pull it (the `bootReport`
2311
+ // pull/push pattern). A cached broadcast, when we have one, answers synchronously-enough without a
2312
+ // round trip. A failed pull (detached, or a lane-less engine) leaves the subscription silent rather
2313
+ // than throwing at an observer.
2314
+ if (lastOutboxStatus != null) {
2315
+ listener(lastOutboxStatus);
2316
+ } else {
2317
+ void client
2318
+ .outboxStatus()
2319
+ .then((status) => {
2320
+ lastOutboxStatus ??= status;
2321
+ if (outboxStatusListeners.has(listener)) listener(status);
2322
+ })
2323
+ .catch(() => undefined);
2324
+ }
2325
+ return () => {
2326
+ outboxStatusListeners.delete(listener);
2327
+ };
2328
+ },
2329
+ onEventLaneReport: (listener) => {
2330
+ eventLaneReportListeners.add(listener);
2331
+ return () => {
2332
+ eventLaneReportListeners.delete(listener);
2333
+ };
2334
+ },
2252
2335
  flush: (table) => rpc<void>("flush", [table]),
2253
2336
  reconcile: (table) => rpc<void>("reconcile", [table]),
2254
2337
  retryFailed: (table) => rpc<void>("retryFailed", [table]),
@@ -2271,7 +2354,7 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
2271
2354
  },
2272
2355
  discardConflict: (table, entityKey) => rpc<void>("discardConflict", [table, entityKey]),
2273
2356
  discardQuarantined: (table, entityKey) => rpc<void>("discardQuarantined", [table, entityKey]),
2274
- diagnostics: (table) => rpc<{ mutation: MutationDiagnostics }>("diagnostics", [table]),
2357
+ diagnostics: (table) => rpc<{ mutation: MutationDiagnostics; outbox?: OutboxStatus }>("diagnostics", [table]),
2275
2358
  // The registry-wide mutation-status API (slice 4) over the SAME factory the in-process client uses,
2276
2359
  // wired to this facade's shared seams: the live-rows bridge (`subscribeLiveRows`) and the one-shot
2277
2360
  // `rawQuery` RPC. No new bridge message — `client.mutations` behaves identically to the in-process client.
@@ -29,6 +29,7 @@ import {
29
29
  import { type ConvergenceTrigger, createIntervalConvergenceTrigger } from "../convergence";
30
30
  import { setSyncDebugSink, syncDebug } from "../debug";
31
31
  import { describeErrorChain } from "../error-chain";
32
+ import type { EventLaneOptions } from "../event-lane";
32
33
  import {
33
34
  type ClientPGlite,
34
35
  createClientPGlite,
@@ -143,6 +144,17 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
143
144
  storePath?: string;
144
145
  maxMutationAttempts?: number;
145
146
  syncEnabled?: boolean;
147
+ /**
148
+ * The **Event lane**'s ingestion endpoint (ADR-0053 decision 3). Omit it and the worker derives it from
149
+ * {@link batchWriteUrl} (`…/api/mutations` → `…/api/events`). See `createSyncClient`'s `batchEventUrl`.
150
+ */
151
+ batchEventUrl?: string;
152
+ /**
153
+ * The Event lane's client-level flush policy (ADR-0053): batch caps, the fallback interval, backoff, and
154
+ * per-Event-stream overrides. A worker-ENTRY option, never an attach option — flush cadence is one
155
+ * engine-wide policy, and the Outbox it drains is shared by every attached tab.
156
+ */
157
+ events?: EventLaneOptions;
146
158
  /**
147
159
  * How close to expiry (ms) a cached token may be before a read/write that needs it triggers a pull
148
160
  * broadcast (ADR-0032 decision 3). Default 30s — comfortably ahead of a long-poll cycle.
@@ -621,6 +633,10 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
621
633
  ...(options.requestHeaders ? { requestHeaders: options.requestHeaders } : {}),
622
634
  ...(options.writeRequestHeaders ? { writeRequestHeaders: options.writeRequestHeaders } : {}),
623
635
  ...(options.maxMutationAttempts != null ? { maxMutationAttempts: options.maxMutationAttempts } : {}),
636
+ // The Event lane (ADR-0053): endpoint + flush policy are worker-entry config, exactly like the write
637
+ // path's. The Outbox is engine-wide, so one policy governs every attached tab's appends.
638
+ ...(options.batchEventUrl ? { batchEventUrl: options.batchEventUrl } : {}),
639
+ ...(options.events ? { events: options.events } : {}),
624
640
  onStatusChange: (status) => emitStatus(status),
625
641
  onConflict: (details) => broadcastEvent({ kind: "conflict", details }),
626
642
  onQuarantine: (details) => broadcastEvent({ kind: "quarantine", details }),
@@ -643,6 +659,25 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
643
659
 
644
660
  const whenBooted = () => bootedPromise;
645
661
 
662
+ // ─── Event-lane broadcast bridge (ADR-0053 decision 2) ───────────────────────────────────────────
663
+ // ONE Outbox lives in the worker, so the engine's two observation surfaces are subscribed ONCE here and
664
+ // fanned out to every attached port. The drain signal's push carries only TRANSITIONS (the engine's own
665
+ // semantics); a tab attaching later folds the current state from the `outboxStatus` pull instead, exactly
666
+ // as a late attach folds the boot report. Subscribing here also means the ENGINE always has a report
667
+ // subscriber, so its no-subscriber warn never fires in the worker's invisible console — the tab-side
668
+ // surface owns that default logging, where a developer can actually see it.
669
+ const wireEventLaneBroadcast = (booted: SyncClient<TRegistry>): void => {
670
+ try {
671
+ booted.onOutboxStatus((status) => broadcastEvent({ kind: "outbox-status", status }));
672
+ booted.onEventLaneReport((report) => broadcastEvent({ kind: "event-lane-report", report }));
673
+ } catch (error) {
674
+ // A client with no Event lane (a non-canonical write URL, or a caller-owned PGlite) refuses these
675
+ // subscriptions. Nothing to bridge then — the RPCs refuse identically, so the tab still gets the
676
+ // honest error at its own call site.
677
+ syncDebug("worker: no Event lane to bridge", { error });
678
+ }
679
+ };
680
+
646
681
  // ─── Write / mutation-state RPC dispatch ─────────────────────────────────────────────────────────
647
682
  const dispatchRpc = async (active: SyncClient<TRegistry>, op: RpcOp, args: unknown[]): Promise<unknown> => {
648
683
  // Guarded-read parser re-application (ADR-0032 decision 4). A guarded read compiled by the tab's
@@ -707,6 +742,18 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
707
742
  return active.desync(args[0] as TableKey);
708
743
  case "discardEphemeral":
709
744
  return active.discardEphemeral(args[0] as TableKey);
745
+ case "appendEvent":
746
+ // The Event lane (ADR-0053 decision 2) in ONE round trip: validation (the registered zod schema +
747
+ // the payload-size cap), the uuid/`occurredAtUs` stamps, and the durable Outbox insert all happen
748
+ // HERE, on the engine that owns the store — so the attach client and the in-process client share one
749
+ // implementation. A refusal rejects the RPC and rebuilds tab-side as the same name-tagged error.
750
+ return active.appendEvent(args[0] as string, args[1]);
751
+ case "flushEvents":
752
+ return active.flushEvents();
753
+ case "outboxStatus":
754
+ // The drain signal's PULL: a tab attaching after the engine's last transition has no broadcast to
755
+ // fold, so its first `onOutboxStatus` subscriber is served from this (the `bootReport` pattern).
756
+ return active.outboxStatus();
710
757
  case "ensureSynced":
711
758
  // Lazy activation (ADR-0021) on the worker's real client. Engine-wide but additive/idempotent — a tab
712
759
  // activating a group another tab already started is a no-op, so no cross-tab revert hazard (cf. desync).
@@ -857,6 +904,9 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
857
904
  {
858
905
  deliverInitial: (rows) => {
859
906
  // Initial snapshot verbatim (not a diff), correlated to the subscribe request so the tab resolves.
907
+ // Row COUNT on the rail: the register line proves the query ran, but only this line shows what the
908
+ // store actually held — a warm boot delivering 0 rows is the "empty store" diagnosis in one glance.
909
+ syncDebug("live-initial post", { rows: rows.length, hydrating: hydratingTables.length });
860
910
  postBridgeMessage(
861
911
  port,
862
912
  codec,
@@ -1149,6 +1199,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
1149
1199
  // and fold the current set into every subsequent ack for late attachers.
1150
1200
  if (!milestonesWired) {
1151
1201
  milestonesWired = true;
1202
+ wireEventLaneBroadcast(booted);
1152
1203
  void booted.writeReady.then(
1153
1204
  () => markMilestone("writeReady"),
1154
1205
  (error: unknown) => failMilestone("writeReady", error),
@@ -290,6 +290,14 @@ export type RpcOp =
290
290
  | "discardQuarantined"
291
291
  | "desync"
292
292
  | "discardEphemeral"
293
+ // The Event lane (ADR-0053 decision 2). `appendEvent` is ONE round trip carrying `[stream, payload]`: the
294
+ // registered zod validation, the size cap, and the uuid/timestamp stamps all run WORKER-side on the shared
295
+ // engine, so both client forms share one implementation and one Outbox. It rejects with the same typed
296
+ // refusals (name-tagged across the bridge). `flushEvents` is the manual drain; `outboxStatus` is the PULL
297
+ // that gives a newly-attached tab the drain signal's CURRENT state (the push is the `outbox-status` event).
298
+ | "appendEvent"
299
+ | "flushEvents"
300
+ | "outboxStatus"
293
301
  // Lazy activation (ADR-0021): start the consistency groups of the given relation keys on the shared engine.
294
302
  // Engine-WIDE but additive/idempotent (unlike `desync`), so it is a plain fire-and-await RPC — carries
295
303
  // `[keys]`, resolves once the streams are started (catch-up may still be in flight).
@@ -467,6 +475,12 @@ export type BridgeEvent =
467
475
  | { kind: "conflict"; details: unknown }
468
476
  | { kind: "quarantine"; details: unknown }
469
477
  | { kind: "reject"; details: unknown }
478
+ // The Event lane's two observation surfaces (ADR-0053 decision 2), broadcast from the engine's single
479
+ // Outbox to every attached tab. `outbox-status` is the drain signal's TRANSITION push (a tab that attaches
480
+ // later folds the current state from the `outboxStatus` pull instead); `event-lane-report` carries one
481
+ // flush pass's terminal verdicts, deferred verdicts, and backoff transitions.
482
+ | { kind: "outbox-status"; status: unknown }
483
+ | { kind: "event-lane-report"; report: unknown }
470
484
  | { kind: "schema-change"; event: unknown }
471
485
  | { kind: "sync-error"; message: string }
472
486
  | { kind: "timing"; label: string; ms: number; data?: Record<string, unknown> }