@pgxsinkit/client 0.6.1 → 0.6.3

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 (42) hide show
  1. package/dist/circuits/group-sync.d.ts.map +1 -1
  2. package/dist/circuits/sync-engine.d.ts.map +1 -1
  3. package/dist/event-lane.d.ts.map +1 -1
  4. package/dist/export-data.d.ts.map +1 -1
  5. package/dist/export-dump.d.ts.map +1 -1
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +229 -94
  9. package/dist/index.js.map +20 -20
  10. package/dist/local-tables.d.ts.map +1 -1
  11. package/dist/mutation-state.d.ts +3 -1
  12. package/dist/mutation-state.d.ts.map +1 -1
  13. package/dist/mutation.d.ts.map +1 -1
  14. package/dist/opfs-effects.d.ts.map +1 -1
  15. package/dist/schema.d.ts.map +1 -1
  16. package/dist/sync/subscription-state.d.ts.map +1 -1
  17. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  18. package/dist/worker/define-sync-worker.d.ts +1 -1
  19. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  20. package/dist/worker/engine-router.d.ts.map +1 -1
  21. package/package.json +7 -9
  22. package/skills/core/SKILL.md +9 -6
  23. package/skills/operating/SKILL.md +1 -1
  24. package/src/circuits/group-sync.ts +6 -6
  25. package/src/circuits/shape-group.ts +1 -1
  26. package/src/circuits/stream-source.ts +2 -2
  27. package/src/circuits/sync-engine.ts +4 -4
  28. package/src/event-lane.ts +4 -4
  29. package/src/export-data.ts +5 -1
  30. package/src/export-dump.ts +1 -1
  31. package/src/index.ts +16 -10
  32. package/src/local-tables.ts +4 -4
  33. package/src/mutation-state.ts +3 -1
  34. package/src/mutation.ts +281 -123
  35. package/src/opfs-effects.ts +1 -1
  36. package/src/schema.ts +2 -2
  37. package/src/sync/subscription-state.ts +1 -1
  38. package/src/worker/attach-sync-client.ts +13 -12
  39. package/src/worker/define-sync-worker.ts +9 -5
  40. package/src/worker/election-coordinator.ts +1 -1
  41. package/src/worker/engine-router.ts +3 -3
  42. package/oxlint-plugin.js +0 -143
package/dist/index.js CHANGED
@@ -220,8 +220,8 @@ import {
220
220
  buildOverlayResolutionBarrier,
221
221
  buildSyncStateView,
222
222
  getLocalSyncPrimaryKeyColumns,
223
- getSyncRegistrySchema,
224
223
  getProjectedColumns,
224
+ getSyncRegistrySchema,
225
225
  hashString,
226
226
  maybeQuoteIdentifier,
227
227
  quoteIdentifier,
@@ -3271,7 +3271,6 @@ var init_group_sync = __esm(() => {
3271
3271
  init_drizzle_executor();
3272
3272
  init_subscription_state();
3273
3273
  init_subscription_client();
3274
- init_subscription_client();
3275
3274
  init_sync_engine();
3276
3275
  });
3277
3276
 
@@ -4314,7 +4313,11 @@ async function performDataExport(deps, options = {}) {
4314
4313
  const pgDumpArgs = ["--no-owner", ...deps.syncedTableNames.flatMap((name) => ["-t", name])];
4315
4314
  const { sqlBytes, phases } = await runThrowawayCloneDump(deps.pgwasm, startPerf, {
4316
4315
  pgDumpArgs,
4317
- ...deps.cloneCleanupSql.length > 0 ? { prepareClone: async (clone) => void await clone.exec(deps.cloneCleanupSql) } : {}
4316
+ ...deps.cloneCleanupSql.length > 0 ? {
4317
+ prepareClone: async (clone) => {
4318
+ await clone.exec(deps.cloneCleanupSql);
4319
+ }
4320
+ } : {}
4318
4321
  });
4319
4322
  const header = buildArtefactCommentHeader(deps.syncedTableNames, escapeHatch) + deps.enumHeaderSql;
4320
4323
  const storeId = deriveStoreId(deps.storePath);
@@ -4631,7 +4634,7 @@ var init_mutation_state = __esm(() => {
4631
4634
  MUTATION_TRANSITIONS = {
4632
4635
  pending: ["sending", "quarantined"],
4633
4636
  sending: ["acked", "failed", "quarantined", "conflicted", "rejected", "pending"],
4634
- failed: ["pending", "quarantined"],
4637
+ failed: ["pending", "quarantined", "rejected"],
4635
4638
  quarantined: [],
4636
4639
  conflicted: [],
4637
4640
  rejected: [],
@@ -4643,6 +4646,7 @@ var init_mutation_state = __esm(() => {
4643
4646
  // packages/client/src/mutation.ts
4644
4647
  import {
4645
4648
  and as and5,
4649
+ asc as asc2,
4646
4650
  desc,
4647
4651
  eq as eq6,
4648
4652
  exists,
@@ -4652,6 +4656,7 @@ import {
4652
4656
  is,
4653
4657
  isNotNull,
4654
4658
  isNull as isNull3,
4659
+ like as like2,
4655
4660
  lt,
4656
4661
  ne,
4657
4662
  notExists as notExists2,
@@ -4938,7 +4943,8 @@ function createMutationRuntime(options) {
4938
4943
  mutationKind: "create",
4939
4944
  payloadJson: jsonStringifyPayload({
4940
4945
  kind: "create",
4941
- value: item.input
4946
+ value: item.input,
4947
+ localValue: item.optimisticRecord
4942
4948
  }),
4943
4949
  nowUs: item.nowUs,
4944
4950
  baseServerVersion: null
@@ -5224,6 +5230,7 @@ function createMutationRuntime(options) {
5224
5230
  }));
5225
5231
  const url = mutationUrls.authoritative;
5226
5232
  let acksByMutationId;
5233
+ let rejectedRequest;
5227
5234
  try {
5228
5235
  const authToken = await untilAborted(Promise.resolve(options.getAuthToken?.()));
5229
5236
  let response = await fetch(url, {
@@ -5248,96 +5255,116 @@ function createMutationRuntime(options) {
5248
5255
  const responseJson = await response.json();
5249
5256
  acksByMutationId = new Map(responseJson.acks.map((ack) => [ack.mutationId, ack]));
5250
5257
  } catch (error) {
5251
- const failedAtUs = nowMicroseconds();
5252
- const httpStatus = error instanceof MutationRequestError ? error.status : null;
5253
- const errorMessage = error instanceof Error ? error.message : "Authoritative write failed";
5254
- for (const rows of byContext.values()) {
5255
- await applyMutationStatusUpdates(options.db, rows[0].context, rows.map((row) => {
5256
- const attemptCount = row.attemptCount + 1;
5257
- const outcome = resolveBatchFailureOutcome(attemptCount, maxMutationAttempts, failedAtUs);
5258
- return {
5259
- mutationId: row.mutationId,
5260
- status: outcome.status,
5261
- attemptCount,
5262
- updatedAtUs: failedAtUs,
5263
- lastError: errorMessage,
5264
- nextRetryAtUs: outcome.nextRetryAtUs,
5265
- lastHttpStatus: httpStatus,
5266
- conflictReason: null
5267
- };
5268
- }));
5258
+ if (error instanceof MutationRequestError && classifyFailureStatus(error.status) === "quarantined") {
5259
+ rejectedRequest = error;
5260
+ acksByMutationId = new Map(mutations.map((mutation) => [
5261
+ mutation.mutationId,
5262
+ { ...mutation, status: "rejected", httpStatus: error.status, rejectionReason: error.message }
5263
+ ]));
5264
+ } else {
5265
+ const failedAtUs = nowMicroseconds();
5266
+ const httpStatus = error instanceof MutationRequestError ? error.status : null;
5267
+ const errorMessage = error instanceof Error ? error.message : "Authoritative write failed";
5268
+ for (const rows of byContext.values()) {
5269
+ await applyMutationStatusUpdates(options.db, rows[0].context, rows.map((row) => {
5270
+ const attemptCount = row.attemptCount + 1;
5271
+ const outcome = resolveBatchFailureOutcome(attemptCount, maxMutationAttempts, failedAtUs);
5272
+ return {
5273
+ mutationId: row.mutationId,
5274
+ status: outcome.status,
5275
+ attemptCount,
5276
+ updatedAtUs: failedAtUs,
5277
+ lastError: errorMessage,
5278
+ nextRetryAtUs: outcome.nextRetryAtUs,
5279
+ lastHttpStatus: httpStatus,
5280
+ conflictReason: null
5281
+ };
5282
+ }));
5283
+ }
5284
+ throw error;
5269
5285
  }
5270
- throw error;
5271
5286
  }
5272
5287
  const ackedAtUs = nowMicroseconds();
5273
5288
  const failedAtUs = nowMicroseconds();
5274
- const rejectedIds = new Set;
5289
+ const rejectedIds = new Set(prepared.filter((row) => acksByMutationId.get(row.mutationId)?.status === "rejected").map((row) => row.mutationId));
5275
5290
  const conflictedIds = new Set;
5276
- for (const rows of byContext.values()) {
5277
- await applyMutationStatusUpdates(options.db, rows[0].context, rows.map((row) => {
5278
- const ack = acksByMutationId.get(row.mutationId);
5279
- if (ack?.status === "rejected") {
5280
- rejectedIds.add(row.mutationId);
5281
- return {
5282
- mutationId: row.mutationId,
5283
- status: "rejected",
5284
- attemptCount: row.attemptCount + 1,
5285
- updatedAtUs: failedAtUs,
5286
- lastError: ack.rejectionReason ?? "Rejected by the authoritative endpoint",
5287
- nextRetryAtUs: null,
5288
- lastHttpStatus: ack.httpStatus ?? 409,
5289
- conflictReason: ack.rejectionReason ?? "Rejected by the authoritative endpoint"
5290
- };
5291
- }
5292
- if (ack?.status === "conflicted") {
5293
- conflictedIds.add(row.mutationId);
5291
+ const settleUnit = async () => {
5292
+ for (const rows of byContext.values()) {
5293
+ await applyMutationStatusUpdates(options.db, rows[0].context, rows.map((row) => {
5294
+ const ack = acksByMutationId.get(row.mutationId);
5295
+ if (ack?.status === "rejected") {
5296
+ rejectedIds.add(row.mutationId);
5297
+ return {
5298
+ mutationId: row.mutationId,
5299
+ status: "rejected",
5300
+ attemptCount: row.attemptCount + 1,
5301
+ updatedAtUs: failedAtUs,
5302
+ lastError: ack.rejectionReason ?? "Rejected by the authoritative endpoint",
5303
+ nextRetryAtUs: null,
5304
+ lastHttpStatus: ack.httpStatus ?? 409,
5305
+ conflictReason: ack.rejectionReason ?? "Rejected by the authoritative endpoint"
5306
+ };
5307
+ }
5308
+ if (ack?.status === "conflicted") {
5309
+ conflictedIds.add(row.mutationId);
5310
+ return {
5311
+ mutationId: row.mutationId,
5312
+ status: "conflicted",
5313
+ attemptCount: row.attemptCount + 1,
5314
+ updatedAtUs: failedAtUs,
5315
+ serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,
5316
+ replaceServerUpdatedAtUs: true,
5317
+ lastError: ack.conflictReason ?? "Stale write rejected (reject-if-stale)",
5318
+ nextRetryAtUs: null,
5319
+ lastHttpStatus: ack.httpStatus ?? 409,
5320
+ conflictReason: ack.conflictReason ?? "Stale write rejected (reject-if-stale)"
5321
+ };
5322
+ }
5323
+ if (!ack || ack.status !== "acked") {
5324
+ const attemptCount = row.attemptCount + 1;
5325
+ const outcome = resolveFailureOutcome(ack?.httpStatus ?? null, attemptCount, maxMutationAttempts, failedAtUs);
5326
+ return {
5327
+ mutationId: row.mutationId,
5328
+ status: outcome.status,
5329
+ attemptCount,
5330
+ updatedAtUs: failedAtUs,
5331
+ lastError: ack?.conflictReason ?? "Authoritative write not acknowledged",
5332
+ nextRetryAtUs: outcome.nextRetryAtUs,
5333
+ lastHttpStatus: ack?.httpStatus ?? null,
5334
+ conflictReason: null
5335
+ };
5336
+ }
5294
5337
  return {
5295
5338
  mutationId: row.mutationId,
5296
- status: "conflicted",
5339
+ status: "acked",
5297
5340
  attemptCount: row.attemptCount + 1,
5298
- updatedAtUs: failedAtUs,
5341
+ updatedAtUs: ackedAtUs,
5342
+ ackedAtUs,
5343
+ replaceAckedAtUs: true,
5299
5344
  serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,
5300
5345
  replaceServerUpdatedAtUs: true,
5301
- lastError: ack.conflictReason ?? "Stale write rejected (reject-if-stale)",
5346
+ lastError: null,
5302
5347
  nextRetryAtUs: null,
5303
- lastHttpStatus: ack.httpStatus ?? 409,
5304
- conflictReason: ack.conflictReason ?? "Stale write rejected (reject-if-stale)"
5305
- };
5306
- }
5307
- if (!ack || ack.status !== "acked") {
5308
- const attemptCount = row.attemptCount + 1;
5309
- const outcome = resolveFailureOutcome(ack?.httpStatus ?? null, attemptCount, maxMutationAttempts, failedAtUs);
5310
- return {
5311
- mutationId: row.mutationId,
5312
- status: outcome.status,
5313
- attemptCount,
5314
- updatedAtUs: failedAtUs,
5315
- lastError: ack?.conflictReason ?? "Authoritative write not acknowledged",
5316
- nextRetryAtUs: outcome.nextRetryAtUs,
5317
- lastHttpStatus: ack?.httpStatus ?? null,
5348
+ lastHttpStatus: row.mutationKind === "delete" ? 204 : 200,
5318
5349
  conflictReason: null
5319
5350
  };
5351
+ }));
5352
+ }
5353
+ if (rejectedIds.size > 0) {
5354
+ const restored = new Set;
5355
+ for (const row of prepared) {
5356
+ const key = `${row.context.key}:${row.entityKeyJson}`;
5357
+ if (rejectedIds.has(row.mutationId) && !restored.has(key)) {
5358
+ await restoreOverlayAfterRejection(options.db, row.context, row.entityKey, row.entityKeyJson);
5359
+ restored.add(key);
5360
+ }
5320
5361
  }
5321
- return {
5322
- mutationId: row.mutationId,
5323
- status: "acked",
5324
- attemptCount: row.attemptCount + 1,
5325
- updatedAtUs: ackedAtUs,
5326
- ackedAtUs,
5327
- replaceAckedAtUs: true,
5328
- serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,
5329
- replaceServerUpdatedAtUs: true,
5330
- lastError: null,
5331
- nextRetryAtUs: null,
5332
- lastHttpStatus: row.mutationKind === "delete" ? 204 : 200,
5333
- conflictReason: null
5334
- };
5335
- }));
5336
- }
5337
- for (const row of prepared) {
5338
- if (rejectedIds.has(row.mutationId)) {
5339
- await discardOverlayForSettledEntity(options.db, row.context, row.entityKey, row.entityKeyJson);
5340
5362
  }
5363
+ };
5364
+ if (rejectedIds.size > 0) {
5365
+ await runInTransaction(settleUnit);
5366
+ } else {
5367
+ await settleUnit();
5341
5368
  }
5342
5369
  const affectedContexts = [...byContext.keys()].map((key) => tableContexts[key]).filter((context) => context != null);
5343
5370
  for (const context of affectedContexts) {
@@ -5356,6 +5383,8 @@ function createMutationRuntime(options) {
5356
5383
  }
5357
5384
  }
5358
5385
  await settleRecoveryMarker();
5386
+ if (rejectedRequest)
5387
+ throw rejectedRequest;
5359
5388
  return { acks: [...acksByMutationId.values()] };
5360
5389
  },
5361
5390
  reconcile: async (table) => {
@@ -5366,13 +5395,62 @@ function createMutationRuntime(options) {
5366
5395
  },
5367
5396
  retryFailed: async (table) => {
5368
5397
  assertValidMutationTransition("failed", "pending");
5398
+ assertValidMutationTransition("failed", "rejected");
5369
5399
  const contexts = filterContexts(tableContexts, table);
5370
5400
  const nowUs = nowMicroseconds();
5401
+ const allContexts = filterContexts(tableContexts, undefined);
5402
+ const declinedUnits = new Set;
5403
+ for (const context of contexts) {
5404
+ const journal = context.tables.journal;
5405
+ const query = queryBuilder.select({
5406
+ unit: sql6`${journal.writeUnit}`.as("unit"),
5407
+ httpStatus: sql6`${journal.lastHttpStatus}`.as("httpStatus")
5408
+ }).from(journal).where(and5(eq6(journal.status, "failed"), like2(journal.writeMode, "pessimistic%"), isNotNull(journal.writeUnit))).toSQL();
5409
+ for (const row of (await options.db.query(query.sql, query.params)).rows) {
5410
+ if (classifyFailureStatus(row.httpStatus) === "quarantined")
5411
+ declinedUnits.add(row.unit);
5412
+ }
5413
+ }
5414
+ const repaired = new Set;
5415
+ for (const unitId of declinedUnits) {
5416
+ await runInTransaction(async () => {
5417
+ const rows = await readUnitPendingRows(options.db, allContexts, unitId, null);
5418
+ if (!rows.length || rows.some((row) => row.status !== "failed" || classifyFailureStatus(row.lastHttpStatus) !== "quarantined"))
5419
+ return;
5420
+ const entities = new Set;
5421
+ for (const row of rows) {
5422
+ const context = tableContexts[row.tableKey];
5423
+ await applyMutationStatusUpdates(options.db, context, [
5424
+ {
5425
+ mutationId: row.mutationId,
5426
+ status: "rejected",
5427
+ attemptCount: row.attemptCount,
5428
+ updatedAtUs: nowUs,
5429
+ lastError: row.lastError,
5430
+ conflictReason: row.lastError ?? "Rejected by the authoritative endpoint",
5431
+ lastHttpStatus: row.lastHttpStatus,
5432
+ nextRetryAtUs: null
5433
+ }
5434
+ ]);
5435
+ repaired.add(row.mutationId);
5436
+ }
5437
+ for (const row of rows) {
5438
+ const key = `${row.tableKey}:${row.entityKeyJson}`;
5439
+ if (!entities.has(key)) {
5440
+ await restoreOverlayAfterRejection(options.db, tableContexts[row.tableKey], JSON.parse(row.entityKeyJson), row.entityKeyJson);
5441
+ entities.add(key);
5442
+ }
5443
+ }
5444
+ });
5445
+ }
5371
5446
  for (const context of contexts) {
5372
5447
  const journal = context.tables.journal;
5373
5448
  const query = queryBuilder.update(journal).set({ status: "pending", nextRetryAtUs: nowUs, updatedAtUs: nowUs, conflictReason: null }).where(eq6(journal.status, "failed")).toSQL();
5374
5449
  await options.db.query(query.sql, query.params);
5375
5450
  }
5451
+ if (repaired.size > 0 && options.onReject) {
5452
+ await options.onReject(await readMutationDetailsForContexts(options.db, allContexts, repaired));
5453
+ }
5376
5454
  },
5377
5455
  recoverSending: async (table) => {
5378
5456
  assertValidMutationTransition("sending", "pending");
@@ -5916,13 +5994,13 @@ async function readPendingBatchRows(db, contexts, nowUs, batchSize) {
5916
5994
  const result = await db.query(query.sql, query.params);
5917
5995
  return result.rows;
5918
5996
  }
5919
- async function readUnitPendingRows(db, contexts, unitId) {
5997
+ async function readUnitPendingRows(db, contexts, unitId, statuses = ["pending", "failed"]) {
5920
5998
  if (contexts.length === 0) {
5921
5999
  return [];
5922
6000
  }
5923
6001
  const branches = contexts.map((context) => {
5924
6002
  const journal = context.tables.journal;
5925
- return queryBuilder.select(buildPendingRowsProjection(context)).from(journal).where(and5(eq6(journal.writeUnit, unitId), inArray2(journal.status, ["pending", "failed"])));
6003
+ return queryBuilder.select(buildPendingRowsProjection(context)).from(journal).where(and5(eq6(journal.writeUnit, unitId), statuses ? inArray2(journal.status, statuses) : undefined));
5926
6004
  });
5927
6005
  const query = queryDialect.sqlToQuery(sql6`SELECT * FROM (${sql6.join(branches, sql6` UNION ALL `)}) AS unit ORDER BY unit."mutationSeq" ASC`);
5928
6006
  const result = await db.query(query.sql, query.params);
@@ -6253,15 +6331,60 @@ async function discardTerminalEntity(db, context, entityKey, entityKeyJson, term
6253
6331
  throw error;
6254
6332
  }
6255
6333
  }
6256
- function buildOverlayDiscardQuery(context, entityKey, entityKeyJson, owedStatuses) {
6334
+ function buildOverlayDiscardQuery(context, entityKey, entityKeyJson) {
6257
6335
  const overlay = context.tables.overlay;
6258
6336
  const journal = context.tables.journal;
6259
- const owed = queryBuilder.select({ one: sql6`1` }).from(journal).where(owedStatuses ? and5(eq6(journal.entityKeyJson, entityKeyJson), inArray2(journal.status, owedStatuses)) : eq6(journal.entityKeyJson, entityKeyJson));
6337
+ const owed = queryBuilder.select({ one: sql6`1` }).from(journal).where(eq6(journal.entityKeyJson, entityKeyJson));
6260
6338
  return queryBuilder.delete(overlay).where(and5(...context.pkColumnNames.map((columnName, index) => eq6(context.overlayPkColumns[index], entityKey[columnName])), notExists2(owed))).toSQL();
6261
6339
  }
6262
- async function discardOverlayForSettledEntity(db, context, entityKey, entityKeyJson) {
6263
- const query = buildOverlayDiscardQuery(context, entityKey, entityKeyJson, ["pending", "sending", "failed"]);
6264
- await db.query(query.sql, query.params);
6340
+ async function restoreOverlayAfterRejection(db, context, entityKey, entityKeyJson) {
6341
+ const syncedQuery = queryDialect.sqlToQuery(sql6`SELECT ${buildProjectedSelectColumns(context, context.syncedColumnsByPropertyKey)}
6342
+ FROM ${context.tables.synced}
6343
+ WHERE ${and5(...context.pkColumnNames.map((name, i) => eq6(context.syncedPkColumns[i], entityKey[name])))}`);
6344
+ const synced = (await db.query(syncedQuery.sql, syncedQuery.params)).rows[0];
6345
+ const journal = context.tables.journal;
6346
+ const query = queryBuilder.select({
6347
+ kind: sql6`${journal.mutationKind}`.as("kind"),
6348
+ payload: sql6`${journal.payloadJson}`.as("payload"),
6349
+ status: journal.status,
6350
+ writeMode: sql6`${journal.writeMode}`.as("writeMode"),
6351
+ enqueuedAtUs: sql6`${journal.enqueuedAtUs}::text`.as("enqueuedAtUs"),
6352
+ serverUpdatedAtUs: sql6`${journal.serverUpdatedAtUs}::text`.as("serverUpdatedAtUs")
6353
+ }).from(journal).where(and5(eq6(journal.entityKeyJson, entityKeyJson), ne(journal.status, "rejected"))).orderBy(asc2(journal.mutationSeq)).toSQL();
6354
+ const rows = (await db.query(query.sql, query.params)).rows;
6355
+ let record = synced ?? null;
6356
+ let overlayKind = "pending_update";
6357
+ let localUpdatedAtUs = "0";
6358
+ let hasOverlay = false;
6359
+ const rawVersion = context.serverVersionPropertyKey && synced?.[context.serverVersionPropertyKey];
6360
+ const syncedVersion = typeof rawVersion === "string" || typeof rawVersion === "number" || typeof rawVersion === "bigint" ? BigInt(rawVersion) : null;
6361
+ for (const row of rows) {
6362
+ if (row.writeMode === "pessimistic-blind" || row.status === "acked" && row.serverUpdatedAtUs !== null && syncedVersion != null && BigInt(row.serverUpdatedAtUs) <= syncedVersion)
6363
+ continue;
6364
+ const payload = ensureRecord(JSON.parse(row.payload));
6365
+ if (row.kind === "create") {
6366
+ record = ensureRecord(payload["localValue"] ?? createOptimisticRecordFromContext(context, payload["value"]));
6367
+ overlayKind = "pending_create";
6368
+ } else if (record && row.kind === "update") {
6369
+ record = {
6370
+ ...record,
6371
+ ...ensureRecord(payload["patch"]),
6372
+ ...buildUpdateManagedNowStamp(context, row.enqueuedAtUs)
6373
+ };
6374
+ } else if (record && row.kind === "delete") {
6375
+ overlayKind = "pending_delete";
6376
+ }
6377
+ if (record) {
6378
+ hasOverlay = true;
6379
+ localUpdatedAtUs = row.enqueuedAtUs;
6380
+ }
6381
+ }
6382
+ if (hasOverlay && record) {
6383
+ await upsertOverlayRecordsBulk(db, context, [{ entityKey, record, overlayKind, localUpdatedAtUs }]);
6384
+ } else {
6385
+ const remove = queryBuilder.delete(context.tables.overlay).where(and5(...context.pkColumnNames.map((name, i) => eq6(context.overlayPkColumns[i], entityKey[name])))).toSQL();
6386
+ await db.query(remove.sql, remove.params);
6387
+ }
6265
6388
  }
6266
6389
  async function reconcileTable(db, context) {
6267
6390
  const journal = context.tables.journal;
@@ -8511,7 +8634,12 @@ function defineSyncWorker(options) {
8511
8634
  };
8512
8635
  const emitStatus = (status) => {
8513
8636
  broadcastEvent({ kind: "status", status });
8514
- for (const [groupKey, ready] of Object.entries(status.groups ?? {})) {
8637
+ const groups = status.groups ?? {};
8638
+ for (const groupKey of seenReadyGroups) {
8639
+ if (groups[groupKey] !== true)
8640
+ seenReadyGroups.delete(groupKey);
8641
+ }
8642
+ for (const [groupKey, ready] of Object.entries(groups)) {
8515
8643
  if (ready && !seenReadyGroups.has(groupKey)) {
8516
8644
  seenReadyGroups.add(groupKey);
8517
8645
  broadcastEvent({ kind: "groupReady", groupKey });
@@ -10255,13 +10383,16 @@ async function attachSyncClient(options) {
10255
10383
  switch (event.kind) {
10256
10384
  case "status": {
10257
10385
  Object.assign(status, event.status);
10258
- options.onStatusChange?.(event.status);
10259
- if (event.status.phase === "ready")
10260
- markReady();
10386
+ if (event.status.groups === undefined)
10387
+ delete status.groups;
10388
+ readyGroups.clear();
10261
10389
  for (const [groupKey, ready] of Object.entries(event.status.groups ?? {})) {
10262
10390
  if (ready)
10263
10391
  markGroupReady(groupKey);
10264
10392
  }
10393
+ options.onStatusChange?.(event.status);
10394
+ if (event.status.phase === "ready")
10395
+ markReady();
10265
10396
  break;
10266
10397
  }
10267
10398
  case "groupReady": {
@@ -11403,7 +11534,6 @@ var init_attach_sync_client = __esm(() => {
11403
11534
  init_store_boot();
11404
11535
  init_store_meta();
11405
11536
  init_store_path();
11406
- init_store_path();
11407
11537
  init_define_sync_worker();
11408
11538
  init_election_coordinator();
11409
11539
  init_engine_control();
@@ -12343,8 +12473,13 @@ async function createSyncClient(options) {
12343
12473
  }
12344
12474
  const activeSync = sync;
12345
12475
  const groupKey = activeSync?.groupKeyForTable(key) ?? entry.consistencyGroup ?? entry.shape?.shapeKey;
12346
- if (activeSync != null && groupKey != null)
12476
+ if (activeSync != null && groupKey != null) {
12347
12477
  activeSync.stopGroup(groupKey);
12478
+ if (status.groups?.[groupKey] === true) {
12479
+ status.groups = { ...status.groups, [groupKey]: false };
12480
+ options.onStatusChange?.(status);
12481
+ }
12482
+ }
12348
12483
  if (groupKey != null)
12349
12484
  await clearLazyGroupActivation(pgwasm, options.registry, groupKey);
12350
12485
  if (groupKey != null)
@@ -12934,4 +13069,4 @@ export {
12934
13069
  wrapLiveQueryForMaterialization
12935
13070
  };
12936
13071
 
12937
- //# debugId=0070DC25354F3B0A64756E2164756E21
13072
+ //# debugId=F8970E1C5B37AF6B64756E2164756E21