@tearleads/client-sdk 0.1.236 → 0.1.237

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.
@@ -53,6 +53,10 @@ const accessLevelColumn = "effective_access_level";
53
53
  * - `(appKind, localId)` is the primary key and scopes local document lookups.
54
54
  * - `(appKind, documentId) where documentId is not null` supports resolving a
55
55
  * server document id back to the local row during discovery and relinking.
56
+ * - `(appKind, localId)` over records whose `pendingBaseVersion` differs from
57
+ * a non-empty `snapshotEndVersion` serves the pending-write queue's
58
+ * deferred-tail scan, which repeats that condition, so it reads only
59
+ * unsettled records instead of every synced one.
56
60
  */
57
61
  export const documents = sqliteTable("documents", {
58
62
  appKind: text("app_kind").notNull(),
@@ -79,6 +83,9 @@ export const documents = sqliteTable("documents", {
79
83
  index("documents_app_document_idx")
80
84
  .on(table.appKind, table.documentId)
81
85
  .where(sql `${table.documentId} IS NOT NULL`),
86
+ index("documents_deferred_tail_idx")
87
+ .on(table.appKind, table.localId)
88
+ .where(sql `${table.snapshotEndVersion} <> '' AND ${table.pendingBaseVersion} IS NOT ${table.snapshotEndVersion}`),
82
89
  ]);
83
90
  /**
84
91
  * Full-history persistence for local documents (checkpoint + tail) — the ONLY
@@ -1 +1 @@
1
- {"version":3,"file":"documentRecordSchema.js","sourceRoot":"","sources":["documentRecordSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EACL,KAAK,EACL,OAAO,EACP,UAAU,EACV,WAAW,EACX,IAAI,EACJ,WAAW,GACZ,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,oBAAoB,EAAuB,MAAM,mBAAmB,CAAC;AAE9E,MAAM,iBAAiB,GAAG,wBAAwB,CAAC;AACnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,WAAW,CAClC,WAAW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e,EAAE,CAAC,WAAW,CAAC;KAC/B;CACF,CAAC","sourcesContent":["import { sql } from \"drizzle-orm\";\nimport {\n index,\n integer,\n primaryKey,\n sqliteTable,\n text,\n uniqueIndex,\n} from \"drizzle-orm/sqlite-core\";\nimport { defineSqlTableSchema, type SqlTableSchema } from \"../sqlTableSchema\";\n\nconst accessLevelColumn = \"effective_access_level\";\n/**\n * Durable Loro-backed document records shared by app features.\n *\n * This table stores encrypted document runtime state for multiple app domains.\n * `appKind` namespaces records for documents and container metadata. User-facing\n * list data is projected into feature-specific read models.\n *\n * Columns:\n * - `appKind`: Local domain namespace for the row, such as `documents` or\n * `container-metadata`.\n * - `localId`: Stable local id inside `appKind`. It may be created before a\n * server `documentId` exists.\n * - `documentId`: Server document id once the record is known remotely, or\n * `null` while the document is local-only.\n * - `accessEpoch`: Latest access epoch persisted for the document. Defaults to\n * the initial epoch.\n * - `accessStateHash`: Current document access/manifest state hash returned by\n * sync, when known.\n * - `lastCommitLsn`: Last remote commit cursor applied to this local document.\n * - `documentManifestBundle`: Serialized document manifest bundle used for\n * encrypted document sync.\n * - `contentKeyBundle`: Serialized content-key material needed to open the\n * local document.\n * - `documentKekTargets`: Serialized KEK target state for document key wraps.\n * - `pendingBaseVersion`: Encoded oplog version through which every persisted\n * op is already enqueued or synced. Persisted so a restart restores the\n * outgoing-delta marker instead of re-seeding it past a device-first\n * `deferRemoteSync` write's un-advanced op. `null` when unset.\n * - `snapshotEndVersion`: Encoded end version vector of the persisted content\n * (which lives in the durable-history tables, never on this row), written on\n * every content persist. Lets the pending-write queue's deferred-tail scan\n * compare version coverage without loading content. Empty string when the\n * document has never hydrated content, which readers treat as \"no deferred\n * tail claimable\".\n * - `recoveryGeneration`: Atomic raw-history recovery writer fence.\n * - `recoveryDocumentId`: Former server id for cross-client post-purge recreation.\n * - `pullContinuation`: Durable progress for the next bounded remote pull.\n * - `syncFailureStatus`, `syncFailureMessage`, `syncFailureAttemptedAt`: The\n * last terminal sync failure or quarantined incoming update for this scope.\n * The durable write queue (queued rows of `documentHistoryUpdates`) has no\n * status columns, so these let the write-queue view and footer explain why\n * the document is blocked. `syncFailureMessage` is non-null exactly when a\n * failure is recorded; a newer failure replaces the old, and a later fully\n * validated sync pass, a remote reset, or the scope's teardown clears all\n * three.\n * - `updatedAt`: Local timestamp for the last persisted runtime-state update.\n *\n * Indexes:\n * - `(appKind, localId)` is the primary key and scopes local document lookups.\n * - `(appKind, documentId) where documentId is not null` supports resolving a\n * server document id back to the local row during discovery and relinking.\n */\nexport const documents = sqliteTable(\n \"documents\",\n {\n appKind: text(\"app_kind\").notNull(),\n localId: text(\"local_id\").notNull(),\n documentId: text(\"document_id\"),\n accessEpoch: integer(\"access_epoch\").notNull().default(1),\n accessStateHash: text(\"access_state_hash\"),\n effectiveAccessLevel: text(accessLevelColumn).notNull().default(\"read\"),\n lastCommitLsn: text(\"last_commit_lsn\"),\n documentManifestBundle: text(\"document_manifest_bundle\"),\n contentKeyBundle: text(\"content_key_bundle\"),\n documentKekTargets: text(\"document_kek_targets\"),\n pendingBaseVersion: text(\"pending_base_version\"),\n pullContinuation: text(\"pull_continuation\"),\n recoveryGeneration: integer(\"recovery_generation\").notNull().default(0),\n recoveryDocumentId: text(\"recovery_document_id\"),\n snapshotEndVersion: text(\"snapshot_end_version\").notNull().default(\"\"),\n syncFailureStatus: integer(\"sync_failure_status\"),\n syncFailureMessage: text(\"sync_failure_message\"),\n syncFailureAttemptedAt: text(\"sync_failure_attempted_at\"),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.appKind, table.localId] }),\n index(\"documents_app_document_idx\")\n .on(table.appKind, table.documentId)\n .where(sql`${table.documentId} IS NOT NULL`),\n ],\n);\n\n/**\n * Full-history persistence for local documents (checkpoint + tail) — the ONLY\n * durable content source. Record rows in `documents` carry runtime metadata\n * and the content frontier (`snapshotEndVersion`), never content. The\n * checkpoint holds a full-history snapshot refreshed only at compaction, and\n * the tail appends every update (local deltas and decrypted remote updates)\n * written since. Restore = import checkpoint + replay tail; compaction =\n * export full history from the live doc, replace the checkpoint, clear the\n * tail — all bounded and amortized. Container metadata stores its content (an\n * exported-updates blob) as its checkpoint row, with no tail.\n */\nexport const documentHistoryCheckpoints = sqliteTable(\n \"document_history_checkpoints\",\n {\n appKind: text(\"app_kind\").notNull(),\n localId: text(\"local_id\").notNull(),\n snapshot: text(\"snapshot\").notNull(),\n endVersionVector: text(\"end_version_vector\").notNull(),\n revision: text(\"revision\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [primaryKey({ columns: [table.appKind, table.localId] })],\n);\n\n/**\n * The local update log: one row per Loro update, serving as both the history\n * tail (restore = checkpoint + tail) and the outbound write queue.\n *\n * Every locally authored update is stored once. While it waits for sync it\n * carries an `updateId` (the id submitted to the server) and the version-vector\n * metadata the submission needs; settlement clears them, leaving the row as\n * ordinary tail history until compaction folds it into a checkpoint. Before a\n * send, a contiguous run of queued local rows may be replaced by one merged\n * row holding exactly their operations: the first row is updated in place\n * (same `id`, `createdAt` and `rowid`, so the same queue and replay position)\n * under a fresh `updateId`, and the other rows are deleted.\n *\n * Columns:\n * - `id`: Row id; tail compaction deletes by it.\n * - `appKind`, `localId`: Document scope matching `documents`.\n * - `updateData`: Serialized Loro update payload.\n * - `origin`: \"local\" (authored on this device) or \"remote\" (decrypted\n * pulled update) for tail rows. Restores use it to advance the\n * outgoing-delta marker across remote rows — their ops are already\n * server-side — while a local row left behind by a crash stays below the\n * marker so the next edit re-derives and sends it. \"outbox\" marks a queued\n * update with no tail role (container metadata, whose content is its\n * checkpoint, and full-state re-uploads after a remote reset); restores and\n * compaction never see it and settlement deletes it.\n * - `createdAt`: Insertion timestamp; with `rowid`, deterministic replay order.\n * - `updateId`: Present exactly while the row is queued for sync; rekeyed\n * after a lost acknowledgement poisons the submitted id, and replaced by a\n * fresh id when queued rows merge. An id never names two payloads.\n * - `partialStartVersionVector` / `partialEndVersionVector`: Version vectors\n * around a queued partial update.\n * - `sourceVersionVector`: Present on a queued rotation baseline checkpoint.\n * - `rekeyCount`: Durable bound on rekeys of a queued row; a merged row takes\n * the largest count among the rows it replaces.\n *\n * Invariant: compaction never deletes a queued row, so a checkpoint can cover\n * a queued update's operations without removing it from the queue.\n */\nexport const documentHistoryUpdates = sqliteTable(\n \"document_history_updates\",\n {\n id: text(\"id\"),\n appKind: text(\"app_kind\").notNull(),\n localId: text(\"local_id\").notNull(),\n updateData: text(\"update_data\").notNull(),\n origin: text(\"origin\").notNull(),\n createdAt: text(\"created_at\").notNull(),\n updateId: text(\"update_id\"),\n partialStartVersionVector: text(\"partial_start_version_vector\"),\n partialEndVersionVector: text(\"partial_end_version_vector\"),\n sourceVersionVector: text(\"source_version_vector\"),\n rekeyCount: integer(\"rekey_count\").notNull().default(0),\n },\n (table) => [\n primaryKey({ columns: [table.id] }),\n index(\"document_history_updates_scope_created_idx\").on(\n table.appKind,\n table.localId,\n table.createdAt,\n ),\n uniqueIndex(\"document_history_updates_update_id_idx\")\n .on(table.updateId)\n .where(sql`${table.updateId} IS NOT NULL`),\n // Queued rows only: pending counts and pending loads skip settled history.\n index(\"document_history_updates_queued_scope_idx\")\n .on(table.appKind, table.localId, table.createdAt)\n .where(sql`${table.updateId} IS NOT NULL`),\n ],\n);\n\nexport const documentTables: ReadonlyArray<SqlTableSchema> = [\n {\n ...defineSqlTableSchema(documents),\n requiredColumns: [\n \"pull_continuation\",\n \"recovery_generation\",\n \"recovery_document_id\",\n \"sync_failure_status\",\n \"sync_failure_message\",\n \"sync_failure_attempted_at\",\n ],\n },\n defineSqlTableSchema(documentHistoryCheckpoints),\n {\n ...defineSqlTableSchema(documentHistoryUpdates),\n requiredColumns: [\"update_id\"],\n },\n];\n"]}
1
+ {"version":3,"file":"documentRecordSchema.js","sourceRoot":"","sources":["documentRecordSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EACL,KAAK,EACL,OAAO,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AAC;IAC5C,2EAA2E;IAC3E,KAAK,CAAC,2CAA2C,CAAC;SAC/C,EAAE,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,SAAS,CAAC;SACjD,KAAK,CAAC,GAAG,CAAA,GAAG,KAAK,CAAC,QAAQ,cAAc,CAAC;CAC7C,CACF,CAAC;AAEF,MAAM,CAAC,MAAM,cAAc,GAAkC;IAC3D;QACE,GAAG,oBAAoB,CAAC,SAAS,CAAC;QAClC,eAAe,EAAE;YACf,mBAAmB;YACnB,qBAAqB;YACrB,sBAAsB;YACtB,qBAAqB;YACrB,sBAAsB;YACtB,2BAA2B;SAC5B;KACF;IACD,oBAAoB,CAAC,0BAA0B,CAAC;IAChD;QACE,GAAG,oBAAoB,CAAC,sBAAsB,CAAC;QAC/C,eAAe,EAAE,CAAC,WAAW,CAAC;KAC/B;CACF,CAAC","sourcesContent":["import { sql } from \"drizzle-orm\";\nimport {\n index,\n integer,\n primaryKey,\n sqliteTable,\n text,\n uniqueIndex,\n} from \"drizzle-orm/sqlite-core\";\nimport { defineSqlTableSchema, type SqlTableSchema } from \"../sqlTableSchema\";\n\nconst accessLevelColumn = \"effective_access_level\";\n/**\n * Durable Loro-backed document records shared by app features.\n *\n * This table stores encrypted document runtime state for multiple app domains.\n * `appKind` namespaces records for documents and container metadata. User-facing\n * list data is projected into feature-specific read models.\n *\n * Columns:\n * - `appKind`: Local domain namespace for the row, such as `documents` or\n * `container-metadata`.\n * - `localId`: Stable local id inside `appKind`. It may be created before a\n * server `documentId` exists.\n * - `documentId`: Server document id once the record is known remotely, or\n * `null` while the document is local-only.\n * - `accessEpoch`: Latest access epoch persisted for the document. Defaults to\n * the initial epoch.\n * - `accessStateHash`: Current document access/manifest state hash returned by\n * sync, when known.\n * - `lastCommitLsn`: Last remote commit cursor applied to this local document.\n * - `documentManifestBundle`: Serialized document manifest bundle used for\n * encrypted document sync.\n * - `contentKeyBundle`: Serialized content-key material needed to open the\n * local document.\n * - `documentKekTargets`: Serialized KEK target state for document key wraps.\n * - `pendingBaseVersion`: Encoded oplog version through which every persisted\n * op is already enqueued or synced. Persisted so a restart restores the\n * outgoing-delta marker instead of re-seeding it past a device-first\n * `deferRemoteSync` write's un-advanced op. `null` when unset.\n * - `snapshotEndVersion`: Encoded end version vector of the persisted content\n * (which lives in the durable-history tables, never on this row), written on\n * every content persist. Lets the pending-write queue's deferred-tail scan\n * compare version coverage without loading content. Empty string when the\n * document has never hydrated content, which readers treat as \"no deferred\n * tail claimable\".\n * - `recoveryGeneration`: Atomic raw-history recovery writer fence.\n * - `recoveryDocumentId`: Former server id for cross-client post-purge recreation.\n * - `pullContinuation`: Durable progress for the next bounded remote pull.\n * - `syncFailureStatus`, `syncFailureMessage`, `syncFailureAttemptedAt`: The\n * last terminal sync failure or quarantined incoming update for this scope.\n * The durable write queue (queued rows of `documentHistoryUpdates`) has no\n * status columns, so these let the write-queue view and footer explain why\n * the document is blocked. `syncFailureMessage` is non-null exactly when a\n * failure is recorded; a newer failure replaces the old, and a later fully\n * validated sync pass, a remote reset, or the scope's teardown clears all\n * three.\n * - `updatedAt`: Local timestamp for the last persisted runtime-state update.\n *\n * Indexes:\n * - `(appKind, localId)` is the primary key and scopes local document lookups.\n * - `(appKind, documentId) where documentId is not null` supports resolving a\n * server document id back to the local row during discovery and relinking.\n * - `(appKind, localId)` over records whose `pendingBaseVersion` differs from\n * a non-empty `snapshotEndVersion` serves the pending-write queue's\n * deferred-tail scan, which repeats that condition, so it reads only\n * unsettled records instead of every synced one.\n */\nexport const documents = sqliteTable(\n \"documents\",\n {\n appKind: text(\"app_kind\").notNull(),\n localId: text(\"local_id\").notNull(),\n documentId: text(\"document_id\"),\n accessEpoch: integer(\"access_epoch\").notNull().default(1),\n accessStateHash: text(\"access_state_hash\"),\n effectiveAccessLevel: text(accessLevelColumn).notNull().default(\"read\"),\n lastCommitLsn: text(\"last_commit_lsn\"),\n documentManifestBundle: text(\"document_manifest_bundle\"),\n contentKeyBundle: text(\"content_key_bundle\"),\n documentKekTargets: text(\"document_kek_targets\"),\n pendingBaseVersion: text(\"pending_base_version\"),\n pullContinuation: text(\"pull_continuation\"),\n recoveryGeneration: integer(\"recovery_generation\").notNull().default(0),\n recoveryDocumentId: text(\"recovery_document_id\"),\n snapshotEndVersion: text(\"snapshot_end_version\").notNull().default(\"\"),\n syncFailureStatus: integer(\"sync_failure_status\"),\n syncFailureMessage: text(\"sync_failure_message\"),\n syncFailureAttemptedAt: text(\"sync_failure_attempted_at\"),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.appKind, table.localId] }),\n index(\"documents_app_document_idx\")\n .on(table.appKind, table.documentId)\n .where(sql`${table.documentId} IS NOT NULL`),\n index(\"documents_deferred_tail_idx\")\n .on(table.appKind, table.localId)\n .where(\n sql`${table.snapshotEndVersion} <> '' AND ${table.pendingBaseVersion} IS NOT ${table.snapshotEndVersion}`,\n ),\n ],\n);\n\n/**\n * Full-history persistence for local documents (checkpoint + tail) — the ONLY\n * durable content source. Record rows in `documents` carry runtime metadata\n * and the content frontier (`snapshotEndVersion`), never content. The\n * checkpoint holds a full-history snapshot refreshed only at compaction, and\n * the tail appends every update (local deltas and decrypted remote updates)\n * written since. Restore = import checkpoint + replay tail; compaction =\n * export full history from the live doc, replace the checkpoint, clear the\n * tail — all bounded and amortized. Container metadata stores its content (an\n * exported-updates blob) as its checkpoint row, with no tail.\n */\nexport const documentHistoryCheckpoints = sqliteTable(\n \"document_history_checkpoints\",\n {\n appKind: text(\"app_kind\").notNull(),\n localId: text(\"local_id\").notNull(),\n snapshot: text(\"snapshot\").notNull(),\n endVersionVector: text(\"end_version_vector\").notNull(),\n revision: text(\"revision\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [primaryKey({ columns: [table.appKind, table.localId] })],\n);\n\n/**\n * The local update log: one row per Loro update, serving as both the history\n * tail (restore = checkpoint + tail) and the outbound write queue.\n *\n * Every locally authored update is stored once. While it waits for sync it\n * carries an `updateId` (the id submitted to the server) and the version-vector\n * metadata the submission needs; settlement clears them, leaving the row as\n * ordinary tail history until compaction folds it into a checkpoint. Before a\n * send, a contiguous run of queued local rows may be replaced by one merged\n * row holding exactly their operations: the first row is updated in place\n * (same `id`, `createdAt` and `rowid`, so the same queue and replay position)\n * under a fresh `updateId`, and the other rows are deleted.\n *\n * Columns:\n * - `id`: Row id; tail compaction deletes by it.\n * - `appKind`, `localId`: Document scope matching `documents`.\n * - `updateData`: Serialized Loro update payload.\n * - `origin`: \"local\" (authored on this device) or \"remote\" (decrypted\n * pulled update) for tail rows. Restores use it to advance the\n * outgoing-delta marker across remote rows — their ops are already\n * server-side — while a local row left behind by a crash stays below the\n * marker so the next edit re-derives and sends it. \"outbox\" marks a queued\n * update with no tail role (container metadata, whose content is its\n * checkpoint, and full-state re-uploads after a remote reset); restores and\n * compaction never see it and settlement deletes it.\n * - `createdAt`: Insertion timestamp; with `rowid`, deterministic replay order.\n * - `updateId`: Present exactly while the row is queued for sync; rekeyed\n * after a lost acknowledgement poisons the submitted id, and replaced by a\n * fresh id when queued rows merge. An id never names two payloads.\n * - `partialStartVersionVector` / `partialEndVersionVector`: Version vectors\n * around a queued partial update.\n * - `sourceVersionVector`: Present on a queued rotation baseline checkpoint.\n * - `rekeyCount`: Durable bound on rekeys of a queued row; a merged row takes\n * the largest count among the rows it replaces.\n *\n * Invariant: compaction never deletes a queued row, so a checkpoint can cover\n * a queued update's operations without removing it from the queue.\n */\nexport const documentHistoryUpdates = sqliteTable(\n \"document_history_updates\",\n {\n id: text(\"id\"),\n appKind: text(\"app_kind\").notNull(),\n localId: text(\"local_id\").notNull(),\n updateData: text(\"update_data\").notNull(),\n origin: text(\"origin\").notNull(),\n createdAt: text(\"created_at\").notNull(),\n updateId: text(\"update_id\"),\n partialStartVersionVector: text(\"partial_start_version_vector\"),\n partialEndVersionVector: text(\"partial_end_version_vector\"),\n sourceVersionVector: text(\"source_version_vector\"),\n rekeyCount: integer(\"rekey_count\").notNull().default(0),\n },\n (table) => [\n primaryKey({ columns: [table.id] }),\n index(\"document_history_updates_scope_created_idx\").on(\n table.appKind,\n table.localId,\n table.createdAt,\n ),\n uniqueIndex(\"document_history_updates_update_id_idx\")\n .on(table.updateId)\n .where(sql`${table.updateId} IS NOT NULL`),\n // Queued rows only: pending counts and pending loads skip settled history.\n index(\"document_history_updates_queued_scope_idx\")\n .on(table.appKind, table.localId, table.createdAt)\n .where(sql`${table.updateId} IS NOT NULL`),\n ],\n);\n\nexport const documentTables: ReadonlyArray<SqlTableSchema> = [\n {\n ...defineSqlTableSchema(documents),\n requiredColumns: [\n \"pull_continuation\",\n \"recovery_generation\",\n \"recovery_document_id\",\n \"sync_failure_status\",\n \"sync_failure_message\",\n \"sync_failure_attempted_at\",\n ],\n },\n defineSqlTableSchema(documentHistoryCheckpoints),\n {\n ...defineSqlTableSchema(documentHistoryUpdates),\n requiredColumns: [\"update_id\"],\n },\n];\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.236",
3
+ "version": "0.1.237",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -47,6 +47,10 @@ const DEFERRED_TAIL_CANDIDATE_SQL = `
47
47
  ON stored.app_kind = 'container-metadata'
48
48
  AND metadata_container.id = stored.local_id
49
49
  WHERE stored.snapshot_end_version <> ''
50
+ -- A marker equal to the content frontier covers it, so a settled record
51
+ -- is never a candidate. With the term above this matches
52
+ -- documents_deferred_tail_idx, so the scan reads only unsettled records.
53
+ AND stored.pending_base_version IS NOT stored.snapshot_end_version
50
54
  -- Dormant retained metadata (row 4, access_revoked) has no containers
51
55
  -- row; keep it out of deferred-tail candidates until re-attach, matching
52
56
  -- the pending-write sources guard.
@@ -1 +1 @@
1
- {"version":3,"file":"deferredTails.js","sourceRoot":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CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACtC,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,uBAAuB,GAAG;;;;;;;;;;;;;;;;;;;;;;CAsB/B,CAAC;AAEF;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,OAAgB,EAChB,KAA2C;IAE3C,MAAM,IAAI,GAAG,MAAM,OAAO,CAAC,uBAAuB,EAAE;QAClD,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;KACd,CAAC,CAAC;IACH,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,cAAc,GAAG,UAAU,CAAC,GAAG,EAAE,sBAAsB,CAAC,CAAC;IAC/D,IAAI,CAAC,cAAc,EAAE,CAAC;QACpB,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,gBAAgB,CAAC;QACtB,cAAc;QACd,uBAAuB,EAAE,UAAU,CAAC,GAAG,EAAE,4BAA4B,CAAC;QACtE,kBAAkB,EAAE,UAAU,CAAC,GAAG,EAAE,sBAAsB,CAAC;KAC5D,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { mergeVersionVectors, satisfiesVersionVector } from \"@tearleads/loro\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n getContainerDisplayNameSql,\n getContainerOrganizationAttributionSql,\n} from \"../documentQueries/sql\";\nimport type { PendingWriteCandidate } from \"./aggregation\";\nimport type { PendingWriteQueueObjectKind } from \"./pendingWritesTypes\";\nimport { readString } from \"./rowReaders\";\n\n// Deliberately never loads document content: the diagnostic listing runs\n// repeatedly while sync drains, and materializing every content blob would\n// make the scan O(total document content). `snapshot_end_version` is the\n// write-time-derived end version vector of the persisted content.\nconst DEFERRED_TAIL_CANDIDATE_SQL = `\n SELECT\n stored.app_kind AS app_kind,\n stored.local_id AS local_id,\n stored.document_id AS stored_remote_id,\n stored.snapshot_end_version AS snapshot_end_version,\n stored.pending_base_version AS pending_base_version,\n stored.updated_at AS updated_at,\n (\n SELECT pending.partial_end_version_vector\n FROM document_history_updates pending\n WHERE pending.app_kind = stored.app_kind\n AND pending.local_id = stored.local_id\n AND pending.update_id IS NOT NULL\n ORDER BY pending.created_at DESC, pending.rowid DESC\n LIMIT 1\n ) AS latest_pending_end_version,\n document_projection.title AS document_name,\n document_projection.container_id AS document_container_id,\n ${getContainerOrganizationAttributionSql({\n containerAlias: \"document_container\",\n projectionAlias: \"document_projection\",\n })} AS document_organization_id,\n CASE\n WHEN metadata_container.server_created_at IS NULL THEN NULL\n ELSE metadata_container.id\n END AS container_remote_id,\n ${getContainerDisplayNameSql(\"metadata_container\")} AS container_name,\n metadata_container.id AS metadata_container_id,\n NULLIF(metadata_container.organization_id, '') AS metadata_organization_id,\n stored.sync_failure_message AS failure_message,\n stored.sync_failure_attempted_at AS failure_attempted_at\n FROM documents stored\n LEFT JOIN document_projection\n ON stored.app_kind = 'documents'\n AND document_projection.local_id = stored.local_id\n LEFT JOIN containers document_container\n ON document_container.id = document_projection.container_id\n LEFT JOIN containers metadata_container\n ON stored.app_kind = 'container-metadata'\n AND metadata_container.id = stored.local_id\n WHERE stored.snapshot_end_version <> ''\n -- Dormant retained metadata (row 4, access_revoked) has no containers\n -- row; keep it out of deferred-tail candidates until re-attach, matching\n -- the pending-write sources guard.\n AND (stored.app_kind <> 'container-metadata'\n OR metadata_container.id IS NOT NULL)\n AND (\n stored.pending_base_version IS NOT NULL\n OR EXISTS (\n SELECT 1\n FROM document_history_updates pending\n WHERE pending.app_kind = stored.app_kind\n AND pending.local_id = stored.local_id\n AND pending.update_id IS NOT NULL\n )\n )\n`;\n\nfunction hasUncoveredTail(input: {\n currentVersion: string;\n latestPendingEndVersion: string | null;\n pendingBaseVersion: string | null;\n}): boolean {\n const coverageVersions = [\n input.latestPendingEndVersion,\n input.pendingBaseVersion,\n ].filter((value): value is string => value !== null);\n const validCoverageVersions: string[] = [];\n for (const coverageVersion of coverageVersions) {\n try {\n validCoverageVersions.push(mergeVersionVectors([coverageVersion]));\n } catch {\n // Corrupt coverage must not make the diagnostic claim an uncovered write.\n return false;\n }\n }\n if (validCoverageVersions.length === 0) {\n return false;\n }\n\n try {\n const mergedCoverage = mergeVersionVectors(validCoverageVersions);\n return !satisfiesVersionVector(mergedCoverage, input.currentVersion);\n } catch {\n // Corrupt coverage must not make the diagnostic claim an uncovered write.\n return false;\n }\n}\n\nfunction getObjectKind(appKind: string): PendingWriteQueueObjectKind {\n if (appKind === \"documents\") return \"document\";\n if (appKind === \"container-metadata\") return \"container\";\n return \"unknown\";\n}\n\nfunction mapDeferredTailCandidate(\n row: Record<string, unknown>,\n): PendingWriteCandidate | null {\n const appKind = readString(row, \"app_kind\");\n const localId = readString(row, \"local_id\");\n const currentVersion = readString(row, \"snapshot_end_version\");\n if (!appKind || !localId || !currentVersion) {\n return null;\n }\n if (\n !hasUncoveredTail({\n currentVersion,\n latestPendingEndVersion: readString(row, \"latest_pending_end_version\"),\n pendingBaseVersion: readString(row, \"pending_base_version\"),\n })\n ) {\n return null;\n }\n\n const objectKind = getObjectKind(appKind);\n const updatedAt = readString(row, \"updated_at\");\n return {\n byteLength: 0,\n containerId:\n objectKind === \"container\"\n ? readString(row, \"metadata_container_id\")\n : objectKind === \"document\"\n ? readString(row, \"document_container_id\")\n : null,\n count: 1,\n createdAt: updatedAt,\n inclusion: \"always\",\n kind: \"deferred-update\",\n // Carry the scope's recorded sync failure so a covering deferred-update\n // candidate never hides the diagnostic a suppressed failure-only item\n // would have shown.\n lastAttemptedAt: readString(row, \"failure_attempted_at\"),\n lastError: readString(row, \"failure_message\"),\n localId,\n name:\n objectKind === \"container\"\n ? readString(row, \"container_name\")\n : objectKind === \"document\"\n ? readString(row, \"document_name\")\n : null,\n namespace: objectKind === \"unknown\" ? appKind : null,\n objectKind,\n organizationId:\n objectKind === \"container\"\n ? readString(row, \"metadata_organization_id\")\n : objectKind === \"document\"\n ? readString(row, \"document_organization_id\")\n : null,\n remoteId:\n objectKind === \"container\"\n ? readString(row, \"container_remote_id\")\n : readString(row, \"stored_remote_id\"),\n status: \"pending\",\n targetContainerId: null,\n updatedAt,\n };\n}\n\nexport async function listDeferredPendingWriteCandidates(\n execSql: ExecSql,\n): Promise<PendingWriteCandidate[]> {\n const rows = await execSql(DEFERRED_TAIL_CANDIDATE_SQL);\n return rows.flatMap((row) => {\n const candidate = mapDeferredTailCandidate(row);\n return candidate ? [candidate] : [];\n });\n}\n\nconst DEFERRED_TAIL_SCOPE_SQL = `\n SELECT\n stored.snapshot_end_version AS snapshot_end_version,\n stored.pending_base_version AS pending_base_version,\n (\n SELECT pending.partial_end_version_vector\n FROM document_history_updates pending\n WHERE pending.app_kind = stored.app_kind\n AND pending.local_id = stored.local_id\n AND pending.update_id IS NOT NULL\n ORDER BY pending.created_at DESC, pending.rowid DESC\n LIMIT 1\n ) AS latest_pending_end_version\n FROM documents stored\n WHERE stored.app_kind = ? AND stored.local_id = ?\n AND stored.snapshot_end_version <> ''\n -- Dormant retained metadata (row 4, access_revoked) has no containers\n -- row; it is not queued work until re-attach, matching the candidate\n -- scan's guard.\n AND (stored.app_kind <> 'container-metadata'\n OR EXISTS (SELECT 1 FROM containers WHERE containers.id = stored.local_id))\n LIMIT 1\n`;\n\n/**\n * Whether this one scope has a deferred write: durable-tail content ahead of\n * its covered frontier, possibly with no queued update rows at all. The same\n * coverage check as the candidate scan, narrowed to a single scope, so\n * \"queued work\" classifications agree with the item the panel rendered.\n */\nexport async function hasDeferredTailScopeWork(\n execSql: ExecSql,\n scope: { appKind: string; localId: string },\n): Promise<boolean> {\n const rows = await execSql(DEFERRED_TAIL_SCOPE_SQL, [\n scope.appKind,\n scope.localId,\n ]);\n const row = rows[0];\n if (!row) {\n return false;\n }\n const currentVersion = readString(row, \"snapshot_end_version\");\n if (!currentVersion) {\n return false;\n }\n return hasUncoveredTail({\n currentVersion,\n latestPendingEndVersion: readString(row, \"latest_pending_end_version\"),\n pendingBaseVersion: readString(row, \"pending_base_version\"),\n });\n}\n"]}
1
+ {"version":3,"file":"deferredTails.js","sourceRoot":"","sources":["deferredTails.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAE9E,OAAO,EACL,0BAA0B,EAC1B,sCAAsC,GACvC,MAAM,wBAAwB,CAAC;AAGhC,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE1C,yEAAyE;AACzE,2EAA2E;AAC3E,yEAAyE;AACzE,kEAAkE;AAClE,MAAM,2BAA2B,GAAG;;;;;;;;;;;;;;;;;;;MAmB9B,sCAAsC,CAAC;IACvC,cAAc,EAAE,oBAAoB;IACpC,eAAe,EAAE,qBAAqB;CACvC,CAAC;;;;;MAKA,0BAA0B,CAAC,oBAAoB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkCrD,CAAC;AAEF,SAAS,gBAAgB,CAAC,KAIzB;IACC,MAAM,gBAAgB,GAAG;QACvB,KAAK,CAAC,uBAAuB;QAC7B,KAAK,CAAC,kBAAkB;KACzB,CAAC,MAAM,CAAC,CAAC,KAAK,EAAmB,EAAE,CAAC,KAAK,KAAK,IAAI,CAAC,CAAC;IACrD,MAAM,qBAAqB,GAAa,EAAE,CAAC;IAC3C,KAAK,MAAM,eAAe,IAAI,gBAAgB,EAAE,CAAC;QAC/C,IAAI,CAAC;YACH,qBAAqB,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC;QACrE,CAAC;QAAC,MAAM,CAAC;YACP,0EAA0E;YAC1E,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IACD,IAAI,qBAAqB,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACvC,OAAO,KAAK,CAAC;IACf,CAAC;IAED,IA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AC,CAAC;IACxD,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;QAC1B,MAAM,SAAS,GAAG,wBAAwB,CAAC,GAAG,CAAC,CAAC;QAChD,OAAO,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACtC,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,uBAAuB,GAAG;;;;;;;;;;;;;;;;;;;;;;CAsB/B,CAAC;AAEF;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,OAAgB,EAChB,KAA2C;IAE3C,MAAM,IAAI,GAAG,MAAM,OAAO,CAAC,uBAAuB,EAAE;QAClD,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;KACd,CAAC,CAAC;IACH,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,cAAc,GAAG,UAAU,CAAC,GAAG,EAAE,sBAAsB,CAAC,CAAC;IAC/D,IAAI,CAAC,cAAc,EAAE,CAAC;QACpB,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,gBAAgB,CAAC;QACtB,cAAc;QACd,uBAAuB,EAAE,UAAU,CAAC,GAAG,EAAE,4BAA4B,CAAC;QACtE,kBAAkB,EAAE,UAAU,CAAC,GAAG,EAAE,sBAAsB,CAAC;KAC5D,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { mergeVersionVectors, satisfiesVersionVector } from \"@tearleads/loro\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n getContainerDisplayNameSql,\n getContainerOrganizationAttributionSql,\n} from \"../documentQueries/sql\";\nimport type { PendingWriteCandidate } from \"./aggregation\";\nimport type { PendingWriteQueueObjectKind } from \"./pendingWritesTypes\";\nimport { readString } from \"./rowReaders\";\n\n// Deliberately never loads document content: the diagnostic listing runs\n// repeatedly while sync drains, and materializing every content blob would\n// make the scan O(total document content). `snapshot_end_version` is the\n// write-time-derived end version vector of the persisted content.\nconst DEFERRED_TAIL_CANDIDATE_SQL = `\n SELECT\n stored.app_kind AS app_kind,\n stored.local_id AS local_id,\n stored.document_id AS stored_remote_id,\n stored.snapshot_end_version AS snapshot_end_version,\n stored.pending_base_version AS pending_base_version,\n stored.updated_at AS updated_at,\n (\n SELECT pending.partial_end_version_vector\n FROM document_history_updates pending\n WHERE pending.app_kind = stored.app_kind\n AND pending.local_id = stored.local_id\n AND pending.update_id IS NOT NULL\n ORDER BY pending.created_at DESC, pending.rowid DESC\n LIMIT 1\n ) AS latest_pending_end_version,\n document_projection.title AS document_name,\n document_projection.container_id AS document_container_id,\n ${getContainerOrganizationAttributionSql({\n containerAlias: \"document_container\",\n projectionAlias: \"document_projection\",\n })} AS document_organization_id,\n CASE\n WHEN metadata_container.server_created_at IS NULL THEN NULL\n ELSE metadata_container.id\n END AS container_remote_id,\n ${getContainerDisplayNameSql(\"metadata_container\")} AS container_name,\n metadata_container.id AS metadata_container_id,\n NULLIF(metadata_container.organization_id, '') AS metadata_organization_id,\n stored.sync_failure_message AS failure_message,\n stored.sync_failure_attempted_at AS failure_attempted_at\n FROM documents stored\n LEFT JOIN document_projection\n ON stored.app_kind = 'documents'\n AND document_projection.local_id = stored.local_id\n LEFT JOIN containers document_container\n ON document_container.id = document_projection.container_id\n LEFT JOIN containers metadata_container\n ON stored.app_kind = 'container-metadata'\n AND metadata_container.id = stored.local_id\n WHERE stored.snapshot_end_version <> ''\n -- A marker equal to the content frontier covers it, so a settled record\n -- is never a candidate. With the term above this matches\n -- documents_deferred_tail_idx, so the scan reads only unsettled records.\n AND stored.pending_base_version IS NOT stored.snapshot_end_version\n -- Dormant retained metadata (row 4, access_revoked) has no containers\n -- row; keep it out of deferred-tail candidates until re-attach, matching\n -- the pending-write sources guard.\n AND (stored.app_kind <> 'container-metadata'\n OR metadata_container.id IS NOT NULL)\n AND (\n stored.pending_base_version IS NOT NULL\n OR EXISTS (\n SELECT 1\n FROM document_history_updates pending\n WHERE pending.app_kind = stored.app_kind\n AND pending.local_id = stored.local_id\n AND pending.update_id IS NOT NULL\n )\n )\n`;\n\nfunction hasUncoveredTail(input: {\n currentVersion: string;\n latestPendingEndVersion: string | null;\n pendingBaseVersion: string | null;\n}): boolean {\n const coverageVersions = [\n input.latestPendingEndVersion,\n input.pendingBaseVersion,\n ].filter((value): value is string => value !== null);\n const validCoverageVersions: string[] = [];\n for (const coverageVersion of coverageVersions) {\n try {\n validCoverageVersions.push(mergeVersionVectors([coverageVersion]));\n } catch {\n // Corrupt coverage must not make the diagnostic claim an uncovered write.\n return false;\n }\n }\n if (validCoverageVersions.length === 0) {\n return false;\n }\n\n try {\n const mergedCoverage = mergeVersionVectors(validCoverageVersions);\n return !satisfiesVersionVector(mergedCoverage, input.currentVersion);\n } catch {\n // Corrupt coverage must not make the diagnostic claim an uncovered write.\n return false;\n }\n}\n\nfunction getObjectKind(appKind: string): PendingWriteQueueObjectKind {\n if (appKind === \"documents\") return \"document\";\n if (appKind === \"container-metadata\") return \"container\";\n return \"unknown\";\n}\n\nfunction mapDeferredTailCandidate(\n row: Record<string, unknown>,\n): PendingWriteCandidate | null {\n const appKind = readString(row, \"app_kind\");\n const localId = readString(row, \"local_id\");\n const currentVersion = readString(row, \"snapshot_end_version\");\n if (!appKind || !localId || !currentVersion) {\n return null;\n }\n if (\n !hasUncoveredTail({\n currentVersion,\n latestPendingEndVersion: readString(row, \"latest_pending_end_version\"),\n pendingBaseVersion: readString(row, \"pending_base_version\"),\n })\n ) {\n return null;\n }\n\n const objectKind = getObjectKind(appKind);\n const updatedAt = readString(row, \"updated_at\");\n return {\n byteLength: 0,\n containerId:\n objectKind === \"container\"\n ? readString(row, \"metadata_container_id\")\n : objectKind === \"document\"\n ? readString(row, \"document_container_id\")\n : null,\n count: 1,\n createdAt: updatedAt,\n inclusion: \"always\",\n kind: \"deferred-update\",\n // Carry the scope's recorded sync failure so a covering deferred-update\n // candidate never hides the diagnostic a suppressed failure-only item\n // would have shown.\n lastAttemptedAt: readString(row, \"failure_attempted_at\"),\n lastError: readString(row, \"failure_message\"),\n localId,\n name:\n objectKind === \"container\"\n ? readString(row, \"container_name\")\n : objectKind === \"document\"\n ? readString(row, \"document_name\")\n : null,\n namespace: objectKind === \"unknown\" ? appKind : null,\n objectKind,\n organizationId:\n objectKind === \"container\"\n ? readString(row, \"metadata_organization_id\")\n : objectKind === \"document\"\n ? readString(row, \"document_organization_id\")\n : null,\n remoteId:\n objectKind === \"container\"\n ? readString(row, \"container_remote_id\")\n : readString(row, \"stored_remote_id\"),\n status: \"pending\",\n targetContainerId: null,\n updatedAt,\n };\n}\n\nexport async function listDeferredPendingWriteCandidates(\n execSql: ExecSql,\n): Promise<PendingWriteCandidate[]> {\n const rows = await execSql(DEFERRED_TAIL_CANDIDATE_SQL);\n return rows.flatMap((row) => {\n const candidate = mapDeferredTailCandidate(row);\n return candidate ? [candidate] : [];\n });\n}\n\nconst DEFERRED_TAIL_SCOPE_SQL = `\n SELECT\n stored.snapshot_end_version AS snapshot_end_version,\n stored.pending_base_version AS pending_base_version,\n (\n SELECT pending.partial_end_version_vector\n FROM document_history_updates pending\n WHERE pending.app_kind = stored.app_kind\n AND pending.local_id = stored.local_id\n AND pending.update_id IS NOT NULL\n ORDER BY pending.created_at DESC, pending.rowid DESC\n LIMIT 1\n ) AS latest_pending_end_version\n FROM documents stored\n WHERE stored.app_kind = ? AND stored.local_id = ?\n AND stored.snapshot_end_version <> ''\n -- Dormant retained metadata (row 4, access_revoked) has no containers\n -- row; it is not queued work until re-attach, matching the candidate\n -- scan's guard.\n AND (stored.app_kind <> 'container-metadata'\n OR EXISTS (SELECT 1 FROM containers WHERE containers.id = stored.local_id))\n LIMIT 1\n`;\n\n/**\n * Whether this one scope has a deferred write: durable-tail content ahead of\n * its covered frontier, possibly with no queued update rows at all. The same\n * coverage check as the candidate scan, narrowed to a single scope, so\n * \"queued work\" classifications agree with the item the panel rendered.\n */\nexport async function hasDeferredTailScopeWork(\n execSql: ExecSql,\n scope: { appKind: string; localId: string },\n): Promise<boolean> {\n const rows = await execSql(DEFERRED_TAIL_SCOPE_SQL, [\n scope.appKind,\n scope.localId,\n ]);\n const row = rows[0];\n if (!row) {\n return false;\n }\n const currentVersion = readString(row, \"snapshot_end_version\");\n if (!currentVersion) {\n return false;\n }\n return hasUncoveredTail({\n currentVersion,\n latestPendingEndVersion: readString(row, \"latest_pending_end_version\"),\n pendingBaseVersion: readString(row, \"pending_base_version\"),\n });\n}\n"]}