@reventlessdev/reventless-postgres 3.0.0-alpha.3 → 3.0.0-alpha.4

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.
Files changed (66) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/lib/bs/.compiler.log +2 -2
  3. package/lib/bs/ReventlessPostgres.cmi +0 -0
  4. package/lib/bs/ReventlessPostgres.cmt +0 -0
  5. package/lib/bs/ReventlessPostgres.mlmap +1 -0
  6. package/lib/bs/compiler-info.json +1 -1
  7. package/lib/bs/src/DcbEventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
  8. package/lib/bs/src/DcbEventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
  9. package/lib/bs/src/EventLogChangeFeed-ReventlessPostgres.cmi +0 -0
  10. package/lib/bs/src/EventLogChangeFeed-ReventlessPostgres.cmj +0 -0
  11. package/lib/bs/src/EventLogChangeFeed-ReventlessPostgres.cmt +0 -0
  12. package/lib/bs/src/EventLogChangeFeed.ast +0 -0
  13. package/lib/bs/src/EventLogChangeFeed.res +184 -0
  14. package/lib/bs/src/EventLogChangeFeed.res.mjs +134 -0
  15. package/lib/bs/src/EventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
  16. package/lib/bs/src/EventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
  17. package/lib/bs/src/PgChangeFeed-ReventlessPostgres.cmi +0 -0
  18. package/lib/bs/src/PgChangeFeed-ReventlessPostgres.cmt +0 -0
  19. package/lib/bs/src/PgSchema-ReventlessPostgres.cmi +0 -0
  20. package/lib/bs/src/PgSchema-ReventlessPostgres.cmt +0 -0
  21. package/lib/bs/src/PgSchema.ast +0 -0
  22. package/lib/bs/src/PgSchema.res +36 -2
  23. package/lib/bs/src/PgSchema.res.mjs +9 -2
  24. package/lib/bs/src/QueryDbStorage_Postgres-ReventlessPostgres.cmi +0 -0
  25. package/lib/bs/src/QueryDbStorage_Postgres-ReventlessPostgres.cmt +0 -0
  26. package/lib/bs/src/QueryEnginePostgres-ReventlessPostgres.cmi +0 -0
  27. package/lib/bs/src/QueryEnginePostgres-ReventlessPostgres.cmt +0 -0
  28. package/lib/bs/tests/PostgresIntegrationTest-ReventlessPostgres.cmi +0 -0
  29. package/lib/bs/tests/PostgresIntegrationTest-ReventlessPostgres.cmt +0 -0
  30. package/lib/bs/tests/PostgresIntegrationTest.ast +0 -0
  31. package/lib/bs/tests/PostgresIntegrationTest.res +68 -0
  32. package/lib/bs/tests/PostgresIntegrationTest.res.mjs +49 -0
  33. package/lib/ocaml/.compiler.log +2 -2
  34. package/lib/ocaml/DcbEventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
  35. package/lib/ocaml/DcbEventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
  36. package/lib/ocaml/EventLogChangeFeed-ReventlessPostgres.cmi +0 -0
  37. package/lib/ocaml/EventLogChangeFeed-ReventlessPostgres.cmj +0 -0
  38. package/lib/ocaml/EventLogChangeFeed-ReventlessPostgres.cmt +0 -0
  39. package/lib/ocaml/EventLogChangeFeed.ast +0 -0
  40. package/lib/ocaml/EventLogChangeFeed.res +184 -0
  41. package/lib/ocaml/EventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
  42. package/lib/ocaml/EventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
  43. package/lib/ocaml/PgChangeFeed-ReventlessPostgres.cmi +0 -0
  44. package/lib/ocaml/PgChangeFeed-ReventlessPostgres.cmt +0 -0
  45. package/lib/ocaml/PgSchema-ReventlessPostgres.cmi +0 -0
  46. package/lib/ocaml/PgSchema-ReventlessPostgres.cmt +0 -0
  47. package/lib/ocaml/PgSchema.ast +0 -0
  48. package/lib/ocaml/PgSchema.res +36 -2
  49. package/lib/ocaml/PostgresIntegrationTest-ReventlessPostgres.cmi +0 -0
  50. package/lib/ocaml/PostgresIntegrationTest-ReventlessPostgres.cmt +0 -0
  51. package/lib/ocaml/PostgresIntegrationTest.ast +0 -0
  52. package/lib/ocaml/PostgresIntegrationTest.res +68 -0
  53. package/lib/ocaml/QueryDbStorage_Postgres-ReventlessPostgres.cmi +0 -0
  54. package/lib/ocaml/QueryDbStorage_Postgres-ReventlessPostgres.cmt +0 -0
  55. package/lib/ocaml/QueryEnginePostgres-ReventlessPostgres.cmi +0 -0
  56. package/lib/ocaml/QueryEnginePostgres-ReventlessPostgres.cmt +0 -0
  57. package/lib/ocaml/ReventlessPostgres.cmi +0 -0
  58. package/lib/ocaml/ReventlessPostgres.cmt +0 -0
  59. package/lib/ocaml/ReventlessPostgres.mlmap +1 -0
  60. package/package.json +5 -5
  61. package/src/EventLogChangeFeed.res +184 -0
  62. package/src/EventLogChangeFeed.res.mjs +134 -0
  63. package/src/PgSchema.res +36 -2
  64. package/src/PgSchema.res.mjs +9 -2
  65. package/tests/PostgresIntegrationTest.res +68 -0
  66. package/tests/PostgresIntegrationTest.res.mjs +49 -0
@@ -0,0 +1,134 @@
1
+ // Generated by ReScript, PLEASE EDIT WITH CARE
2
+
3
+ import * as Stdlib_Int from "@rescript/runtime/lib/es6/Stdlib_Int.js";
4
+ import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.js";
5
+ import * as PgDriver$ReventlessPostgres from "./PgDriver.res.mjs";
6
+ import * as DcbEventLogStorage_Postgres$ReventlessPostgres from "./DcbEventLogStorage_Postgres.res.mjs";
7
+
8
+ let selectColumns = "\n lpad(transaction_id::text, 20, '0') || ':' || lpad(global_seq::text, 20, '0') AS cursor,\n aggregate_id,\n seq_nr,\n payload,\n msg_id\n";
9
+
10
+ function coerceInt(v) {
11
+ switch (typeof v) {
12
+ case "string" :
13
+ return Stdlib_Option.getOr(Stdlib_Int.fromString(v, undefined), 0);
14
+ case "number" :
15
+ return v | 0;
16
+ default:
17
+ return 0;
18
+ }
19
+ }
20
+
21
+ function rowToEvent(row) {
22
+ let str = key => {
23
+ let match = row[key];
24
+ if (typeof match === "string") {
25
+ return match;
26
+ } else {
27
+ return "";
28
+ }
29
+ };
30
+ let match = row["msg_id"];
31
+ let tmp;
32
+ tmp = typeof match === "string" ? match : undefined;
33
+ return {
34
+ cursor: str("cursor"),
35
+ aggregateId: str("aggregate_id"),
36
+ seqNr: Stdlib_Option.getOr(Stdlib_Option.map(row["seq_nr"], coerceInt), 0),
37
+ payload: Stdlib_Option.getOr(row["payload"], null),
38
+ msgId: tmp
39
+ };
40
+ }
41
+
42
+ async function readBatch(pool, logName, after, limitOpt) {
43
+ let limit = limitOpt !== undefined ? limitOpt : 500;
44
+ let params = [logName];
45
+ let where = "log_name = $1 AND transaction_id < pg_snapshot_xmin(pg_current_snapshot())";
46
+ let match = Stdlib_Option.flatMap(after, DcbEventLogStorage_Postgres$ReventlessPostgres.decodeCursor);
47
+ if (match !== undefined) {
48
+ params.push(match[0]);
49
+ params.push(match[1]);
50
+ where = where + " AND (transaction_id > $2::xid8 OR (transaction_id = $2::xid8 AND global_seq > $3::bigint))";
51
+ }
52
+ let sql = `SELECT ` + selectColumns + ` FROM event_log WHERE ` + where + ` ORDER BY transaction_id ASC, global_seq ASC LIMIT ` + limit.toString();
53
+ let rows = await PgDriver$ReventlessPostgres.query(pool, sql, params);
54
+ let events = rows.map(rowToEvent);
55
+ let last = events[events.length - 1 | 0];
56
+ let cursor = last !== undefined ? last.cursor : undefined;
57
+ return {
58
+ events: events,
59
+ cursor: cursor
60
+ };
61
+ }
62
+
63
+ async function loadCheckpoint(pool, subscriber) {
64
+ let row = await PgDriver$ReventlessPostgres.queryOne(pool, "SELECT lpad(last_tx::text, 20, '0') || ':' || lpad(last_global_seq::text, 20, '0') AS cursor\n FROM event_log_subscription WHERE subscriber = $1 AND last_global_seq > 0", [subscriber]);
65
+ if (row === undefined) {
66
+ return;
67
+ }
68
+ let match = row["cursor"];
69
+ if (typeof match === "string") {
70
+ return match;
71
+ }
72
+ }
73
+
74
+ async function saveCheckpoint(pool, subscriber, cursor) {
75
+ let match = DcbEventLogStorage_Postgres$ReventlessPostgres.decodeCursor(cursor);
76
+ if (match !== undefined) {
77
+ await PgDriver$ReventlessPostgres.query(pool, "INSERT INTO event_log_subscription(subscriber, last_tx, last_global_seq)\n VALUES ($1, $2::xid8, $3::bigint)\n ON CONFLICT (subscriber)\n DO UPDATE SET last_tx = EXCLUDED.last_tx, last_global_seq = EXCLUDED.last_global_seq", [
78
+ subscriber,
79
+ match[0],
80
+ match[1]
81
+ ]);
82
+ return;
83
+ }
84
+ }
85
+
86
+ function listen(pool, logName, onWake) {
87
+ return PgDriver$ReventlessPostgres.listen(pool, "evlog_" + logName, param => onWake());
88
+ }
89
+
90
+ function unlisten(client, logName) {
91
+ return PgDriver$ReventlessPostgres.unlisten(client, "evlog_" + logName);
92
+ }
93
+
94
+ async function drain(pool, logName, subscriber, limitOpt, handle) {
95
+ let limit = limitOpt !== undefined ? limitOpt : 500;
96
+ let processed = 0;
97
+ let cursor = await loadCheckpoint(pool, subscriber);
98
+ let $$continue = true;
99
+ while ($$continue) {
100
+ let match = await readBatch(pool, logName, cursor, limit);
101
+ let events = match.events;
102
+ if (events.length === 0) {
103
+ $$continue = false;
104
+ } else {
105
+ let newCursor = match.cursor;
106
+ await handle(events);
107
+ if (newCursor !== undefined) {
108
+ await saveCheckpoint(pool, subscriber, newCursor);
109
+ cursor = newCursor;
110
+ }
111
+ processed = processed + events.length | 0;
112
+ if (events.length < limit) {
113
+ $$continue = false;
114
+ }
115
+ }
116
+ };
117
+ return processed;
118
+ }
119
+
120
+ let Dcb;
121
+
122
+ export {
123
+ Dcb,
124
+ selectColumns,
125
+ coerceInt,
126
+ rowToEvent,
127
+ readBatch,
128
+ loadCheckpoint,
129
+ saveCheckpoint,
130
+ listen,
131
+ unlisten,
132
+ drain,
133
+ }
134
+ /* PgDriver-ReventlessPostgres Not a pure module */
package/src/PgSchema.res CHANGED
@@ -36,6 +36,19 @@ let tableStatements = [
36
36
  schema_hash text NOT NULL,
37
37
  PRIMARY KEY (log_name, aggregate_id)
38
38
  )",
39
+ // --- Classic change feed (B2.5) ---
40
+ // Stamp every classic event with its committing xid8 so the feed can apply the
41
+ // same xmin read barrier the DCB feed uses — global_seq (an IDENTITY assigned at
42
+ // INSERT, before commit) is unsafe as a feed cursor on its own (a late-committing
43
+ // lower global_seq would be skipped). Idempotent; the volatile default auto-stamps
44
+ // every future insert with no change to EventLogStorage_Postgres.append.
45
+ "ALTER TABLE event_log ADD COLUMN IF NOT EXISTS transaction_id xid8 NOT NULL DEFAULT pg_current_xact_id()",
46
+ "CREATE INDEX IF NOT EXISTS event_log_tx_gseq ON event_log (log_name, transaction_id, global_seq)",
47
+ "CREATE TABLE IF NOT EXISTS event_log_subscription (
48
+ subscriber text PRIMARY KEY,
49
+ last_tx xid8 NOT NULL DEFAULT '0'::xid8,
50
+ last_global_seq bigint NOT NULL DEFAULT 0
51
+ )",
39
52
  // --- DCB event log (Phase B) ---
40
53
  "CREATE TABLE IF NOT EXISTS dcb_event (
41
54
  log_name text NOT NULL,
@@ -236,7 +249,28 @@ END;
236
249
  $fn$;
237
250
  "
238
251
 
239
- let functionStatements = [dcbConditionWhereFn, dcbAppendFn]
252
+ // Classic change-feed wakeup (B2.5). A statement-level AFTER INSERT trigger fires
253
+ // one pg_notify per distinct log_name touched by the statement, so the classic feed
254
+ // gets the same near-real-time wakeup the DCB append's inline pg_notify provides —
255
+ // without touching EventLogStorage_Postgres.append. No-op if nobody is LISTENing; a
256
+ // low-frequency fallback tick in the consumer covers missed notifications.
257
+ let eventLogNotifyFn = "
258
+ CREATE OR REPLACE FUNCTION event_log_notify() RETURNS trigger
259
+ LANGUAGE plpgsql AS $fn$
260
+ BEGIN
261
+ PERFORM pg_notify('evlog_' || log_name, '')
262
+ FROM (SELECT DISTINCT log_name FROM new_rows) s;
263
+ RETURN NULL;
264
+ END;
265
+ $fn$;
266
+
267
+ CREATE OR REPLACE TRIGGER event_log_notify_trg
268
+ AFTER INSERT ON event_log
269
+ REFERENCING NEW TABLE AS new_rows
270
+ FOR EACH STATEMENT EXECUTE FUNCTION event_log_notify();
271
+ "
272
+
273
+ let functionStatements = [dcbConditionWhereFn, dcbAppendFn, eventLogNotifyFn]
240
274
 
241
275
  let ensureSchema = async (pool: PgDriver.pool): unit => {
242
276
  for i in 0 to tableStatements->Array.length - 1 {
@@ -251,6 +285,6 @@ let ensureSchema = async (pool: PgDriver.pool): unit => {
251
285
  // Mirrors the reventless-local contract that reset wipes data, not structure.
252
286
  let truncateAll = async (pool: PgDriver.pool): unit => {
253
287
  await pool->PgDriver.exec(
254
- "TRUNCATE event_log, snapshot, dcb_event, dcb_scope, dcb_subscription RESTART IDENTITY",
288
+ "TRUNCATE event_log, snapshot, dcb_event, dcb_scope, dcb_subscription, event_log_subscription RESTART IDENTITY",
255
289
  )
256
290
  }
@@ -5,6 +5,9 @@ import * as PgDriver$ReventlessPostgres from "./PgDriver.res.mjs";
5
5
  let tableStatements = [
6
6
  "CREATE TABLE IF NOT EXISTS event_log (\n log_name text NOT NULL,\n aggregate_id text NOT NULL,\n seq_nr bigint NOT NULL,\n payload jsonb NOT NULL,\n msg_id text,\n global_seq bigint GENERATED ALWAYS AS IDENTITY,\n PRIMARY KEY (log_name, aggregate_id, seq_nr)\n )",
7
7
  "CREATE TABLE IF NOT EXISTS snapshot (\n log_name text NOT NULL,\n aggregate_id text NOT NULL,\n seq_nr bigint NOT NULL,\n state jsonb NOT NULL,\n schema_hash text NOT NULL,\n PRIMARY KEY (log_name, aggregate_id)\n )",
8
+ "ALTER TABLE event_log ADD COLUMN IF NOT EXISTS transaction_id xid8 NOT NULL DEFAULT pg_current_xact_id()",
9
+ "CREATE INDEX IF NOT EXISTS event_log_tx_gseq ON event_log (log_name, transaction_id, global_seq)",
10
+ "CREATE TABLE IF NOT EXISTS event_log_subscription (\n subscriber text PRIMARY KEY,\n last_tx xid8 NOT NULL DEFAULT '0'::xid8,\n last_global_seq bigint NOT NULL DEFAULT 0\n )",
8
11
  "CREATE TABLE IF NOT EXISTS dcb_event (\n log_name text NOT NULL,\n position bigint GENERATED ALWAYS AS IDENTITY,\n transaction_id xid8 NOT NULL DEFAULT pg_current_xact_id(),\n event_type text NOT NULL,\n tags text[] NOT NULL DEFAULT '{}',\n data jsonb NOT NULL,\n meta jsonb NOT NULL,\n recorded_at timestamptz NOT NULL DEFAULT now(),\n PRIMARY KEY (log_name, position)\n )",
9
12
  "CREATE INDEX IF NOT EXISTS dcb_event_tags_gin ON dcb_event USING gin (tags)",
10
13
  "CREATE INDEX IF NOT EXISTS dcb_event_type_pos ON dcb_event (log_name, event_type, position)",
@@ -17,9 +20,12 @@ let dcbConditionWhereFn = "\nCREATE OR REPLACE FUNCTION dcb_after_frag(p_tx xid8
17
20
 
18
21
  let dcbAppendFn = "\nCREATE OR REPLACE FUNCTION dcb_append(\n p_log_name text,\n p_events jsonb,\n p_condition jsonb DEFAULT NULL,\n p_lock_strategy text DEFAULT 'advisory'\n) RETURNS text\nLANGUAGE plpgsql AS $fn$\nDECLARE\n v_lock_keys bigint[];\n v_after_raw text;\n v_after_tx xid8;\n v_after_pos bigint;\n v_where text;\n v_conflict boolean;\n v_last_pos bigint;\n v_key bigint;\nBEGIN\n -- 1. Lock keys: every tag in written events UNION every tag in the condition.\n SELECT array_agg(DISTINCT k ORDER BY k) INTO v_lock_keys\n FROM (\n SELECT hashtextextended(p_log_name || '=' || tag, 0) AS k\n FROM jsonb_array_elements(p_events) ev,\n jsonb_array_elements_text(ev->'tags') tag\n UNION\n SELECT hashtextextended(p_log_name || '=' || tag, 0) AS k\n FROM jsonb_array_elements(COALESCE(p_condition->'query', '[]'::jsonb)) qi,\n jsonb_array_elements_text(COALESCE(qi->'tags', '[]'::jsonb)) tag\n ) s;\n\n -- 2. Acquire in sorted order.\n IF v_lock_keys IS NOT NULL THEN\n IF p_lock_strategy = 'rows' THEN\n INSERT INTO dcb_scope(log_name, scope_hash)\n SELECT p_log_name, k FROM unnest(v_lock_keys) k\n ON CONFLICT DO NOTHING;\n PERFORM 1 FROM dcb_scope\n WHERE log_name = p_log_name AND scope_hash = ANY(v_lock_keys)\n ORDER BY scope_hash\n FOR UPDATE;\n ELSE\n FOREACH v_key IN ARRAY v_lock_keys LOOP\n PERFORM pg_advisory_xact_lock(v_key);\n END LOOP;\n END IF;\n END IF;\n\n -- 3. Exact condition check under the held locks (READ COMMITTED is race-free\n -- here: a conflicting concurrent writer is either committed+visible or\n -- blocked on our lock).\n IF p_condition IS NOT NULL THEN\n v_after_raw := NULLIF(p_condition->>'after', '');\n IF v_after_raw IS NOT NULL THEN\n -- Cursor is '<xid8>:<position>', each zero-padded to 20 digits. Strip the\n -- padding before casting (bigint tolerates leading zeros; be explicit for\n -- xid8, guarding the all-zeros case).\n v_after_tx := COALESCE(NULLIF(ltrim(split_part(v_after_raw, ':', 1), '0'), ''), '0')::xid8;\n v_after_pos := split_part(v_after_raw, ':', 2)::bigint;\n END IF;\n v_where := dcb_condition_where(p_log_name, p_condition->'query', v_after_tx, v_after_pos);\n EXECUTE 'SELECT EXISTS (SELECT 1 FROM dcb_event WHERE ' || v_where || ')'\n INTO v_conflict;\n IF v_conflict THEN\n RAISE EXCEPTION 'dcb_conflict' USING ERRCODE = 'P0001';\n END IF;\n END IF;\n\n -- 4. Insert every event in array order; positions come from the IDENTITY seq.\n WITH ins AS (\n INSERT INTO dcb_event(log_name, event_type, tags, data, meta)\n SELECT p_log_name,\n ev->>'event_type',\n ARRAY(SELECT jsonb_array_elements_text(ev->'tags')),\n ev->'data',\n ev->'meta'\n FROM jsonb_array_elements(p_events) WITH ORDINALITY AS t(ev, ord)\n ORDER BY ord\n RETURNING position\n )\n SELECT max(position) INTO v_last_pos FROM ins;\n\n -- 5. Wake the change feed (Phase D). No-op if nobody is LISTENing.\n PERFORM pg_notify('dcb_' || p_log_name, v_last_pos::text);\n\n RETURN lpad(pg_current_xact_id()::text, 20, '0') || ':' || lpad(v_last_pos::text, 20, '0');\nEND;\n$fn$;\n";
19
22
 
23
+ let eventLogNotifyFn = "\nCREATE OR REPLACE FUNCTION event_log_notify() RETURNS trigger\nLANGUAGE plpgsql AS $fn$\nBEGIN\n PERFORM pg_notify('evlog_' || log_name, '')\n FROM (SELECT DISTINCT log_name FROM new_rows) s;\n RETURN NULL;\nEND;\n$fn$;\n\nCREATE OR REPLACE TRIGGER event_log_notify_trg\n AFTER INSERT ON event_log\n REFERENCING NEW TABLE AS new_rows\n FOR EACH STATEMENT EXECUTE FUNCTION event_log_notify();\n";
24
+
20
25
  let functionStatements = [
21
26
  dcbConditionWhereFn,
22
- dcbAppendFn
27
+ dcbAppendFn,
28
+ eventLogNotifyFn
23
29
  ];
24
30
 
25
31
  async function ensureSchema(pool) {
@@ -32,13 +38,14 @@ async function ensureSchema(pool) {
32
38
  }
33
39
 
34
40
  async function truncateAll(pool) {
35
- return await PgDriver$ReventlessPostgres.exec(pool, "TRUNCATE event_log, snapshot, dcb_event, dcb_scope, dcb_subscription RESTART IDENTITY");
41
+ return await PgDriver$ReventlessPostgres.exec(pool, "TRUNCATE event_log, snapshot, dcb_event, dcb_scope, dcb_subscription, event_log_subscription RESTART IDENTITY");
36
42
  }
37
43
 
38
44
  export {
39
45
  tableStatements,
40
46
  dcbConditionWhereFn,
41
47
  dcbAppendFn,
48
+ eventLogNotifyFn,
42
49
  functionStatements,
43
50
  ensureSchema,
44
51
  truncateAll,
@@ -233,4 +233,72 @@ switch processEnv->Dict.get("PG_URL") {
233
233
  expect(again)->toBe(0)
234
234
  })
235
235
  })
236
+
237
+ describe("classic change feed (event_log, B2.5)", () => {
238
+ testPromise("drains classic events in commit order, with fields, then checkpoints", async () => {
239
+ let (_n, ops, _s) = EventLogStorage_Postgres.makeStorage(~pool, ~name="cf-orders", ~opts)
240
+ let _ = await ops.append(0, "agg-1", [evJson("m0", 1), evJson("m1", 2)])
241
+ let _ = await ops.append(0, "agg-2", [evJson("m2", 3)])
242
+
243
+ let collected = ref([])
244
+ let processed = await EventLogChangeFeed.drain(
245
+ pool,
246
+ ~logName="cf-orders",
247
+ ~subscriber="cf-sub",
248
+ ~handle=async evs => collected := collected.contents->Array.concat(evs),
249
+ )
250
+ expect(processed)->toBe(3)
251
+ expect(collected.contents->Array.length)->toBe(3)
252
+
253
+ // Fields round-trip from the stored row.
254
+ let first = collected.contents->Array.getUnsafe(0)
255
+ expect(first.aggregateId)->toBe("agg-1")
256
+ expect(first.seqNr)->toBe(0)
257
+ expect(first.msgId)->toEqual(Some("m0"))
258
+
259
+ // Cursors are strictly increasing in drain order.
260
+ let cursors = collected.contents->Array.map(e => e.cursor)
261
+ let increasing = ref(true)
262
+ for i in 1 to cursors->Array.length - 1 {
263
+ if cursors->Array.getUnsafe(i) <= cursors->Array.getUnsafe(i - 1) {
264
+ increasing := false
265
+ }
266
+ }
267
+ expect(increasing.contents)->toBe(true)
268
+
269
+ // Second drain from the saved checkpoint sees nothing new.
270
+ let again = await EventLogChangeFeed.drain(
271
+ pool,
272
+ ~logName="cf-orders",
273
+ ~subscriber="cf-sub",
274
+ ~handle=async _ => (),
275
+ )
276
+ expect(again)->toBe(0)
277
+ })
278
+
279
+ testPromise("concurrent appends across aggregates: every event drained exactly once", async () => {
280
+ let (_n, ops, _s) = EventLogStorage_Postgres.makeStorage(~pool, ~name="cf-concurrent", ~opts)
281
+ let n = 20
282
+ // One event per aggregate, all dispatched before awaiting — genuinely
283
+ // concurrent on the pool, so global_seq is assigned in interleaved/undefined
284
+ // commit order. The xmin fence must still drain every event exactly once.
285
+ let promises =
286
+ Array.make(~length=n, 0)->Array.mapWithIndex((_, i) =>
287
+ ops.append(0, "agg-" ++ Int.toString(i), [evJson("m" ++ Int.toString(i), i)])
288
+ )
289
+ let _ = await Promise.all(promises)
290
+
291
+ let collected = ref([])
292
+ let _ = await EventLogChangeFeed.drain(
293
+ pool,
294
+ ~logName="cf-concurrent",
295
+ ~subscriber="cf-conc-sub",
296
+ ~handle=async evs => collected := collected.contents->Array.concat(evs),
297
+ )
298
+ // No skips: all N events present. No dupes: N distinct cursors.
299
+ expect(collected.contents->Array.length)->toBe(n)
300
+ let distinctCursors = collected.contents->Array.map(e => e.cursor)->Set.fromArray
301
+ expect(distinctCursors->Set.size)->toBe(n)
302
+ })
303
+ })
236
304
  }
@@ -6,6 +6,7 @@ import * as Message$ReventlessCore from "@reventlessdev/reventless-core/src/Mess
6
6
  import * as PgDriver$ReventlessPostgres from "../src/PgDriver.res.mjs";
7
7
  import * as PgSchema$ReventlessPostgres from "../src/PgSchema.res.mjs";
8
8
  import * as PgChangeFeed$ReventlessPostgres from "../src/PgChangeFeed.res.mjs";
9
+ import * as EventLogChangeFeed$ReventlessPostgres from "../src/EventLogChangeFeed.res.mjs";
9
10
  import * as EventLogStorage_Postgres$ReventlessPostgres from "../src/EventLogStorage_Postgres.res.mjs";
10
11
  import * as DcbEventLogStorage_Postgres$ReventlessPostgres from "../src/DcbEventLogStorage_Postgres.res.mjs";
11
12
 
@@ -313,6 +314,54 @@ if (url !== undefined) {
313
314
  globalThis.expect(again).toBe(0);
314
315
  });
315
316
  });
317
+ globalThis.describe("classic change feed (event_log, B2.5)", () => {
318
+ globalThis.test("drains classic events in commit order, with fields, then checkpoints", async () => {
319
+ let match = EventLogStorage_Postgres$ReventlessPostgres.makeStorage(pool, "cf-orders", opts, undefined);
320
+ let ops = match[1];
321
+ await ops.append(0, "agg-1", [
322
+ evJson("m0", 1),
323
+ evJson("m1", 2)
324
+ ]);
325
+ await ops.append(0, "agg-2", [evJson("m2", 3)]);
326
+ let collected = {
327
+ contents: []
328
+ };
329
+ let processed = await EventLogChangeFeed$ReventlessPostgres.drain(pool, "cf-orders", "cf-sub", undefined, async evs => {
330
+ collected.contents = collected.contents.concat(evs);
331
+ });
332
+ globalThis.expect(processed).toBe(3);
333
+ globalThis.expect(collected.contents.length).toBe(3);
334
+ let first = collected.contents[0];
335
+ globalThis.expect(first.aggregateId).toBe("agg-1");
336
+ globalThis.expect(first.seqNr).toBe(0);
337
+ globalThis.expect(first.msgId).toEqual("m0");
338
+ let cursors = collected.contents.map(e => e.cursor);
339
+ let increasing = true;
340
+ for (let i = 1, i_finish = cursors.length; i < i_finish; ++i) {
341
+ if (cursors[i] <= cursors[i - 1 | 0]) {
342
+ increasing = false;
343
+ }
344
+ }
345
+ globalThis.expect(increasing).toBe(true);
346
+ let again = await EventLogChangeFeed$ReventlessPostgres.drain(pool, "cf-orders", "cf-sub", undefined, async param => {});
347
+ globalThis.expect(again).toBe(0);
348
+ });
349
+ globalThis.test("concurrent appends across aggregates: every event drained exactly once", async () => {
350
+ let match = EventLogStorage_Postgres$ReventlessPostgres.makeStorage(pool, "cf-concurrent", opts, undefined);
351
+ let ops = match[1];
352
+ let promises = Stdlib_Array.make(20, 0).map((param, i) => ops.append(0, "agg-" + i.toString(), [evJson("m" + i.toString(), i)]));
353
+ await Promise.all(promises);
354
+ let collected = {
355
+ contents: []
356
+ };
357
+ await EventLogChangeFeed$ReventlessPostgres.drain(pool, "cf-concurrent", "cf-conc-sub", undefined, async evs => {
358
+ collected.contents = collected.contents.concat(evs);
359
+ });
360
+ globalThis.expect(collected.contents.length).toBe(20);
361
+ let distinctCursors = new Set(collected.contents.map(e => e.cursor));
362
+ globalThis.expect(distinctCursors.size).toBe(20);
363
+ });
364
+ });
316
365
  } else {
317
366
  globalThis.test("Postgres integration (skipped — set PG_URL to run)", () => {
318
367
  globalThis.expect(true).toBe(true);