@nicia-ai/typegraph 0.65.0 → 0.66.1

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 (196) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/{atomic-mutation-program-BznZQ06C.d.ts → atomic-mutation-program-BhP75Qn0.d.ts} +1 -1
  3. package/dist/{atomic-mutation-program-Bfu5z-je.d.cts → atomic-mutation-program-DMdmc4s0.d.cts} +1 -1
  4. package/dist/backend/drizzle/engine/index.cjs +13 -13
  5. package/dist/backend/drizzle/engine/index.d.cts +9 -9
  6. package/dist/backend/drizzle/engine/index.d.ts +9 -9
  7. package/dist/backend/drizzle/engine/index.js +8 -8
  8. package/dist/backend/drizzle/indexes.d.cts +1 -1
  9. package/dist/backend/drizzle/indexes.d.ts +1 -1
  10. package/dist/backend/index.cjs +91 -91
  11. package/dist/backend/index.d.cts +7 -7
  12. package/dist/backend/index.d.ts +7 -7
  13. package/dist/backend/index.js +8 -8
  14. package/dist/backend/postgres/index.cjs +23 -23
  15. package/dist/backend/postgres/index.d.cts +8 -8
  16. package/dist/backend/postgres/index.d.ts +8 -8
  17. package/dist/backend/postgres/index.js +8 -8
  18. package/dist/backend/postgres/pglite-store.cjs +1 -1
  19. package/dist/backend/postgres/pglite-store.d.cts +6 -6
  20. package/dist/backend/postgres/pglite-store.d.ts +6 -6
  21. package/dist/backend/postgres/pglite-store.js +1 -1
  22. package/dist/backend/postgres/pglite.cjs +10 -10
  23. package/dist/backend/postgres/pglite.d.cts +3 -3
  24. package/dist/backend/postgres/pglite.d.ts +3 -3
  25. package/dist/backend/postgres/pglite.js +9 -9
  26. package/dist/backend/sqlite/index.cjs +21 -21
  27. package/dist/backend/sqlite/index.d.cts +7 -7
  28. package/dist/backend/sqlite/index.d.ts +7 -7
  29. package/dist/backend/sqlite/index.js +8 -8
  30. package/dist/backend/sqlite/libsql.cjs +14 -14
  31. package/dist/backend/sqlite/libsql.d.cts +3 -3
  32. package/dist/backend/sqlite/libsql.d.ts +3 -3
  33. package/dist/backend/sqlite/libsql.js +8 -8
  34. package/dist/backend/sqlite/local-store.cjs +1 -1
  35. package/dist/backend/sqlite/local-store.d.cts +6 -6
  36. package/dist/backend/sqlite/local-store.d.ts +6 -6
  37. package/dist/backend/sqlite/local-store.js +1 -1
  38. package/dist/backend/sqlite/local.cjs +10 -10
  39. package/dist/backend/sqlite/local.d.cts +3 -3
  40. package/dist/backend/sqlite/local.d.ts +3 -3
  41. package/dist/backend/sqlite/local.js +9 -9
  42. package/dist/{chunk-PFXNQFFY.js → chunk-2DJKHZQ4.js} +75 -8
  43. package/dist/chunk-2DJKHZQ4.js.map +1 -0
  44. package/dist/{chunk-337ONI2I.js → chunk-3SUZXB5X.js} +146 -80
  45. package/dist/chunk-3SUZXB5X.js.map +1 -0
  46. package/dist/{chunk-4VTCIEK3.js → chunk-4TQOIBWH.js} +3 -3
  47. package/dist/{chunk-4VTCIEK3.js.map → chunk-4TQOIBWH.js.map} +1 -1
  48. package/dist/{chunk-JRWKRBI5.cjs → chunk-5JOCIMQ3.cjs} +6 -6
  49. package/dist/{chunk-JRWKRBI5.cjs.map → chunk-5JOCIMQ3.cjs.map} +1 -1
  50. package/dist/{chunk-BWQA3POT.cjs → chunk-6B3LQUYG.cjs} +206 -138
  51. package/dist/chunk-6B3LQUYG.cjs.map +1 -0
  52. package/dist/{chunk-RQPCUHIH.js → chunk-6ECNYQDW.js} +3 -3
  53. package/dist/{chunk-RQPCUHIH.js.map → chunk-6ECNYQDW.js.map} +1 -1
  54. package/dist/{chunk-OLB75LRQ.js → chunk-6GKKAQMW.js} +5 -5
  55. package/dist/{chunk-OLB75LRQ.js.map → chunk-6GKKAQMW.js.map} +1 -1
  56. package/dist/{chunk-OC5ROP7V.cjs → chunk-6JRVV2SS.cjs} +8 -2
  57. package/dist/chunk-6JRVV2SS.cjs.map +1 -0
  58. package/dist/{chunk-DSX3P4S5.cjs → chunk-76OB5RSH.cjs} +6 -6
  59. package/dist/{chunk-DSX3P4S5.cjs.map → chunk-76OB5RSH.cjs.map} +1 -1
  60. package/dist/{chunk-DHRLOQLQ.cjs → chunk-7LQTDGV5.cjs} +11 -11
  61. package/dist/{chunk-DHRLOQLQ.cjs.map → chunk-7LQTDGV5.cjs.map} +1 -1
  62. package/dist/{chunk-Q25QYSOH.js → chunk-7YJHUY4T.js} +9 -9
  63. package/dist/{chunk-Q25QYSOH.js.map → chunk-7YJHUY4T.js.map} +1 -1
  64. package/dist/{chunk-JERQGJKG.cjs → chunk-ANMCKLZQ.cjs} +18 -18
  65. package/dist/{chunk-JERQGJKG.cjs.map → chunk-ANMCKLZQ.cjs.map} +1 -1
  66. package/dist/{chunk-BBOMNH44.js → chunk-BABP4D5B.js} +3 -3
  67. package/dist/{chunk-BBOMNH44.js.map → chunk-BABP4D5B.js.map} +1 -1
  68. package/dist/{chunk-EVGZ2TRQ.js → chunk-BE75G3M5.js} +3 -3
  69. package/dist/{chunk-EVGZ2TRQ.js.map → chunk-BE75G3M5.js.map} +1 -1
  70. package/dist/{chunk-FXGZT3WO.cjs → chunk-BX42F7IJ.cjs} +41 -41
  71. package/dist/{chunk-FXGZT3WO.cjs.map → chunk-BX42F7IJ.cjs.map} +1 -1
  72. package/dist/{chunk-G6T23JU7.js → chunk-CDKNGCE7.js} +3 -3
  73. package/dist/{chunk-G6T23JU7.js.map → chunk-CDKNGCE7.js.map} +1 -1
  74. package/dist/{chunk-BNTJ5YFO.cjs → chunk-EACDHXJL.cjs} +4 -4
  75. package/dist/{chunk-BNTJ5YFO.cjs.map → chunk-EACDHXJL.cjs.map} +1 -1
  76. package/dist/{chunk-SNDJUTMB.cjs → chunk-EBQX7MYL.cjs} +72 -72
  77. package/dist/{chunk-SNDJUTMB.cjs.map → chunk-EBQX7MYL.cjs.map} +1 -1
  78. package/dist/{chunk-GKSAEUX6.js → chunk-FXOFJ4FS.js} +7 -7
  79. package/dist/{chunk-GKSAEUX6.js.map → chunk-FXOFJ4FS.js.map} +1 -1
  80. package/dist/{chunk-ZOWRACZQ.cjs → chunk-G7OKJDMG.cjs} +5 -5
  81. package/dist/{chunk-ZOWRACZQ.cjs.map → chunk-G7OKJDMG.cjs.map} +1 -1
  82. package/dist/{chunk-MKJPBSID.cjs → chunk-I7SBZJI2.cjs} +4 -4
  83. package/dist/{chunk-MKJPBSID.cjs.map → chunk-I7SBZJI2.cjs.map} +1 -1
  84. package/dist/{chunk-H346QK3V.cjs → chunk-K7YACILO.cjs} +9 -9
  85. package/dist/{chunk-H346QK3V.cjs.map → chunk-K7YACILO.cjs.map} +1 -1
  86. package/dist/{chunk-3KWF25MF.cjs → chunk-MN325MG4.cjs} +313 -246
  87. package/dist/chunk-MN325MG4.cjs.map +1 -0
  88. package/dist/{chunk-KDNRACRG.cjs → chunk-MRUOOAIQ.cjs} +4 -4
  89. package/dist/{chunk-KDNRACRG.cjs.map → chunk-MRUOOAIQ.cjs.map} +1 -1
  90. package/dist/{chunk-HTSJTWUT.js → chunk-OF63ZHSD.js} +4 -4
  91. package/dist/{chunk-HTSJTWUT.js.map → chunk-OF63ZHSD.js.map} +1 -1
  92. package/dist/{chunk-NGA3THGU.cjs → chunk-QR7W37HG.cjs} +14 -14
  93. package/dist/{chunk-NGA3THGU.cjs.map → chunk-QR7W37HG.cjs.map} +1 -1
  94. package/dist/{chunk-QFEO4M5W.js → chunk-RTPMG6LQ.js} +11 -11
  95. package/dist/{chunk-QFEO4M5W.js.map → chunk-RTPMG6LQ.js.map} +1 -1
  96. package/dist/{chunk-PFD4NUYV.js → chunk-SSDHR2C2.js} +3 -3
  97. package/dist/{chunk-PFD4NUYV.js.map → chunk-SSDHR2C2.js.map} +1 -1
  98. package/dist/{chunk-THK3SCQA.js → chunk-SYXTWPX6.js} +5 -5
  99. package/dist/{chunk-THK3SCQA.js.map → chunk-SYXTWPX6.js.map} +1 -1
  100. package/dist/{chunk-XSLQYGNR.cjs → chunk-T3VU3YRQ.cjs} +69 -69
  101. package/dist/{chunk-XSLQYGNR.cjs.map → chunk-T3VU3YRQ.cjs.map} +1 -1
  102. package/dist/{chunk-MIBWA6HX.js → chunk-TR7QTODF.js} +213 -33
  103. package/dist/chunk-TR7QTODF.js.map +1 -0
  104. package/dist/{chunk-AD3NLSV5.js → chunk-TU22BFMP.js} +8 -2
  105. package/dist/chunk-TU22BFMP.js.map +1 -0
  106. package/dist/{chunk-WTMSUIRO.js → chunk-UFKYMQJ5.js} +3 -3
  107. package/dist/{chunk-WTMSUIRO.js.map → chunk-UFKYMQJ5.js.map} +1 -1
  108. package/dist/{chunk-35LDKSMM.cjs → chunk-VNJMM2QQ.cjs} +30 -30
  109. package/dist/{chunk-35LDKSMM.cjs.map → chunk-VNJMM2QQ.cjs.map} +1 -1
  110. package/dist/{chunk-53ZEBIMD.js → chunk-WB55URNM.js} +6 -6
  111. package/dist/{chunk-53ZEBIMD.js.map → chunk-WB55URNM.js.map} +1 -1
  112. package/dist/{chunk-L2GBVYRU.cjs → chunk-WWSYGZED.cjs} +11 -11
  113. package/dist/{chunk-L2GBVYRU.cjs.map → chunk-WWSYGZED.cjs.map} +1 -1
  114. package/dist/{chunk-D2JPOFRZ.cjs → chunk-WY3IFEKV.cjs} +191 -191
  115. package/dist/{chunk-D2JPOFRZ.cjs.map → chunk-WY3IFEKV.cjs.map} +1 -1
  116. package/dist/{chunk-3RSFLZ7A.cjs → chunk-Y4X6ODVY.cjs} +943 -763
  117. package/dist/chunk-Y4X6ODVY.cjs.map +1 -0
  118. package/dist/{chunk-VZRXXABW.js → chunk-YHMXF7OZ.js} +5 -5
  119. package/dist/{chunk-VZRXXABW.js.map → chunk-YHMXF7OZ.js.map} +1 -1
  120. package/dist/{chunk-VROJKWZ7.js → chunk-ZONDBN6H.js} +5 -5
  121. package/dist/{chunk-VROJKWZ7.js.map → chunk-ZONDBN6H.js.map} +1 -1
  122. package/dist/core/index.d.cts +3 -3
  123. package/dist/core/index.d.ts +3 -3
  124. package/dist/{ddl-DvW9aobX.d.ts → ddl-2q7xLM1X.d.ts} +3 -3
  125. package/dist/{ddl-BjuXbPfw.d.cts → ddl-D_09BfbN.d.cts} +3 -3
  126. package/dist/graph-extension/index.d.cts +2 -2
  127. package/dist/graph-extension/index.d.ts +2 -2
  128. package/dist/graph-merge/index.cjs +156 -156
  129. package/dist/graph-merge/index.d.cts +7 -7
  130. package/dist/graph-merge/index.d.ts +7 -7
  131. package/dist/graph-merge/index.js +14 -14
  132. package/dist/{graph-templates-1vMqlPsu.d.cts → graph-templates-B5Q7oYAA.d.cts} +2 -2
  133. package/dist/{graph-templates-Y52w16dH.d.ts → graph-templates-D9N-Z9kw.d.ts} +2 -2
  134. package/dist/index.cjs +99 -99
  135. package/dist/index.d.cts +10 -10
  136. package/dist/index.d.ts +10 -10
  137. package/dist/index.js +18 -18
  138. package/dist/indexes/index.d.cts +4 -4
  139. package/dist/indexes/index.d.ts +4 -4
  140. package/dist/{ingestion-import-target-CCKeXZbW.d.ts → ingestion-import-target-B8EU6ug2.d.ts} +1 -1
  141. package/dist/{ingestion-import-target-774QRgkF.d.cts → ingestion-import-target-C5sHNFJF.d.cts} +1 -1
  142. package/dist/interchange/index.cjs +34 -34
  143. package/dist/interchange/index.d.cts +7 -7
  144. package/dist/interchange/index.d.ts +7 -7
  145. package/dist/interchange/index.js +11 -11
  146. package/dist/{local-store-impl-DFKS7QTV.js → local-store-impl-ERPNYOCL.js} +18 -18
  147. package/dist/{local-store-impl-DFKS7QTV.js.map → local-store-impl-ERPNYOCL.js.map} +1 -1
  148. package/dist/{local-store-impl-3E4VLFCI.cjs → local-store-impl-OUINMCYI.cjs} +22 -22
  149. package/dist/{local-store-impl-3E4VLFCI.cjs.map → local-store-impl-OUINMCYI.cjs.map} +1 -1
  150. package/dist/{pglite-store-impl-N63GGBU2.js → pglite-store-impl-DUJBQZS5.js} +18 -18
  151. package/dist/{pglite-store-impl-N63GGBU2.js.map → pglite-store-impl-DUJBQZS5.js.map} +1 -1
  152. package/dist/{pglite-store-impl-T75O3LVQ.cjs → pglite-store-impl-Z3SOOP75.cjs} +22 -22
  153. package/dist/{pglite-store-impl-T75O3LVQ.cjs.map → pglite-store-impl-Z3SOOP75.cjs.map} +1 -1
  154. package/dist/{postgres-C9gitL71.d.ts → postgres-BbTYW3b_.d.ts} +3 -3
  155. package/dist/{postgres-BONrXHb4.d.cts → postgres-DOBXcZVg.d.cts} +1 -1
  156. package/dist/{postgres-DAFRdnTr.d.ts → postgres-DhZixg92.d.ts} +1 -1
  157. package/dist/{postgres-2FYdVYCm.d.cts → postgres-Dp3MpyJt.d.cts} +3 -3
  158. package/dist/{profile-CAD65CqS.d.ts → profile-Ch5SSewK.d.ts} +8 -8
  159. package/dist/{profile-Bmcg07Ki.d.cts → profile-DppApFgt.d.cts} +8 -8
  160. package/dist/profiler/index.d.cts +8 -8
  161. package/dist/profiler/index.d.ts +8 -8
  162. package/dist/provenance/index.cjs +22 -22
  163. package/dist/provenance/index.d.cts +6 -6
  164. package/dist/provenance/index.d.ts +6 -6
  165. package/dist/provenance/index.js +6 -6
  166. package/dist/{repair-validity-windows-CinP91t7.d.cts → repair-validity-windows-CpP_GpIx.d.cts} +1 -1
  167. package/dist/{repair-validity-windows-BJz4nffP.d.ts → repair-validity-windows-lfe275bY.d.ts} +1 -1
  168. package/dist/{resolve-DgOSlXx_.d.ts → resolve-CoYqHqno.d.cts} +7 -2
  169. package/dist/{resolve-DQXSEN_A.d.cts → resolve-DV0Iposp.d.ts} +7 -2
  170. package/dist/schema/index.cjs +37 -37
  171. package/dist/schema/index.d.cts +7 -7
  172. package/dist/schema/index.d.ts +7 -7
  173. package/dist/schema/index.js +7 -7
  174. package/dist/{searchable-DMdCwkXO.d.cts → searchable-C7Xt6g45.d.cts} +1 -1
  175. package/dist/{searchable-BPRF0Bah.d.ts → searchable-KKXrPet3.d.ts} +1 -1
  176. package/dist/{sqlite-DgbYa-1Y.d.cts → sqlite-BkQM9ZeI.d.cts} +1 -1
  177. package/dist/{sqlite-Co_uIpfs.d.cts → sqlite-BpRtjC36.d.cts} +3 -3
  178. package/dist/{sqlite-DcDAAYow.d.ts → sqlite-CH0Zq0Qv.d.ts} +3 -3
  179. package/dist/{sqlite-UlG5prJQ.d.ts → sqlite-CcCSeXGg.d.ts} +1 -1
  180. package/dist/{store-HxoFyQMu.d.cts → store-3nfPQK5j.d.cts} +30 -7
  181. package/dist/{store-C9T1c9Az.d.ts → store-C8ZPl7OW.d.ts} +30 -7
  182. package/dist/{types-CRCyg1fJ.d.cts → types-BynPp5kU.d.cts} +18 -2
  183. package/dist/{types-CRCyg1fJ.d.ts → types-BynPp5kU.d.ts} +18 -2
  184. package/dist/{types-Dg_prBqC.d.ts → types-C9YwrkSe.d.ts} +1 -1
  185. package/dist/{types-B5AUesS1.d.cts → types-JG-4CG6P.d.cts} +1 -1
  186. package/dist/{where-gRyc3jj_.d.cts → where-D1gBDqQ_.d.cts} +1 -1
  187. package/dist/{where-D-NDKMPw.d.ts → where-D2GqMFp-.d.ts} +1 -1
  188. package/package.json +1 -1
  189. package/dist/chunk-337ONI2I.js.map +0 -1
  190. package/dist/chunk-3KWF25MF.cjs.map +0 -1
  191. package/dist/chunk-3RSFLZ7A.cjs.map +0 -1
  192. package/dist/chunk-AD3NLSV5.js.map +0 -1
  193. package/dist/chunk-BWQA3POT.cjs.map +0 -1
  194. package/dist/chunk-MIBWA6HX.js.map +0 -1
  195. package/dist/chunk-OC5ROP7V.cjs.map +0 -1
  196. package/dist/chunk-PFXNQFFY.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/backend/migrate-recorded-time.ts","../src/backend/repair-validity-windows.ts"],"names":["shortHash","createSqlSchema","ConfigurationError","asCompiledStatementSql","sql","canonicalizeDatabaseTimestamp","RECORDED_MAX_REVISION","requireCatalog","asCompiledRowsSql","resolveRecordedTimeOwnership","resolvedTableNames","UnsupportedBackendCapabilityError","asRecordedInstant","ValidationError","createRecordedInstant","statementExecutionMembers","statementExecutionVerdict","runOptionallyInTransaction"],"mappings":";;;;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C,MAAA,EAAQ,UAAU,IAAA,KAAS;AAAA,OAC7B;AAAA,IACF,CAAA;AAAA,IACA,qBAAA,CAAsB,QAAQ,IAAI;AAAA,GACpC;AACF","file":"chunk-NGA3THGU.cjs","sourcesContent":["/**\n * One-time offline migration from timestamp-only recorded relations to numeric\n * revisions. The durable remap table lets applications translate checkpoints\n * stored outside TypeGraph before deleting the migration metadata.\n */\nimport {\n asRecordedInstant,\n createRecordedInstant,\n RECORDED_MAX_REVISION,\n type RecordedInstant,\n} from \"../core/temporal\";\nimport {\n ConfigurationError,\n UnsupportedBackendCapabilityError,\n ValidationError,\n} from \"../errors\";\nimport {\n createSqlSchema,\n type ResolvedSqlTableNames,\n type SqlTableNames,\n} from \"../query/compiler/schema\";\nimport { shortHash } from \"../query/dialect/vector-strategy\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql, asCompiledStatementSql } from \"../query/sql-intent\";\nimport { canonicalizeDatabaseTimestamp } from \"../utils/date\";\nimport { requireCatalog } from \"./capabilities/catalog\";\nimport { resolveRecordedTimeOwnership } from \"./capabilities/recorded-time-ownership\";\nimport { resolvedTableNames } from \"./table-names\";\nimport {\n type GraphBackend,\n type RecordedRelationDdl,\n type RecordedTableNames,\n type TransactionBackend,\n} from \"./types\";\n\nconst LEGACY_RECORDED_MAX = \"9999-12-31T23:59:59.999Z\";\nconst MIGRATION_SUFFIX = \"legacy_recorded_anchors\";\n\nconst RECORDED_NODE_COLUMNS = [\n \"history_id\",\n \"graph_id\",\n \"kind\",\n \"id\",\n \"props\",\n \"version\",\n \"valid_from\",\n \"valid_to\",\n \"created_at\",\n \"updated_at\",\n \"deleted_at\",\n \"recorded_from\",\n \"recorded_to\",\n \"op\",\n \"schema_version\",\n \"tx_id\",\n \"meta\",\n] as const;\n\nconst RECORDED_EDGE_COLUMNS = [\n \"history_id\",\n \"graph_id\",\n \"id\",\n \"kind\",\n \"from_kind\",\n \"from_id\",\n \"to_kind\",\n \"to_id\",\n \"props\",\n \"valid_from\",\n \"valid_to\",\n \"created_at\",\n \"updated_at\",\n \"deleted_at\",\n \"recorded_from\",\n \"recorded_to\",\n \"op\",\n \"schema_version\",\n \"tx_id\",\n \"meta\",\n] as const;\n\ntype LegacyInstantRow = Readonly<{\n graph_id: unknown;\n recorded_at: unknown;\n}>;\n\ntype MappingRow = Readonly<{\n graphId: string;\n legacyRecordedAt: string;\n recordedAt: string;\n revision: number;\n}>;\n\ntype RemapRow = Readonly<{ recorded_at: unknown; revision: unknown }>;\ntype MappingCountRow = Readonly<{ anchors: unknown; graphs: unknown }>;\ntype MissingMappingRow = Readonly<{ missing: unknown }>;\n\nexport type MigrateLegacyRecordedTimeOptions = Readonly<{\n backend: GraphBackend;\n /** Patch selected backend table names; unstated names remain configured. */\n tableNames?: Partial<SqlTableNames> | undefined;\n /** Override the durable legacy-anchor mapping table name. */\n mappingTableName?: string | undefined;\n}>;\n\nexport type MigrateLegacyRecordedTimeResult = Readonly<{\n /** `true` when timestamp columns were rewritten during this call. */\n migrated: boolean;\n /** Number of graphs represented in the legacy commit order. */\n graphs: number;\n /** Number of distinct legacy anchors available for remapping. */\n anchors: number;\n /** Physical table retaining the old-anchor → revision mapping. */\n mappingTableName: string;\n}>;\n\nexport type MigrateRecordedAnchorOptions = Readonly<{\n backend: Pick<GraphBackend, \"dialect\" | \"execute\" | \"tableNames\">;\n graphId: string;\n anchor: string;\n /** Patch selected backend table names; unstated names remain configured. */\n tableNames?: Partial<SqlTableNames> | undefined;\n mappingTableName?: string | undefined;\n}>;\n\nexport type DeleteLegacyRecordedAnchorMapOptions = Readonly<{\n backend: Pick<\n GraphBackend,\n \"dialect\" | \"execute\" | \"executeStatement\" | \"tableNames\" | \"transaction\"\n >;\n graphId: string;\n /** Patch selected backend table names; unstated names remain configured. */\n tableNames?: Partial<SqlTableNames> | undefined;\n mappingTableName?: string | undefined;\n /** Drop the mapping table when this deletion leaves it empty. */\n dropWhenEmpty?: boolean | undefined;\n}>;\n\nfunction shortenedIdentifier(value: string): string {\n if (value.length <= 63) return value;\n return `${value.slice(0, 50)}_${shortHash(value)}`;\n}\n\nfunction mappingTableName(\n tables: ResolvedSqlTableNames,\n override: string | undefined,\n): string {\n const candidate = override ?? `${tables.recordedClock}_${MIGRATION_SUFFIX}`;\n return createSqlSchema({\n recordedClock: shortenedIdentifier(candidate),\n }).tables.recordedClock;\n}\n\nfunction temporaryTableName(tableName: string, role: string): string {\n return shortenedIdentifier(`__tg_${role}_${shortHash(tableName)}`);\n}\n\nfunction requireStatements(\n target: Pick<TransactionBackend, \"dialect\" | \"executeStatement\">,\n): NonNullable<TransactionBackend[\"executeStatement\"]> {\n if (target.executeStatement === undefined) {\n throw new ConfigurationError(\n \"Recorded-time migration requires executeStatement support.\",\n { dialect: target.dialect },\n { suggestion: \"Use a built-in SQLite or PostgreSQL backend.\" },\n );\n }\n return target.executeStatement;\n}\n\nasync function executeStatement(\n target: Pick<TransactionBackend, \"dialect\" | \"executeStatement\">,\n statement: SqlFragment,\n): Promise<void> {\n await requireStatements(target)(asCompiledStatementSql(statement));\n}\n\nasync function executeDdl(\n target: Pick<TransactionBackend, \"dialect\" | \"executeStatement\">,\n ddl: string,\n): Promise<void> {\n await executeStatement(target, sql.raw(ddl));\n}\n\nfunction canonicalLegacyInstant(value: unknown): string {\n const canonical = canonicalizeDatabaseTimestamp(value);\n if (canonical === undefined) {\n throw new ConfigurationError(\n \"Legacy recorded-time relation contained an invalid timestamp.\",\n { value },\n );\n }\n return canonical;\n}\n\nfunction safeRevision(value: unknown): number {\n const revision =\n typeof value === \"bigint\" ? Number(value)\n : typeof value === \"string\" && /^\\d+$/.test(value) ? Number(value)\n : value;\n if (\n typeof revision !== \"number\" ||\n !Number.isSafeInteger(revision) ||\n revision < 1 ||\n revision >= RECORDED_MAX_REVISION\n ) {\n throw new ConfigurationError(\n \"Recorded anchor mapping contained an invalid revision.\",\n { value },\n );\n }\n return revision;\n}\n\nasync function columnNames(\n target: Pick<TransactionBackend, \"catalog\">,\n tableName: string,\n): Promise<ReadonlySet<string>> {\n const catalog = requireCatalog(target, \"migrateLegacyRecordedTime\");\n const columns = await catalog.columnTypes(tableName);\n return new Set(columns.map((column) => column.name));\n}\n\nasync function readLegacyInstants(\n target: TransactionBackend,\n tables: ResolvedSqlTableNames,\n): Promise<readonly MappingRow[]> {\n const rows = await target.execute<LegacyInstantRow>(\n asCompiledRowsSql(sql`\n SELECT graph_id, recorded_from AS recorded_at\n FROM ${sql.identifier(tables.recordedNodes)}\n UNION\n SELECT graph_id, recorded_to AS recorded_at\n FROM ${sql.identifier(tables.recordedNodes)}\n WHERE recorded_to <> ${LEGACY_RECORDED_MAX}\n UNION\n SELECT graph_id, recorded_from AS recorded_at\n FROM ${sql.identifier(tables.recordedEdges)}\n UNION\n SELECT graph_id, recorded_to AS recorded_at\n FROM ${sql.identifier(tables.recordedEdges)}\n WHERE recorded_to <> ${LEGACY_RECORDED_MAX}\n UNION\n SELECT graph_id, recorded_at\n FROM ${sql.identifier(tables.recordedClock)}\n `),\n );\n const instants = rows.map((row) => {\n if (typeof row.graph_id !== \"string\") {\n throw new ConfigurationError(\n \"Legacy recorded-time relation contained an invalid graph id.\",\n { graphId: row.graph_id },\n );\n }\n return {\n graphId: row.graph_id,\n recordedAt: canonicalLegacyInstant(row.recorded_at),\n };\n });\n instants.sort((left, right) => {\n if (left.graphId < right.graphId) return -1;\n if (left.graphId > right.graphId) return 1;\n if (left.recordedAt < right.recordedAt) return -1;\n if (left.recordedAt > right.recordedAt) return 1;\n return 0;\n });\n\n const mapping: MappingRow[] = [];\n let graphId: string | undefined;\n let revision = 0;\n let previousInstant: string | undefined;\n for (const instant of instants) {\n if (instant.graphId !== graphId) {\n graphId = instant.graphId;\n revision = 0;\n previousInstant = undefined;\n }\n if (instant.recordedAt === previousInstant) continue;\n revision += 1;\n mapping.push({\n graphId: instant.graphId,\n legacyRecordedAt: instant.recordedAt,\n recordedAt: instant.recordedAt,\n revision,\n });\n previousInstant = instant.recordedAt;\n }\n return mapping;\n}\n\nfunction migrationMapDdl(\n dialect: GraphBackend[\"dialect\"],\n table: string,\n): string {\n const revisionType = dialect === \"postgres\" ? \"BIGINT\" : \"INTEGER\";\n const recordedAtType = dialect === \"postgres\" ? \"TIMESTAMPTZ\" : \"TEXT\";\n return `CREATE TABLE IF NOT EXISTS \"${table}\" (\n graph_id TEXT NOT NULL,\n legacy_recorded_at TEXT NOT NULL,\n revision ${revisionType} NOT NULL,\n recorded_at ${recordedAtType} NOT NULL,\n PRIMARY KEY (graph_id, legacy_recorded_at)\n);`;\n}\n\nasync function writeMappingRows(\n target: TransactionBackend,\n tableName: string,\n rows: readonly MappingRow[],\n): Promise<void> {\n await executeStatement(target, sql`DELETE FROM ${sql.identifier(tableName)}`);\n const rowsPerStatement = Math.max(\n 1,\n Math.floor((target.capabilities.maxBindParameters ?? 900) / 4),\n );\n for (let start = 0; start < rows.length; start += rowsPerStatement) {\n const values = rows\n .slice(start, start + rowsPerStatement)\n .map(\n (row) =>\n sql`(${row.graphId}, ${row.legacyRecordedAt}, ${row.revision}, ${row.recordedAt})`,\n );\n await executeStatement(\n target,\n sql`\n INSERT INTO ${sql.identifier(tableName)}\n (graph_id, legacy_recorded_at, revision, recorded_at)\n VALUES ${sql.join(values, sql`, `)}\n `,\n );\n }\n}\n\ntype RecordedDdlSet = Readonly<\n Record<keyof RecordedTableNames, RecordedRelationDdl>\n>;\n\ntype PrimaryKeyConstraintRename =\n | Readonly<{ status: \"none\" }>\n | Readonly<{ status: \"rename\"; from: string; to: string }>;\n\n/**\n * The two calls the offline migration makes to the port, plus their\n * composition. `primaryKeyConstraintRenames` carries the backend-authored\n * decision itself, so the swap cannot re-derive it or silently ignore one\n * supplied name.\n */\ntype RecordedMigrationDdl = Readonly<{\n /**\n * The temp-named `CREATE TABLE` (so the swap-in relation is empty and safe\n * to populate) paired with the final-named `indexes` (so the swapped-in\n * relation ends up carrying the SAME index/constraint statements the final\n * table would get if provisioned fresh).\n */\n ddl: RecordedDdlSet;\n primaryKeyConstraintRenames: Readonly<\n Record<keyof RecordedTableNames, PrimaryKeyConstraintRename>\n >;\n}>;\n\n/**\n * The offline migration's own composition of the port's per-name-set DDL.\n * `recordedTableDdl` is called exactly once per name set — mirroring the\n * two-Drizzle-table-build shape this replaces — and the backend-authored\n * constraint-name pair is resolved here before any migration SQL executes.\n */\nfunction recordedMigrationDdl(\n recordedTableDdl: NonNullable<GraphBackend[\"recordedTableDdl\"]>,\n finalNames: RecordedTableNames,\n temporaryNames: RecordedTableNames,\n): RecordedMigrationDdl {\n const temporaryDdl = recordedTableDdl(temporaryNames);\n const finalDdl = recordedTableDdl(finalNames);\n function composed(key: keyof RecordedTableNames): RecordedRelationDdl {\n return {\n createTable: temporaryDdl[key].createTable,\n indexes: finalDdl[key].indexes,\n };\n }\n function primaryKeyConstraintRename(\n key: keyof RecordedTableNames,\n ): PrimaryKeyConstraintRename {\n const temporaryConstraintName = temporaryDdl[key].primaryKeyConstraintName;\n const finalConstraintName = finalDdl[key].primaryKeyConstraintName;\n if (\n temporaryConstraintName === undefined &&\n finalConstraintName === undefined\n )\n return { status: \"none\" };\n if (\n temporaryConstraintName === undefined ||\n finalConstraintName === undefined\n )\n throw new ConfigurationError(\n \"Recorded relation DDL must name both primary-key constraints or neither.\",\n {\n code: \"RECORDED_DDL_CONSTRAINT_NAME_MISMATCH\",\n relation: key,\n finalTable: finalNames[key],\n temporaryConstraintName,\n finalConstraintName,\n },\n );\n return {\n status: \"rename\",\n from: temporaryConstraintName,\n to: finalConstraintName,\n };\n }\n return {\n ddl: {\n recordedClock: composed(\"recordedClock\"),\n recordedEdges: composed(\"recordedEdges\"),\n recordedNodes: composed(\"recordedNodes\"),\n },\n primaryKeyConstraintRenames: {\n recordedClock: primaryKeyConstraintRename(\"recordedClock\"),\n recordedEdges: primaryKeyConstraintRename(\"recordedEdges\"),\n recordedNodes: primaryKeyConstraintRename(\"recordedNodes\"),\n },\n };\n}\n\nfunction migratedColumn(column: string, legacyAlias: string): SqlFragment {\n if (column === \"recorded_from\") return sql`from_map.revision`;\n if (column === \"recorded_to\") {\n return sql`\n CASE\n WHEN ${sql.raw(legacyAlias)}.recorded_to = ${LEGACY_RECORDED_MAX}\n THEN ${RECORDED_MAX_REVISION}\n ELSE to_map.revision\n END\n `;\n }\n return sql`${sql.raw(legacyAlias)}.${sql.identifier(column)}`;\n}\n\nfunction mappingMatch(\n dialect: GraphBackend[\"dialect\"],\n mappingAlias: \"anchor_map\" | \"from_map\" | \"to_map\",\n legacyColumn: \"recorded_at\" | \"recorded_from\" | \"recorded_to\",\n): SqlFragment {\n const mapping = sql.raw(mappingAlias);\n const legacy = sql.raw(`legacy.${legacyColumn}`);\n return dialect === \"postgres\" ?\n sql`${mapping}.recorded_at = ${legacy}`\n : sql`${mapping}.legacy_recorded_at = ${legacy}`;\n}\n\nfunction missingMappingCount(value: unknown, legacyTable: string): number {\n const count = Number(value);\n if (!Number.isSafeInteger(count) || count < 0) {\n throw new ConfigurationError(\n \"Recorded-time migration returned an invalid integrity-check count.\",\n { legacyTable, value },\n );\n }\n return count;\n}\n\nasync function assertRecordedRelationMappings(\n target: TransactionBackend,\n options: Readonly<{ legacyTable: string; mappingTable: string }>,\n): Promise<void> {\n const fromMatch = mappingMatch(target.dialect, \"from_map\", \"recorded_from\");\n const toMatch = mappingMatch(target.dialect, \"to_map\", \"recorded_to\");\n const rows = await target.execute<MissingMappingRow>(\n asCompiledRowsSql(sql`\n SELECT COUNT(*) AS missing\n FROM ${sql.identifier(options.legacyTable)} AS legacy\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS from_map\n ON from_map.graph_id = legacy.graph_id AND ${fromMatch}\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS to_map\n ON to_map.graph_id = legacy.graph_id AND ${toMatch}\n WHERE from_map.revision IS NULL\n OR (\n legacy.recorded_to <> ${LEGACY_RECORDED_MAX}\n AND to_map.revision IS NULL\n )\n `),\n );\n const missing = missingMappingCount(rows[0]?.missing, options.legacyTable);\n if (missing === 0) return;\n throw new ConfigurationError(\n \"Legacy recorded-time boundaries could not be mapped exactly.\",\n { legacyTable: options.legacyTable, missingRows: missing },\n {\n suggestion:\n \"Ensure every legacy boundary is a valid millisecond-precision timestamp produced by the preview recorded clock before retrying the offline migration.\",\n },\n );\n}\n\nasync function assertRecordedClockMappings(\n target: TransactionBackend,\n options: Readonly<{ legacyTable: string; mappingTable: string }>,\n): Promise<void> {\n const match = mappingMatch(target.dialect, \"anchor_map\", \"recorded_at\");\n const rows = await target.execute<MissingMappingRow>(\n asCompiledRowsSql(sql`\n SELECT COUNT(*) AS missing\n FROM ${sql.identifier(options.legacyTable)} AS legacy\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS anchor_map\n ON anchor_map.graph_id = legacy.graph_id AND ${match}\n WHERE anchor_map.revision IS NULL\n `),\n );\n const missing = missingMappingCount(rows[0]?.missing, options.legacyTable);\n if (missing === 0) return;\n throw new ConfigurationError(\n \"Legacy recorded clock values could not be mapped exactly.\",\n { legacyTable: options.legacyTable, missingRows: missing },\n {\n suggestion:\n \"Ensure every legacy clock value is a valid millisecond-precision timestamp produced by the preview recorded clock before retrying the offline migration.\",\n },\n );\n}\n\nasync function copyRecordedRelation(\n target: TransactionBackend,\n options: Readonly<{\n columns: readonly string[];\n legacyTable: string;\n mappingTable: string;\n temporaryTable: string;\n }>,\n): Promise<void> {\n const columnList = options.columns.map((column) => sql.identifier(column));\n const values = options.columns.map((column) =>\n migratedColumn(column, \"legacy\"),\n );\n await assertRecordedRelationMappings(target, options);\n const fromMatch = mappingMatch(target.dialect, \"from_map\", \"recorded_from\");\n const toMatch = mappingMatch(target.dialect, \"to_map\", \"recorded_to\");\n await executeStatement(\n target,\n sql`\n INSERT INTO ${sql.identifier(options.temporaryTable)}\n (${sql.join(columnList, sql`, `)})\n SELECT ${sql.join(values, sql`, `)}\n FROM ${sql.identifier(options.legacyTable)} AS legacy\n -- LEFT JOIN is deliberate: a missing mapping reaches the NOT NULL\n -- revision columns and fails loud instead of silently dropping history.\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS from_map\n ON from_map.graph_id = legacy.graph_id AND ${fromMatch}\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS to_map\n ON to_map.graph_id = legacy.graph_id AND ${toMatch}\n `,\n );\n}\n\nasync function copyRecordedClock(\n target: TransactionBackend,\n options: Readonly<{\n legacyTable: string;\n mappingTable: string;\n temporaryTable: string;\n }>,\n): Promise<void> {\n await assertRecordedClockMappings(target, options);\n const match = mappingMatch(target.dialect, \"anchor_map\", \"recorded_at\");\n await executeStatement(\n target,\n sql`\n INSERT INTO ${sql.identifier(options.temporaryTable)}\n (graph_id, revision, recorded_at)\n SELECT legacy.graph_id, anchor_map.revision, legacy.recorded_at\n FROM ${sql.identifier(options.legacyTable)} AS legacy\n -- Preserve fail-loud behavior if the preflight invariant changes later.\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS anchor_map\n ON anchor_map.graph_id = legacy.graph_id AND ${match}\n `,\n );\n}\n\nasync function replaceLegacyTables(\n target: TransactionBackend,\n tables: ResolvedSqlTableNames,\n mappingTable: string,\n recordedTableDdl: NonNullable<GraphBackend[\"recordedTableDdl\"]>,\n): Promise<void> {\n const temporary: RecordedTableNames = {\n recordedNodes: temporaryTableName(tables.recordedNodes, \"rn\"),\n recordedEdges: temporaryTableName(tables.recordedEdges, \"re\"),\n recordedClock: temporaryTableName(tables.recordedClock, \"rc\"),\n };\n const finalNames: RecordedTableNames = {\n recordedNodes: tables.recordedNodes,\n recordedEdges: tables.recordedEdges,\n recordedClock: tables.recordedClock,\n };\n const { ddl, primaryKeyConstraintRenames } = recordedMigrationDdl(\n recordedTableDdl,\n finalNames,\n temporary,\n );\n for (const table of Object.values(temporary)) {\n await executeStatement(\n target,\n sql`DROP TABLE IF EXISTS ${sql.identifier(table)}`,\n );\n }\n await executeDdl(target, ddl.recordedNodes.createTable);\n await executeDdl(target, ddl.recordedEdges.createTable);\n await executeDdl(target, ddl.recordedClock.createTable);\n await copyRecordedRelation(target, {\n columns: RECORDED_NODE_COLUMNS,\n legacyTable: tables.recordedNodes,\n mappingTable,\n temporaryTable: temporary.recordedNodes,\n });\n await copyRecordedRelation(target, {\n columns: RECORDED_EDGE_COLUMNS,\n legacyTable: tables.recordedEdges,\n mappingTable,\n temporaryTable: temporary.recordedEdges,\n });\n await copyRecordedClock(target, {\n legacyTable: tables.recordedClock,\n mappingTable,\n temporaryTable: temporary.recordedClock,\n });\n\n await executeStatement(\n target,\n sql`DROP TABLE ${sql.identifier(tables.recordedNodes)}`,\n );\n await executeStatement(\n target,\n sql`DROP TABLE ${sql.identifier(tables.recordedEdges)}`,\n );\n await executeStatement(\n target,\n sql`DROP TABLE ${sql.identifier(tables.recordedClock)}`,\n );\n await renameTable(target, temporary.recordedNodes, tables.recordedNodes);\n await renameTable(target, temporary.recordedEdges, tables.recordedEdges);\n await renameTable(target, temporary.recordedClock, tables.recordedClock);\n await renamePrimaryKeyConstraint(\n target,\n tables.recordedNodes,\n primaryKeyConstraintRenames.recordedNodes,\n );\n await renamePrimaryKeyConstraint(\n target,\n tables.recordedEdges,\n primaryKeyConstraintRenames.recordedEdges,\n );\n await renamePrimaryKeyConstraint(\n target,\n tables.recordedClock,\n primaryKeyConstraintRenames.recordedClock,\n );\n for (const statement of [\n ...ddl.recordedNodes.indexes,\n ...ddl.recordedEdges.indexes,\n ...ddl.recordedClock.indexes,\n ]) {\n await executeDdl(target, statement);\n }\n}\n\n/**\n * Renames the temporary table's PRIMARY KEY constraint to the final table's\n * name, once the swap has renamed the table itself. Both names come from the\n * authoring backend's `recordedTableDdl` (an ENGINE convention it alone\n * knows — engines that do not name PK constraints separately, e.g. SQLite,\n * return `undefined` for both, and this is a no-op). Identifier reduction on\n * an over-long target stays this migration's own decision — `shortenedIdentifier`\n * is applied to the target only, never the source (see {@link RecordedRelationDdl}).\n */\nasync function renamePrimaryKeyConstraint(\n target: TransactionBackend,\n finalTable: string,\n rename: PrimaryKeyConstraintRename,\n): Promise<void> {\n if (rename.status === \"none\") return;\n await executeStatement(\n target,\n sql`\n ALTER TABLE ${sql.identifier(finalTable)}\n RENAME CONSTRAINT ${sql.identifier(rename.from)}\n TO ${sql.identifier(shortenedIdentifier(rename.to))}\n `,\n );\n}\n\nasync function renameTable(\n target: TransactionBackend,\n from: string,\n to: string,\n): Promise<void> {\n try {\n await executeStatement(\n target,\n sql`ALTER TABLE ${sql.identifier(from)} RENAME TO ${sql.identifier(to)}`,\n );\n } catch (error) {\n throw new ConfigurationError(\n \"Could not rename a migrated recorded-time table.\",\n { from, to },\n { cause: error },\n );\n }\n}\n\n/**\n * Rewrites timestamp-only recorded relations to numeric revisions.\n *\n * Run offline before opening a Store with the new schema. The durable mapping\n * table is retained so external checkpoint stores can call\n * {@link migrateRecordedAnchor}; delete each graph's rows after its downstream\n * checkpoints have been rewritten.\n */\nexport async function migrateLegacyRecordedTime(\n options: MigrateLegacyRecordedTimeOptions,\n): Promise<MigrateLegacyRecordedTimeResult> {\n if (resolveRecordedTimeOwnership(options.backend) === \"engine-native\") {\n // The rewrite below targets TypeGraph's own recorded relations\n // (`recorded_from`/`recorded_to` columns on `typegraph_recorded_*`\n // tables); an engine-native backend keeps none of those, so there is\n // nothing here for this migration to rewrite.\n throw new ConfigurationError(\n \"migrateLegacyRecordedTime is not supported under engine-native recorded time.\",\n { code: \"ENGINE_NATIVE_MIGRATE_RECORDED_TIME_UNSUPPORTED\" },\n {\n suggestion:\n \"This migration rewrites TypeGraph's own recorded relations, which an engine-native backend does not have.\",\n },\n );\n }\n const tables = resolvedTableNames(options.backend, options.tableNames);\n const mapTable = mappingTableName(tables, options.mappingTableName);\n const recordedTableDdl = options.backend.recordedTableDdl;\n return options.backend.transaction(async (target) => {\n const clockColumns = await columnNames(target, tables.recordedClock);\n if (clockColumns.size === 0) {\n return {\n migrated: false,\n graphs: 0,\n anchors: 0,\n mappingTableName: mapTable,\n };\n }\n if (clockColumns.has(\"revision\")) {\n const mapColumns = await columnNames(target, mapTable);\n if (mapColumns.size === 0) {\n return {\n migrated: false,\n graphs: 0,\n anchors: 0,\n mappingTableName: mapTable,\n };\n }\n const rows = await target.execute<MappingCountRow>(\n asCompiledRowsSql(sql`\n SELECT COUNT(*) AS anchors, COUNT(DISTINCT graph_id) AS graphs\n FROM ${sql.identifier(mapTable)}\n `),\n );\n const anchors = Number(rows[0]?.anchors ?? 0);\n const graphs = Number(rows[0]?.graphs ?? 0);\n return {\n migrated: false,\n graphs: Number.isSafeInteger(graphs) ? graphs : 0,\n anchors: Number.isSafeInteger(anchors) ? anchors : 0,\n mappingTableName: mapTable,\n };\n }\n const nodeColumns = await columnNames(target, tables.recordedNodes);\n const edgeColumns = await columnNames(target, tables.recordedEdges);\n if (\n !nodeColumns.has(\"recorded_from\") ||\n !edgeColumns.has(\"recorded_from\")\n ) {\n throw new ConfigurationError(\n \"Legacy recorded-time schema is incomplete.\",\n { tables },\n );\n }\n\n if (recordedTableDdl === undefined) {\n throw new UnsupportedBackendCapabilityError(\n \"migrateLegacyRecordedTime\",\n \"recordedTableDdl\",\n { dialect: target.dialect, tables },\n \"Migrating the timestamp-only preview recorded schema needs the backend to author its own recorded-relation DDL. Only the bundled SQLite and PostgreSQL backends created that schema.\",\n );\n }\n\n await executeDdl(target, migrationMapDdl(target.dialect, mapTable));\n const mapping = await readLegacyInstants(target, tables);\n await writeMappingRows(target, mapTable, mapping);\n await replaceLegacyTables(target, tables, mapTable, recordedTableDdl);\n return {\n migrated: true,\n graphs: new Set(mapping.map((row) => row.graphId)).size,\n anchors: mapping.length,\n mappingTableName: mapTable,\n };\n });\n}\n\n/** Remaps one timestamp-only checkpoint after {@link migrateLegacyRecordedTime}. */\nexport async function migrateRecordedAnchor(\n options: MigrateRecordedAnchorOptions,\n): Promise<RecordedInstant> {\n try {\n return asRecordedInstant(options.anchor);\n } catch (error) {\n if (!(error instanceof ValidationError)) throw error;\n }\n const legacyRecordedAt = canonicalLegacyInstant(options.anchor);\n const tables = resolvedTableNames(options.backend, options.tableNames);\n const mapTable = mappingTableName(tables, options.mappingTableName);\n const rows = await options.backend.execute<RemapRow>(\n asCompiledRowsSql(sql`\n SELECT revision, recorded_at\n FROM ${sql.identifier(mapTable)}\n WHERE graph_id = ${options.graphId}\n AND legacy_recorded_at = ${legacyRecordedAt}\n `),\n );\n const row = rows[0];\n if (row === undefined) {\n throw new ConfigurationError(\n \"No migrated recorded anchor matches this graph and legacy timestamp.\",\n { anchor: options.anchor, graphId: options.graphId },\n {\n suggestion:\n \"Run migrateLegacyRecordedTime() before deleting its mapping rows, and pass the graph that produced the checkpoint.\",\n },\n );\n }\n return createRecordedInstant(\n safeRevision(row.revision),\n canonicalLegacyInstant(row.recorded_at),\n );\n}\n\n/**\n * Deletes one graph's legacy remap rows after downstream checkpoints migrate.\n * Set `dropWhenEmpty` to remove the migration table after the final graph.\n */\nexport async function deleteLegacyRecordedAnchorMap(\n options: DeleteLegacyRecordedAnchorMapOptions,\n): Promise<void> {\n requireStatements(options.backend);\n const tables = resolvedTableNames(options.backend, options.tableNames);\n const mapTable = mappingTableName(tables, options.mappingTableName);\n await options.backend.transaction(async (target) => {\n await executeStatement(\n target,\n sql`\n DELETE FROM ${sql.identifier(mapTable)}\n WHERE graph_id = ${options.graphId}\n `,\n );\n if (options.dropWhenEmpty !== true) return;\n const rows = await target.execute<MappingCountRow>(\n asCompiledRowsSql(sql`\n SELECT COUNT(*) AS anchors, COUNT(DISTINCT graph_id) AS graphs\n FROM ${sql.identifier(mapTable)}\n `),\n );\n const remaining = missingMappingCount(rows[0]?.anchors, mapTable);\n if (remaining === 0) {\n await executeStatement(\n target,\n sql`DROP TABLE ${sql.identifier(mapTable)}`,\n );\n }\n });\n}\n","/**\n * Offline repair for validity windows that older library versions stored\n * inverted (`valid_from > valid_to`).\n *\n * Such a row is readable at no coordinate at all: `asOf(t)` needs\n * `valid_from <= t < valid_to`, and no `t` satisfies both when the bounds are\n * backwards. The library no longer mints them — a write that stamps a lower\n * bound the caller did not state stores no bound rather than an inverting one —\n * but deploying that fix rewrites nothing, so rows written by an older version\n * (or by direct SQL) stay invisible until an operator repairs them.\n *\n * The repair normalizes those rows to \"ended at T, start unknown\"\n * (`valid_from = NULL`), which is the shape the current write paths store. It\n * deliberately does **not** bump `version`, touch `updated_at`, or mint a\n * recorded revision: it normalizes a storage convention for rows that were\n * never observable at any coordinate, so it is not a logical write — and\n * minting a revision would make the pre-repair recorded state re-materialize\n * the inverted shape at `asOfRecorded` coordinates.\n *\n * Operator consequences, all of them stated in the docs as well:\n *\n * 1. **Run `\"apply\"` with writers stopped.** A concurrent window-bearing update\n * may fence its write on the validity lower bound it read, so a repair that\n * lands in between can make the peer's first `UPDATE` match no row. Store\n * node/edge updates re-read and re-judge against the repaired bound; an\n * interchange update records a per-row target-changed error instead of\n * claiming the row was written. `\"report\"` needs no quiescing — it scans in\n * a read-only transaction, so it cannot write.\n * 2. **Repaired rows become visible** at `asOf` coordinates before their end.\n * That is the point, and it is a read-visibility change to historical\n * queries.\n * 3. **Outstanding `base@V` merge tokens are invalidated** for repaired rows —\n * `valid_from` is part of the base content fingerprint. Quiesce merges,\n * repair, then re-baseline branches.\n * 4. **Prefer `relations: \"live-and-recorded\"`.** Repairing only the live axis\n * leaves the recorded twin carrying the inverted window, which\n * re-materializes the invisible row at any `asOfRecorded` coordinate.\n */\nimport { ConfigurationError } from \"../errors\";\nimport type {\n ResolvedSqlTableNames,\n SqlTableNames,\n} from \"../query/compiler/schema\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql, asCompiledStatementSql } from \"../query/sql-intent\";\nimport { statementExecutionMembers } from \"./capabilities/bind\";\nimport type { STATEMENT_EXECUTION } from \"./capabilities/bundle-registry\";\nimport {\n type BundleVerdictOf,\n statementExecutionVerdict,\n} from \"./capabilities/resolve\";\nimport { resolvedTableNames } from \"./table-names\";\nimport {\n type GraphBackend,\n runOptionallyInTransaction,\n type RunOptionallyInTransactionOptions,\n type TransactionBackend,\n} from \"./types\";\n\n/** A relation whose rows carry a validity window this repair can normalize. */\nexport type RepairRelation =\n \"nodes\" | \"edges\" | \"recordedNodes\" | \"recordedEdges\";\n\n/**\n * Which relations one call scans.\n *\n * `\"live-and-recorded\"` is the recommended scope. `\"live\"` is correct in\n * exactly two cases: the store captures no history and the `recorded_*` tables\n * do not exist, or the operator is deliberately preserving the recorded axis as\n * an audit record of what was stored before the repair — and accepts that\n * historical `asOfRecorded` reads keep returning the invisible shape.\n */\nexport type RepairRelationScope = \"live\" | \"live-and-recorded\";\n\n/** Inputs for detecting or repairing legacy inverted validity windows. */\nexport type RepairInvertedWindowsOptions = Readonly<{\n backend: GraphBackend;\n /** Omit to sweep every graph in the database. */\n graphId?: string | undefined;\n /** Required: the scope is a decision, not a default. */\n relations: RepairRelationScope;\n /**\n * `\"report\"` counts and writes nothing; `\"apply\"` counts and then normalizes\n * the rows it counted.\n */\n mode: \"report\" | \"apply\";\n /**\n * Patch selected backend table names, exactly as migrate-recorded-time does.\n * Unstated names continue to come from `backend.tableNames`; see\n * {@link resolvedTableNames}.\n */\n tableNames?: Partial<SqlTableNames> | undefined;\n}>;\n\n/** Counts and execution guarantees observed by one repair/report call. */\nexport type RepairInvertedWindowsReport = Readonly<{\n /** Echoes the scope actually scanned — a count of 0 and \"not scanned\" are different facts. */\n relations: RepairRelationScope;\n /**\n * Rows whose stored window is inverted: found in `\"report\"` mode, repaired in\n * `\"apply\"` mode. `undefined` means NOT SCANNED, never \"clean\".\n */\n counts: Readonly<Record<RepairRelation, number | undefined>>;\n /**\n * Rows whose stored bounds are not canonical ISO and were therefore not\n * classified. SQLite only in substance: on PostgreSQL the columns are\n * `timestamptz`, so a scanned relation always reports `0` (never `undefined`\n * — that value is reserved for \"not scanned\", on both dialects).\n *\n * `\"apply\"` refuses while any scanned relation reports a non-zero count:\n * classifying those rows needs a timestamp semantics this repair does not\n * own, and skipping them silently would be an accepted option ignored.\n */\n nonCanonical: Readonly<Record<RepairRelation, number | undefined>>;\n /**\n * Whether every statement of this call ran in ONE transaction. `false` on a\n * backend that reports `capabilities.execution.interactiveTransactions === false`, where the call\n * degrades to per-relation statements.\n *\n * Reported by the seam, not inferred from backend object identity:\n * {@link runOptionallyInTransaction} explicitly tells its callback whether it\n * opened a transaction. \"One snapshot\" and \"four snapshots\" are different\n * facts about a report, and the report must state which occurred even when a\n * custom backend passes the same object into its transaction callback.\n *\n * When `false`, a `\"report\"`'s counts may come from different snapshots and a\n * crash mid-`\"apply\"` can leave the live axis repaired and the recorded axis\n * not. Both are survivable the same way: each relation's statement is\n * idempotent and convergent, so a re-run finishes the job and a later\n * `\"report\"` proves it.\n */\n atomic: boolean;\n}>;\n\nconst LIVE_RELATIONS = [\n \"nodes\",\n \"edges\",\n] as const satisfies readonly RepairRelation[];\n\nconst RECORDED_RELATIONS = [\n \"recordedNodes\",\n \"recordedEdges\",\n] as const satisfies readonly RepairRelation[];\n\n/**\n * Canonical fixed-width UTC ISO 8601, as a SQLite `GLOB` pattern.\n *\n * SQLite stores the bounds as `TEXT` and compares them lexicographically, which\n * equals chronological order only for canonical values. This repair exists to\n * clean up rows written by older paths and by direct SQL, so it cannot assume\n * canonicality — it establishes it per row instead.\n */\nconst CANONICAL_INSTANT_GLOB =\n \"[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z\";\n\ntype RepairTarget = GraphBackend | TransactionBackend;\n\ntype CountRow = Readonly<{ matches: unknown }>;\n\nfunction scopedRelations(\n scope: RepairRelationScope,\n): readonly RepairRelation[] {\n return scope === \"live\" ? LIVE_RELATIONS : (\n [...LIVE_RELATIONS, ...RECORDED_RELATIONS]\n );\n}\n\nfunction relationTable(\n tables: ResolvedSqlTableNames,\n relation: RepairRelation,\n): string {\n switch (relation) {\n case \"nodes\": {\n return tables.nodes;\n }\n case \"edges\": {\n return tables.edges;\n }\n case \"recordedNodes\": {\n return tables.recordedNodes;\n }\n case \"recordedEdges\": {\n return tables.recordedEdges;\n }\n }\n}\n\nfunction graphScopeClauses(\n graphId: string | undefined,\n): readonly SqlFragment[] {\n return graphId === undefined ? [] : [sql`graph_id = ${graphId}`];\n}\n\nfunction canonicalBoundsClauses(\n dialect: GraphBackend[\"dialect\"],\n): readonly SqlFragment[] {\n if (dialect !== \"sqlite\") return [];\n return [\n sql`valid_from GLOB ${CANONICAL_INSTANT_GLOB}`,\n sql`valid_to GLOB ${CANONICAL_INSTANT_GLOB}`,\n ];\n}\n\n/**\n * The one spelling of \"this stored window is inverted\".\n *\n * Both modes compile it: `\"report\"` into `SELECT COUNT(*) … WHERE <this>` and\n * `\"apply\"` into `UPDATE … SET valid_from = NULL WHERE <this>`, so the count\n * and the repair cannot disagree about which rows are in scope.\n *\n * The comparison is strict (`>`). A stored zero-width window is a legal shape a\n * caller may have stated in full, and this repair does not second-guess it.\n */\nexport function invertedValidityWindowPredicate(\n options: Readonly<{\n dialect: GraphBackend[\"dialect\"];\n graphId?: string | undefined;\n }>,\n): SqlFragment {\n return sql.join(\n [\n sql`valid_from IS NOT NULL`,\n sql`valid_to IS NOT NULL`,\n ...canonicalBoundsClauses(options.dialect),\n sql`valid_from > valid_to`,\n ...graphScopeClauses(options.graphId),\n ],\n sql` AND `,\n );\n}\n\n/**\n * Rows carrying both bounds where either one is not canonical, and which the\n * inverted predicate therefore refuses to classify. SQLite only: PostgreSQL\n * stores `timestamptz`, where every stored value compares chronologically.\n */\nfunction nonCanonicalWindowPredicate(graphId: string | undefined): SqlFragment {\n return sql.join(\n [\n sql`valid_from IS NOT NULL`,\n sql`valid_to IS NOT NULL`,\n sql`(valid_from NOT GLOB ${CANONICAL_INSTANT_GLOB} OR valid_to NOT GLOB ${CANONICAL_INSTANT_GLOB})`,\n ...graphScopeClauses(graphId),\n ],\n sql` AND `,\n );\n}\n\nfunction safeCount(value: unknown, table: string): number {\n const count = Number(value);\n if (!Number.isSafeInteger(count) || count < 0) {\n throw new ConfigurationError(\n \"Validity-window repair returned an invalid row count.\",\n { table, value },\n );\n }\n return count;\n}\n\nasync function countMatching(\n target: RepairTarget,\n table: string,\n predicate: SqlFragment,\n): Promise<number> {\n const rows = await target.execute<CountRow>(\n asCompiledRowsSql(sql`\n SELECT COUNT(*) AS matches\n FROM ${sql.identifier(table)}\n WHERE ${predicate}\n `),\n );\n return safeCount(rows[0]?.matches, table);\n}\n\n/**\n * `\"apply\"` writes, so it needs the optional non-row-returning statement path.\n * `\"report\"` deliberately does not: `execute` is a required member, so\n * detection stays available on every backend even where repair is not.\n *\n * Shared by both throw sites below: the public entry refuses BEFORE opening a\n * transaction (so an unsupported backend never pays for one), and\n * {@link repairRelation}'s own guard exists ONLY because a nested closure\n * cannot inherit the entry's narrowing of `verdict` to `{ supported: true }` —\n * it can never fire at runtime, since the entry already refused. One message,\n * two structurally-required call sites.\n */\nfunction statementExecutionRequiredError(\n dialect: GraphBackend[\"dialect\"],\n): ConfigurationError {\n return new ConfigurationError(\n \"Repairing inverted validity windows requires executeStatement support.\",\n { dialect, mode: \"apply\" },\n {\n suggestion:\n 'Use a built-in SQLite or PostgreSQL backend to apply the repair. Detection needs no such support: call this with mode: \"report\" to count the affected rows on any backend.',\n },\n );\n}\n\n/**\n * Translates the recorded-capture wrapper's refusal instead of swallowing it.\n *\n * A history-enabled store replaces `executeStatement` with a rejecting stub, so\n * `\"apply\"` against that backend fails with a message about raw SQL rather than\n * about this repair. The remedy is specific enough to be worth naming: hand the\n * repair the raw backend the history store was constructed from. Bypassing\n * capture is the intended behavior here, not a workaround — the repair mints no\n * revision by design.\n */\nfunction translatedCaptureRefusal(error: unknown): unknown {\n if (\n !(error instanceof ConfigurationError) ||\n error.details[\"code\"] !== \"RECORDED_CAPTURE_RAW_SQL_DISABLED\"\n ) {\n return error;\n }\n return new ConfigurationError(\n \"Repairing inverted validity windows cannot run against a history-capturing backend.\",\n { code: \"RECORDED_CAPTURE_RAW_SQL_DISABLED\", mode: \"apply\" },\n {\n cause: error,\n suggestion:\n 'Pass the raw backend you constructed the history store from. The repair deliberately mints no revision — it normalizes storage for rows that were never visible at any coordinate — so bypassing recorded-time capture is the intended behavior, not a workaround. mode: \"report\" needs no such care: it runs against the capture-wrapped backend.',\n },\n );\n}\n\nasync function repairRelation(\n target: RepairTarget,\n verdict: BundleVerdictOf<typeof STATEMENT_EXECUTION>,\n table: string,\n predicate: SqlFragment,\n): Promise<void> {\n // Unreachable at runtime: `repairInvertedValidityWindows` already refused an\n // unsupported backend before opening the transaction this runs inside. The\n // check exists only so `verdict` narrows for `statementExecutionMembers` —\n // TypeScript does not carry the entry's narrowing into this closure.\n if (!verdict.supported) {\n throw statementExecutionRequiredError(target.dialect);\n }\n try {\n await statementExecutionMembers(target, verdict).executeStatement(\n asCompiledStatementSql(sql`\n UPDATE ${sql.identifier(table)}\n SET valid_from = NULL\n WHERE ${predicate}\n `),\n );\n } catch (error) {\n throw translatedCaptureRefusal(error);\n }\n}\n\nfunction assertClassifiableBounds(\n nonCanonical: ReadonlyMap<RepairRelation, number>,\n): void {\n const unclassified = [...nonCanonical].filter(([, count]) => count > 0);\n if (unclassified.length === 0) return;\n throw new ConfigurationError(\n \"Refusing to repair validity windows: some scanned rows store non-canonical bounds.\",\n { nonCanonical: Object.fromEntries(unclassified) },\n {\n suggestion:\n 'Normalize those bounds to canonical UTC ISO 8601 (YYYY-MM-DDTHH:MM:SS.mmmZ) and re-run, or narrow the call with graphId. Classifying them here would need a timestamp semantics this repair does not own, and skipping them silently would report a repair it did not make. mode: \"report\" still counts them.',\n },\n );\n}\n\n/**\n * Declares `\"report\"`'s read-only-ness to the ENGINE rather than only to the\n * reader of this file.\n *\n * The docs send an operator to diagnose against the live store's backend and\n * require quiescing only for `\"apply\"`, so the scan must not behave like a\n * writer: on SQLite a default transaction is `BEGIN IMMEDIATE`, which reserves\n * the single writer slot for the duration of up to four full-table `COUNT(*)`\n * scans and can fail `SQLITE_BUSY` against an active writer; `read_only` issues\n * a plain `BEGIN` instead. On PostgreSQL it issues `BEGIN … READ ONLY`, which\n * makes \"report writes nothing\" enforced by the engine and not merely asserted\n * by a test.\n *\n * `\"apply\"` writes, so it takes the default read-write transaction.\n */\nfunction transactionOptionsFor(\n mode: RepairInvertedWindowsOptions[\"mode\"],\n): RunOptionallyInTransactionOptions | undefined {\n return mode === \"report\" ?\n { transaction: { accessMode: \"read_only\" } }\n : undefined;\n}\n\nfunction relationRecord(\n counts: ReadonlyMap<RepairRelation, number>,\n): Readonly<Record<RepairRelation, number | undefined>> {\n return {\n nodes: counts.get(\"nodes\"),\n edges: counts.get(\"edges\"),\n recordedNodes: counts.get(\"recordedNodes\"),\n recordedEdges: counts.get(\"recordedEdges\"),\n };\n}\n\n/**\n * Counts — and, in `\"apply\"` mode, normalizes — rows whose stored validity\n * window is inverted.\n *\n * ```typescript\n * // Diagnose with the store's backend: `report` reads only, so it runs\n * // anywhere, including a capture-wrapped or statement-less backend.\n * const report = await repairInvertedValidityWindows({\n * backend: anyBackend,\n * relations: \"live-and-recorded\",\n * mode: \"report\",\n * });\n *\n * // Repair with the raw one, while writers are stopped.\n * await repairInvertedValidityWindows({\n * backend: rawBackend,\n * relations: \"live-and-recorded\",\n * mode: \"apply\",\n * });\n * ```\n *\n * Idempotent and convergent: a second `\"apply\"` reports zero, because the rows\n * the first one repaired no longer match the predicate.\n *\n * No batching, deliberately. Unlike the recorded-time migration, which rewrites\n * every row, this statement touches only rows the library mis-stored — an empty\n * set on a healthy graph. A deployment that reports a count large enough to\n * worry about should run it per `graphId`.\n *\n * @throws ConfigurationError in `\"apply\"` mode when the backend cannot execute\n * statements, when the backend is a recorded-capture wrapper, or when any\n * scanned relation stores non-canonical bounds. A transaction TARGET that\n * disagrees with the top-level verdict (missing `executeStatement` the\n * top-level backend has) refuses separately, with I20's\n * `BUNDLE_PORT_SURFACE_MISMATCH` — the per-bundle port check\n * `statementExecutionMembers` performs, not a second spelling of this one.\n */\nexport async function repairInvertedValidityWindows(\n options: RepairInvertedWindowsOptions,\n): Promise<RepairInvertedWindowsReport> {\n const tables = resolvedTableNames(options.backend, options.tableNames);\n const relations = scopedRelations(options.relations);\n const verdict = statementExecutionVerdict(options.backend);\n // Refuse before opening a transaction: a backend with no statement path can\n // never apply, whatever the scan finds.\n if (options.mode === \"apply\" && !verdict.supported) {\n throw statementExecutionRequiredError(options.backend.dialect);\n }\n\n return runOptionallyInTransaction(\n options.backend,\n async (target, execution) => {\n const predicate = invertedValidityWindowPredicate({\n dialect: target.dialect,\n graphId: options.graphId,\n });\n const inverted = new Map<RepairRelation, number>();\n const nonCanonical = new Map<RepairRelation, number>();\n for (const relation of relations) {\n const table = relationTable(tables, relation);\n nonCanonical.set(\n relation,\n target.dialect === \"sqlite\" ?\n await countMatching(\n target,\n table,\n nonCanonicalWindowPredicate(options.graphId),\n )\n : 0,\n );\n inverted.set(relation, await countMatching(target, table, predicate));\n }\n\n if (options.mode === \"apply\") {\n assertClassifiableBounds(nonCanonical);\n for (const relation of relations) {\n await repairRelation(\n target,\n verdict,\n relationTable(tables, relation),\n predicate,\n );\n }\n }\n\n return {\n relations: options.relations,\n counts: relationRecord(inverted),\n nonCanonical: relationRecord(nonCanonical),\n // Keep the report's long-standing `atomic` compatibility field while\n // consuming the richer execution-mode decision from the transaction\n // seam. A sequential callback is not an interactive transaction even\n // when an adapter happens to execute one statement atomically.\n atomic: execution.mode === \"interactive-transaction\",\n };\n },\n transactionOptionsFor(options.mode),\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/backend/migrate-recorded-time.ts","../src/backend/repair-validity-windows.ts"],"names":["shortHash","createSqlSchema","ConfigurationError","asCompiledStatementSql","sql","canonicalizeDatabaseTimestamp","RECORDED_MAX_REVISION","requireCatalog","asCompiledRowsSql","resolveRecordedTimeOwnership","resolvedTableNames","UnsupportedBackendCapabilityError","asRecordedInstant","ValidationError","createRecordedInstant","statementExecutionMembers","statementExecutionVerdict","runOptionallyInTransaction"],"mappings":";;;;;;;;;;;;AAmCA,IAAM,mBAAA,GAAsB,0BAAA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7B;AAAA,IACF,CAAA;AAAA,IACA,qBAAA,CAAsB,QAAQ,IAAI;AAAA,GACpC;AACF","file":"chunk-QR7W37HG.cjs","sourcesContent":["/**\n * One-time offline migration from timestamp-only recorded relations to numeric\n * revisions. The durable remap table lets applications translate checkpoints\n * stored outside TypeGraph before deleting the migration metadata.\n */\nimport {\n asRecordedInstant,\n createRecordedInstant,\n RECORDED_MAX_REVISION,\n type RecordedInstant,\n} from \"../core/temporal\";\nimport {\n ConfigurationError,\n UnsupportedBackendCapabilityError,\n ValidationError,\n} from \"../errors\";\nimport {\n createSqlSchema,\n type ResolvedSqlTableNames,\n type SqlTableNames,\n} from \"../query/compiler/schema\";\nimport { shortHash } from \"../query/dialect/vector-strategy\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql, asCompiledStatementSql } from \"../query/sql-intent\";\nimport { canonicalizeDatabaseTimestamp } from \"../utils/date\";\nimport { requireCatalog } from \"./capabilities/catalog\";\nimport { resolveRecordedTimeOwnership } from \"./capabilities/recorded-time-ownership\";\nimport { resolvedTableNames } from \"./table-names\";\nimport {\n type GraphBackend,\n type RecordedRelationDdl,\n type RecordedTableNames,\n type TransactionBackend,\n} from \"./types\";\n\nconst LEGACY_RECORDED_MAX = \"9999-12-31T23:59:59.999Z\";\nconst MIGRATION_SUFFIX = \"legacy_recorded_anchors\";\n\nconst RECORDED_NODE_COLUMNS = [\n \"history_id\",\n \"graph_id\",\n \"kind\",\n \"id\",\n \"props\",\n \"version\",\n \"valid_from\",\n \"valid_to\",\n \"created_at\",\n \"updated_at\",\n \"deleted_at\",\n \"recorded_from\",\n \"recorded_to\",\n \"op\",\n \"schema_version\",\n \"tx_id\",\n \"meta\",\n] as const;\n\nconst RECORDED_EDGE_COLUMNS = [\n \"history_id\",\n \"graph_id\",\n \"id\",\n \"kind\",\n \"from_kind\",\n \"from_id\",\n \"to_kind\",\n \"to_id\",\n \"props\",\n \"valid_from\",\n \"valid_to\",\n \"created_at\",\n \"updated_at\",\n \"deleted_at\",\n \"recorded_from\",\n \"recorded_to\",\n \"op\",\n \"schema_version\",\n \"tx_id\",\n \"meta\",\n] as const;\n\ntype LegacyInstantRow = Readonly<{\n graph_id: unknown;\n recorded_at: unknown;\n}>;\n\ntype MappingRow = Readonly<{\n graphId: string;\n legacyRecordedAt: string;\n recordedAt: string;\n revision: number;\n}>;\n\ntype RemapRow = Readonly<{ recorded_at: unknown; revision: unknown }>;\ntype MappingCountRow = Readonly<{ anchors: unknown; graphs: unknown }>;\ntype MissingMappingRow = Readonly<{ missing: unknown }>;\n\nexport type MigrateLegacyRecordedTimeOptions = Readonly<{\n backend: GraphBackend;\n /** Patch selected backend table names; unstated names remain configured. */\n tableNames?: Partial<SqlTableNames> | undefined;\n /** Override the durable legacy-anchor mapping table name. */\n mappingTableName?: string | undefined;\n}>;\n\nexport type MigrateLegacyRecordedTimeResult = Readonly<{\n /** `true` when timestamp columns were rewritten during this call. */\n migrated: boolean;\n /** Number of graphs represented in the legacy commit order. */\n graphs: number;\n /** Number of distinct legacy anchors available for remapping. */\n anchors: number;\n /** Physical table retaining the old-anchor → revision mapping. */\n mappingTableName: string;\n}>;\n\nexport type MigrateRecordedAnchorOptions = Readonly<{\n backend: Pick<GraphBackend, \"dialect\" | \"execute\" | \"tableNames\">;\n graphId: string;\n anchor: string;\n /** Patch selected backend table names; unstated names remain configured. */\n tableNames?: Partial<SqlTableNames> | undefined;\n mappingTableName?: string | undefined;\n}>;\n\nexport type DeleteLegacyRecordedAnchorMapOptions = Readonly<{\n backend: Pick<\n GraphBackend,\n \"dialect\" | \"execute\" | \"executeStatement\" | \"tableNames\" | \"transaction\"\n >;\n graphId: string;\n /** Patch selected backend table names; unstated names remain configured. */\n tableNames?: Partial<SqlTableNames> | undefined;\n mappingTableName?: string | undefined;\n /** Drop the mapping table when this deletion leaves it empty. */\n dropWhenEmpty?: boolean | undefined;\n}>;\n\nfunction shortenedIdentifier(value: string): string {\n if (value.length <= 63) return value;\n return `${value.slice(0, 50)}_${shortHash(value)}`;\n}\n\nfunction mappingTableName(\n tables: ResolvedSqlTableNames,\n override: string | undefined,\n): string {\n const candidate = override ?? `${tables.recordedClock}_${MIGRATION_SUFFIX}`;\n return createSqlSchema({\n recordedClock: shortenedIdentifier(candidate),\n }).tables.recordedClock;\n}\n\nfunction temporaryTableName(tableName: string, role: string): string {\n return shortenedIdentifier(`__tg_${role}_${shortHash(tableName)}`);\n}\n\nfunction requireStatements(\n target: Pick<TransactionBackend, \"dialect\" | \"executeStatement\">,\n): NonNullable<TransactionBackend[\"executeStatement\"]> {\n if (target.executeStatement === undefined) {\n throw new ConfigurationError(\n \"Recorded-time migration requires executeStatement support.\",\n { dialect: target.dialect },\n { suggestion: \"Use a built-in SQLite or PostgreSQL backend.\" },\n );\n }\n return target.executeStatement;\n}\n\nasync function executeStatement(\n target: Pick<TransactionBackend, \"dialect\" | \"executeStatement\">,\n statement: SqlFragment,\n): Promise<void> {\n await requireStatements(target)(asCompiledStatementSql(statement));\n}\n\nasync function executeDdl(\n target: Pick<TransactionBackend, \"dialect\" | \"executeStatement\">,\n ddl: string,\n): Promise<void> {\n await executeStatement(target, sql.raw(ddl));\n}\n\nfunction canonicalLegacyInstant(value: unknown): string {\n const canonical = canonicalizeDatabaseTimestamp(value);\n if (canonical === undefined) {\n throw new ConfigurationError(\n \"Legacy recorded-time relation contained an invalid timestamp.\",\n { value },\n );\n }\n return canonical;\n}\n\nfunction safeRevision(value: unknown): number {\n const revision =\n typeof value === \"bigint\" ? Number(value)\n : typeof value === \"string\" && /^\\d+$/.test(value) ? Number(value)\n : value;\n if (\n typeof revision !== \"number\" ||\n !Number.isSafeInteger(revision) ||\n revision < 1 ||\n revision >= RECORDED_MAX_REVISION\n ) {\n throw new ConfigurationError(\n \"Recorded anchor mapping contained an invalid revision.\",\n { value },\n );\n }\n return revision;\n}\n\nasync function columnNames(\n target: Pick<TransactionBackend, \"catalog\">,\n tableName: string,\n): Promise<ReadonlySet<string>> {\n const catalog = requireCatalog(target, \"migrateLegacyRecordedTime\");\n const columns = await catalog.columnTypes(tableName);\n return new Set(columns.map((column) => column.name));\n}\n\nasync function readLegacyInstants(\n target: TransactionBackend,\n tables: ResolvedSqlTableNames,\n): Promise<readonly MappingRow[]> {\n const rows = await target.execute<LegacyInstantRow>(\n asCompiledRowsSql(sql`\n SELECT graph_id, recorded_from AS recorded_at\n FROM ${sql.identifier(tables.recordedNodes)}\n UNION\n SELECT graph_id, recorded_to AS recorded_at\n FROM ${sql.identifier(tables.recordedNodes)}\n WHERE recorded_to <> ${LEGACY_RECORDED_MAX}\n UNION\n SELECT graph_id, recorded_from AS recorded_at\n FROM ${sql.identifier(tables.recordedEdges)}\n UNION\n SELECT graph_id, recorded_to AS recorded_at\n FROM ${sql.identifier(tables.recordedEdges)}\n WHERE recorded_to <> ${LEGACY_RECORDED_MAX}\n UNION\n SELECT graph_id, recorded_at\n FROM ${sql.identifier(tables.recordedClock)}\n `),\n );\n const instants = rows.map((row) => {\n if (typeof row.graph_id !== \"string\") {\n throw new ConfigurationError(\n \"Legacy recorded-time relation contained an invalid graph id.\",\n { graphId: row.graph_id },\n );\n }\n return {\n graphId: row.graph_id,\n recordedAt: canonicalLegacyInstant(row.recorded_at),\n };\n });\n instants.sort((left, right) => {\n if (left.graphId < right.graphId) return -1;\n if (left.graphId > right.graphId) return 1;\n if (left.recordedAt < right.recordedAt) return -1;\n if (left.recordedAt > right.recordedAt) return 1;\n return 0;\n });\n\n const mapping: MappingRow[] = [];\n let graphId: string | undefined;\n let revision = 0;\n let previousInstant: string | undefined;\n for (const instant of instants) {\n if (instant.graphId !== graphId) {\n graphId = instant.graphId;\n revision = 0;\n previousInstant = undefined;\n }\n if (instant.recordedAt === previousInstant) continue;\n revision += 1;\n mapping.push({\n graphId: instant.graphId,\n legacyRecordedAt: instant.recordedAt,\n recordedAt: instant.recordedAt,\n revision,\n });\n previousInstant = instant.recordedAt;\n }\n return mapping;\n}\n\nfunction migrationMapDdl(\n dialect: GraphBackend[\"dialect\"],\n table: string,\n): string {\n const revisionType = dialect === \"postgres\" ? \"BIGINT\" : \"INTEGER\";\n const recordedAtType = dialect === \"postgres\" ? \"TIMESTAMPTZ\" : \"TEXT\";\n return `CREATE TABLE IF NOT EXISTS \"${table}\" (\n graph_id TEXT NOT NULL,\n legacy_recorded_at TEXT NOT NULL,\n revision ${revisionType} NOT NULL,\n recorded_at ${recordedAtType} NOT NULL,\n PRIMARY KEY (graph_id, legacy_recorded_at)\n);`;\n}\n\nasync function writeMappingRows(\n target: TransactionBackend,\n tableName: string,\n rows: readonly MappingRow[],\n): Promise<void> {\n await executeStatement(target, sql`DELETE FROM ${sql.identifier(tableName)}`);\n const rowsPerStatement = Math.max(\n 1,\n Math.floor((target.capabilities.maxBindParameters ?? 900) / 4),\n );\n for (let start = 0; start < rows.length; start += rowsPerStatement) {\n const values = rows\n .slice(start, start + rowsPerStatement)\n .map(\n (row) =>\n sql`(${row.graphId}, ${row.legacyRecordedAt}, ${row.revision}, ${row.recordedAt})`,\n );\n await executeStatement(\n target,\n sql`\n INSERT INTO ${sql.identifier(tableName)}\n (graph_id, legacy_recorded_at, revision, recorded_at)\n VALUES ${sql.join(values, sql`, `)}\n `,\n );\n }\n}\n\ntype RecordedDdlSet = Readonly<\n Record<keyof RecordedTableNames, RecordedRelationDdl>\n>;\n\ntype PrimaryKeyConstraintRename =\n | Readonly<{ status: \"none\" }>\n | Readonly<{ status: \"rename\"; from: string; to: string }>;\n\n/**\n * The two calls the offline migration makes to the port, plus their\n * composition. `primaryKeyConstraintRenames` carries the backend-authored\n * decision itself, so the swap cannot re-derive it or silently ignore one\n * supplied name.\n */\ntype RecordedMigrationDdl = Readonly<{\n /**\n * The temp-named `CREATE TABLE` (so the swap-in relation is empty and safe\n * to populate) paired with the final-named `indexes` (so the swapped-in\n * relation ends up carrying the SAME index/constraint statements the final\n * table would get if provisioned fresh).\n */\n ddl: RecordedDdlSet;\n primaryKeyConstraintRenames: Readonly<\n Record<keyof RecordedTableNames, PrimaryKeyConstraintRename>\n >;\n}>;\n\n/**\n * The offline migration's own composition of the port's per-name-set DDL.\n * `recordedTableDdl` is called exactly once per name set — mirroring the\n * two-Drizzle-table-build shape this replaces — and the backend-authored\n * constraint-name pair is resolved here before any migration SQL executes.\n */\nfunction recordedMigrationDdl(\n recordedTableDdl: NonNullable<GraphBackend[\"recordedTableDdl\"]>,\n finalNames: RecordedTableNames,\n temporaryNames: RecordedTableNames,\n): RecordedMigrationDdl {\n const temporaryDdl = recordedTableDdl(temporaryNames);\n const finalDdl = recordedTableDdl(finalNames);\n function composed(key: keyof RecordedTableNames): RecordedRelationDdl {\n return {\n createTable: temporaryDdl[key].createTable,\n indexes: finalDdl[key].indexes,\n };\n }\n function primaryKeyConstraintRename(\n key: keyof RecordedTableNames,\n ): PrimaryKeyConstraintRename {\n const temporaryConstraintName = temporaryDdl[key].primaryKeyConstraintName;\n const finalConstraintName = finalDdl[key].primaryKeyConstraintName;\n if (\n temporaryConstraintName === undefined &&\n finalConstraintName === undefined\n )\n return { status: \"none\" };\n if (\n temporaryConstraintName === undefined ||\n finalConstraintName === undefined\n )\n throw new ConfigurationError(\n \"Recorded relation DDL must name both primary-key constraints or neither.\",\n {\n code: \"RECORDED_DDL_CONSTRAINT_NAME_MISMATCH\",\n relation: key,\n finalTable: finalNames[key],\n temporaryConstraintName,\n finalConstraintName,\n },\n );\n return {\n status: \"rename\",\n from: temporaryConstraintName,\n to: finalConstraintName,\n };\n }\n return {\n ddl: {\n recordedClock: composed(\"recordedClock\"),\n recordedEdges: composed(\"recordedEdges\"),\n recordedNodes: composed(\"recordedNodes\"),\n },\n primaryKeyConstraintRenames: {\n recordedClock: primaryKeyConstraintRename(\"recordedClock\"),\n recordedEdges: primaryKeyConstraintRename(\"recordedEdges\"),\n recordedNodes: primaryKeyConstraintRename(\"recordedNodes\"),\n },\n };\n}\n\nfunction migratedColumn(column: string, legacyAlias: string): SqlFragment {\n if (column === \"recorded_from\") return sql`from_map.revision`;\n if (column === \"recorded_to\") {\n return sql`\n CASE\n WHEN ${sql.raw(legacyAlias)}.recorded_to = ${LEGACY_RECORDED_MAX}\n THEN ${RECORDED_MAX_REVISION}\n ELSE to_map.revision\n END\n `;\n }\n return sql`${sql.raw(legacyAlias)}.${sql.identifier(column)}`;\n}\n\nfunction mappingMatch(\n dialect: GraphBackend[\"dialect\"],\n mappingAlias: \"anchor_map\" | \"from_map\" | \"to_map\",\n legacyColumn: \"recorded_at\" | \"recorded_from\" | \"recorded_to\",\n): SqlFragment {\n const mapping = sql.raw(mappingAlias);\n const legacy = sql.raw(`legacy.${legacyColumn}`);\n return dialect === \"postgres\" ?\n sql`${mapping}.recorded_at = ${legacy}`\n : sql`${mapping}.legacy_recorded_at = ${legacy}`;\n}\n\nfunction missingMappingCount(value: unknown, legacyTable: string): number {\n const count = Number(value);\n if (!Number.isSafeInteger(count) || count < 0) {\n throw new ConfigurationError(\n \"Recorded-time migration returned an invalid integrity-check count.\",\n { legacyTable, value },\n );\n }\n return count;\n}\n\nasync function assertRecordedRelationMappings(\n target: TransactionBackend,\n options: Readonly<{ legacyTable: string; mappingTable: string }>,\n): Promise<void> {\n const fromMatch = mappingMatch(target.dialect, \"from_map\", \"recorded_from\");\n const toMatch = mappingMatch(target.dialect, \"to_map\", \"recorded_to\");\n const rows = await target.execute<MissingMappingRow>(\n asCompiledRowsSql(sql`\n SELECT COUNT(*) AS missing\n FROM ${sql.identifier(options.legacyTable)} AS legacy\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS from_map\n ON from_map.graph_id = legacy.graph_id AND ${fromMatch}\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS to_map\n ON to_map.graph_id = legacy.graph_id AND ${toMatch}\n WHERE from_map.revision IS NULL\n OR (\n legacy.recorded_to <> ${LEGACY_RECORDED_MAX}\n AND to_map.revision IS NULL\n )\n `),\n );\n const missing = missingMappingCount(rows[0]?.missing, options.legacyTable);\n if (missing === 0) return;\n throw new ConfigurationError(\n \"Legacy recorded-time boundaries could not be mapped exactly.\",\n { legacyTable: options.legacyTable, missingRows: missing },\n {\n suggestion:\n \"Ensure every legacy boundary is a valid millisecond-precision timestamp produced by the preview recorded clock before retrying the offline migration.\",\n },\n );\n}\n\nasync function assertRecordedClockMappings(\n target: TransactionBackend,\n options: Readonly<{ legacyTable: string; mappingTable: string }>,\n): Promise<void> {\n const match = mappingMatch(target.dialect, \"anchor_map\", \"recorded_at\");\n const rows = await target.execute<MissingMappingRow>(\n asCompiledRowsSql(sql`\n SELECT COUNT(*) AS missing\n FROM ${sql.identifier(options.legacyTable)} AS legacy\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS anchor_map\n ON anchor_map.graph_id = legacy.graph_id AND ${match}\n WHERE anchor_map.revision IS NULL\n `),\n );\n const missing = missingMappingCount(rows[0]?.missing, options.legacyTable);\n if (missing === 0) return;\n throw new ConfigurationError(\n \"Legacy recorded clock values could not be mapped exactly.\",\n { legacyTable: options.legacyTable, missingRows: missing },\n {\n suggestion:\n \"Ensure every legacy clock value is a valid millisecond-precision timestamp produced by the preview recorded clock before retrying the offline migration.\",\n },\n );\n}\n\nasync function copyRecordedRelation(\n target: TransactionBackend,\n options: Readonly<{\n columns: readonly string[];\n legacyTable: string;\n mappingTable: string;\n temporaryTable: string;\n }>,\n): Promise<void> {\n const columnList = options.columns.map((column) => sql.identifier(column));\n const values = options.columns.map((column) =>\n migratedColumn(column, \"legacy\"),\n );\n await assertRecordedRelationMappings(target, options);\n const fromMatch = mappingMatch(target.dialect, \"from_map\", \"recorded_from\");\n const toMatch = mappingMatch(target.dialect, \"to_map\", \"recorded_to\");\n await executeStatement(\n target,\n sql`\n INSERT INTO ${sql.identifier(options.temporaryTable)}\n (${sql.join(columnList, sql`, `)})\n SELECT ${sql.join(values, sql`, `)}\n FROM ${sql.identifier(options.legacyTable)} AS legacy\n -- LEFT JOIN is deliberate: a missing mapping reaches the NOT NULL\n -- revision columns and fails loud instead of silently dropping history.\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS from_map\n ON from_map.graph_id = legacy.graph_id AND ${fromMatch}\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS to_map\n ON to_map.graph_id = legacy.graph_id AND ${toMatch}\n `,\n );\n}\n\nasync function copyRecordedClock(\n target: TransactionBackend,\n options: Readonly<{\n legacyTable: string;\n mappingTable: string;\n temporaryTable: string;\n }>,\n): Promise<void> {\n await assertRecordedClockMappings(target, options);\n const match = mappingMatch(target.dialect, \"anchor_map\", \"recorded_at\");\n await executeStatement(\n target,\n sql`\n INSERT INTO ${sql.identifier(options.temporaryTable)}\n (graph_id, revision, recorded_at)\n SELECT legacy.graph_id, anchor_map.revision, legacy.recorded_at\n FROM ${sql.identifier(options.legacyTable)} AS legacy\n -- Preserve fail-loud behavior if the preflight invariant changes later.\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS anchor_map\n ON anchor_map.graph_id = legacy.graph_id AND ${match}\n `,\n );\n}\n\nasync function replaceLegacyTables(\n target: TransactionBackend,\n tables: ResolvedSqlTableNames,\n mappingTable: string,\n recordedTableDdl: NonNullable<GraphBackend[\"recordedTableDdl\"]>,\n): Promise<void> {\n const temporary: RecordedTableNames = {\n recordedNodes: temporaryTableName(tables.recordedNodes, \"rn\"),\n recordedEdges: temporaryTableName(tables.recordedEdges, \"re\"),\n recordedClock: temporaryTableName(tables.recordedClock, \"rc\"),\n };\n const finalNames: RecordedTableNames = {\n recordedNodes: tables.recordedNodes,\n recordedEdges: tables.recordedEdges,\n recordedClock: tables.recordedClock,\n };\n const { ddl, primaryKeyConstraintRenames } = recordedMigrationDdl(\n recordedTableDdl,\n finalNames,\n temporary,\n );\n for (const table of Object.values(temporary)) {\n await executeStatement(\n target,\n sql`DROP TABLE IF EXISTS ${sql.identifier(table)}`,\n );\n }\n await executeDdl(target, ddl.recordedNodes.createTable);\n await executeDdl(target, ddl.recordedEdges.createTable);\n await executeDdl(target, ddl.recordedClock.createTable);\n await copyRecordedRelation(target, {\n columns: RECORDED_NODE_COLUMNS,\n legacyTable: tables.recordedNodes,\n mappingTable,\n temporaryTable: temporary.recordedNodes,\n });\n await copyRecordedRelation(target, {\n columns: RECORDED_EDGE_COLUMNS,\n legacyTable: tables.recordedEdges,\n mappingTable,\n temporaryTable: temporary.recordedEdges,\n });\n await copyRecordedClock(target, {\n legacyTable: tables.recordedClock,\n mappingTable,\n temporaryTable: temporary.recordedClock,\n });\n\n await executeStatement(\n target,\n sql`DROP TABLE ${sql.identifier(tables.recordedNodes)}`,\n );\n await executeStatement(\n target,\n sql`DROP TABLE ${sql.identifier(tables.recordedEdges)}`,\n );\n await executeStatement(\n target,\n sql`DROP TABLE ${sql.identifier(tables.recordedClock)}`,\n );\n await renameTable(target, temporary.recordedNodes, tables.recordedNodes);\n await renameTable(target, temporary.recordedEdges, tables.recordedEdges);\n await renameTable(target, temporary.recordedClock, tables.recordedClock);\n await renamePrimaryKeyConstraint(\n target,\n tables.recordedNodes,\n primaryKeyConstraintRenames.recordedNodes,\n );\n await renamePrimaryKeyConstraint(\n target,\n tables.recordedEdges,\n primaryKeyConstraintRenames.recordedEdges,\n );\n await renamePrimaryKeyConstraint(\n target,\n tables.recordedClock,\n primaryKeyConstraintRenames.recordedClock,\n );\n for (const statement of [\n ...ddl.recordedNodes.indexes,\n ...ddl.recordedEdges.indexes,\n ...ddl.recordedClock.indexes,\n ]) {\n await executeDdl(target, statement);\n }\n}\n\n/**\n * Renames the temporary table's PRIMARY KEY constraint to the final table's\n * name, once the swap has renamed the table itself. Both names come from the\n * authoring backend's `recordedTableDdl` (an ENGINE convention it alone\n * knows — engines that do not name PK constraints separately, e.g. SQLite,\n * return `undefined` for both, and this is a no-op). Identifier reduction on\n * an over-long target stays this migration's own decision — `shortenedIdentifier`\n * is applied to the target only, never the source (see {@link RecordedRelationDdl}).\n */\nasync function renamePrimaryKeyConstraint(\n target: TransactionBackend,\n finalTable: string,\n rename: PrimaryKeyConstraintRename,\n): Promise<void> {\n if (rename.status === \"none\") return;\n await executeStatement(\n target,\n sql`\n ALTER TABLE ${sql.identifier(finalTable)}\n RENAME CONSTRAINT ${sql.identifier(rename.from)}\n TO ${sql.identifier(shortenedIdentifier(rename.to))}\n `,\n );\n}\n\nasync function renameTable(\n target: TransactionBackend,\n from: string,\n to: string,\n): Promise<void> {\n try {\n await executeStatement(\n target,\n sql`ALTER TABLE ${sql.identifier(from)} RENAME TO ${sql.identifier(to)}`,\n );\n } catch (error) {\n throw new ConfigurationError(\n \"Could not rename a migrated recorded-time table.\",\n { from, to },\n { cause: error },\n );\n }\n}\n\n/**\n * Rewrites timestamp-only recorded relations to numeric revisions.\n *\n * Run offline before opening a Store with the new schema. The durable mapping\n * table is retained so external checkpoint stores can call\n * {@link migrateRecordedAnchor}; delete each graph's rows after its downstream\n * checkpoints have been rewritten.\n */\nexport async function migrateLegacyRecordedTime(\n options: MigrateLegacyRecordedTimeOptions,\n): Promise<MigrateLegacyRecordedTimeResult> {\n if (resolveRecordedTimeOwnership(options.backend) === \"engine-native\") {\n // The rewrite below targets TypeGraph's own recorded relations\n // (`recorded_from`/`recorded_to` columns on `typegraph_recorded_*`\n // tables); an engine-native backend keeps none of those, so there is\n // nothing here for this migration to rewrite.\n throw new ConfigurationError(\n \"migrateLegacyRecordedTime is not supported under engine-native recorded time.\",\n { code: \"ENGINE_NATIVE_MIGRATE_RECORDED_TIME_UNSUPPORTED\" },\n {\n suggestion:\n \"This migration rewrites TypeGraph's own recorded relations, which an engine-native backend does not have.\",\n },\n );\n }\n const tables = resolvedTableNames(options.backend, options.tableNames);\n const mapTable = mappingTableName(tables, options.mappingTableName);\n const recordedTableDdl = options.backend.recordedTableDdl;\n return options.backend.transaction(async (target) => {\n const clockColumns = await columnNames(target, tables.recordedClock);\n if (clockColumns.size === 0) {\n return {\n migrated: false,\n graphs: 0,\n anchors: 0,\n mappingTableName: mapTable,\n };\n }\n if (clockColumns.has(\"revision\")) {\n const mapColumns = await columnNames(target, mapTable);\n if (mapColumns.size === 0) {\n return {\n migrated: false,\n graphs: 0,\n anchors: 0,\n mappingTableName: mapTable,\n };\n }\n const rows = await target.execute<MappingCountRow>(\n asCompiledRowsSql(sql`\n SELECT COUNT(*) AS anchors, COUNT(DISTINCT graph_id) AS graphs\n FROM ${sql.identifier(mapTable)}\n `),\n );\n const anchors = Number(rows[0]?.anchors ?? 0);\n const graphs = Number(rows[0]?.graphs ?? 0);\n return {\n migrated: false,\n graphs: Number.isSafeInteger(graphs) ? graphs : 0,\n anchors: Number.isSafeInteger(anchors) ? anchors : 0,\n mappingTableName: mapTable,\n };\n }\n const nodeColumns = await columnNames(target, tables.recordedNodes);\n const edgeColumns = await columnNames(target, tables.recordedEdges);\n if (\n !nodeColumns.has(\"recorded_from\") ||\n !edgeColumns.has(\"recorded_from\")\n ) {\n throw new ConfigurationError(\n \"Legacy recorded-time schema is incomplete.\",\n { tables },\n );\n }\n\n if (recordedTableDdl === undefined) {\n throw new UnsupportedBackendCapabilityError(\n \"migrateLegacyRecordedTime\",\n \"recordedTableDdl\",\n { dialect: target.dialect, tables },\n \"Migrating the timestamp-only preview recorded schema needs the backend to author its own recorded-relation DDL. Only the bundled SQLite and PostgreSQL backends created that schema.\",\n );\n }\n\n await executeDdl(target, migrationMapDdl(target.dialect, mapTable));\n const mapping = await readLegacyInstants(target, tables);\n await writeMappingRows(target, mapTable, mapping);\n await replaceLegacyTables(target, tables, mapTable, recordedTableDdl);\n return {\n migrated: true,\n graphs: new Set(mapping.map((row) => row.graphId)).size,\n anchors: mapping.length,\n mappingTableName: mapTable,\n };\n });\n}\n\n/** Remaps one timestamp-only checkpoint after {@link migrateLegacyRecordedTime}. */\nexport async function migrateRecordedAnchor(\n options: MigrateRecordedAnchorOptions,\n): Promise<RecordedInstant> {\n try {\n return asRecordedInstant(options.anchor);\n } catch (error) {\n if (!(error instanceof ValidationError)) throw error;\n }\n const legacyRecordedAt = canonicalLegacyInstant(options.anchor);\n const tables = resolvedTableNames(options.backend, options.tableNames);\n const mapTable = mappingTableName(tables, options.mappingTableName);\n const rows = await options.backend.execute<RemapRow>(\n asCompiledRowsSql(sql`\n SELECT revision, recorded_at\n FROM ${sql.identifier(mapTable)}\n WHERE graph_id = ${options.graphId}\n AND legacy_recorded_at = ${legacyRecordedAt}\n `),\n );\n const row = rows[0];\n if (row === undefined) {\n throw new ConfigurationError(\n \"No migrated recorded anchor matches this graph and legacy timestamp.\",\n { anchor: options.anchor, graphId: options.graphId },\n {\n suggestion:\n \"Run migrateLegacyRecordedTime() before deleting its mapping rows, and pass the graph that produced the checkpoint.\",\n },\n );\n }\n return createRecordedInstant(\n safeRevision(row.revision),\n canonicalLegacyInstant(row.recorded_at),\n );\n}\n\n/**\n * Deletes one graph's legacy remap rows after downstream checkpoints migrate.\n * Set `dropWhenEmpty` to remove the migration table after the final graph.\n */\nexport async function deleteLegacyRecordedAnchorMap(\n options: DeleteLegacyRecordedAnchorMapOptions,\n): Promise<void> {\n requireStatements(options.backend);\n const tables = resolvedTableNames(options.backend, options.tableNames);\n const mapTable = mappingTableName(tables, options.mappingTableName);\n await options.backend.transaction(async (target) => {\n await executeStatement(\n target,\n sql`\n DELETE FROM ${sql.identifier(mapTable)}\n WHERE graph_id = ${options.graphId}\n `,\n );\n if (options.dropWhenEmpty !== true) return;\n const rows = await target.execute<MappingCountRow>(\n asCompiledRowsSql(sql`\n SELECT COUNT(*) AS anchors, COUNT(DISTINCT graph_id) AS graphs\n FROM ${sql.identifier(mapTable)}\n `),\n );\n const remaining = missingMappingCount(rows[0]?.anchors, mapTable);\n if (remaining === 0) {\n await executeStatement(\n target,\n sql`DROP TABLE ${sql.identifier(mapTable)}`,\n );\n }\n });\n}\n","/**\n * Offline repair for validity windows that older library versions stored\n * inverted (`valid_from > valid_to`).\n *\n * Such a row is readable at no coordinate at all: `asOf(t)` needs\n * `valid_from <= t < valid_to`, and no `t` satisfies both when the bounds are\n * backwards. The library no longer mints them — a write that stamps a lower\n * bound the caller did not state stores no bound rather than an inverting one —\n * but deploying that fix rewrites nothing, so rows written by an older version\n * (or by direct SQL) stay invisible until an operator repairs them.\n *\n * The repair normalizes those rows to \"ended at T, start unknown\"\n * (`valid_from = NULL`), which is the shape the current write paths store. It\n * deliberately does **not** bump `version`, touch `updated_at`, or mint a\n * recorded revision: it normalizes a storage convention for rows that were\n * never observable at any coordinate, so it is not a logical write — and\n * minting a revision would make the pre-repair recorded state re-materialize\n * the inverted shape at `asOfRecorded` coordinates.\n *\n * Operator consequences, all of them stated in the docs as well:\n *\n * 1. **Run `\"apply\"` with writers stopped.** A concurrent window-bearing update\n * may fence its write on the validity lower bound it read, so a repair that\n * lands in between can make the peer's first `UPDATE` match no row. Store\n * node/edge updates re-read and re-judge against the repaired bound; an\n * interchange update records a per-row target-changed error instead of\n * claiming the row was written. `\"report\"` needs no quiescing — it scans in\n * a read-only transaction, so it cannot write.\n * 2. **Repaired rows become visible** at `asOf` coordinates before their end.\n * That is the point, and it is a read-visibility change to historical\n * queries.\n * 3. **Outstanding `base@V` merge tokens are invalidated** for repaired rows —\n * `valid_from` is part of the base content fingerprint. Quiesce merges,\n * repair, then re-baseline branches.\n * 4. **Prefer `relations: \"live-and-recorded\"`.** Repairing only the live axis\n * leaves the recorded twin carrying the inverted window, which\n * re-materializes the invisible row at any `asOfRecorded` coordinate.\n */\nimport { ConfigurationError } from \"../errors\";\nimport type {\n ResolvedSqlTableNames,\n SqlTableNames,\n} from \"../query/compiler/schema\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql, asCompiledStatementSql } from \"../query/sql-intent\";\nimport { statementExecutionMembers } from \"./capabilities/bind\";\nimport type { STATEMENT_EXECUTION } from \"./capabilities/bundle-registry\";\nimport {\n type BundleVerdictOf,\n statementExecutionVerdict,\n} from \"./capabilities/resolve\";\nimport { resolvedTableNames } from \"./table-names\";\nimport {\n type GraphBackend,\n runOptionallyInTransaction,\n type RunOptionallyInTransactionOptions,\n type TransactionBackend,\n} from \"./types\";\n\n/** A relation whose rows carry a validity window this repair can normalize. */\nexport type RepairRelation =\n \"nodes\" | \"edges\" | \"recordedNodes\" | \"recordedEdges\";\n\n/**\n * Which relations one call scans.\n *\n * `\"live-and-recorded\"` is the recommended scope. `\"live\"` is correct in\n * exactly two cases: the store captures no history and the `recorded_*` tables\n * do not exist, or the operator is deliberately preserving the recorded axis as\n * an audit record of what was stored before the repair — and accepts that\n * historical `asOfRecorded` reads keep returning the invisible shape.\n */\nexport type RepairRelationScope = \"live\" | \"live-and-recorded\";\n\n/** Inputs for detecting or repairing legacy inverted validity windows. */\nexport type RepairInvertedWindowsOptions = Readonly<{\n backend: GraphBackend;\n /** Omit to sweep every graph in the database. */\n graphId?: string | undefined;\n /** Required: the scope is a decision, not a default. */\n relations: RepairRelationScope;\n /**\n * `\"report\"` counts and writes nothing; `\"apply\"` counts and then normalizes\n * the rows it counted.\n */\n mode: \"report\" | \"apply\";\n /**\n * Patch selected backend table names, exactly as migrate-recorded-time does.\n * Unstated names continue to come from `backend.tableNames`; see\n * {@link resolvedTableNames}.\n */\n tableNames?: Partial<SqlTableNames> | undefined;\n}>;\n\n/** Counts and execution guarantees observed by one repair/report call. */\nexport type RepairInvertedWindowsReport = Readonly<{\n /** Echoes the scope actually scanned — a count of 0 and \"not scanned\" are different facts. */\n relations: RepairRelationScope;\n /**\n * Rows whose stored window is inverted: found in `\"report\"` mode, repaired in\n * `\"apply\"` mode. `undefined` means NOT SCANNED, never \"clean\".\n */\n counts: Readonly<Record<RepairRelation, number | undefined>>;\n /**\n * Rows whose stored bounds are not canonical ISO and were therefore not\n * classified. SQLite only in substance: on PostgreSQL the columns are\n * `timestamptz`, so a scanned relation always reports `0` (never `undefined`\n * — that value is reserved for \"not scanned\", on both dialects).\n *\n * `\"apply\"` refuses while any scanned relation reports a non-zero count:\n * classifying those rows needs a timestamp semantics this repair does not\n * own, and skipping them silently would be an accepted option ignored.\n */\n nonCanonical: Readonly<Record<RepairRelation, number | undefined>>;\n /**\n * Whether every statement of this call ran in ONE transaction. `false` on a\n * backend that reports `capabilities.execution.interactiveTransactions === false`, where the call\n * degrades to per-relation statements.\n *\n * Reported by the seam, not inferred from backend object identity:\n * {@link runOptionallyInTransaction} explicitly tells its callback whether it\n * opened a transaction. \"One snapshot\" and \"four snapshots\" are different\n * facts about a report, and the report must state which occurred even when a\n * custom backend passes the same object into its transaction callback.\n *\n * When `false`, a `\"report\"`'s counts may come from different snapshots and a\n * crash mid-`\"apply\"` can leave the live axis repaired and the recorded axis\n * not. Both are survivable the same way: each relation's statement is\n * idempotent and convergent, so a re-run finishes the job and a later\n * `\"report\"` proves it.\n */\n atomic: boolean;\n}>;\n\nconst LIVE_RELATIONS = [\n \"nodes\",\n \"edges\",\n] as const satisfies readonly RepairRelation[];\n\nconst RECORDED_RELATIONS = [\n \"recordedNodes\",\n \"recordedEdges\",\n] as const satisfies readonly RepairRelation[];\n\n/**\n * Canonical fixed-width UTC ISO 8601, as a SQLite `GLOB` pattern.\n *\n * SQLite stores the bounds as `TEXT` and compares them lexicographically, which\n * equals chronological order only for canonical values. This repair exists to\n * clean up rows written by older paths and by direct SQL, so it cannot assume\n * canonicality — it establishes it per row instead.\n */\nconst CANONICAL_INSTANT_GLOB =\n \"[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z\";\n\ntype RepairTarget = GraphBackend | TransactionBackend;\n\ntype CountRow = Readonly<{ matches: unknown }>;\n\nfunction scopedRelations(\n scope: RepairRelationScope,\n): readonly RepairRelation[] {\n return scope === \"live\" ? LIVE_RELATIONS : (\n [...LIVE_RELATIONS, ...RECORDED_RELATIONS]\n );\n}\n\nfunction relationTable(\n tables: ResolvedSqlTableNames,\n relation: RepairRelation,\n): string {\n switch (relation) {\n case \"nodes\": {\n return tables.nodes;\n }\n case \"edges\": {\n return tables.edges;\n }\n case \"recordedNodes\": {\n return tables.recordedNodes;\n }\n case \"recordedEdges\": {\n return tables.recordedEdges;\n }\n }\n}\n\nfunction graphScopeClauses(\n graphId: string | undefined,\n): readonly SqlFragment[] {\n return graphId === undefined ? [] : [sql`graph_id = ${graphId}`];\n}\n\nfunction canonicalBoundsClauses(\n dialect: GraphBackend[\"dialect\"],\n): readonly SqlFragment[] {\n if (dialect !== \"sqlite\") return [];\n return [\n sql`valid_from GLOB ${CANONICAL_INSTANT_GLOB}`,\n sql`valid_to GLOB ${CANONICAL_INSTANT_GLOB}`,\n ];\n}\n\n/**\n * The one spelling of \"this stored window is inverted\".\n *\n * Both modes compile it: `\"report\"` into `SELECT COUNT(*) … WHERE <this>` and\n * `\"apply\"` into `UPDATE … SET valid_from = NULL WHERE <this>`, so the count\n * and the repair cannot disagree about which rows are in scope.\n *\n * The comparison is strict (`>`). A stored zero-width window is a legal shape a\n * caller may have stated in full, and this repair does not second-guess it.\n */\nexport function invertedValidityWindowPredicate(\n options: Readonly<{\n dialect: GraphBackend[\"dialect\"];\n graphId?: string | undefined;\n }>,\n): SqlFragment {\n return sql.join(\n [\n sql`valid_from IS NOT NULL`,\n sql`valid_to IS NOT NULL`,\n ...canonicalBoundsClauses(options.dialect),\n sql`valid_from > valid_to`,\n ...graphScopeClauses(options.graphId),\n ],\n sql` AND `,\n );\n}\n\n/**\n * Rows carrying both bounds where either one is not canonical, and which the\n * inverted predicate therefore refuses to classify. SQLite only: PostgreSQL\n * stores `timestamptz`, where every stored value compares chronologically.\n */\nfunction nonCanonicalWindowPredicate(graphId: string | undefined): SqlFragment {\n return sql.join(\n [\n sql`valid_from IS NOT NULL`,\n sql`valid_to IS NOT NULL`,\n sql`(valid_from NOT GLOB ${CANONICAL_INSTANT_GLOB} OR valid_to NOT GLOB ${CANONICAL_INSTANT_GLOB})`,\n ...graphScopeClauses(graphId),\n ],\n sql` AND `,\n );\n}\n\nfunction safeCount(value: unknown, table: string): number {\n const count = Number(value);\n if (!Number.isSafeInteger(count) || count < 0) {\n throw new ConfigurationError(\n \"Validity-window repair returned an invalid row count.\",\n { table, value },\n );\n }\n return count;\n}\n\nasync function countMatching(\n target: RepairTarget,\n table: string,\n predicate: SqlFragment,\n): Promise<number> {\n const rows = await target.execute<CountRow>(\n asCompiledRowsSql(sql`\n SELECT COUNT(*) AS matches\n FROM ${sql.identifier(table)}\n WHERE ${predicate}\n `),\n );\n return safeCount(rows[0]?.matches, table);\n}\n\n/**\n * `\"apply\"` writes, so it needs the optional non-row-returning statement path.\n * `\"report\"` deliberately does not: `execute` is a required member, so\n * detection stays available on every backend even where repair is not.\n *\n * Shared by both throw sites below: the public entry refuses BEFORE opening a\n * transaction (so an unsupported backend never pays for one), and\n * {@link repairRelation}'s own guard exists ONLY because a nested closure\n * cannot inherit the entry's narrowing of `verdict` to `{ supported: true }` —\n * it can never fire at runtime, since the entry already refused. One message,\n * two structurally-required call sites.\n */\nfunction statementExecutionRequiredError(\n dialect: GraphBackend[\"dialect\"],\n): ConfigurationError {\n return new ConfigurationError(\n \"Repairing inverted validity windows requires executeStatement support.\",\n { dialect, mode: \"apply\" },\n {\n suggestion:\n 'Use a built-in SQLite or PostgreSQL backend to apply the repair. Detection needs no such support: call this with mode: \"report\" to count the affected rows on any backend.',\n },\n );\n}\n\n/**\n * Translates the recorded-capture wrapper's refusal instead of swallowing it.\n *\n * A history-enabled store replaces `executeStatement` with a rejecting stub, so\n * `\"apply\"` against that backend fails with a message about raw SQL rather than\n * about this repair. The remedy is specific enough to be worth naming: hand the\n * repair the raw backend the history store was constructed from. Bypassing\n * capture is the intended behavior here, not a workaround — the repair mints no\n * revision by design.\n */\nfunction translatedCaptureRefusal(error: unknown): unknown {\n if (\n !(error instanceof ConfigurationError) ||\n error.details[\"code\"] !== \"RECORDED_CAPTURE_RAW_SQL_DISABLED\"\n ) {\n return error;\n }\n return new ConfigurationError(\n \"Repairing inverted validity windows cannot run against a history-capturing backend.\",\n { code: \"RECORDED_CAPTURE_RAW_SQL_DISABLED\", mode: \"apply\" },\n {\n cause: error,\n suggestion:\n 'Pass the raw backend you constructed the history store from. The repair deliberately mints no revision — it normalizes storage for rows that were never visible at any coordinate — so bypassing recorded-time capture is the intended behavior, not a workaround. mode: \"report\" needs no such care: it runs against the capture-wrapped backend.',\n },\n );\n}\n\nasync function repairRelation(\n target: RepairTarget,\n verdict: BundleVerdictOf<typeof STATEMENT_EXECUTION>,\n table: string,\n predicate: SqlFragment,\n): Promise<void> {\n // Unreachable at runtime: `repairInvertedValidityWindows` already refused an\n // unsupported backend before opening the transaction this runs inside. The\n // check exists only so `verdict` narrows for `statementExecutionMembers` —\n // TypeScript does not carry the entry's narrowing into this closure.\n if (!verdict.supported) {\n throw statementExecutionRequiredError(target.dialect);\n }\n try {\n await statementExecutionMembers(target, verdict).executeStatement(\n asCompiledStatementSql(sql`\n UPDATE ${sql.identifier(table)}\n SET valid_from = NULL\n WHERE ${predicate}\n `),\n );\n } catch (error) {\n throw translatedCaptureRefusal(error);\n }\n}\n\nfunction assertClassifiableBounds(\n nonCanonical: ReadonlyMap<RepairRelation, number>,\n): void {\n const unclassified = [...nonCanonical].filter(([, count]) => count > 0);\n if (unclassified.length === 0) return;\n throw new ConfigurationError(\n \"Refusing to repair validity windows: some scanned rows store non-canonical bounds.\",\n { nonCanonical: Object.fromEntries(unclassified) },\n {\n suggestion:\n 'Normalize those bounds to canonical UTC ISO 8601 (YYYY-MM-DDTHH:MM:SS.mmmZ) and re-run, or narrow the call with graphId. Classifying them here would need a timestamp semantics this repair does not own, and skipping them silently would report a repair it did not make. mode: \"report\" still counts them.',\n },\n );\n}\n\n/**\n * Declares `\"report\"`'s read-only-ness to the ENGINE rather than only to the\n * reader of this file.\n *\n * The docs send an operator to diagnose against the live store's backend and\n * require quiescing only for `\"apply\"`, so the scan must not behave like a\n * writer: on SQLite a default transaction is `BEGIN IMMEDIATE`, which reserves\n * the single writer slot for the duration of up to four full-table `COUNT(*)`\n * scans and can fail `SQLITE_BUSY` against an active writer; `read_only` issues\n * a plain `BEGIN` instead. On PostgreSQL it issues `BEGIN … READ ONLY`, which\n * makes \"report writes nothing\" enforced by the engine and not merely asserted\n * by a test.\n *\n * `\"apply\"` writes, so it takes the default read-write transaction.\n */\nfunction transactionOptionsFor(\n mode: RepairInvertedWindowsOptions[\"mode\"],\n): RunOptionallyInTransactionOptions | undefined {\n return mode === \"report\" ?\n { transaction: { accessMode: \"read_only\" } }\n : undefined;\n}\n\nfunction relationRecord(\n counts: ReadonlyMap<RepairRelation, number>,\n): Readonly<Record<RepairRelation, number | undefined>> {\n return {\n nodes: counts.get(\"nodes\"),\n edges: counts.get(\"edges\"),\n recordedNodes: counts.get(\"recordedNodes\"),\n recordedEdges: counts.get(\"recordedEdges\"),\n };\n}\n\n/**\n * Counts — and, in `\"apply\"` mode, normalizes — rows whose stored validity\n * window is inverted.\n *\n * ```typescript\n * // Diagnose with the store's backend: `report` reads only, so it runs\n * // anywhere, including a capture-wrapped or statement-less backend.\n * const report = await repairInvertedValidityWindows({\n * backend: anyBackend,\n * relations: \"live-and-recorded\",\n * mode: \"report\",\n * });\n *\n * // Repair with the raw one, while writers are stopped.\n * await repairInvertedValidityWindows({\n * backend: rawBackend,\n * relations: \"live-and-recorded\",\n * mode: \"apply\",\n * });\n * ```\n *\n * Idempotent and convergent: a second `\"apply\"` reports zero, because the rows\n * the first one repaired no longer match the predicate.\n *\n * No batching, deliberately. Unlike the recorded-time migration, which rewrites\n * every row, this statement touches only rows the library mis-stored — an empty\n * set on a healthy graph. A deployment that reports a count large enough to\n * worry about should run it per `graphId`.\n *\n * @throws ConfigurationError in `\"apply\"` mode when the backend cannot execute\n * statements, when the backend is a recorded-capture wrapper, or when any\n * scanned relation stores non-canonical bounds. A transaction TARGET that\n * disagrees with the top-level verdict (missing `executeStatement` the\n * top-level backend has) refuses separately, with I20's\n * `BUNDLE_PORT_SURFACE_MISMATCH` — the per-bundle port check\n * `statementExecutionMembers` performs, not a second spelling of this one.\n */\nexport async function repairInvertedValidityWindows(\n options: RepairInvertedWindowsOptions,\n): Promise<RepairInvertedWindowsReport> {\n const tables = resolvedTableNames(options.backend, options.tableNames);\n const relations = scopedRelations(options.relations);\n const verdict = statementExecutionVerdict(options.backend);\n // Refuse before opening a transaction: a backend with no statement path can\n // never apply, whatever the scan finds.\n if (options.mode === \"apply\" && !verdict.supported) {\n throw statementExecutionRequiredError(options.backend.dialect);\n }\n\n return runOptionallyInTransaction(\n options.backend,\n async (target, execution) => {\n const predicate = invertedValidityWindowPredicate({\n dialect: target.dialect,\n graphId: options.graphId,\n });\n const inverted = new Map<RepairRelation, number>();\n const nonCanonical = new Map<RepairRelation, number>();\n for (const relation of relations) {\n const table = relationTable(tables, relation);\n nonCanonical.set(\n relation,\n target.dialect === \"sqlite\" ?\n await countMatching(\n target,\n table,\n nonCanonicalWindowPredicate(options.graphId),\n )\n : 0,\n );\n inverted.set(relation, await countMatching(target, table, predicate));\n }\n\n if (options.mode === \"apply\") {\n assertClassifiableBounds(nonCanonical);\n for (const relation of relations) {\n await repairRelation(\n target,\n verdict,\n relationTable(tables, relation),\n predicate,\n );\n }\n }\n\n return {\n relations: options.relations,\n counts: relationRecord(inverted),\n nonCanonical: relationRecord(nonCanonical),\n // Keep the report's long-standing `atomic` compatibility field while\n // consuming the richer execution-mode decision from the transaction\n // seam. A sequential callback is not an interactive transaction even\n // when an adapter happens to execute one statement atomically.\n atomic: execution.mode === \"interactive-transaction\",\n };\n },\n transactionOptionsFor(options.mode),\n );\n}\n"]}
@@ -1,13 +1,13 @@
1
- import { nodeClaimSites, getEmbeddingFields, groupNodeUniquenessProbes, nodeClaimEntries, refuseNodeCreateClaimError, refuseFulltextUnavailable, assertFulltextMember, planNodeCreateClaims, createUniquenessContext, isUniquenessClaimEntry, probeUniqueKey, resolveNodeFulltextProjection, resolveNodeEmbeddingProjectionTransitions, checkUniquenessConstraints, createNodeWriteContext, applyResolvedNodeUpdateBatch, applyNodeSetUpdate, applyNodeResurrect, applyNodeHardDelete, applyNodeSoftDelete, applyNodeUpdate, withNodeCreateClaimsBatch, applyNodeInsertSyncFansBatch, withNodeCreateClaims, applyNodeInsertSyncFans, resolveNodeEmbeddingProjections, resolvedNodeUniqueSidecarBatchIsReachable, resolvedNodeUpdatePreservesClaimKeys } from './chunk-GKSAEUX6.js';
2
- import { isBundledRootAutocommitEligible, supportsNodeInsertProjectionRequirements, rephaseAtomicNodeClaimPlan, supportsNodeCreatePlan, supportsNodeInsertProjections, resolvedNodeUpdateBatchFitsBindBudget } from './chunk-RQPCUHIH.js';
3
- import { EDGE_CARDINALITY_SPECS, claimEdgeCardinalityBatch, claimEdgeCardinality, purgeEdgeClaims } from './chunk-G6T23JU7.js';
1
+ import { nodeClaimSites, getEmbeddingFields, groupNodeUniquenessProbes, nodeClaimEntries, refuseNodeCreateClaimError, refuseFulltextUnavailable, assertFulltextMember, planNodeCreateClaims, createUniquenessContext, isUniquenessClaimEntry, probeUniqueKey, resolveNodeFulltextProjection, resolveNodeEmbeddingProjectionTransitions, checkUniquenessConstraints, createNodeWriteContext, applyResolvedNodeUpdateBatch, applyNodeSetUpdate, applyNodeResurrect, applyNodeHardDelete, applyNodeSoftDelete, applyNodeUpdate, withNodeCreateClaimsBatch, applyNodeInsertSyncFansBatch, withNodeCreateClaims, applyNodeInsertSyncFans, resolveNodeEmbeddingProjections, resolvedNodeUniqueSidecarBatchIsReachable, resolvedNodeUpdatePreservesClaimKeys } from './chunk-FXOFJ4FS.js';
2
+ import { isBundledRootAutocommitEligible, supportsNodeInsertProjectionRequirements, rephaseAtomicNodeClaimPlan, supportsNodeCreatePlan, supportsNodeInsertProjections, resolvedNodeUpdateBatchFitsBindBudget } from './chunk-6ECNYQDW.js';
3
+ import { EDGE_CARDINALITY_SPECS, claimEdgeCardinalityBatch, claimEdgeCardinality, purgeEdgeClaims } from './chunk-CDKNGCE7.js';
4
4
  import { resolveBackendFulltext } from './chunk-N535PWMA.js';
5
- import { resolveAtomicMutationPrograms, AtomicNodeDeleteRestrictedRefusalError, supportsAtomicNodeClaimFamily, supportsAtomicNodeProjections, supportsAtomicNodeClaims } from './chunk-WTMSUIRO.js';
6
- import { refKey } from './chunk-THK3SCQA.js';
7
- import { runInWriteTransaction, runHookedWriteOperation, uncapturedGraphWriteLock, diagnoseFusedSchemaFenceNoRow, validateNodeProps, memoizeLeasedSchemaFence, getNodeRowsByIds, generateId, compareAndSetAbsent, hasLeasedSchemaFence, lockSchemaVersionForStoreWrite, nodeInsertDispatch, edgeInsertDispatch, runInsertBatch, runInsertBatchReturning, runInsertNoReturn, runInsertIfAbsent } from './chunk-337ONI2I.js';
8
- import { canonicalEqual, chunk } from './chunk-4VTCIEK3.js';
9
- import { missingRequiredExtras } from './chunk-EVGZ2TRQ.js';
10
- import { rowPropsToObject, isLiveNodeRow, deriveBackend, isSchemaFencedInsertEligible, bindExtraIfReachable, BATCH_POINT_READ, UNIQUE_SIDECAR_BATCH, createSqlSchema, DEFAULT_SQL_SCHEMA, supportsAtomicBatch, executeAuthoritativeGraphCommand } from './chunk-AD3NLSV5.js';
5
+ import { resolveAtomicMutationPrograms, AtomicNodeDeleteRestrictedRefusalError, supportsAtomicNodeClaimFamily, supportsAtomicNodeProjections, supportsAtomicNodeClaims } from './chunk-UFKYMQJ5.js';
6
+ import { refKey } from './chunk-SYXTWPX6.js';
7
+ import { runInWriteTransaction, runHookedWriteOperation, uncapturedGraphWriteLock, diagnoseFusedSchemaFenceNoRow, validateNodeProps, memoizeLeasedSchemaFence, getNodeRowsByIds, generateId, compareAndSetAbsent, hasLeasedSchemaFence, lockSchemaVersionForStoreWrite, nodeInsertDispatch, edgeInsertDispatch, runInsertBatch, runInsertBatchReturning, runInsertNoReturn, runInsertIfAbsent } from './chunk-3SUZXB5X.js';
8
+ import { canonicalEqual, chunk } from './chunk-4TQOIBWH.js';
9
+ import { missingRequiredExtras } from './chunk-BE75G3M5.js';
10
+ import { rowPropsToObject, isLiveNodeRow, deriveBackend, isSchemaFencedInsertEligible, bindExtraIfReachable, BATCH_POINT_READ, UNIQUE_SIDECAR_BATCH, createSqlSchema, DEFAULT_SQL_SCHEMA, supportsAtomicBatch, executeAuthoritativeGraphCommand } from './chunk-TU22BFMP.js';
11
11
  import { isPortableEdgeMatchIdentityValue } from './chunk-NMRLVAVN.js';
12
12
  import { checkDisjointness, checkUniqueEdge, checkCardinality, encodeTupleKey, checkWherePredicate, computeUniqueKey, uniquenessProbeKinds } from './chunk-OXJNL2PW.js';
13
13
  import { assertsStoredLowerBound, assertsStoredUpperBound, validateStatedValidityLowerBound, validateOptionalCanonicalIsoDate, assertOrderedValidityWindow, nowIso, resolveStampedValidityLowerBound, preservesImmutableLowerBound, assertWritableValidityWindow } from './chunk-CY657YYY.js';
@@ -4442,5 +4442,5 @@ async function executeNodeBulkGetOrCreateByConstraint(ctx, kind, constraintName,
4442
4442
  }
4443
4443
 
4444
4444
  export { AutocommitWriteRequiresTransaction, ResolvedMutationSetMoved, appliedResolvedMutationSet, assertAtomicDeleteSchemaFenceMatched, assertClearValidToSupported, assertValidityEndMutation, assertsStoredWindowState, atomicResolvedUpdateAttemptBudget, buildEdgeMatchKey, canFuseSchemaFenceInFirstWrite, canonicalPersistedJsonValue, checkCardinalityConstraint, checkDisjointnessConstraint, classifyDurableEdgeBatchOutcomes, createEdgeBatchValidationBackend, createNodeBatchValidationSeams, edgeMatchIdentityUpdateRefusal, edgeWriteNeedsConstraintFence, edgeWritePlan, executeNodeBulkFindByConstraint, executeNodeBulkFindByIndex, executeNodeBulkGetOrCreateByConstraint, executeNodeCreate, executeNodeCreateBatch, executeNodeCreateNoReturnBatch, executeNodeDelete, executeNodeDeleteBatch, executeNodeFindByConstraint, executeNodeGetOrCreateByConstraint, executeNodeHardDelete, executeNodeReplacementBatch, executeNodeResolvedMutationSet, executeNodeSetUpdate, executeNodeUpdate, executeNodeUpsertUpdateBatch, graphOwesClaims, isAutocommitSingleStatementWrite, mixedWritePlan, nestedManagedWriteTarget, nodeUpsertDirtyCheck, normalizePersistedEdgeMatchProps, prepareNodeReplacement, primeBatchValidationCaches, resolveAtomicEdgeBatchExecutor, resolveAtomicEdgeConvergenceExecutor, resolveAtomicEdgeDeleteBatchExecutor, resolveAtomicEdgeResolvedMutationSetExecutor, resolveAtomicEdgeResolvedUpdateBatchExecutor, resolveEdgeMatchIdentityStorage, rowToEdge, rowToEdgeMeta, rowToNode, rowToNodeMeta, runAtomicProgramWithHooks, runAutocommitSingleStatementWritePlan, runHookedWritePlan, runResolvedMutationSetConverging, runWritePlan, unfencedTarget, unsupportedResolvedMutationSet, validityEndAfterMutation, withAlreadyExistsTranslation, writeResultAlwaysChanges };
4445
- //# sourceMappingURL=chunk-QFEO4M5W.js.map
4446
- //# sourceMappingURL=chunk-QFEO4M5W.js.map
4445
+ //# sourceMappingURL=chunk-RTPMG6LQ.js.map
4446
+ //# sourceMappingURL=chunk-RTPMG6LQ.js.map