@sentropic/cluster-mesh 0.23.5 → 0.24.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.
Files changed (149) hide show
  1. package/assets/storage/engram-memory/C6-FREEZE.md +63 -0
  2. package/assets/storage/engram-memory/contract-manifest.json +6 -4
  3. package/assets/storage/engram-memory/equivalence.json +1 -1
  4. package/assets/storage/engram-memory/neutral-asset-inventory.json +53 -0
  5. package/assets/storage/engram-memory/neutral-equivalence.json +44 -0
  6. package/assets/storage/postgres/007-consumed-counters.sql +17 -0
  7. package/assets/storage/postgres/008-instance-ownership.sql +35 -0
  8. package/assets/storage/postgres/engram-memory/001-projections.sql +14 -0
  9. package/assets/storage/postgres/engram-memory/002-host-ledger.sql +14 -0
  10. package/assets/storage/postgres/engram-memory/manifest.json +29 -0
  11. package/assets/storage/postgres/manifest.json +26 -0
  12. package/contracts/engram-memory-neutral-contract-v1.d.ts +367 -0
  13. package/dist/comments/postgres.d.ts +1 -0
  14. package/dist/comments/postgres.d.ts.map +1 -1
  15. package/dist/engram-memory/binding.d.ts +115 -0
  16. package/dist/engram-memory/binding.d.ts.map +1 -0
  17. package/dist/engram-memory/binding.js +239 -0
  18. package/dist/engram-memory/binding.js.map +1 -0
  19. package/dist/engram-memory/commit-result-recovery.d.ts +12 -0
  20. package/dist/engram-memory/commit-result-recovery.d.ts.map +1 -0
  21. package/dist/engram-memory/commit-result-recovery.js +14 -0
  22. package/dist/engram-memory/commit-result-recovery.js.map +1 -0
  23. package/dist/engram-memory/contract.d.ts +7 -1
  24. package/dist/engram-memory/contract.d.ts.map +1 -1
  25. package/dist/engram-memory/contract.js +7 -1
  26. package/dist/engram-memory/contract.js.map +1 -1
  27. package/dist/engram-memory/host-maintenance.d.ts +40 -0
  28. package/dist/engram-memory/host-maintenance.d.ts.map +1 -0
  29. package/dist/engram-memory/host-maintenance.js +44 -0
  30. package/dist/engram-memory/host-maintenance.js.map +1 -0
  31. package/dist/engram-memory/ledger.d.ts +75 -0
  32. package/dist/engram-memory/ledger.d.ts.map +1 -0
  33. package/dist/engram-memory/ledger.js +286 -0
  34. package/dist/engram-memory/ledger.js.map +1 -0
  35. package/dist/engram-memory/manifest.d.ts +1 -1
  36. package/dist/engram-memory/manifest.d.ts.map +1 -1
  37. package/dist/engram-memory/manifest.js +2 -1
  38. package/dist/engram-memory/manifest.js.map +1 -1
  39. package/dist/engram-memory/neutral-contract.d.ts +368 -0
  40. package/dist/engram-memory/neutral-contract.d.ts.map +1 -0
  41. package/dist/engram-memory/neutral-contract.js +39 -0
  42. package/dist/engram-memory/neutral-contract.js.map +1 -0
  43. package/dist/engram-memory/neutral-handle.d.ts +62 -0
  44. package/dist/engram-memory/neutral-handle.d.ts.map +1 -0
  45. package/dist/engram-memory/neutral-handle.js +131 -0
  46. package/dist/engram-memory/neutral-handle.js.map +1 -0
  47. package/dist/engram-memory/postgres-queries.d.ts +1 -1
  48. package/dist/engram-memory/postgres-queries.d.ts.map +1 -1
  49. package/dist/engram-memory/postgres-queries.js +111 -21
  50. package/dist/engram-memory/postgres-queries.js.map +1 -1
  51. package/dist/engram-memory/postgres.d.ts +51 -10
  52. package/dist/engram-memory/postgres.d.ts.map +1 -1
  53. package/dist/engram-memory/postgres.js +118 -17
  54. package/dist/engram-memory/postgres.js.map +1 -1
  55. package/dist/engram-memory/projection.d.ts +12 -0
  56. package/dist/engram-memory/projection.d.ts.map +1 -0
  57. package/dist/engram-memory/projection.js +123 -0
  58. package/dist/engram-memory/projection.js.map +1 -0
  59. package/dist/engram-memory/wire-adaptation.d.ts +61 -0
  60. package/dist/engram-memory/wire-adaptation.d.ts.map +1 -0
  61. package/dist/engram-memory/wire-adaptation.js +223 -0
  62. package/dist/engram-memory/wire-adaptation.js.map +1 -0
  63. package/dist/modules/catalog.js +1 -1
  64. package/dist/storage/atomic.d.ts +66 -1
  65. package/dist/storage/atomic.d.ts.map +1 -1
  66. package/dist/storage/atomic.js +173 -1
  67. package/dist/storage/atomic.js.map +1 -1
  68. package/dist/storage/backend.d.ts +3 -0
  69. package/dist/storage/backend.d.ts.map +1 -1
  70. package/dist/storage/backend.js +8 -0
  71. package/dist/storage/backend.js.map +1 -1
  72. package/dist/storage/contracts.d.ts +13 -0
  73. package/dist/storage/contracts.d.ts.map +1 -1
  74. package/dist/storage/contracts.js +12 -0
  75. package/dist/storage/contracts.js.map +1 -1
  76. package/dist/storage/instance-ownership.d.ts.map +1 -1
  77. package/dist/storage/instance-ownership.js +25 -7
  78. package/dist/storage/instance-ownership.js.map +1 -1
  79. package/dist/storage/postgres/codec.d.ts +1 -0
  80. package/dist/storage/postgres/codec.d.ts.map +1 -1
  81. package/dist/storage/postgres/codec.js +19 -0
  82. package/dist/storage/postgres/codec.js.map +1 -1
  83. package/dist/storage/postgres/commit-results.d.ts +6 -0
  84. package/dist/storage/postgres/commit-results.d.ts.map +1 -0
  85. package/dist/storage/postgres/commit-results.js +28 -0
  86. package/dist/storage/postgres/commit-results.js.map +1 -0
  87. package/dist/storage/postgres/core.d.ts +3 -1
  88. package/dist/storage/postgres/core.d.ts.map +1 -1
  89. package/dist/storage/postgres/core.js +99 -36
  90. package/dist/storage/postgres/core.js.map +1 -1
  91. package/dist/storage/postgres/effects.d.ts +1 -1
  92. package/dist/storage/postgres/effects.d.ts.map +1 -1
  93. package/dist/storage/postgres/effects.js +31 -6
  94. package/dist/storage/postgres/effects.js.map +1 -1
  95. package/dist/storage/postgres/errors.d.ts.map +1 -1
  96. package/dist/storage/postgres/errors.js +13 -0
  97. package/dist/storage/postgres/errors.js.map +1 -1
  98. package/dist/storage/postgres/index.d.ts +1 -0
  99. package/dist/storage/postgres/index.d.ts.map +1 -1
  100. package/dist/storage/postgres/index.js +1 -0
  101. package/dist/storage/postgres/index.js.map +1 -1
  102. package/dist/storage/postgres/instance-guard.d.ts +48 -0
  103. package/dist/storage/postgres/instance-guard.d.ts.map +1 -0
  104. package/dist/storage/postgres/instance-guard.js +147 -0
  105. package/dist/storage/postgres/instance-guard.js.map +1 -0
  106. package/dist/storage/postgres/instance-ownership.d.ts +22 -0
  107. package/dist/storage/postgres/instance-ownership.d.ts.map +1 -0
  108. package/dist/storage/postgres/instance-ownership.js +165 -0
  109. package/dist/storage/postgres/instance-ownership.js.map +1 -0
  110. package/dist/storage/postgres/journal.d.ts +24 -8
  111. package/dist/storage/postgres/journal.d.ts.map +1 -1
  112. package/dist/storage/postgres/journal.js +43 -32
  113. package/dist/storage/postgres/journal.js.map +1 -1
  114. package/dist/storage/postgres/migrations.d.ts +2 -1
  115. package/dist/storage/postgres/migrations.d.ts.map +1 -1
  116. package/dist/storage/postgres/migrations.js +14 -4
  117. package/dist/storage/postgres/migrations.js.map +1 -1
  118. package/dist/storage/postgres/ordinary-transactions.d.ts.map +1 -1
  119. package/dist/storage/postgres/ordinary-transactions.js +3 -2
  120. package/dist/storage/postgres/ordinary-transactions.js.map +1 -1
  121. package/dist/storage/postgres/profiles.d.ts +15 -8
  122. package/dist/storage/postgres/profiles.d.ts.map +1 -1
  123. package/dist/storage/postgres/protocol.d.ts +14 -0
  124. package/dist/storage/postgres/protocol.d.ts.map +1 -1
  125. package/dist/storage/postgres/protocol.js.map +1 -1
  126. package/dist/storage/postgres/queries.js +5 -5
  127. package/dist/storage/postgres/queries.js.map +1 -1
  128. package/dist/storage/postgres/readers.js +2 -2
  129. package/dist/storage/postgres/readers.js.map +1 -1
  130. package/dist/storage/postgres/roots.d.ts.map +1 -1
  131. package/dist/storage/postgres/roots.js +10 -6
  132. package/dist/storage/postgres/roots.js.map +1 -1
  133. package/dist/storage/postgres/scope.d.ts +17 -8
  134. package/dist/storage/postgres/scope.d.ts.map +1 -1
  135. package/dist/storage/postgres/scope.js +4 -0
  136. package/dist/storage/postgres/scope.js.map +1 -1
  137. package/dist/storage/postgres/snapshots.d.ts +2 -2
  138. package/dist/storage/postgres/snapshots.d.ts.map +1 -1
  139. package/dist/storage/postgres/snapshots.js +7 -4
  140. package/dist/storage/postgres/snapshots.js.map +1 -1
  141. package/dist/storage/postgres/transactions.d.ts +11 -0
  142. package/dist/storage/postgres/transactions.d.ts.map +1 -1
  143. package/dist/storage/postgres/transactions.js +21 -0
  144. package/dist/storage/postgres/transactions.js.map +1 -1
  145. package/dist/storage/u64.d.ts +18 -0
  146. package/dist/storage/u64.d.ts.map +1 -0
  147. package/dist/storage/u64.js +54 -0
  148. package/dist/storage/u64.js.map +1 -0
  149. package/package.json +3 -2
@@ -0,0 +1,147 @@
1
+ // PostgreSQL installed ownership guards (lot E4, R1).
2
+ // G-P0a feeds the open path: the deprecated asset-name scan, the module
3
+ // record readback and the ownership catalog verification run before any
4
+ // acquisition. G-P0b is the commit-point guard running INSIDE the commit
5
+ // transaction: the per-kernel driver wrapper below carries the commit session
6
+ // through AsyncLocalStorage, so the guard verifies and renews on the very
7
+ // session that commits (no second transaction, no pool deadlock, no TOCTOU
8
+ // window). No transaction rewiring: the existing onCommitPossession seam is
9
+ // reused, chained only for opt-in canonical kernels.
10
+ import { AsyncLocalStorage } from 'node:async_hooks';
11
+ import { CanonicalOwnershipError } from '../instance-ownership.js';
12
+ import { decodePgText } from './codec.js';
13
+ import { PostgresStorageError } from './errors.js';
14
+ import { renewPgInstanceLease, verifyPgInstanceOwnership } from './instance-ownership.js';
15
+ const DEPRECATED_ASSET_NAME = /(?:^|[^a-z])(?:legacy|deprecated|backup|tmp|temp|old|bak|copy)(?:[^a-z]|$)/i;
16
+ export const assertNoDeprecatedAssetNames = (assets) => {
17
+ for (const asset of assets) {
18
+ if (DEPRECATED_ASSET_NAME.test(asset.file))
19
+ throw new PostgresStorageError('configuration');
20
+ }
21
+ };
22
+ export const ensurePgModuleRecord = async (session, schema, record) => {
23
+ await session.execute({
24
+ text: `INSERT INTO ${schema}.modules(module, incarnation) VALUES($1, $2) ON CONFLICT(module) DO NOTHING`,
25
+ values: [record.moduleId, record.effectiveIncarnation],
26
+ });
27
+ const result = await session.execute({
28
+ text: `SELECT incarnation, descriptor_digest FROM ${schema}.modules WHERE module=$1`,
29
+ values: [record.moduleId],
30
+ });
31
+ if (result.rows[0] === undefined)
32
+ throw new PostgresStorageError('configuration');
33
+ const stored = decodePgText(result.rows[0]?.incarnation);
34
+ if (record.incarnation !== undefined && record.incarnation !== stored) {
35
+ throw new PostgresStorageError('configuration');
36
+ }
37
+ const registered = result.rows[0]?.descriptor_digest;
38
+ const digest = registered === null || registered === undefined ? null : decodePgText(registered);
39
+ const wanted = record.wantedDescriptorDigest ?? null;
40
+ if (digest !== null && digest !== wanted)
41
+ throw new PostgresStorageError('configuration');
42
+ if (wanted && digest === null) {
43
+ const pinned = await session.execute({
44
+ text: `UPDATE ${schema}.modules SET descriptor_digest=$1
45
+ WHERE module=$2 AND descriptor_digest IS NULL
46
+ AND NOT EXISTS(SELECT 1 FROM ${schema}.scopes
47
+ WHERE module=$2 AND version>0) RETURNING module`,
48
+ values: [wanted, record.moduleId],
49
+ });
50
+ if (pinned.rows.length !== 1)
51
+ throw new PostgresStorageError('configuration');
52
+ }
53
+ return stored;
54
+ };
55
+ export const createOwnershipCell = (schema, moduleId, leaseMs) => ({
56
+ handle: null,
57
+ released: false,
58
+ schema,
59
+ moduleId,
60
+ leaseMs,
61
+ });
62
+ /**
63
+ * Per-kernel driver wrapper. Every transaction of an opted-in kernel first
64
+ * verifies the retained session on its own session (reads) or verifies and
65
+ * renews the lease (read-write); released kernels are refused without SQL.
66
+ * Non-opt-in kernels (cell handle unset) pass through untouched. The commit
67
+ * session is exposed for the G-P0b hook through AsyncLocalStorage, so the
68
+ * decision guard runs inside the real COMMIT transaction.
69
+ */
70
+ export const wrapDriverWithOwnership = (driver, cell) => {
71
+ const current = new AsyncLocalStorage();
72
+ return {
73
+ driver: {
74
+ transaction: async (options, operation) => driver.transaction(options, async (session) => {
75
+ if (cell.handle !== null) {
76
+ if (cell.released)
77
+ throw new CanonicalOwnershipError('stale-epoch', 'released ownership handle');
78
+ if (options.readOnly) {
79
+ await verifyPgInstanceOwnership(session, cell.schema, cell.moduleId, cell.handle, false);
80
+ }
81
+ else {
82
+ await renewPgInstanceLease(session, cell.schema, cell.moduleId, cell.handle, false, cell.leaseMs);
83
+ }
84
+ }
85
+ return current.run(session, () => operation(session));
86
+ }),
87
+ },
88
+ useSession: () => current.getStore(),
89
+ };
90
+ };
91
+ /** G-P0b: durable re-validation and renewal on the committing session itself,
92
+ * before the caller hook; any refusal rolls back with the commit. */
93
+ export const chainPossessionGuard = (useSession, cell, caller) => async () => {
94
+ const session = useSession();
95
+ const handle = cell.handle;
96
+ if (!session || !handle || cell.released) {
97
+ throw new CanonicalOwnershipError('terminal-loss', 'commit without retained session');
98
+ }
99
+ await renewPgInstanceLease(session, cell.schema, cell.moduleId, handle, false, cell.leaseMs);
100
+ await caller?.();
101
+ };
102
+ /** G-P0a installed catalog check: the 008 table, the deferred lease trigger
103
+ * and its guard function must exist with the contracted binding (enabled,
104
+ * deferred, AFTER UPDATE ROW) — a fingerprint cannot see trigger state.
105
+ * Refusal is `open-refused` (registry/SQLite parity for opt-in opens), never
106
+ * a storage configuration error. The trigger is born `tgenabled='O'`
107
+ * (origin+local, the PostgreSQL default for constraint triggers); `'A'`
108
+ * (always) is accepted too. */
109
+ export const assertPgOwnershipCatalog = async (session, dataSchema) => {
110
+ const refuse = () => {
111
+ throw new CanonicalOwnershipError('open-refused', 'instance ownership catalog is not installed or was tampered with');
112
+ };
113
+ const columns = await session.execute({
114
+ text: `SELECT column_name, data_type FROM information_schema.columns WHERE table_schema=$1 AND table_name='instance_ownership'`,
115
+ values: [dataSchema],
116
+ });
117
+ const byName = new Map(columns.rows.map((row) => [decodePgText(row.column_name), decodePgText(row.data_type)]));
118
+ if (byName.get('module') !== 'text' || byName.get('instance') !== 'text' || byName.get('epoch') !== 'text')
119
+ refuse();
120
+ if (byName.get('holder_until') !== 'timestamp with time zone')
121
+ refuse();
122
+ const checks = await session.execute({
123
+ text: `SELECT pg_get_constraintdef(oid) AS definition FROM pg_constraint WHERE conrelid=$1::regclass AND contype='c'`,
124
+ values: [`"${dataSchema}".instance_ownership`],
125
+ });
126
+ if (!checks.rows.some((row) => typeof row.definition === 'string' && row.definition.includes('18446744073709551615')))
127
+ refuse();
128
+ const triggers = await session.execute({
129
+ text: `SELECT t.tgname, t.tgenabled, t.tgdeferrable, t.tginitdeferred, t.tgtype, p.proname, l.lanname, p.prosrc
130
+ FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid
131
+ JOIN pg_namespace n ON n.oid = c.relnamespace
132
+ JOIN pg_proc p ON p.oid = t.tgfoid JOIN pg_language l ON l.oid = p.prolang
133
+ WHERE n.nspname=$1 AND c.relname='instance_ownership' AND NOT t.tgisinternal`,
134
+ values: [dataSchema],
135
+ });
136
+ const trigger = triggers.rows.find((row) => row.tgname === 'instance_ownership_lease') ?? refuse();
137
+ if ((trigger.tgenabled !== 'O' && trigger.tgenabled !== 'A') || trigger.tgdeferrable !== true || trigger.tginitdeferred !== true)
138
+ refuse();
139
+ if (trigger.tgtype !== 17)
140
+ refuse();
141
+ if (trigger.proname !== 'instance_ownership_guard' || trigger.lanname !== 'plpgsql')
142
+ refuse();
143
+ const prosrc = typeof trigger.prosrc === 'string' ? trigger.prosrc : '';
144
+ if (!prosrc.includes('holder_until') || !prosrc.includes('clock_timestamp'))
145
+ refuse();
146
+ };
147
+ //# sourceMappingURL=instance-guard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instance-guard.js","sourceRoot":"","sources":["../../../src/storage/postgres/instance-guard.ts"],"names":[],"mappings":"AAAA,sDAAsD;AACtD,wEAAwE;AACxE,wEAAwE;AACxE,yEAAyE;AACzE,8EAA8E;AAC9E,0EAA0E;AAC1E,2EAA2E;AAC3E,4EAA4E;AAC5E,qDAAqD;AACrD,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,uBAAuB,EAAgC,MAAM,0BAA0B,CAAC;AACjG,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,EA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,IAAI,GAAG,CAAC,UAAU,CAAC,QAAQ,CAAC,sBAAsB,CAAC,CAAC;QAAE,MAAM,EAAE,CAAC;IAChI,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,OAAO,CAAC;QACrC,IAAI,EAAE;;;;mFAIyE;QAC/E,MAAM,EAAE,CAAC,UAAU,CAAC;KACrB,CAAC,CAAC;IACH,MAAM,OAAO,GAAG,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,MAAM,KAAK,0BAA0B,CAAC,IAAI,MAAM,EAAE,CAAC;IACnG,IAAI,CAAC,OAAO,CAAC,SAAS,KAAK,GAAG,IAAI,OAAO,CAAC,SAAS,KAAK,GAAG,CAAC,IAAI,OAAO,CAAC,YAAY,KAAK,IAAI,IAAI,OAAO,CAAC,cAAc,KAAK,IAAI;QAAE,MAAM,EAAE,CAAC;IAC3I,IAAI,OAAO,CAAC,MAAM,KAAK,EAAE;QAAE,MAAM,EAAE,CAAC;IACpC,IAAI,OAAO,CAAC,OAAO,KAAK,0BAA0B,IAAI,OAAO,CAAC,OAAO,KAAK,SAAS;QAAE,MAAM,EAAE,CAAC;IAC9F,MAAM,MAAM,GAAG,OAAO,OAAO,CAAC,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;IACxE,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,CAAC;QAAE,MAAM,EAAE,CAAC;AACxF,CAAC,CAAC"}
@@ -0,0 +1,22 @@
1
+ import { CanonicalInstanceRegistry, type CanonicalInstanceHandle } from '../instance-ownership.js';
2
+ import type { PgSession } from './protocol.js';
3
+ export declare const DEFAULT_LEASE_MS: number;
4
+ /** Stable store key: one live holder per data schema and owning module. */
5
+ export declare const resolvePgStoreKey: (dataSchema: string, moduleId: string) => string;
6
+ export interface PgInstanceOwnershipSession {
7
+ readonly handle: CanonicalInstanceHandle;
8
+ verify(session: PgSession): Promise<void>;
9
+ release(): Promise<void>;
10
+ }
11
+ /** A lock-wait, serialization or deadlock race against a concurrent opener.
12
+ * Used on the lock/claim statements and at the open boundary (a race lost
13
+ * at COMMIT time still means a concurrent acquisition is in progress). */
14
+ export declare const acquisitionRaced: (error: unknown) => boolean;
15
+ export declare const acquirePgInstanceOwnership: (session: PgSession, schema: string, storeKey: string, moduleId: string, registry: CanonicalInstanceRegistry, leaseMs: number) => Promise<{
16
+ handle: CanonicalInstanceHandle;
17
+ registryHandle: CanonicalInstanceHandle;
18
+ }>;
19
+ export declare const verifyPgInstanceOwnership: (session: PgSession, schema: string, moduleId: string, handle: CanonicalInstanceHandle, released: boolean) => Promise<void>;
20
+ export declare const renewPgInstanceLease: (session: PgSession, schema: string, moduleId: string, handle: CanonicalInstanceHandle, released: boolean, leaseMs: number) => Promise<void>;
21
+ export declare const expirePgInstanceLease: (session: PgSession, schema: string, moduleId: string, handle: CanonicalInstanceHandle) => Promise<void>;
22
+ //# sourceMappingURL=instance-ownership.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instance-ownership.d.ts","sourceRoot":"","sources":["../../../src/storage/postgres/instance-ownership.ts"],"names":[],"mappings":"AAYA,OAAO,EACL,yBAAyB,EAEzB,KAAK,uBAAuB,EAC7B,MAAM,0BAA0B,CAAC;AAIlC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE/C,eAAO,MAAM,gBAAgB,QAAgB,CAAC;AAE9C,2EAA2E;AAC3E,eAAO,MAAM,iBAAiB,eAAgB,MAAM,YAAY,MAAM,KAAG,MAC3B,CAAC;AAE/C,MAAM,WAAW,0BAA0B;IACzC,QAAQ,CAAC,MAAM,EAAE,uBAAuB,CAAC;IACzC,MAAM,CAAC,OAAO,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1C,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1B;AAeD;;0EAE0E;AAC1E,eAAO,MAAM,gBAAgB,UAAW,OAAO,KAAG,OAKjD,CAAC;AAgDF,eAAO,MAAM,0BAA0B,YAC5B,SAAS,UACV,MAAM,YACJ,MAAM,YACN,MAAM,YACN,yBAAyB,WAC1B,MAAM,KACd,QAAQ;IAAE,MAAM,EAAE,uBAAuB,CAAC;IAAC,cAAc,EAAE,uBAAuB,CAAA;CAAE,CAoCtF,CAAC;AAEF,eAAO,MAAM,yBAAyB,YAC3B,SAAS,UACV,MAAM,YACJ,MAAM,UACR,uBAAuB,YACrB,OAAO,KAChB,QAAQ,IAAI,CAUd,CAAC;AAEF,eAAO,MAAM,oBAAoB,YACtB,SAAS,UACV,MAAM,YACJ,MAAM,UACR,uBAAuB,YACrB,OAAO,WACR,MAAM,KACd,QAAQ,IAAI,CASd,CAAC;AAMF,eAAO,MAAM,qBAAqB,YACvB,SAAS,UACV,MAAM,YACJ,MAAM,UACR,uBAAuB,KAC9B,QAAQ,IAAI,CAUd,CAAC"}
@@ -0,0 +1,165 @@
1
+ // PostgreSQL durable CanonicalInstanceOwnershipV1 (lot E4, R1).
2
+ // Reuses the neutral contract name/version/meaning/digest, the handle shape
3
+ // and the CanonicalOwnershipError codes; adds no second ownership contract.
4
+ // Design (see BRANCH.md Feedback Loop): a retained lease row per owning
5
+ // module. The holder keeps holder_until live by renewal; a second opener is
6
+ // refused promptly (instance-busy, no queue, no supersede). Code mapping
7
+ // follows the neutral registry exactly: superseded/released/unknown holder
8
+ // is stale-epoch; only explicit terminal state or a dead unclaimed lease is
9
+ // terminal-loss; live second openers are instance-busy; open-time refusals
10
+ // are open-refused. PG surfaces these unwrapped (classifyPgFailure passes
11
+ // CanonicalOwnershipError through, like SQLite throwing it directly).
12
+ import { randomUUID } from 'node:crypto';
13
+ import { CanonicalOwnershipError, } from '../instance-ownership.js';
14
+ import { isPositiveU64Counter, nextU64Counter } from '../u64.js';
15
+ import { PostgresStorageError } from './errors.js';
16
+ import { decodePgText } from './codec.js';
17
+ export const DEFAULT_LEASE_MS = 5 * 60 * 1000;
18
+ /** Stable store key: one live holder per data schema and owning module. */
19
+ export const resolvePgStoreKey = (dataSchema, moduleId) => JSON.stringify(['pg', dataSchema, moduleId]);
20
+ const missingOwnershipTable = (error) => {
21
+ if (typeof error !== 'object' || error === null)
22
+ return false;
23
+ const fields = error;
24
+ return fields.code === '42P01' || fields.sqlState === '42P01';
25
+ };
26
+ /** A lock-wait, serialization or deadlock race against a concurrent opener.
27
+ * Used on the lock/claim statements and at the open boundary (a race lost
28
+ * at COMMIT time still means a concurrent acquisition is in progress). */
29
+ export const acquisitionRaced = (error) => {
30
+ if (typeof error !== 'object' || error === null)
31
+ return false;
32
+ const fields = error;
33
+ const state = fields.sqlState ?? fields.code;
34
+ return state === '55P03' || state === '40001' || state === '40P01';
35
+ };
36
+ const decodeLeaseMs = (value) => {
37
+ if (value instanceof Date)
38
+ return value.getTime();
39
+ if (typeof value === 'string' || typeof value === 'number') {
40
+ const ms = new Date(value).getTime();
41
+ if (!Number.isNaN(ms))
42
+ return ms;
43
+ }
44
+ throw new PostgresStorageError('corruption');
45
+ };
46
+ const readPair = async (session, schema, moduleId, lock) => {
47
+ let result;
48
+ try {
49
+ result = await session.execute({
50
+ text: `SELECT instance, epoch, holder_until, clock_timestamp() AS now FROM ${schema}.instance_ownership WHERE module=$1${lock ? ' FOR UPDATE' : ''}`,
51
+ values: [moduleId],
52
+ });
53
+ }
54
+ catch (error) {
55
+ if (missingOwnershipTable(error)) {
56
+ throw new CanonicalOwnershipError('open-refused', 'instance ownership is not installed for this store');
57
+ }
58
+ if (lock && acquisitionRaced(error)) {
59
+ throw new CanonicalOwnershipError('instance-busy', 'concurrent acquisition in progress');
60
+ }
61
+ throw error;
62
+ }
63
+ const row = result.rows[0];
64
+ if (row === undefined)
65
+ return null;
66
+ try {
67
+ const epoch = decodePgText(row.epoch);
68
+ if (!isPositiveU64Counter(epoch)) {
69
+ throw new CanonicalOwnershipError('open-refused', 'stored ownership epoch is out of domain');
70
+ }
71
+ return {
72
+ instance: decodePgText(row.instance),
73
+ epoch,
74
+ holderUntilMs: decodeLeaseMs(row.holder_until),
75
+ nowMs: decodeLeaseMs(row.now),
76
+ };
77
+ }
78
+ catch (error) {
79
+ if (error instanceof CanonicalOwnershipError)
80
+ throw error;
81
+ throw new CanonicalOwnershipError('open-refused', 'stored ownership pair is unreadable');
82
+ }
83
+ };
84
+ const leaseParams = (leaseMs) => leaseMs / 1000;
85
+ export const acquirePgInstanceOwnership = async (session, schema, storeKey, moduleId, registry, leaseMs) => {
86
+ // The durable claim runs first; a registry refusal afterwards rolls the
87
+ // open transaction back, so a busy holder never leaves a moved epoch
88
+ // behind. A shared registry refuses a second live holder of this process
89
+ // promptly (no queue); a fresh registry lets the lease row arbitrate
90
+ // across processes through refusal (never supersede).
91
+ for (let attempt = 0; attempt < 2; attempt++) {
92
+ const row = await readPair(session, schema, moduleId, true);
93
+ if (row !== null && row.holderUntilMs > row.nowMs) {
94
+ throw new CanonicalOwnershipError('instance-busy', `live holder retained for ${storeKey}`);
95
+ }
96
+ const epoch = row === null ? '1' : nextU64Counter(row.epoch);
97
+ if (epoch === undefined) {
98
+ throw new CanonicalOwnershipError('stale-epoch', `epoch allocation exhausted at ${row?.epoch}`);
99
+ }
100
+ const instance = row === null ? `instance-${randomUUID()}` : row.instance;
101
+ const claimed = await session.execute({
102
+ text: row === null
103
+ ? `INSERT INTO ${schema}.instance_ownership(module, instance, epoch, holder_until) VALUES($1, $2, $3, clock_timestamp() + make_interval(secs => $4)) ON CONFLICT(module) DO NOTHING`
104
+ : `UPDATE ${schema}.instance_ownership SET instance=$2, epoch=$3, holder_until = clock_timestamp() + make_interval(secs => $4) WHERE module=$1`,
105
+ values: [moduleId, instance, epoch, leaseParams(leaseMs)],
106
+ }).catch((error) => {
107
+ if (acquisitionRaced(error)) {
108
+ throw new CanonicalOwnershipError('instance-busy', 'concurrent acquisition in progress');
109
+ }
110
+ throw error;
111
+ });
112
+ if (row === null && claimed.rowCount === 0)
113
+ continue;
114
+ if (row !== null && claimed.rowCount !== 1) {
115
+ throw new CanonicalOwnershipError('instance-busy', `concurrent open won the store ${storeKey}`);
116
+ }
117
+ const registryHandle = registry.acquire(storeKey, epoch);
118
+ const handle = Object.freeze({ instanceId: instance, storageEpoch: epoch, storeKey });
119
+ return { handle, registryHandle };
120
+ }
121
+ throw new CanonicalOwnershipError('instance-busy', `concurrent acquisition in progress for ${storeKey}`);
122
+ };
123
+ export const verifyPgInstanceOwnership = async (session, schema, moduleId, handle, released) => {
124
+ if (released)
125
+ throw new CanonicalOwnershipError('stale-epoch', 'ownership handle was released');
126
+ const row = await readPair(session, schema, moduleId, false);
127
+ if (row === null)
128
+ throw new CanonicalOwnershipError('terminal-loss', 'ownership row is gone');
129
+ if (row.instance !== handle.instanceId)
130
+ throw new CanonicalOwnershipError('terminal-loss', 'ownership moved to another instance');
131
+ if (row.epoch !== handle.storageEpoch) {
132
+ if (row.holderUntilMs > row.nowMs)
133
+ throw new CanonicalOwnershipError('stale-epoch', 'ownership superseded by a live successor');
134
+ throw new CanonicalOwnershipError('terminal-loss', 'ownership moved to a newer epoch');
135
+ }
136
+ if (row.holderUntilMs <= row.nowMs)
137
+ throw new CanonicalOwnershipError('terminal-loss', 'retained session expired');
138
+ };
139
+ export const renewPgInstanceLease = async (session, schema, moduleId, handle, released, leaseMs) => {
140
+ await verifyPgInstanceOwnership(session, schema, moduleId, handle, released);
141
+ const moved = await session.execute({
142
+ text: `UPDATE ${schema}.instance_ownership SET holder_until = clock_timestamp() + make_interval(secs => $4) WHERE module=$1 AND instance=$2 AND epoch=$3`,
143
+ values: [moduleId, handle.instanceId, handle.storageEpoch, leaseParams(leaseMs)],
144
+ });
145
+ if (moved.rowCount !== 1) {
146
+ throw new CanonicalOwnershipError('terminal-loss', 'ownership lost during renewal');
147
+ }
148
+ };
149
+ // Release expires the lease without tripping the deferred UPDATE trigger:
150
+ // the row is replaced (same instance and epoch, dead lease) so a prompt
151
+ // takeover keeps instance continuity. Idempotent: a taken-over row is left
152
+ // alone.
153
+ export const expirePgInstanceLease = async (session, schema, moduleId, handle) => {
154
+ const removed = await session.execute({
155
+ text: `DELETE FROM ${schema}.instance_ownership WHERE module=$1 AND instance=$2 AND epoch=$3`,
156
+ values: [moduleId, handle.instanceId, handle.storageEpoch],
157
+ });
158
+ if (removed.rowCount !== 1)
159
+ return;
160
+ await session.execute({
161
+ text: `INSERT INTO ${schema}.instance_ownership(module, instance, epoch, holder_until) VALUES($1, $2, $3, clock_timestamp()) ON CONFLICT(module) DO NOTHING`,
162
+ values: [moduleId, handle.instanceId, handle.storageEpoch],
163
+ });
164
+ };
165
+ //# sourceMappingURL=instance-ownership.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instance-ownership.js","sourceRoot":"","sources":["../../../src/storage/postgres/instance-ownership.ts"],"names":[],"mappings":"AAAA,gEAAgE;AAChE,4EAA4E;AAC5E,4EAA4E;AAC5E,wEAAwE;AACxE,4EAA4E;AAC5E,yEAAyE;AACzE,2EAA2E;AAC3E,4EAA4E;AAC5E,2EAA2E;AAC3E,0EAA0E;AAC1E,sEAAsE;AACtE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAEL,uBAAuB,GAExB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACjE,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAG1C,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAE9C,2EAA2E;AAC3E,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,UAAkB,EAAE,QAAgB,EAAU,EAAE,CAChF,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,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QACzB,MAAM,IAAI,uBAAuB,CAAC,eAAe,EAAE,+BAA+B,CAAC,CAAC;IACtF,CAAC;AACH,CAAC,CAAC;AAEF,0EAA0E;AAC1E,wEAAwE;AACxE,2EAA2E;AAC3E,SAAS;AACT,MAAM,CAAC,MAAM,qBAAqB,GAAG,KAAK,EACxC,OAAkB,EAClB,MAAc,EACd,QAAgB,EAChB,MAA+B,EAChB,EAAE;IACjB,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,OAAO,CAAC;QACpC,IAAI,EAAE,eAAe,MAAM,kEAAkE;QAC7F,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,YAAY,CAAC;KAC3D,CAAC,CAAC;IACH,IAAI,OAAO,CAAC,QAAQ,KAAK,CAAC;QAAE,OAAO;IACnC,MAAM,OAAO,CAAC,OAAO,CAAC;QACpB,IAAI,EAAE,eAAe,MAAM,iIAAiI;QAC5J,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,YAAY,CAAC;KAC3D,CAAC,CAAC;AACL,CAAC,CAAC"}
@@ -3,22 +3,38 @@ import type { JournalFence } from '../staged-core.js';
3
3
  import type { RootConsumer, RootJournalEvent } from '../staged-state.js';
4
4
  import type { PgCore } from './core.js';
5
5
  import type { PgSession } from './protocol.js';
6
+ export type PgPosition = string | bigint | number;
7
+ export declare const pgPosition: (value: PgPosition) => string;
8
+ type PgConsumer = Omit<RootConsumer, 'cursor' | 'scanned' | 'failedSeq'> & {
9
+ cursor: string;
10
+ scanned: string;
11
+ failedSeq: string | null;
12
+ };
13
+ type PgJournalEvent = Omit<RootJournalEvent, 'seq' | 'segment'> & {
14
+ readonly seq: string;
15
+ readonly segment?: {
16
+ readonly operationKey: string;
17
+ readonly from: string;
18
+ readonly to: string;
19
+ };
20
+ };
6
21
  export declare const currentPgJournalFence: (core: PgCore, grant: ScopeGrant<unknown>) => Promise<JournalFence>;
7
22
  export declare const pgSafeCounter: (value: unknown) => number;
8
23
  export declare const assertPgJournalFence: (core: PgCore, session: PgSession, grant: ScopeGrant<unknown>, fence: JournalFence) => Promise<void>;
9
- export declare const pgConsumer: (core: PgCore, session: PgSession, grant: ScopeGrant<unknown>, consumer: string, lock?: boolean) => Promise<RootConsumer>;
10
- export declare const savePgConsumer: (core: PgCore, session: PgSession, grant: ScopeGrant<unknown>, consumer: string, state: RootConsumer) => Promise<void>;
11
- export declare const readPgJournal: (core: PgCore, grant: ScopeGrant<unknown>, after: number, limit: number, consumer?: string) => Promise<{
12
- events: RootJournalEvent[];
13
- watermark: number;
24
+ export declare const pgConsumer: (core: PgCore, session: PgSession, grant: ScopeGrant<unknown>, consumer: string, lock?: boolean) => Promise<PgConsumer>;
25
+ export declare const savePgConsumer: (core: PgCore, session: PgSession, grant: ScopeGrant<unknown>, consumer: string, state: PgConsumer) => Promise<void>;
26
+ export declare const readPgJournal: (core: PgCore, grant: ScopeGrant<unknown>, suppliedAfter: PgPosition, limit: number, consumer?: string) => Promise<{
27
+ events: PgJournalEvent[];
28
+ watermark: string;
14
29
  }>;
15
- export declare const checkpointPgJournal: (core: PgCore, grant: ScopeGrant<unknown>, consumer: string, expected: number, next: number, fence: JournalFence) => Promise<void>;
30
+ export declare const checkpointPgJournal: (core: PgCore, grant: ScopeGrant<unknown>, consumer: string, suppliedExpected: PgPosition, suppliedNext: PgPosition, fence: JournalFence) => Promise<void>;
16
31
  export declare const inspectPgConsumer: (core: PgCore, grant: ScopeGrant<unknown>, consumer: string) => Promise<{
17
- cursor: number;
32
+ cursor: string;
18
33
  status: "running" | "stalled" | "paused";
19
34
  failedEvent: string | null;
20
35
  failedReason: string | null;
21
- lag: number;
36
+ lag: string;
22
37
  }>;
23
38
  export declare const operatePgConsumer: (core: PgCore, grant: ScopeGrant<unknown>, consumer: string, operation: 'poison' | 'pause' | 'retry', eventId: string | null, reason?: string, fence?: JournalFence) => Promise<void>;
39
+ export {};
24
40
  //# sourceMappingURL=journal.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"journal.d.ts","sourceRoot":"","sources":["../../../src/storage/postgres/journal.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEzE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,KAAK,EAAkB,SAAS,EAAE,MAAM,eAAe,CAAC;AAI/D,eAAO,MAAM,qBAAqB,SAAgB,MAAM,SAAS,WAAW,OAAO,CAAC,KAAG,QAAQ,YAAY,CAqBvG,CAAC;AACL,eAAO,MAAM,aAAa,UAAW,OAAO,KAAG,MAM9C,CAAC;AAOF,eAAO,MAAM,oBAAoB,SACzB,MAAM,WACH,SAAS,SACX,WAAW,OAAO,CAAC,SACnB,YAAY,KAClB,QAAQ,IAAI,CAKd,CAAC;AACF,eAAO,MAAM,UAAU,SACf,MAAM,WACH,SAAS,SACX,WAAW,OAAO,CAAC,YAChB,MAAM,qBAEf,QAAQ,YAAY,CAmCtB,CAAC;AACF,eAAO,MAAM,cAAc,SACnB,MAAM,WACH,SAAS,SACX,WAAW,OAAO,CAAC,YAChB,MAAM,SACT,YAAY,KAClB,QAAQ,IAAI,CAKd,CAAC;AACF,eAAO,MAAM,aAAa,SAClB,MAAM,SACL,WAAW,OAAO,CAAC,SACnB,MAAM,SACN,MAAM,aACF,MAAM;;;EAoElB,CAAC;AACF,eAAO,MAAM,mBAAmB,SACxB,MAAM,SACL,WAAW,OAAO,CAAC,YAChB,MAAM,YACN,MAAM,QACV,MAAM,SACL,YAAY,KAClB,QAAQ,IAAI,CAuBd,CAAC;AACF,eAAO,MAAM,iBAAiB,SAAgB,MAAM,SAAS,WAAW,OAAO,CAAC,YAAY,MAAM;;;;;;EA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M,qBAAqB,SAAgB,MAAM,SAAS,WAAW,OAAO,CAAC,KAAG,QAAQ,YAAY,CAqBvG,CAAC;AACL,eAAO,MAAM,aAAa,UAAW,OAAO,KAAG,MAM9C,CAAC;AAOF,eAAO,MAAM,oBAAoB,SACzB,MAAM,WACH,SAAS,SACX,WAAW,OAAO,CAAC,SACnB,YAAY,KAClB,QAAQ,IAAI,CAKd,CAAC;AACF,eAAO,MAAM,UAAU,SACf,MAAM,WACH,SAAS,SACX,WAAW,OAAO,CAAC,YAChB,MAAM,qBAEf,QAAQ,UAAU,CAmCpB,CAAC;AACF,eAAO,MAAM,cAAc,SACnB,MAAM,WACH,SAAS,SACX,WAAW,OAAO,CAAC,YAChB,MAAM,SACT,UAAU,KAChB,QAAQ,IAAI,CAKd,CAAC;AACF,eAAO,MAAM,aAAa,SAClB,MAAM,SACL,WAAW,OAAO,CAAC,iBACX,UAAU,SAClB,MAAM,aACF,MAAM;;;EAmElB,CAAC;AACF,eAAO,MAAM,mBAAmB,SACxB,MAAM,SACL,WAAW,OAAO,CAAC,YAChB,MAAM,oBACE,UAAU,gBACd,UAAU,SACjB,YAAY,KAClB,QAAQ,IAAI,CAwBd,CAAC;AACF,eAAO,MAAM,iBAAiB,SAAgB,MAAM,SAAS,WAAW,OAAO,CAAC,YAAY,MAAM;;;;;;EAY9F,CAAC;AACL,eAAO,MAAM,iBAAiB,SACtB,MAAM,SACL,WAAW,OAAO,CAAC,YAChB,MAAM,aACL,QAAQ,GAAG,OAAO,GAAG,OAAO,WAC9B,MAAM,GAAG,IAAI,WACb,MAAM,UACP,YAAY,KACnB,QAAQ,IAAI,CA6Cd,CAAC"}
@@ -1,7 +1,16 @@
1
1
  import { StorageCapacityExceededError, StorageCasConflictError, StorageInvalidCommandError } from '../errors.js';
2
- import { decodePgCounter, decodePgJson, decodePgText } from './codec.js';
2
+ import { decodePgCounter, decodePgCounterU64, decodePgJson, decodePgText } from './codec.js';
3
3
  import { PostgresStorageError } from './errors.js';
4
4
  import { createHash } from 'node:crypto';
5
+ // Numbers are accepted only as legacy safe inputs, never as database counters.
6
+ export const pgPosition = (value) => {
7
+ if (typeof value === 'number') {
8
+ if (!Number.isSafeInteger(value) || value < 0)
9
+ throw new StorageInvalidCommandError('invalid journal position');
10
+ return String(value);
11
+ }
12
+ return decodePgCounterU64(value);
13
+ };
5
14
  export const currentPgJournalFence = async (core, grant) => core.tx.run(false, async (session) => {
6
15
  await core.check(session, grant, 'maintain', true);
7
16
  const lane = `journal:${createHash('sha256').update(grant.principalId, 'utf8').digest('hex')}`;
@@ -16,7 +25,7 @@ export const currentPgJournalFence = async (core, grant) => core.tx.run(false, a
16
25
  });
17
26
  const fence = {
18
27
  fenceId: lane,
19
- epoch: decodePgCounter(result.rows[0]?.epoch),
28
+ epoch: decodePgCounterU64(result.rows[0]?.epoch),
20
29
  incarnation: core.incarnation,
21
30
  ownerId: grant.principalId,
22
31
  };
@@ -46,8 +55,8 @@ export const pgConsumer = async (core, session, grant, consumer, lock = true) =>
46
55
  if (typeof consumer !== 'string' || !consumer || consumer.length > 1024)
47
56
  throw new StorageInvalidCommandError('invalid consumer');
48
57
  const initial = {
49
- cursor: 0,
50
- scanned: 0,
58
+ cursor: '0',
59
+ scanned: '0',
51
60
  status: 'running',
52
61
  failedEvent: null,
53
62
  failedReason: null,
@@ -68,10 +77,11 @@ export const pgConsumer = async (core, session, grant, consumer, lock = true) =>
68
77
  if (!result.rows[0])
69
78
  return initial;
70
79
  const state = decodePgJson(decodePgText(result.rows[0].state));
71
- if (!Number.isSafeInteger(state.cursor) ||
72
- !Number.isSafeInteger(state.scanned) ||
73
- state.cursor < 0 ||
74
- state.scanned < state.cursor ||
80
+ state.cursor = pgPosition(state.cursor);
81
+ state.scanned = pgPosition(state.scanned);
82
+ if (state.failedSeq !== null)
83
+ state.failedSeq = pgPosition(state.failedSeq);
84
+ if (BigInt(state.scanned) < BigInt(state.cursor) ||
75
85
  !['running', 'paused', 'stalled'].includes(state.status) ||
76
86
  !Array.isArray(state.actions))
77
87
  throw new PostgresStorageError('corruption');
@@ -83,10 +93,9 @@ export const savePgConsumer = async (core, session, grant, consumer, state) => {
83
93
  values: [JSON.stringify(state), core.roots.key(grant.scope), consumer],
84
94
  });
85
95
  };
86
- export const readPgJournal = async (core, grant, after, limit, consumer) => {
87
- if (!Number.isSafeInteger(after) ||
88
- after < 0 ||
89
- !Number.isSafeInteger(limit) ||
96
+ export const readPgJournal = async (core, grant, suppliedAfter, limit, consumer) => {
97
+ const after = BigInt(pgPosition(suppliedAfter));
98
+ if (!Number.isSafeInteger(limit) ||
90
99
  limit < 1 ||
91
100
  limit > core.work().maxRecords)
92
101
  throw new StorageInvalidCommandError('invalid journal window');
@@ -95,8 +104,8 @@ export const readPgJournal = async (core, grant, after, limit, consumer) => {
95
104
  if (consumer !== undefined)
96
105
  await core.check(session, grant, 'maintain', true);
97
106
  const base = await core.roots.capture(session, grant.scope);
98
- const watermark = pgSafeCounter(base.sequence);
99
- if (after > watermark)
107
+ const watermark = decodePgCounterU64(base.sequence);
108
+ if (after > BigInt(watermark))
100
109
  throw new StorageInvalidCommandError('journal position exceeds watermark');
101
110
  const state = consumer === undefined ? undefined : await pgConsumer(core, session, grant, consumer);
102
111
  const events = [];
@@ -110,14 +119,14 @@ export const readPgJournal = async (core, grant, after, limit, consumer) => {
110
119
  }
111
120
  : await session.execute({
112
121
  text: `SELECT j.sequence::text, j.event::text FROM ${core.roots.schema}.journal AS j
113
- WHERE j.scope_key=$1 AND j.sequence>$2::bigint ORDER BY j.sequence
122
+ WHERE j.scope_key=$1 AND j.sequence>$2::numeric ORDER BY j.sequence
114
123
  LIMIT $3`,
115
124
  values: [core.roots.key(grant.scope), String(after), limit],
116
125
  });
117
126
  for (const row of result.rows) {
118
- const seq = pgSafeCounter(row.sequence);
127
+ const seq = decodePgCounterU64(row.sequence);
119
128
  const event = decodePgJson(decodePgText(row.event));
120
- if (seq !== after + events.length + 1 || String(seq) !== event.seq || typeof event.eventId !== 'string')
129
+ if (BigInt(seq) !== after + BigInt(events.length) + 1n || seq !== event.seq || typeof event.eventId !== 'string')
121
130
  throw new PostgresStorageError('corruption');
122
131
  const value = {
123
132
  ...event,
@@ -127,8 +136,8 @@ export const readPgJournal = async (core, grant, after, limit, consumer) => {
127
136
  ? {
128
137
  segment: {
129
138
  ...event.segment,
130
- from: pgSafeCounter(event.segment.from),
131
- to: pgSafeCounter(event.segment.to),
139
+ from: decodePgCounterU64(event.segment.from),
140
+ to: decodePgCounterU64(event.segment.to),
132
141
  },
133
142
  }
134
143
  : { segment: undefined }),
@@ -138,13 +147,13 @@ export const readPgJournal = async (core, grant, after, limit, consumer) => {
138
147
  break;
139
148
  events.push(value);
140
149
  if (state) {
141
- if (after <= state.scanned)
142
- state.scanned = Math.max(state.scanned, seq);
150
+ if (after <= BigInt(state.scanned) && BigInt(seq) > BigInt(state.scanned))
151
+ state.scanned = seq;
143
152
  if (state.retryAuthorized && state.failedEvent === value.eventId)
144
153
  state.deliveredPoison = true;
145
154
  }
146
155
  }
147
- if (events.length === 0 && after < watermark)
156
+ if (events.length === 0 && after < BigInt(watermark))
148
157
  throw new StorageCapacityExceededError('journal replay is unavailable or event exceeds its byte budget');
149
158
  }
150
159
  if (state)
@@ -152,20 +161,21 @@ export const readPgJournal = async (core, grant, after, limit, consumer) => {
152
161
  return { events, watermark };
153
162
  });
154
163
  };
155
- export const checkpointPgJournal = async (core, grant, consumer, expected, next, fence) => {
164
+ export const checkpointPgJournal = async (core, grant, consumer, suppliedExpected, suppliedNext, fence) => {
165
+ const expected = pgPosition(suppliedExpected);
166
+ const next = pgPosition(suppliedNext);
156
167
  await core.tx.run(false, async (session) => {
157
168
  await assertPgJournalFence(core, session, grant, fence);
158
169
  const state = await pgConsumer(core, session, grant, consumer);
159
170
  if (state.cursor !== expected)
160
171
  throw new StorageCasConflictError('checkpoint changed');
161
- if (!Number.isSafeInteger(next) ||
162
- next < expected ||
163
- next > state.scanned ||
172
+ if (BigInt(next) < BigInt(expected) ||
173
+ BigInt(next) > BigInt(state.scanned) ||
164
174
  state.status !== 'running' ||
165
- (state.failedSeq !== null && next >= state.failedSeq && (!state.retryAuthorized || !state.deliveredPoison)))
175
+ (state.failedSeq !== null && BigInt(next) >= BigInt(state.failedSeq) && (!state.retryAuthorized || !state.deliveredPoison)))
166
176
  throw new StorageInvalidCommandError('checkpoint exceeds delivered progress or unresolved poison');
167
177
  state.cursor = next;
168
- if (state.failedSeq !== null && next >= state.failedSeq) {
178
+ if (state.failedSeq !== null && BigInt(next) >= BigInt(state.failedSeq)) {
169
179
  state.failedSeq = null;
170
180
  state.failedEvent = null;
171
181
  state.failedReason = null;
@@ -184,7 +194,7 @@ export const inspectPgConsumer = async (core, grant, consumer) => core.tx.run(tr
184
194
  status: state.status,
185
195
  failedEvent: state.failedEvent,
186
196
  failedReason: state.failedReason,
187
- lag: pgSafeCounter(base.sequence) - state.cursor,
197
+ lag: (BigInt(decodePgCounterU64(base.sequence)) - BigInt(state.cursor)).toString(),
188
198
  };
189
199
  });
190
200
  export const operatePgConsumer = async (core, grant, consumer, operation, eventId, reason, fence) => {
@@ -201,9 +211,10 @@ export const operatePgConsumer = async (core, grant, consumer, operation, eventI
201
211
  text: `SELECT sequence::text FROM ${core.roots.schema}.journal WHERE scope_key=$1 AND event_id=$2`,
202
212
  values: [core.roots.key(grant.scope), eventId],
203
213
  });
204
- const seq = rows.rows[0] ? pgSafeCounter(rows.rows[0].sequence) : -1;
205
- if (seq <= state.cursor ||
206
- seq > state.scanned ||
214
+ const seq = rows.rows[0] ? decodePgCounterU64(rows.rows[0].sequence) : null;
215
+ if (seq === null ||
216
+ BigInt(seq) <= BigInt(state.cursor) ||
217
+ BigInt(seq) > BigInt(state.scanned) ||
207
218
  !reason ||
208
219
  reason.length > 4096 ||
209
220
  (state.failedEvent !== null && state.failedEvent !== eventId))