@pgxsinkit/client 0.2.7 → 0.3.0
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/README.md +2 -1
- package/dist/boot-report.d.ts +5 -2
- package/dist/boot-report.d.ts.map +1 -1
- package/dist/circuits/envelope-to-change.d.ts +35 -0
- package/dist/circuits/envelope-to-change.d.ts.map +1 -0
- package/dist/circuits/group-sync.d.ts +123 -0
- package/dist/circuits/group-sync.d.ts.map +1 -0
- package/dist/circuits/shape-group.d.ts +77 -0
- package/dist/circuits/shape-group.d.ts.map +1 -0
- package/dist/circuits/stream-inbox.d.ts +126 -0
- package/dist/circuits/stream-inbox.d.ts.map +1 -0
- package/dist/circuits/stream-source.d.ts +90 -0
- package/dist/circuits/stream-source.d.ts.map +1 -0
- package/dist/circuits/subscription-client.d.ts +143 -0
- package/dist/circuits/subscription-client.d.ts.map +1 -0
- package/dist/circuits/sync-engine.d.ts +131 -0
- package/dist/circuits/sync-engine.d.ts.map +1 -0
- package/dist/debug.d.ts +0 -10
- package/dist/debug.d.ts.map +1 -1
- package/dist/export-dump.d.ts.map +1 -1
- package/dist/index.d.ts +47 -19
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6258 -6443
- package/dist/index.js.map +26 -26
- package/dist/local-tables.d.ts +1 -1
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/sync/apply.d.ts +13 -21
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/copy.d.ts +8 -8
- package/dist/sync/fold.d.ts +40 -0
- package/dist/sync/fold.d.ts.map +1 -0
- package/dist/sync/metadata-tables.d.ts +25 -1
- package/dist/sync/metadata-tables.d.ts.map +1 -1
- package/dist/sync/subscription-state.d.ts +21 -2
- package/dist/sync/subscription-state.d.ts.map +1 -1
- package/dist/sync/types.d.ts +9 -129
- package/dist/sync/types.d.ts.map +1 -1
- package/dist/testing.js +3 -3
- package/dist/testing.js.map +2 -2
- package/dist/worker/attach-sync-client.d.ts +3 -1
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +17 -1
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/engine-control.d.ts +53 -0
- package/dist/worker/engine-control.d.ts.map +1 -1
- package/package.json +4 -5
- package/skills/core/SKILL.md +72 -55
- package/skills/operating/SKILL.md +120 -120
- package/src/boot-report.ts +4 -3
- package/src/circuits/envelope-to-change.ts +102 -0
- package/src/circuits/group-sync.ts +1047 -0
- package/src/circuits/shape-group.ts +158 -0
- package/src/circuits/stream-inbox.ts +225 -0
- package/src/circuits/stream-source.ts +165 -0
- package/src/circuits/subscription-client.ts +353 -0
- package/src/circuits/sync-engine.ts +641 -0
- package/src/debug.ts +1 -85
- package/src/export-dump.ts +3 -2
- package/src/index.ts +290 -273
- package/src/lazy-guard.ts +1 -1
- package/src/local-tables.ts +9 -2
- package/src/schema.ts +2 -11
- package/src/sync/apply.ts +72 -110
- package/src/sync/copy.ts +15 -15
- package/src/sync/fold.ts +94 -0
- package/src/sync/metadata-tables.ts +42 -1
- package/src/sync/subscription-state.ts +21 -3
- package/src/sync/types.ts +13 -141
- package/src/testing.ts +2 -2
- package/src/worker/attach-sync-client.ts +8 -1
- package/src/worker/define-sync-worker.ts +122 -13
- package/src/worker/engine-control.ts +89 -0
- package/dist/read-stream-stall.d.ts +0 -54
- package/dist/read-stream-stall.d.ts.map +0 -1
- package/dist/shape-sync.d.ts +0 -207
- package/dist/shape-sync.d.ts.map +0 -1
- package/dist/sync/index.d.ts +0 -32
- package/dist/sync/index.d.ts.map +0 -1
- package/dist/sync/nudge.d.ts +0 -49
- package/dist/sync/nudge.d.ts.map +0 -1
- package/dist/sync/shape-inbox.d.ts +0 -215
- package/dist/sync/shape-inbox.d.ts.map +0 -1
- package/dist/sync/tags.d.ts +0 -142
- package/dist/sync/tags.d.ts.map +0 -1
- package/dist/sync-auth.d.ts +0 -53
- package/dist/sync-auth.d.ts.map +0 -1
- package/src/read-stream-stall.ts +0 -102
- package/src/shape-sync.ts +0 -533
- package/src/sync/index.ts +0 -1124
- package/src/sync/nudge.ts +0 -110
- package/src/sync/shape-inbox.ts +0 -566
- package/src/sync/tags.ts +0 -390
- package/src/sync-auth.ts +0 -117
package/src/sync/shape-inbox.ts
DELETED
|
@@ -1,566 +0,0 @@
|
|
|
1
|
-
import type { ChangeMessage, MovePattern, Row } from "@electric-sql/client";
|
|
2
|
-
|
|
3
|
-
import type { InsertChangeMessage, Lsn } from "./types";
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* The Shape inbox (ADR-0014 / ISS-06): the pure, in-memory staging buffer between a shape's
|
|
7
|
-
* Electric subscription and the Sync applier. It buffers each shape's change messages keyed by
|
|
8
|
-
* LSN, tracks each shape's complete-LSN frontier, and drains everything up to a target LSN for the
|
|
9
|
-
* applier to write. No database I/O lives here — that is exactly what makes it (and the ADR-0014
|
|
10
|
-
* per-PK fold that will live here) property-testable against an ordered per-row apply oracle.
|
|
11
|
-
*
|
|
12
|
-
* One inbox owns all shapes in a consistency group; the group commits atomically at the lowest
|
|
13
|
-
* complete frontier across its shapes ({@link lowestCompleteLsn}). `must-refetch` truncation stays
|
|
14
|
-
* with the applier (the inbox only drops the affected shape's buffer via {@link resetShape}).
|
|
15
|
-
*
|
|
16
|
-
* COMMIT WATERMARK vs DEDUP FRONTIER (ADR-0031) — the load-bearing separation. Two per-shape LSNs live
|
|
17
|
-
* here and they are deliberately NOT the same number:
|
|
18
|
-
*
|
|
19
|
-
* - {@link completeLsns} — the SOLE dedup threshold. {@link ingestChange} drops any change at or below
|
|
20
|
-
* it as already-seen. Nothing else may narrow what the inbox accepts; a change below a shape's floor
|
|
21
|
-
* (below) but above its raw frontier is still buffered, never dropped.
|
|
22
|
-
* - {@link commitFloors} — a per-shape COMMIT watermark laid down once per catch-up completion (see
|
|
23
|
-
* {@link ingestUpToDate}'s alignment). It only ever RAISES a shape's effective commit frontier in
|
|
24
|
-
* {@link lowestCompleteLsn}; it never gates ingestion.
|
|
25
|
-
*
|
|
26
|
-
* Why the two must be separate: Electric's catch-up (non-live) shape responses are CDN-cacheable
|
|
27
|
-
* (`s-maxage`, `stale-while-revalidate`), and the `up-to-date` control message — with its
|
|
28
|
-
* `global_last_seen_lsn` watermark — rides INSIDE that cached body. So a quiet shape's cached catch-up
|
|
29
|
-
* can assert a STALE watermark (captured before a busy sibling shape's newer writes), which drags the
|
|
30
|
-
* group min-frontier below changes already delivered on the busy shape, holding them buffered until the
|
|
31
|
-
* quiet shape's first LIVE long-poll returns a fresh watermark (~tens of seconds on Electric Cloud). The
|
|
32
|
-
* alignment lifts the commit floors to the freshest ASSERTED global head so those changes commit at
|
|
33
|
-
* catch-up completion — while the dedup frontier stays put, so a late sub-floor change from a shape whose
|
|
34
|
-
* cached catch-up omitted it is still ingested and committed rather than dropped.
|
|
35
|
-
*/
|
|
36
|
-
export class ShapeInbox {
|
|
37
|
-
// Per shape: buffered change messages keyed by their LSN, kept in arrival order within an LSN.
|
|
38
|
-
private readonly changes = new Map<string, Map<Lsn, ChangeMessage<Row<unknown>>[]>>();
|
|
39
|
-
// Per shape: the highest LSN known complete (every change at or below it has been received).
|
|
40
|
-
private readonly completeLsns = new Map<string, Lsn>();
|
|
41
|
-
// Per shape: buffered `move-out` events (ADR-0023), one pattern set per event. The event carries no
|
|
42
|
-
// LSN, so it cannot key `changes`; it is drained and applied at the next commit (the `up-to-date`
|
|
43
|
-
// that follows it), in the same transaction as that frontier's changes.
|
|
44
|
-
private readonly moveOuts = new Map<string, MovePattern[][]>();
|
|
45
|
-
// Per shape: buffered `move-in` snapshot rows (ADR-0024). A move-in row (`is_move_in`) is a row
|
|
46
|
-
// ENTERING the shape; Electric delivers it as a snapshot insert with NO `lsn`/`last`, so it cannot
|
|
47
|
-
// key `changes` either (and the change dedup, which floors a missing lsn to 0, would drop it once the
|
|
48
|
-
// frontier passed 0). Drained and applied — idempotently — at the next commit, like the move-outs.
|
|
49
|
-
private readonly moveIns = new Map<string, ChangeMessage<Row<unknown>>[]>();
|
|
50
|
-
// Per shape: a reset epoch, bumped every time {@link resetShape} rewinds a shape (must-refetch). The
|
|
51
|
-
// commit path records each shape's epoch at PEEK time and passes it back to the acks; an ack no-ops for
|
|
52
|
-
// any shape whose epoch has since changed. This closes the mid-commit-reset hole: if a must-refetch +
|
|
53
|
-
// re-snapshot arrives for shape B WHILE a commit that peeked B is in flight, B's frontier is rewound and
|
|
54
|
-
// its buffers replaced with post-reset content; without the epoch guard the succeeding commit's
|
|
55
|
-
// `ackUpTo`/`ackMove*` would delete/splice that never-peeked post-reset content, leaving B truncated-empty.
|
|
56
|
-
private readonly epochs = new Map<string, number>();
|
|
57
|
-
// Per shape: whether a snapshot (LSN-0) row is currently accepted PAST the dedup frontier. Set on
|
|
58
|
-
// registration and every {@link resetShape} (must-refetch); re-armed (cleared) the first time a change
|
|
59
|
-
// with a REAL lsn (> 0) is ingested for the shape. Invariant: after a reset — and on a brand-new shape
|
|
60
|
-
// before any real replication LSN has been seen — a re-snapshot's rows are floored to LSN 0, yet the
|
|
61
|
-
// frontier may already sit at a large LSN (a racing bare `up-to-date` advanced it before the rows
|
|
62
|
-
// landed). The LSN-0 dedup ({@link ingestChange}) would then drop the whole re-snapshot. So while this
|
|
63
|
-
// flag is set, LSN-0 rows bypass the dedup; the first real lsn (> 0) proves the stream has moved past
|
|
64
|
-
// the snapshot into the live tail, and re-arms the dedup. The re-snapshot's rows reaching the applier
|
|
65
|
-
// is what keeps the reconcile loop — the completeness guarantee (ADR-0029 D4) — whole.
|
|
66
|
-
private readonly snapshotAccepted = new Map<string, boolean>();
|
|
67
|
-
// Per shape: whether this shape has reported `up-to-date` at least once since registration / its last
|
|
68
|
-
// {@link resetShape}. Set true in {@link ingestUpToDate} even when the reported watermark does NOT
|
|
69
|
-
// advance the frontier (a stale cached watermark still means "this shape has completed a catch-up and
|
|
70
|
-
// asserted a global head"). The catch-up alignment (ADR-0031) fires only once EVERY shape in the group
|
|
71
|
-
// has reported up-to-date — i.e. once the whole group has a first asserted global head to align to.
|
|
72
|
-
private readonly upToDateSeen = new Map<string, boolean>();
|
|
73
|
-
// Per shape: the watermark (`global_last_seen_lsn`) this shape MOST RECENTLY reported via
|
|
74
|
-
// {@link ingestUpToDate}, recorded unconditionally — even a stale cached watermark that does not
|
|
75
|
-
// advance {@link completeLsns}. This is the input to the group-max alignment: the freshest asserted
|
|
76
|
-
// global head across the group is `max` over these REPORTED watermarks (NOT over the frontiers — a
|
|
77
|
-
// frontier can sit ahead of every reported watermark mid-live-batch; see {@link ingestUpToDate}).
|
|
78
|
-
private readonly lastUpToDateLsn = new Map<string, Lsn>();
|
|
79
|
-
// Per shape: the COMMIT floor (ADR-0031) — a watermark that only ever RAISES this shape's effective
|
|
80
|
-
// commit frontier in {@link lowestCompleteLsn}, never its dedup threshold. Laid down once per catch-up
|
|
81
|
-
// completion by the alignment in {@link ingestUpToDate}. Deliberately NOT reset by {@link resetShape}:
|
|
82
|
-
// floors are monotonic, so a reset shape keeps its old floor (its buffer is empty anyway) until the
|
|
83
|
-
// next group-wide realignment lifts it. Default -1 = no floor.
|
|
84
|
-
private readonly commitFloors = new Map<string, Lsn>();
|
|
85
|
-
// Whether the one-time catch-up commit-floor alignment (ADR-0031) has already run for the current
|
|
86
|
-
// registration/reset generation. False at construction; set true when the alignment lays down floors in
|
|
87
|
-
// {@link ingestUpToDate}; reset to false by {@link resetShape} so a must-refetch re-catch-up realigns
|
|
88
|
-
// the group once every shape has completed again (a reset shape re-streams a fresh — possibly cached —
|
|
89
|
-
// catch-up, so the group needs a fresh asserted global head to align to).
|
|
90
|
-
private aligned = false;
|
|
91
|
-
// The freshest asserted global head the last alignment aligned to (`max` over reported watermarks) —
|
|
92
|
-
// surfaced on the debug rail by the caller as the `floor` of the `catch-up watermark aligned` line.
|
|
93
|
-
private lastAlignedFloor: Lsn = BigInt(-1);
|
|
94
|
-
|
|
95
|
-
constructor(shapeNames: Iterable<string>) {
|
|
96
|
-
for (const shapeName of shapeNames) {
|
|
97
|
-
this.changes.set(shapeName, new Map());
|
|
98
|
-
this.completeLsns.set(shapeName, BigInt(-1));
|
|
99
|
-
this.moveOuts.set(shapeName, []);
|
|
100
|
-
this.moveIns.set(shapeName, []);
|
|
101
|
-
this.epochs.set(shapeName, 0);
|
|
102
|
-
this.snapshotAccepted.set(shapeName, true);
|
|
103
|
-
this.upToDateSeen.set(shapeName, false);
|
|
104
|
-
this.lastUpToDateLsn.set(shapeName, BigInt(-1));
|
|
105
|
-
this.commitFloors.set(shapeName, BigInt(-1));
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
/**
|
|
110
|
-
* Whether the shape is still accepting snapshot (LSN-0) rows past the dedup frontier — true from
|
|
111
|
-
* registration / the last {@link resetShape} until the first real-lsn change re-armed the dedup. The
|
|
112
|
-
* commit path reads this to apply such rows idempotently (the racing recovery loops can double-deliver
|
|
113
|
-
* them), consistent with the move-in upsert path, rather than as a plain collision-surfacing insert.
|
|
114
|
-
*/
|
|
115
|
-
acceptsSnapshotRowsFor(shapeName: string): boolean {
|
|
116
|
-
return this.snapshotAccepted.get(shapeName) === true;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
/** The complete-LSN frontier for one shape (the already-seen dedup threshold). */
|
|
120
|
-
completeLsnFor(shapeName: string): Lsn {
|
|
121
|
-
return this.completeLsns.get(shapeName) ?? BigInt(-1);
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* The shape's current reset epoch. The commit path snapshots this for every peeked shape and passes it
|
|
126
|
-
* back to the acks, which no-op for any shape whose epoch changed (a mid-commit {@link resetShape}) so
|
|
127
|
-
* the reset's own truncate+rebuild path owns that shape's post-reset state.
|
|
128
|
-
*/
|
|
129
|
-
epochFor(shapeName: string): number {
|
|
130
|
-
return this.epochs.get(shapeName) ?? 0;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
* Buffer a change message. A message at or below the shape's current complete frontier is
|
|
135
|
-
* already-seen and dropped. `isLastOfLsn` advances the frontier to this LSN.
|
|
136
|
-
*/
|
|
137
|
-
ingestChange(shapeName: string, message: ChangeMessage<Row<unknown>>, lsn: Lsn, isLastOfLsn: boolean): void {
|
|
138
|
-
// A real replication lsn (> 0) proves the stream has moved past the snapshot into the live tail:
|
|
139
|
-
// re-arm the LSN-0 dedup for this shape (see {@link snapshotAccepted}).
|
|
140
|
-
if (lsn > BigInt(0)) {
|
|
141
|
-
this.snapshotAccepted.set(shapeName, false);
|
|
142
|
-
}
|
|
143
|
-
// A snapshot (LSN-0) row while snapshot acceptance is open bypasses the dedup even if the frontier
|
|
144
|
-
// has advanced past 0 — otherwise a re-snapshot delivered AFTER a racing `up-to-date` (which pushed
|
|
145
|
-
// the frontier to a large LSN) would be dropped wholesale, truncating the shape to empty. It still
|
|
146
|
-
// buffers at LSN 0 (and does not advance the frontier), so drains/acks/truncate are unchanged.
|
|
147
|
-
const acceptSnapshotRow = lsn === BigInt(0) && this.acceptsSnapshotRowsFor(shapeName);
|
|
148
|
-
if (!acceptSnapshotRow && lsn <= this.completeLsnFor(shapeName)) {
|
|
149
|
-
return;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
const shapeChanges = this.changes.get(shapeName);
|
|
153
|
-
if (!shapeChanges) {
|
|
154
|
-
return;
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
let lsnMessages = shapeChanges.get(lsn);
|
|
158
|
-
if (!lsnMessages) {
|
|
159
|
-
lsnMessages = [];
|
|
160
|
-
shapeChanges.set(lsn, lsnMessages);
|
|
161
|
-
}
|
|
162
|
-
lsnMessages.push(message);
|
|
163
|
-
|
|
164
|
-
if (isLastOfLsn) {
|
|
165
|
-
this.completeLsns.set(shapeName, lsn);
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
/** The commit floor (ADR-0031) for one shape — the aligned watermark; -1 when no floor has been laid. */
|
|
170
|
-
commitFloorFor(shapeName: string): Lsn {
|
|
171
|
-
return this.commitFloors.get(shapeName) ?? BigInt(-1);
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
/**
|
|
175
|
-
* A shape's EFFECTIVE complete frontier (ADR-0031): `max(completeLsnFor(shape), commitFloorFor(shape))` —
|
|
176
|
-
* the raw dedup frontier raised by any aligned commit floor. This is the exact per-shape quantity
|
|
177
|
-
* {@link lowestCompleteLsn} minimizes over (both go through here, so the two definitions cannot drift),
|
|
178
|
-
* and the input the live-tail sibling nudge reads to decide which siblings still lag a target LSN.
|
|
179
|
-
*/
|
|
180
|
-
effectiveLsnFor(shapeName: string): Lsn {
|
|
181
|
-
const raw = this.completeLsnFor(shapeName);
|
|
182
|
-
const floor = this.commitFloorFor(shapeName);
|
|
183
|
-
return raw > floor ? raw : floor;
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
/**
|
|
187
|
-
* Whether this shape has reported `up-to-date` at least once since registration / its last
|
|
188
|
-
* {@link resetShape} — the {@link upToDateSeen} flag. The live-tail sibling nudge (ADR-0031) reads this:
|
|
189
|
-
* a shape still catching up advances on its own, so only a shape already in its live tail is ever nudged.
|
|
190
|
-
*/
|
|
191
|
-
hasReportedUpToDate(shapeName: string): boolean {
|
|
192
|
-
return this.upToDateSeen.get(shapeName) === true;
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
/** The freshest asserted global head the last catch-up alignment aligned to (ADR-0031); -1 if never aligned. */
|
|
196
|
-
alignedFloor(): Lsn {
|
|
197
|
-
return this.lastAlignedFloor;
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
/**
|
|
201
|
-
* Advance the frontier on an `up-to-date` control message (carries no buffered change) AND run the
|
|
202
|
-
* one-time catch-up commit-floor alignment (ADR-0031) once the whole group has reported up-to-date.
|
|
203
|
-
*
|
|
204
|
-
* Returns `true` iff THIS call performed the alignment (the caller emits a single diagnostic line on
|
|
205
|
-
* that transition); `false` on every other call.
|
|
206
|
-
*/
|
|
207
|
-
ingestUpToDate(shapeName: string, globalLastSeenLsn: Lsn): boolean {
|
|
208
|
-
// Record the report unconditionally: this shape has now completed a catch-up and asserted a global
|
|
209
|
-
// head, and this is the watermark to align to — even if it is stale (below the frontier) and so does
|
|
210
|
-
// NOT advance the dedup frontier below. Both facts feed the alignment; neither is the frontier.
|
|
211
|
-
this.upToDateSeen.set(shapeName, true);
|
|
212
|
-
this.lastUpToDateLsn.set(shapeName, globalLastSeenLsn);
|
|
213
|
-
|
|
214
|
-
// The existing conditional frontier advance is UNCHANGED: a watermark only advances the dedup frontier
|
|
215
|
-
// when it is strictly ahead of it. A stale cached watermark leaves the frontier where it was.
|
|
216
|
-
if (globalLastSeenLsn > this.completeLsnFor(shapeName)) {
|
|
217
|
-
this.completeLsns.set(shapeName, globalLastSeenLsn);
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
// Catch-up commit-floor alignment (ADR-0031), one-time per registration/reset generation: once EVERY
|
|
221
|
-
// shape in the group has reported up-to-date, lift each shape's commit floor to the freshest asserted
|
|
222
|
-
// global head. That is `max` over the REPORTED watermarks ({@link lastUpToDateLsn}) — deliberately NOT
|
|
223
|
-
// over the frontiers ({@link completeLsns}). A frontier can be ahead of every reported watermark when a
|
|
224
|
-
// live change batch is in flight and its sibling shapes' halves have not arrived yet; aligning floors
|
|
225
|
-
// to such a frontier would commit one shape's half of a cross-shape transaction ahead of the other's
|
|
226
|
-
// (a torn write). The freshest asserted global head is a watermark every shape has been told is
|
|
227
|
-
// complete, so aligning to it can never tear a transaction that is still assembling above it.
|
|
228
|
-
if (!this.aligned) {
|
|
229
|
-
let everySeen = true;
|
|
230
|
-
for (const seen of this.upToDateSeen.values()) {
|
|
231
|
-
if (!seen) {
|
|
232
|
-
everySeen = false;
|
|
233
|
-
break;
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
if (everySeen) {
|
|
237
|
-
let groupMax: Lsn = BigInt(-1);
|
|
238
|
-
for (const reported of this.lastUpToDateLsn.values()) {
|
|
239
|
-
if (reported > groupMax) {
|
|
240
|
-
groupMax = reported;
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
for (const shape of this.commitFloors.keys()) {
|
|
244
|
-
const existing = this.commitFloorFor(shape);
|
|
245
|
-
this.commitFloors.set(shape, groupMax > existing ? groupMax : existing);
|
|
246
|
-
}
|
|
247
|
-
this.aligned = true;
|
|
248
|
-
this.lastAlignedFloor = groupMax;
|
|
249
|
-
return true;
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
return false;
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
/** Buffer a `move-out` event's patterns for a shape (ADR-0023); applied at the next commit. */
|
|
256
|
-
ingestMoveOut(shapeName: string, patterns: MovePattern[]): void {
|
|
257
|
-
this.moveOuts.get(shapeName)?.push(patterns);
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
/** Remove and return a shape's buffered `move-out` pattern sets (one per event), in arrival order. */
|
|
261
|
-
drainMoveOuts(shapeName: string): MovePattern[][] {
|
|
262
|
-
const pending = this.moveOuts.get(shapeName) ?? [];
|
|
263
|
-
this.moveOuts.set(shapeName, []);
|
|
264
|
-
return pending;
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
/**
|
|
268
|
-
* Peek — WITHOUT removing — a shape's buffered `move-out` pattern sets (a copy, arrival order). Pairs
|
|
269
|
-
* with {@link ackMoveOuts}: the commit path peeks, applies inside its transaction, and acks (removes)
|
|
270
|
-
* only after the transaction succeeds — so a failed/degraded commit (ADR-0009 decision 5) leaves the
|
|
271
|
-
* revocations buffered rather than silently losing them.
|
|
272
|
-
*/
|
|
273
|
-
peekMoveOuts(shapeName: string): MovePattern[][] {
|
|
274
|
-
return [...(this.moveOuts.get(shapeName) ?? [])];
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
/**
|
|
278
|
-
* Remove the first `count` buffered `move-out` pattern sets for a shape (call only after the commit
|
|
279
|
-
* that consumed a matching {@link peekMoveOuts} of that many entries succeeded). Removing exactly the
|
|
280
|
-
* peeked count — not clear-all — keeps any move-out that arrived DURING the commit (coalescing path)
|
|
281
|
-
* buffered for the next run. `epochAtPeek` is the shape's {@link epochFor} captured at peek time: if a
|
|
282
|
-
* {@link resetShape} bumped it since, the peeked entries no longer exist (the array was replaced), so
|
|
283
|
-
* this no-ops rather than splicing the post-reset replacement.
|
|
284
|
-
*/
|
|
285
|
-
ackMoveOuts(shapeName: string, count: number, epochAtPeek: number): void {
|
|
286
|
-
if (this.epochFor(shapeName) !== epochAtPeek) {
|
|
287
|
-
return;
|
|
288
|
-
}
|
|
289
|
-
this.moveOuts.get(shapeName)?.splice(0, count);
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
/** Whether any shape has a buffered `move-out` awaiting a commit. */
|
|
293
|
-
hasPendingMoveOuts(): boolean {
|
|
294
|
-
for (const pending of this.moveOuts.values()) {
|
|
295
|
-
if (pending.length > 0) return true;
|
|
296
|
-
}
|
|
297
|
-
return false;
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
/** Buffer a `move-in` snapshot row for a shape (ADR-0024); applied idempotently at the next commit. */
|
|
301
|
-
ingestMoveIn(shapeName: string, message: ChangeMessage<Row<unknown>>): void {
|
|
302
|
-
this.moveIns.get(shapeName)?.push(message);
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
/** Remove and return a shape's buffered `move-in` snapshot rows, in arrival order. */
|
|
306
|
-
drainMoveIns(shapeName: string): ChangeMessage<Row<unknown>>[] {
|
|
307
|
-
const pending = this.moveIns.get(shapeName) ?? [];
|
|
308
|
-
this.moveIns.set(shapeName, []);
|
|
309
|
-
return pending;
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
/** Peek — WITHOUT removing — a shape's buffered `move-in` snapshot rows (a copy, arrival order). See {@link peekMoveOuts}. */
|
|
313
|
-
peekMoveIns(shapeName: string): ChangeMessage<Row<unknown>>[] {
|
|
314
|
-
return [...(this.moveIns.get(shapeName) ?? [])];
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
/**
|
|
318
|
-
* Remove the first `count` buffered `move-in` snapshot rows for a shape (post-commit ack; see
|
|
319
|
-
* {@link ackMoveOuts}). No-ops if `epochAtPeek` no longer matches the shape's current epoch (a
|
|
320
|
-
* mid-commit {@link resetShape}), so the post-reset replacement rows survive.
|
|
321
|
-
*/
|
|
322
|
-
ackMoveIns(shapeName: string, count: number, epochAtPeek: number): void {
|
|
323
|
-
if (this.epochFor(shapeName) !== epochAtPeek) {
|
|
324
|
-
return;
|
|
325
|
-
}
|
|
326
|
-
this.moveIns.get(shapeName)?.splice(0, count);
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
/** Whether any shape has a buffered `move-in` awaiting a commit. */
|
|
330
|
-
hasPendingMoveIns(): boolean {
|
|
331
|
-
for (const pending of this.moveIns.values()) {
|
|
332
|
-
if (pending.length > 0) return true;
|
|
333
|
-
}
|
|
334
|
-
return false;
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
/** Reset a shape on `must-refetch`: drop its buffer and rewind its frontier (the applier truncates). */
|
|
338
|
-
resetShape(shapeName: string): void {
|
|
339
|
-
this.changes.get(shapeName)?.clear();
|
|
340
|
-
this.completeLsns.set(shapeName, BigInt(-1));
|
|
341
|
-
this.moveOuts.set(shapeName, []);
|
|
342
|
-
this.moveIns.set(shapeName, []);
|
|
343
|
-
// Re-open snapshot acceptance: the re-snapshot's LSN-0 rows must survive the dedup even if a racing
|
|
344
|
-
// `up-to-date` advances the rewound frontier again before they arrive (see {@link snapshotAccepted}).
|
|
345
|
-
this.snapshotAccepted.set(shapeName, true);
|
|
346
|
-
// ADR-0031: this shape must re-report up-to-date before it counts toward the group again, and its
|
|
347
|
-
// last reported watermark is void (it re-streams a fresh — possibly cached — catch-up). Clear the
|
|
348
|
-
// group's aligned flag so the whole group realigns once every shape has completed again. The commit
|
|
349
|
-
// floor is NOT cleared: floors are monotonic (the buffer is empty post-reset anyway), so the shape
|
|
350
|
-
// keeps its old floor until realignment lifts it.
|
|
351
|
-
this.upToDateSeen.set(shapeName, false);
|
|
352
|
-
this.lastUpToDateLsn.set(shapeName, BigInt(-1));
|
|
353
|
-
this.aligned = false;
|
|
354
|
-
// Bump the epoch so any in-flight commit that peeked this shape BEFORE the reset skips its acks — the
|
|
355
|
-
// post-reset buffers just installed above must survive to be committed on the follow-up pass.
|
|
356
|
-
this.epochs.set(shapeName, this.epochFor(shapeName) + 1);
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
/**
|
|
360
|
-
* The lowest EFFECTIVE complete frontier across all shapes — the atomic group commit target. A shape's
|
|
361
|
-
* effective frontier is `max(completeLsnFor(shape), commitFloorFor(shape))` (ADR-0031): the raw dedup
|
|
362
|
-
* frontier, raised by any aligned commit floor. Aligning the floors up to the freshest asserted global
|
|
363
|
-
* head lets a group whose quiet shapes reported a STALE cached catch-up watermark still commit a busy
|
|
364
|
-
* shape's delivered changes at catch-up completion, instead of holding them until the quiet shapes'
|
|
365
|
-
* first live long-poll. The floor never narrows what {@link ingestChange} accepts (that remains the raw
|
|
366
|
-
* {@link completeLsns}), so a late sub-floor change is still ingested and then committed.
|
|
367
|
-
*/
|
|
368
|
-
lowestCompleteLsn(): Lsn {
|
|
369
|
-
let minimum: Lsn | null = null;
|
|
370
|
-
for (const shapeName of this.completeLsns.keys()) {
|
|
371
|
-
const effective = this.effectiveLsnFor(shapeName);
|
|
372
|
-
if (minimum === null || effective < minimum) {
|
|
373
|
-
minimum = effective;
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
return minimum ?? BigInt(-1);
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
/**
|
|
380
|
-
* Whether any shape has a buffered change entry at an LSN at or below `targetLsn` (ADR-0031). The commit
|
|
381
|
-
* loop uses this to fire a commit for a LATE-arriving change that lands at or below an already-committed
|
|
382
|
-
* target — possible exactly because the aligned commit floor lets {@link ingestChange} accept a change
|
|
383
|
-
* below the floor while the group frontier already sits at (or above) it, so no new frontier advance
|
|
384
|
-
* would otherwise trigger a commit for it.
|
|
385
|
-
*/
|
|
386
|
-
hasBufferedChangesAtOrBelow(targetLsn: Lsn): boolean {
|
|
387
|
-
for (const shapeChanges of this.changes.values()) {
|
|
388
|
-
for (const lsn of shapeChanges.keys()) {
|
|
389
|
-
if (lsn <= targetLsn) {
|
|
390
|
-
return true;
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
return false;
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
/**
|
|
398
|
-
* Peek — WITHOUT removing — every buffered change at or below `targetLsn`, per shape, in buffered-LSN
|
|
399
|
-
* order. The returned map has an entry for every shape (an empty array where nothing peeked). Pairs
|
|
400
|
-
* with {@link ackUpTo}: the commit path peeks, writes the batch inside its transaction, and acks
|
|
401
|
-
* (removes) only after the transaction succeeds — so a failed/degraded commit (ADR-0009 decision 5)
|
|
402
|
-
* holds the batch in the buffer rather than dropping it, and a newer LSN can never land over it.
|
|
403
|
-
*/
|
|
404
|
-
peekUpTo(targetLsn: Lsn): Map<string, ChangeMessage<Row<unknown>>[]> {
|
|
405
|
-
const peeked = new Map<string, ChangeMessage<Row<unknown>>[]>();
|
|
406
|
-
|
|
407
|
-
for (const [shapeName, shapeChanges] of this.changes.entries()) {
|
|
408
|
-
const messages: ChangeMessage<Row<unknown>>[] = [];
|
|
409
|
-
for (const lsn of [...shapeChanges.keys()]) {
|
|
410
|
-
if (lsn <= targetLsn) {
|
|
411
|
-
for (const message of shapeChanges.get(lsn)!) {
|
|
412
|
-
messages.push(message);
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
peeked.set(shapeName, messages);
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
return peeked;
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
/**
|
|
423
|
-
* Remove every buffered change at or below `targetLsn` (call only after the commit that consumed a
|
|
424
|
-
* matching {@link peekUpTo} succeeded). `epochsAtPeek` maps each shape to its {@link epochFor} captured
|
|
425
|
-
* at peek time; a shape whose epoch has since changed is **skipped entirely**.
|
|
426
|
-
*
|
|
427
|
-
* The epoch guard is load-bearing under a frontier REWIND. In the steady state, the frontier only
|
|
428
|
-
* advances, so nothing new at or below `targetLsn` can be buffered between peek and ack. But a mid-commit
|
|
429
|
-
* {@link resetShape} (must-refetch) rewinds a shape's frontier to -1 and lets its re-snapshot buffer at
|
|
430
|
-
* LSN 0 — content that was NOT in this commit's peek. Deleting it here (LSN 0 ≤ `targetLsn`) would drop
|
|
431
|
-
* the rebuild; the epoch bump makes this no-op for that shape so the reset's own rebuild path owns it.
|
|
432
|
-
*/
|
|
433
|
-
ackUpTo(targetLsn: Lsn, epochsAtPeek: Map<string, number>): void {
|
|
434
|
-
for (const [shapeName, shapeChanges] of this.changes.entries()) {
|
|
435
|
-
const peekEpoch = epochsAtPeek.get(shapeName);
|
|
436
|
-
if (peekEpoch !== undefined && this.epochFor(shapeName) !== peekEpoch) {
|
|
437
|
-
continue;
|
|
438
|
-
}
|
|
439
|
-
for (const lsn of [...shapeChanges.keys()]) {
|
|
440
|
-
if (lsn <= targetLsn) {
|
|
441
|
-
shapeChanges.delete(lsn);
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
/** Snapshot every shape's current {@link epochFor} — captured at peek time and passed to the acks. */
|
|
448
|
-
snapshotEpochs(): Map<string, number> {
|
|
449
|
-
return new Map([...this.epochs.keys()].map((shapeName) => [shapeName, this.epochFor(shapeName)]));
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
/**
|
|
453
|
-
* Remove and return every buffered change at or below `targetLsn`, per shape, in buffered-LSN order
|
|
454
|
-
* ({@link peekUpTo} then {@link ackUpTo}). The returned map has an entry for every shape (an empty
|
|
455
|
-
* array where nothing drained).
|
|
456
|
-
*/
|
|
457
|
-
drainUpTo(targetLsn: Lsn): Map<string, ChangeMessage<Row<unknown>>[]> {
|
|
458
|
-
const epochsAtPeek = this.snapshotEpochs();
|
|
459
|
-
const drained = this.peekUpTo(targetLsn);
|
|
460
|
-
this.ackUpTo(targetLsn, epochsAtPeek);
|
|
461
|
-
return drained;
|
|
462
|
-
}
|
|
463
|
-
}
|
|
464
|
-
|
|
465
|
-
type Operation = "insert" | "update" | "delete";
|
|
466
|
-
|
|
467
|
-
/**
|
|
468
|
-
* A drained shape batch folded to **one net operation per primary key** (ADR-0014 decision 1).
|
|
469
|
-
* Each PK appears in at most one of `inserts`/`updates`, and at most once in `deletes` — except a
|
|
470
|
-
* *re-created* PK (`[delete, insert]`), which appears in both `deletes` and `inserts` so the bulk
|
|
471
|
-
* apply clears the pre-existing row before inserting the new one. The Sync applier therefore runs
|
|
472
|
-
* three bulk statements **in the order `deletes → inserts → updates`** (Phase 3): that ordering is
|
|
473
|
-
* what makes a re-create safe, and every other PK is touched by exactly one statement, so the rest
|
|
474
|
-
* of the order is irrelevant within the atomic commit.
|
|
475
|
-
*/
|
|
476
|
-
export interface FoldedShapeBatch {
|
|
477
|
-
/** PKs to delete — net-`delete` keys, plus the clearing delete of each re-created key. */
|
|
478
|
-
deletes: ChangeMessage<Row<unknown>>[];
|
|
479
|
-
/** Full rows to insert — net-`insert` keys, plus each re-created key's new row (merged values). */
|
|
480
|
-
inserts: InsertChangeMessage[];
|
|
481
|
-
/** Merged partial updates — net-`update` keys (carry the PK plus the union of updated columns). */
|
|
482
|
-
updates: ChangeMessage<Row<unknown>>[];
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
/** Clone a representative message, overriding its row value and operation (headers like LSN are kept). */
|
|
486
|
-
function withValue(
|
|
487
|
-
template: ChangeMessage<Row<unknown>>,
|
|
488
|
-
value: Row<unknown>,
|
|
489
|
-
operation: Operation,
|
|
490
|
-
): ChangeMessage<Row<unknown>> {
|
|
491
|
-
return { ...template, value, headers: { ...template.headers, operation } };
|
|
492
|
-
}
|
|
493
|
-
|
|
494
|
-
/** Shallow-merge the row values of an ordered op segment, last-write-wins per column. */
|
|
495
|
-
function mergeValues(segment: ChangeMessage<Row<unknown>>[]): Row<unknown> {
|
|
496
|
-
return Object.assign({}, ...segment.map((message) => message.value)) as Row<unknown>;
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
/**
|
|
500
|
-
* Fold a drained shape batch (ordered by LSN, one shape) to one net operation per primary key
|
|
501
|
-
* (ADR-0014 decision 1), so the read path can bulk-apply without the `UPDATE … FROM` / `INSERT …
|
|
502
|
-
* SELECT json_to_recordset(…)` same-PK join hazard (those use **one arbitrary** matching row when
|
|
503
|
-
* the source holds duplicate PKs). Each PK's ops are replayed in LSN order down to:
|
|
504
|
-
*
|
|
505
|
-
* - **trailing `delete`** ⇒ a single DELETE;
|
|
506
|
-
* - **`insert` with no preceding delete**, then any updates ⇒ a single INSERT with merged values
|
|
507
|
-
* (a *plain* insert — a genuine PK collision still surfaces, never a silent upsert);
|
|
508
|
-
* - **only `update`s** ⇒ a single UPDATE with merged values;
|
|
509
|
-
* - **re-created** (`[delete, … , insert, …]`, no trailing delete) ⇒ DELETE **and** INSERT, so the
|
|
510
|
-
* pre-existing row is cleared first (faithful to the per-row `DELETE`-then-`INSERT`; a plain INSERT
|
|
511
|
-
* would collide with the row the dropped delete was meant to remove);
|
|
512
|
-
* - **`update` after a delete** (`[delete, update]` and kin) is malformed for a faithful stream
|
|
513
|
-
* (an update asserts the row exists) ⇒ throw, surfacing stream corruption rather than silently
|
|
514
|
-
* dropping it.
|
|
515
|
-
*
|
|
516
|
-
* Pure and dependency-free by design (ADR-0014 / ISS-06): property-tested against the oracle
|
|
517
|
-
* *fold-then-bulk ≡ ordered per-row apply* over random same-PK sequences and random initial state.
|
|
518
|
-
*/
|
|
519
|
-
export function foldChangeBatch(messages: ChangeMessage<Row<unknown>>[]): FoldedShapeBatch {
|
|
520
|
-
const groups = new Map<string, ChangeMessage<Row<unknown>>[]>();
|
|
521
|
-
for (const message of messages) {
|
|
522
|
-
let group = groups.get(message.key);
|
|
523
|
-
if (!group) {
|
|
524
|
-
group = [];
|
|
525
|
-
groups.set(message.key, group);
|
|
526
|
-
}
|
|
527
|
-
group.push(message);
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
const folded: FoldedShapeBatch = { deletes: [], inserts: [], updates: [] };
|
|
531
|
-
for (const [key, ops] of groups) {
|
|
532
|
-
foldKey(key, ops, folded);
|
|
533
|
-
}
|
|
534
|
-
return folded;
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
function foldKey(key: string, ops: ChangeMessage<Row<unknown>>[], folded: FoldedShapeBatch): void {
|
|
538
|
-
const lastDeleteIndex = ops.findLastIndex((message) => message.headers.operation === "delete");
|
|
539
|
-
|
|
540
|
-
// A trailing delete is the net effect regardless of anything before it; emit one DELETE.
|
|
541
|
-
if (lastDeleteIndex === ops.length - 1) {
|
|
542
|
-
folded.deletes.push(ops[lastDeleteIndex]!);
|
|
543
|
-
return;
|
|
544
|
-
}
|
|
545
|
-
|
|
546
|
-
// The net is decided by the segment after the last delete (or the whole sequence if none).
|
|
547
|
-
const segment = ops.slice(lastDeleteIndex + 1);
|
|
548
|
-
const merged = mergeValues(segment);
|
|
549
|
-
const template = segment[segment.length - 1]!;
|
|
550
|
-
const startsWithInsert = segment[0]!.headers.operation === "insert";
|
|
551
|
-
const hadDelete = lastDeleteIndex >= 0;
|
|
552
|
-
|
|
553
|
-
if (startsWithInsert) {
|
|
554
|
-
if (hadDelete) {
|
|
555
|
-
// Re-created: clear the pre-existing row, then insert the new one (DELETE before INSERT).
|
|
556
|
-
folded.deletes.push(ops[lastDeleteIndex]!);
|
|
557
|
-
}
|
|
558
|
-
folded.inserts.push(withValue(template, merged, "insert") as InsertChangeMessage);
|
|
559
|
-
return;
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
if (hadDelete) {
|
|
563
|
-
throw new Error(`foldChangeBatch: malformed batch — update after delete for key ${JSON.stringify(key)}`);
|
|
564
|
-
}
|
|
565
|
-
folded.updates.push(withValue(template, merged, "update"));
|
|
566
|
-
}
|