@pgxsinkit/client 0.6.0 → 0.6.2

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 (64) hide show
  1. package/dist/boot-report.d.ts.map +1 -1
  2. package/dist/circuits/envelope-to-change.d.ts.map +1 -1
  3. package/dist/circuits/group-sync.d.ts.map +1 -1
  4. package/dist/circuits/long-poll.d.ts.map +1 -1
  5. package/dist/circuits/shape-group.d.ts.map +1 -1
  6. package/dist/circuits/stream-inbox.d.ts.map +1 -1
  7. package/dist/circuits/stream-source.d.ts.map +1 -1
  8. package/dist/circuits/subscription-client.d.ts.map +1 -1
  9. package/dist/circuits/sync-engine.d.ts.map +1 -1
  10. package/dist/convergence.d.ts.map +1 -1
  11. package/dist/debug.d.ts.map +1 -1
  12. package/dist/error-chain.d.ts.map +1 -1
  13. package/dist/event-lane.d.ts.map +1 -1
  14. package/dist/export-data.d.ts.map +1 -1
  15. package/dist/export-dump.d.ts.map +1 -1
  16. package/dist/export-store.d.ts.map +1 -1
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +205 -85
  19. package/dist/index.js.map +4 -4
  20. package/dist/lazy-guard.d.ts.map +1 -1
  21. package/dist/lifecycle-slot.d.ts.map +1 -1
  22. package/dist/live-rows-sql.d.ts.map +1 -1
  23. package/dist/local-store.d.ts.map +1 -1
  24. package/dist/local-tables.d.ts.map +1 -1
  25. package/dist/mutation-state.d.ts +3 -1
  26. package/dist/mutation-state.d.ts.map +1 -1
  27. package/dist/mutation.d.ts.map +1 -1
  28. package/dist/mutations-api.d.ts.map +1 -1
  29. package/dist/opfs-effects.d.ts.map +1 -1
  30. package/dist/placement-probe.d.ts.map +1 -1
  31. package/dist/retry-after.d.ts.map +1 -1
  32. package/dist/schema.d.ts.map +1 -1
  33. package/dist/store-boot.d.ts.map +1 -1
  34. package/dist/store-build.d.ts.map +1 -1
  35. package/dist/store-engine.d.ts.map +1 -1
  36. package/dist/store-lifecycle.d.ts.map +1 -1
  37. package/dist/store-meta.d.ts.map +1 -1
  38. package/dist/store-ownership-lock.d.ts.map +1 -1
  39. package/dist/store-path.d.ts.map +1 -1
  40. package/dist/sync/apply.d.ts.map +1 -1
  41. package/dist/sync/copy.d.ts.map +1 -1
  42. package/dist/sync/drizzle-executor.d.ts.map +1 -1
  43. package/dist/sync/fold.d.ts.map +1 -1
  44. package/dist/sync/metadata-tables.d.ts.map +1 -1
  45. package/dist/sync/subscription-state.d.ts.map +1 -1
  46. package/dist/sync/types.d.ts.map +1 -1
  47. package/dist/testing.d.ts.map +1 -1
  48. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  49. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  50. package/dist/worker/election-coordinator.d.ts.map +1 -1
  51. package/dist/worker/engine-control.d.ts.map +1 -1
  52. package/dist/worker/engine-router.d.ts.map +1 -1
  53. package/dist/worker/live-diff.d.ts.map +1 -1
  54. package/dist/worker/live-query-fingerprint.d.ts.map +1 -1
  55. package/dist/worker/live-query-manager.d.ts.map +1 -1
  56. package/dist/worker/live-query-params-guard.d.ts.map +1 -1
  57. package/dist/worker/protocol.d.ts.map +1 -1
  58. package/dist/worker/sw-placement.d.ts.map +1 -1
  59. package/dist/worker/token-cache.d.ts.map +1 -1
  60. package/package.json +5 -5
  61. package/skills/core/SKILL.md +9 -1
  62. package/skills/operating/SKILL.md +1 -1
  63. package/src/mutation-state.ts +3 -1
  64. package/src/mutation.ts +279 -121
package/src/mutation.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  and,
3
+ asc,
3
4
  desc,
4
5
  eq,
5
6
  exists,
@@ -9,6 +10,7 @@ import {
9
10
  is,
10
11
  isNotNull,
11
12
  isNull,
13
+ like,
12
14
  lt,
13
15
  ne,
14
16
  notExists,
@@ -823,6 +825,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
823
825
  payloadJson: jsonStringifyPayload({
824
826
  kind: "create",
825
827
  value: item.input,
828
+ localValue: item.optimisticRecord,
826
829
  }),
827
830
  nowUs: item.nowUs,
828
831
  // A create has no Base server version (ADR-0015): its conflict is a PK collision, a
@@ -1226,6 +1229,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1226
1229
 
1227
1230
  const url = mutationUrls.authoritative;
1228
1231
  let acksByMutationId: Map<string, BatchMutationAck["acks"][number]>;
1232
+ let rejectedRequest: MutationRequestError | undefined;
1229
1233
 
1230
1234
  try {
1231
1235
  const authToken = await untilAborted(Promise.resolve(options.getAuthToken?.()));
@@ -1258,124 +1262,150 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1258
1262
  const responseJson = (await response.json()) as BatchMutationAck;
1259
1263
  acksByMutationId = new Map(responseJson.acks.map((ack) => [ack.mutationId, ack]));
1260
1264
  } catch (error) {
1261
- // A pessimistic write is foreground: it never reached the server (transport / non-2xx), so the
1262
- // unit did not happen. Mark it failed — KEEPING the optimistic overlay so a retry can resend — and
1263
- // rethrow so the caller surfaces it. There is no background retry for pessimistic units.
1264
- const failedAtUs = nowMicroseconds();
1265
- const httpStatus = error instanceof MutationRequestError ? error.status : null;
1266
- const errorMessage = error instanceof Error ? error.message : "Authoritative write failed";
1267
- for (const rows of byContext.values()) {
1268
- await applyMutationStatusUpdates(
1269
- options.db,
1270
- rows[0]!.context,
1271
- rows.map((row) => {
1272
- const attemptCount = row.attemptCount + 1;
1273
- const outcome = resolveBatchFailureOutcome(attemptCount, maxMutationAttempts, failedAtUs);
1274
- return {
1275
- mutationId: row.mutationId,
1276
- status: outcome.status,
1277
- attemptCount,
1278
- updatedAtUs: failedAtUs,
1279
- lastError: errorMessage,
1280
- nextRetryAtUs: outcome.nextRetryAtUs,
1281
- lastHttpStatus: httpStatus,
1282
- conflictReason: null,
1283
- };
1284
- }),
1265
+ // A definitive structural refusal declines this whole atomic unit. Settle it through the same
1266
+ // rejection path as a typed business refusal, then preserve the foreground request error.
1267
+ // Transport, auth and server faults leave the outcome unknown and keep the edits for a retry.
1268
+ if (error instanceof MutationRequestError && classifyFailureStatus(error.status) === "quarantined") {
1269
+ rejectedRequest = error;
1270
+ acksByMutationId = new Map(
1271
+ mutations.map((mutation) => [
1272
+ mutation.mutationId,
1273
+ { ...mutation, status: "rejected" as const, httpStatus: error.status, rejectionReason: error.message },
1274
+ ]),
1285
1275
  );
1276
+ } else {
1277
+ const failedAtUs = nowMicroseconds();
1278
+ const httpStatus = error instanceof MutationRequestError ? error.status : null;
1279
+ const errorMessage = error instanceof Error ? error.message : "Authoritative write failed";
1280
+ for (const rows of byContext.values()) {
1281
+ await applyMutationStatusUpdates(
1282
+ options.db,
1283
+ rows[0]!.context,
1284
+ rows.map((row) => {
1285
+ const attemptCount = row.attemptCount + 1;
1286
+ const outcome = resolveBatchFailureOutcome(attemptCount, maxMutationAttempts, failedAtUs);
1287
+ return {
1288
+ mutationId: row.mutationId,
1289
+ status: outcome.status,
1290
+ attemptCount,
1291
+ updatedAtUs: failedAtUs,
1292
+ lastError: errorMessage,
1293
+ nextRetryAtUs: outcome.nextRetryAtUs,
1294
+ lastHttpStatus: httpStatus,
1295
+ conflictReason: null,
1296
+ };
1297
+ }),
1298
+ );
1299
+ }
1300
+ throw error;
1286
1301
  }
1287
- throw error;
1288
1302
  }
1289
1303
 
1290
1304
  // Apply each member's ack.
1291
1305
  const ackedAtUs = nowMicroseconds();
1292
1306
  const failedAtUs = nowMicroseconds();
1293
- const rejectedIds = new Set<string>();
1307
+ const rejectedIds = new Set(
1308
+ prepared
1309
+ .filter((row) => acksByMutationId.get(row.mutationId)?.status === "rejected")
1310
+ .map((row) => row.mutationId),
1311
+ );
1294
1312
  const conflictedIds = new Set<string>();
1295
1313
 
1296
- for (const rows of byContext.values()) {
1297
- await applyMutationStatusUpdates(
1298
- options.db,
1299
- rows[0]!.context,
1300
- rows.map((row) => {
1301
- const ack = acksByMutationId.get(row.mutationId);
1314
+ const settleUnit = async () => {
1315
+ for (const rows of byContext.values()) {
1316
+ await applyMutationStatusUpdates(
1317
+ options.db,
1318
+ rows[0]!.context,
1319
+ rows.map((row) => {
1320
+ const ack = acksByMutationId.get(row.mutationId);
1321
+
1322
+ if (ack?.status === "rejected") {
1323
+ // ADR-0022 §4: a business rejection. Terminal `rejected`; the overlay is auto-discarded below.
1324
+ rejectedIds.add(row.mutationId);
1325
+ return {
1326
+ mutationId: row.mutationId,
1327
+ status: "rejected" as const,
1328
+ attemptCount: row.attemptCount + 1,
1329
+ updatedAtUs: failedAtUs,
1330
+ lastError: ack.rejectionReason ?? "Rejected by the authoritative endpoint",
1331
+ nextRetryAtUs: null,
1332
+ lastHttpStatus: ack.httpStatus ?? 409,
1333
+ conflictReason: ack.rejectionReason ?? "Rejected by the authoritative endpoint",
1334
+ };
1335
+ }
1302
1336
 
1303
- if (ack?.status === "rejected") {
1304
- // ADR-0022 §4: a business rejection. Terminal `rejected`; the overlay is auto-discarded below.
1305
- rejectedIds.add(row.mutationId);
1306
- return {
1307
- mutationId: row.mutationId,
1308
- status: "rejected" as const,
1309
- attemptCount: row.attemptCount + 1,
1310
- updatedAtUs: failedAtUs,
1311
- lastError: ack.rejectionReason ?? "Rejected by the authoritative endpoint",
1312
- nextRetryAtUs: null,
1313
- lastHttpStatus: ack.httpStatus ?? 409,
1314
- conflictReason: ack.rejectionReason ?? "Rejected by the authoritative endpoint",
1315
- };
1316
- }
1337
+ if (ack?.status === "conflicted") {
1338
+ // ADR-0015: a stale member — terminal `conflicted`, overlay KEPT (resolve as a new write).
1339
+ conflictedIds.add(row.mutationId);
1340
+ return {
1341
+ mutationId: row.mutationId,
1342
+ status: "conflicted" as const,
1343
+ attemptCount: row.attemptCount + 1,
1344
+ updatedAtUs: failedAtUs,
1345
+ serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,
1346
+ replaceServerUpdatedAtUs: true,
1347
+ lastError: ack.conflictReason ?? "Stale write rejected (reject-if-stale)",
1348
+ nextRetryAtUs: null,
1349
+ lastHttpStatus: ack.httpStatus ?? 409,
1350
+ conflictReason: ack.conflictReason ?? "Stale write rejected (reject-if-stale)",
1351
+ };
1352
+ }
1353
+
1354
+ if (!ack || ack.status !== "acked") {
1355
+ const attemptCount = row.attemptCount + 1;
1356
+ const outcome = resolveFailureOutcome(
1357
+ ack?.httpStatus ?? null,
1358
+ attemptCount,
1359
+ maxMutationAttempts,
1360
+ failedAtUs,
1361
+ );
1362
+ return {
1363
+ mutationId: row.mutationId,
1364
+ status: outcome.status,
1365
+ attemptCount,
1366
+ updatedAtUs: failedAtUs,
1367
+ lastError: ack?.conflictReason ?? "Authoritative write not acknowledged",
1368
+ nextRetryAtUs: outcome.nextRetryAtUs,
1369
+ lastHttpStatus: ack?.httpStatus ?? null,
1370
+ conflictReason: null,
1371
+ };
1372
+ }
1317
1373
 
1318
- if (ack?.status === "conflicted") {
1319
- // ADR-0015: a stale member — terminal `conflicted`, overlay KEPT (resolve as a new write).
1320
- conflictedIds.add(row.mutationId);
1321
1374
  return {
1322
1375
  mutationId: row.mutationId,
1323
- status: "conflicted" as const,
1376
+ status: "acked" as const,
1324
1377
  attemptCount: row.attemptCount + 1,
1325
- updatedAtUs: failedAtUs,
1378
+ updatedAtUs: ackedAtUs,
1379
+ ackedAtUs,
1380
+ replaceAckedAtUs: true,
1326
1381
  serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,
1327
1382
  replaceServerUpdatedAtUs: true,
1328
- lastError: ack.conflictReason ?? "Stale write rejected (reject-if-stale)",
1383
+ lastError: null,
1329
1384
  nextRetryAtUs: null,
1330
- lastHttpStatus: ack.httpStatus ?? 409,
1331
- conflictReason: ack.conflictReason ?? "Stale write rejected (reject-if-stale)",
1332
- };
1333
- }
1334
-
1335
- if (!ack || ack.status !== "acked") {
1336
- const attemptCount = row.attemptCount + 1;
1337
- const outcome = resolveFailureOutcome(
1338
- ack?.httpStatus ?? null,
1339
- attemptCount,
1340
- maxMutationAttempts,
1341
- failedAtUs,
1342
- );
1343
- return {
1344
- mutationId: row.mutationId,
1345
- status: outcome.status,
1346
- attemptCount,
1347
- updatedAtUs: failedAtUs,
1348
- lastError: ack?.conflictReason ?? "Authoritative write not acknowledged",
1349
- nextRetryAtUs: outcome.nextRetryAtUs,
1350
- lastHttpStatus: ack?.httpStatus ?? null,
1385
+ lastHttpStatus: row.mutationKind === "delete" ? 204 : 200,
1351
1386
  conflictReason: null,
1352
1387
  };
1353
- }
1354
-
1355
- return {
1356
- mutationId: row.mutationId,
1357
- status: "acked" as const,
1358
- attemptCount: row.attemptCount + 1,
1359
- updatedAtUs: ackedAtUs,
1360
- ackedAtUs,
1361
- replaceAckedAtUs: true,
1362
- serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,
1363
- replaceServerUpdatedAtUs: true,
1364
- lastError: null,
1365
- nextRetryAtUs: null,
1366
- lastHttpStatus: row.mutationKind === "delete" ? 204 : 200,
1367
- conflictReason: null,
1368
- };
1369
- }),
1370
- );
1371
- }
1388
+ }),
1389
+ );
1390
+ }
1372
1391
 
1373
- // ADR-0022 §4: auto-discard the optimistic overlay for every rejected entity (the whole unit was
1374
- // declined). The terminal `rejected` journal row is kept for diagnostics + `onReject`.
1375
- for (const row of prepared) {
1376
- if (rejectedIds.has(row.mutationId)) {
1377
- await discardOverlayForSettledEntity(options.db, row.context, row.entityKey, row.entityKeyJson);
1392
+ // Journal settlement and rollback share one commit. A reopened store must never retain an
1393
+ // overlay containing a rejection that its journal has already marked terminal.
1394
+ if (rejectedIds.size > 0) {
1395
+ const restored = new Set<string>();
1396
+ for (const row of prepared) {
1397
+ const key = `${row.context.key}:${row.entityKeyJson}`;
1398
+ if (rejectedIds.has(row.mutationId) && !restored.has(key)) {
1399
+ await restoreOverlayAfterRejection(options.db, row.context, row.entityKey, row.entityKeyJson);
1400
+ restored.add(key);
1401
+ }
1402
+ }
1378
1403
  }
1404
+ };
1405
+ if (rejectedIds.size > 0) {
1406
+ await runInTransaction(settleUnit);
1407
+ } else {
1408
+ await settleUnit();
1379
1409
  }
1380
1410
 
1381
1411
  const affectedContexts = [...byContext.keys()]
@@ -1402,6 +1432,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1402
1432
  // self-verifying clear — it settles the marker to `false` iff no `sending` row remains anywhere.
1403
1433
  await settleRecoveryMarker();
1404
1434
 
1435
+ if (rejectedRequest) throw rejectedRequest;
1405
1436
  return { acks: [...acksByMutationId.values()] };
1406
1437
  },
1407
1438
  reconcile: async (table) => {
@@ -1413,9 +1444,73 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1413
1444
  },
1414
1445
  retryFailed: async (table) => {
1415
1446
  assertValidMutationTransition("failed", "pending");
1447
+ assertValidMutationTransition("failed", "rejected");
1416
1448
  const contexts = filterContexts(tableContexts, table);
1417
1449
  const nowUs = nowMicroseconds();
1418
1450
 
1451
+ // Older clients kept definitive foreground refusals as failed. An explicit retry settles those
1452
+ // known-declined units locally, including their members on other tables, without resending them.
1453
+ const allContexts = filterContexts(tableContexts, undefined);
1454
+ const declinedUnits = new Set<string>();
1455
+ for (const context of contexts) {
1456
+ const journal = context.tables.journal;
1457
+ const query = queryBuilder
1458
+ .select({
1459
+ unit: sql<string>`${journal.writeUnit}`.as("unit"),
1460
+ httpStatus: sql<number>`${journal.lastHttpStatus}`.as("httpStatus"),
1461
+ })
1462
+ .from(journal)
1463
+ .where(
1464
+ and(eq(journal.status, "failed"), like(journal.writeMode, "pessimistic%"), isNotNull(journal.writeUnit)),
1465
+ )
1466
+ .toSQL();
1467
+ for (const row of (
1468
+ await options.db.query<{ unit: string; httpStatus: number }>(query.sql, query.params as unknown[])
1469
+ ).rows) {
1470
+ if (classifyFailureStatus(row.httpStatus) === "quarantined") declinedUnits.add(row.unit);
1471
+ }
1472
+ }
1473
+ const repaired = new Set<string>();
1474
+ for (const unitId of declinedUnits) {
1475
+ await runInTransaction(async () => {
1476
+ const rows = await readUnitPendingRows(options.db, allContexts, unitId, null);
1477
+ if (
1478
+ !rows.length ||
1479
+ rows.some((row) => row.status !== "failed" || classifyFailureStatus(row.lastHttpStatus) !== "quarantined")
1480
+ )
1481
+ return;
1482
+ const entities = new Set<string>();
1483
+ for (const row of rows) {
1484
+ const context = tableContexts[row.tableKey]!;
1485
+ await applyMutationStatusUpdates(options.db, context, [
1486
+ {
1487
+ mutationId: row.mutationId,
1488
+ status: "rejected",
1489
+ attemptCount: row.attemptCount,
1490
+ updatedAtUs: nowUs,
1491
+ lastError: row.lastError,
1492
+ conflictReason: row.lastError ?? "Rejected by the authoritative endpoint",
1493
+ lastHttpStatus: row.lastHttpStatus,
1494
+ nextRetryAtUs: null,
1495
+ },
1496
+ ]);
1497
+ repaired.add(row.mutationId);
1498
+ }
1499
+ for (const row of rows) {
1500
+ const key = `${row.tableKey}:${row.entityKeyJson}`;
1501
+ if (!entities.has(key)) {
1502
+ await restoreOverlayAfterRejection(
1503
+ options.db,
1504
+ tableContexts[row.tableKey]!,
1505
+ JSON.parse(row.entityKeyJson) as Record<string, string>,
1506
+ row.entityKeyJson,
1507
+ );
1508
+ entities.add(key);
1509
+ }
1510
+ }
1511
+ });
1512
+ }
1513
+
1419
1514
  for (const context of contexts) {
1420
1515
  const journal = context.tables.journal;
1421
1516
  const query = queryBuilder
@@ -1425,6 +1520,9 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1425
1520
  .toSQL();
1426
1521
  await options.db.query(query.sql, query.params as unknown[]);
1427
1522
  }
1523
+ if (repaired.size > 0 && options.onReject) {
1524
+ await options.onReject(await readMutationDetailsForContexts(options.db, allContexts, repaired));
1525
+ }
1428
1526
  },
1429
1527
  recoverSending: async (table) => {
1430
1528
  assertValidMutationTransition("sending", "pending");
@@ -2556,6 +2654,7 @@ async function readUnitPendingRows(
2556
2654
  db: MutationDb,
2557
2655
  contexts: TableContext[],
2558
2656
  unitId: string,
2657
+ statuses: MutationStatus[] | null = ["pending", "failed"],
2559
2658
  ): Promise<PendingBatchRow[]> {
2560
2659
  if (contexts.length === 0) {
2561
2660
  return [];
@@ -2566,7 +2665,7 @@ async function readUnitPendingRows(
2566
2665
  return queryBuilder
2567
2666
  .select(buildPendingRowsProjection(context))
2568
2667
  .from(journal)
2569
- .where(and(eq(journal.writeUnit, unitId), inArray(journal.status, ["pending", "failed"])));
2668
+ .where(and(eq(journal.writeUnit, unitId), statuses ? inArray(journal.status, statuses) : undefined));
2570
2669
  });
2571
2670
 
2572
2671
  const query = queryDialect.sqlToQuery(
@@ -3095,26 +3194,15 @@ async function discardTerminalEntity(
3095
3194
  }
3096
3195
 
3097
3196
  /**
3098
- * The shared overlay-discard statement: delete the entity's overlay row unless a journal row still
3099
- * owes the entity — `owedStatuses` narrows which journal rows count as "owed" (all of them for a
3100
- * conflict discard; only the un-sent pending/sending/failed set for a settled-unit discard).
3197
+ * Delete an explicitly discarded entity's overlay only after its journal is empty.
3101
3198
  */
3102
- function buildOverlayDiscardQuery(
3103
- context: TableContext,
3104
- entityKey: Record<string, string>,
3105
- entityKeyJson: string,
3106
- owedStatuses?: MutationStatus[],
3107
- ) {
3199
+ function buildOverlayDiscardQuery(context: TableContext, entityKey: Record<string, string>, entityKeyJson: string) {
3108
3200
  const overlay = context.tables.overlay;
3109
3201
  const journal = context.tables.journal;
3110
3202
  const owed = queryBuilder
3111
3203
  .select({ one: sql`1` })
3112
3204
  .from(journal)
3113
- .where(
3114
- owedStatuses
3115
- ? and(eq(journal.entityKeyJson, entityKeyJson), inArray(journal.status, owedStatuses))
3116
- : eq(journal.entityKeyJson, entityKeyJson),
3117
- );
3205
+ .where(eq(journal.entityKeyJson, entityKeyJson));
3118
3206
 
3119
3207
  return queryBuilder
3120
3208
  .delete(overlay)
@@ -3129,20 +3217,90 @@ function buildOverlayDiscardQuery(
3129
3217
  .toSQL();
3130
3218
  }
3131
3219
 
3132
- /**
3133
- * Auto-discard the optimistic overlay for an entity whose pessimistic write-unit the authoritative endpoint
3134
- * `rejected` (ADR-0022 §4). Unlike {@link discardTerminalEntity} this KEEPS the terminal `rejected` journal
3135
- * row (for diagnostics + `onReject`); it only clears the overlay, and only when no still-owed
3136
- * (`pending`/`sending`/`failed`) journal row depends on it — so a later un-sent write never loses its overlay.
3137
- */
3138
- async function discardOverlayForSettledEntity(
3220
+ /** Rebuild one shared overlay without declined units. The caller owns the local transaction. */
3221
+ async function restoreOverlayAfterRejection(
3139
3222
  db: MutationDb,
3140
3223
  context: TableContext,
3141
3224
  entityKey: Record<string, string>,
3142
3225
  entityKeyJson: string,
3143
3226
  ) {
3144
- const query = buildOverlayDiscardQuery(context, entityKey, entityKeyJson, ["pending", "sending", "failed"]);
3145
- await db.query(query.sql, query.params as unknown[]);
3227
+ const syncedQuery = queryDialect.sqlToQuery(
3228
+ sql`SELECT ${buildProjectedSelectColumns(context, context.syncedColumnsByPropertyKey)}
3229
+ FROM ${context.tables.synced}
3230
+ WHERE ${and(...context.pkColumnNames.map((name, i) => eq(context.syncedPkColumns[i]!, entityKey[name])))}`,
3231
+ );
3232
+ const synced = (await db.query(syncedQuery.sql, syncedQuery.params as unknown[])).rows[0];
3233
+ const journal = context.tables.journal;
3234
+ const query = queryBuilder
3235
+ .select({
3236
+ kind: sql<MutationKind>`${journal.mutationKind}`.as("kind"),
3237
+ payload: sql<string>`${journal.payloadJson}`.as("payload"),
3238
+ status: journal.status,
3239
+ writeMode: sql<string | null>`${journal.writeMode}`.as("writeMode"),
3240
+ enqueuedAtUs: sql<string>`${journal.enqueuedAtUs}::text`.as("enqueuedAtUs"),
3241
+ serverUpdatedAtUs: sql<string | null>`${journal.serverUpdatedAtUs}::text`.as("serverUpdatedAtUs"),
3242
+ })
3243
+ .from(journal)
3244
+ .where(and(eq(journal.entityKeyJson, entityKeyJson), ne(journal.status, "rejected")))
3245
+ .orderBy(asc(journal.mutationSeq))
3246
+ .toSQL();
3247
+ const rows = (
3248
+ await db.query<{
3249
+ kind: MutationKind;
3250
+ payload: string;
3251
+ status: MutationStatus;
3252
+ writeMode: string | null;
3253
+ enqueuedAtUs: string;
3254
+ serverUpdatedAtUs: string | null;
3255
+ }>(query.sql, query.params as unknown[])
3256
+ ).rows;
3257
+ let record = synced ?? null;
3258
+ let overlayKind = "pending_update";
3259
+ let localUpdatedAtUs = "0";
3260
+ let hasOverlay = false;
3261
+ const rawVersion = context.serverVersionPropertyKey && synced?.[context.serverVersionPropertyKey];
3262
+ const syncedVersion =
3263
+ typeof rawVersion === "string" || typeof rawVersion === "number" || typeof rawVersion === "bigint"
3264
+ ? BigInt(rawVersion)
3265
+ : null;
3266
+ for (const row of rows) {
3267
+ // Blind writes never contributed to the visible overlay. An already echoed acknowledgement is
3268
+ // likewise represented by the synced base and must not overwrite newer canonical fields.
3269
+ if (
3270
+ row.writeMode === "pessimistic-blind" ||
3271
+ (row.status === "acked" &&
3272
+ row.serverUpdatedAtUs !== null &&
3273
+ syncedVersion != null &&
3274
+ BigInt(row.serverUpdatedAtUs) <= syncedVersion)
3275
+ )
3276
+ continue;
3277
+ const payload = ensureRecord(JSON.parse(row.payload));
3278
+ if (row.kind === "create") {
3279
+ record = ensureRecord(payload["localValue"] ?? createOptimisticRecordFromContext(context, payload["value"]));
3280
+ overlayKind = "pending_create";
3281
+ } else if (record && row.kind === "update") {
3282
+ record = {
3283
+ ...record,
3284
+ ...ensureRecord(payload["patch"]),
3285
+ ...buildUpdateManagedNowStamp(context, row.enqueuedAtUs),
3286
+ };
3287
+ } else if (record && row.kind === "delete") {
3288
+ overlayKind = "pending_delete";
3289
+ }
3290
+ if (record) {
3291
+ hasOverlay = true;
3292
+ localUpdatedAtUs = row.enqueuedAtUs;
3293
+ }
3294
+ }
3295
+ if (hasOverlay && record) {
3296
+ await upsertOverlayRecordsBulk(db, context, [{ entityKey, record, overlayKind, localUpdatedAtUs }]);
3297
+ } else {
3298
+ const remove = queryBuilder
3299
+ .delete(context.tables.overlay)
3300
+ .where(and(...context.pkColumnNames.map((name, i) => eq(context.overlayPkColumns[i]!, entityKey[name]))))
3301
+ .toSQL();
3302
+ await db.query(remove.sql, remove.params as unknown[]);
3303
+ }
3146
3304
  }
3147
3305
 
3148
3306
  async function reconcileTable(db: MutationDb, context: TableContext) {