@nicia-ai/typegraph 0.49.0 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (370) hide show
  1. package/README.md +12 -0
  2. package/dist/backend/drizzle/indexes.cjs +11 -9
  3. package/dist/backend/drizzle/indexes.d.cts +1 -1
  4. package/dist/backend/drizzle/indexes.d.ts +1 -1
  5. package/dist/backend/drizzle/indexes.js +7 -5
  6. package/dist/backend/index.cjs +190 -53
  7. package/dist/backend/index.d.cts +90 -4
  8. package/dist/backend/index.d.ts +90 -4
  9. package/dist/backend/index.js +9 -12
  10. package/dist/backend/postgres/index.cjs +36 -28
  11. package/dist/backend/postgres/index.d.cts +7 -7
  12. package/dist/backend/postgres/index.d.ts +7 -7
  13. package/dist/backend/postgres/index.js +19 -15
  14. package/dist/backend/postgres/pglite-store.cjs +7 -62
  15. package/dist/backend/postgres/pglite-store.cjs.map +1 -1
  16. package/dist/backend/postgres/pglite-store.d.cts +8 -8
  17. package/dist/backend/postgres/pglite-store.d.ts +8 -8
  18. package/dist/backend/postgres/pglite-store.js +7 -62
  19. package/dist/backend/postgres/pglite-store.js.map +1 -1
  20. package/dist/backend/postgres/pglite.cjs +21 -17
  21. package/dist/backend/postgres/pglite.d.cts +3 -3
  22. package/dist/backend/postgres/pglite.d.ts +3 -3
  23. package/dist/backend/postgres/pglite.js +20 -16
  24. package/dist/backend/sqlite/index.cjs +33 -25
  25. package/dist/backend/sqlite/index.d.cts +7 -7
  26. package/dist/backend/sqlite/index.d.ts +7 -7
  27. package/dist/backend/sqlite/index.js +17 -13
  28. package/dist/backend/sqlite/libsql.cjs +24 -20
  29. package/dist/backend/sqlite/libsql.cjs.map +1 -1
  30. package/dist/backend/sqlite/libsql.d.cts +3 -3
  31. package/dist/backend/sqlite/libsql.d.ts +3 -3
  32. package/dist/backend/sqlite/libsql.js +19 -15
  33. package/dist/backend/sqlite/libsql.js.map +1 -1
  34. package/dist/backend/sqlite/local-store.cjs +9 -64
  35. package/dist/backend/sqlite/local-store.cjs.map +1 -1
  36. package/dist/backend/sqlite/local-store.d.cts +8 -8
  37. package/dist/backend/sqlite/local-store.d.ts +8 -8
  38. package/dist/backend/sqlite/local-store.js +8 -64
  39. package/dist/backend/sqlite/local-store.js.map +1 -1
  40. package/dist/backend/sqlite/local.cjs +25 -20
  41. package/dist/backend/sqlite/local.d.cts +3 -3
  42. package/dist/backend/sqlite/local.d.ts +3 -3
  43. package/dist/backend/sqlite/local.js +21 -16
  44. package/dist/chunk-2CVDZCXH.cjs +1278 -0
  45. package/dist/chunk-2CVDZCXH.cjs.map +1 -0
  46. package/dist/{chunk-MYKHJI2J.js → chunk-2DWTBNSH.js} +3 -3
  47. package/dist/{chunk-MYKHJI2J.js.map → chunk-2DWTBNSH.js.map} +1 -1
  48. package/dist/{chunk-JB6T4GLL.cjs → chunk-2KCTP3U2.cjs} +870 -528
  49. package/dist/chunk-2KCTP3U2.cjs.map +1 -0
  50. package/dist/{chunk-OORXGFL5.cjs → chunk-322TBTOQ.cjs} +48 -48
  51. package/dist/{chunk-OORXGFL5.cjs.map → chunk-322TBTOQ.cjs.map} +1 -1
  52. package/dist/{chunk-FA2AFWLP.cjs → chunk-36SX6QXP.cjs} +31 -12
  53. package/dist/chunk-36SX6QXP.cjs.map +1 -0
  54. package/dist/{chunk-SDBBMD4N.js → chunk-36VYWVQU.js} +3 -3
  55. package/dist/{chunk-SDBBMD4N.js.map → chunk-36VYWVQU.js.map} +1 -1
  56. package/dist/chunk-4DKY6RIU.js +1253 -0
  57. package/dist/chunk-4DKY6RIU.js.map +1 -0
  58. package/dist/chunk-4QKOZYMV.js +9 -0
  59. package/dist/chunk-4QKOZYMV.js.map +1 -0
  60. package/dist/{chunk-WIC7DRXW.js → chunk-57JM6NW3.js} +9 -19
  61. package/dist/chunk-57JM6NW3.js.map +1 -0
  62. package/dist/chunk-5WWEYV4H.cjs +5113 -0
  63. package/dist/chunk-5WWEYV4H.cjs.map +1 -0
  64. package/dist/chunk-6KQEICJ6.cjs +12 -0
  65. package/dist/{chunk-MKJ4KXL5.cjs.map → chunk-6KQEICJ6.cjs.map} +1 -1
  66. package/dist/{chunk-DZAICA5J.js → chunk-6NKSE5AU.js} +4 -4
  67. package/dist/{chunk-DZAICA5J.js.map → chunk-6NKSE5AU.js.map} +1 -1
  68. package/dist/{chunk-KKBDXCLQ.js → chunk-6NLYIMJO.js} +4 -4
  69. package/dist/{chunk-KKBDXCLQ.js.map → chunk-6NLYIMJO.js.map} +1 -1
  70. package/dist/{chunk-BFUOME67.cjs → chunk-7B7I7YAW.cjs} +20 -11
  71. package/dist/chunk-7B7I7YAW.cjs.map +1 -0
  72. package/dist/{chunk-ZDKTPBGV.js → chunk-7G5IYROL.js} +6 -548
  73. package/dist/chunk-7G5IYROL.js.map +1 -0
  74. package/dist/{chunk-3DMMGT6S.js → chunk-7QFRK6PU.js} +4 -8
  75. package/dist/chunk-7QFRK6PU.js.map +1 -0
  76. package/dist/chunk-A4C4NJ5U.cjs +12 -0
  77. package/dist/chunk-A4C4NJ5U.cjs.map +1 -0
  78. package/dist/{chunk-CHAOFCHV.js → chunk-AH2A74OZ.js} +3 -3
  79. package/dist/{chunk-CHAOFCHV.js.map → chunk-AH2A74OZ.js.map} +1 -1
  80. package/dist/{chunk-UGHQV7MP.cjs → chunk-B3MN7EJR.cjs} +228 -162
  81. package/dist/chunk-B3MN7EJR.cjs.map +1 -0
  82. package/dist/{chunk-TZEGUG6D.cjs → chunk-BZ5MVITP.cjs} +4 -4
  83. package/dist/{chunk-TZEGUG6D.cjs.map → chunk-BZ5MVITP.cjs.map} +1 -1
  84. package/dist/{chunk-YVF2EM7B.js → chunk-CAI6SMP6.js} +3 -3
  85. package/dist/{chunk-YVF2EM7B.js.map → chunk-CAI6SMP6.js.map} +1 -1
  86. package/dist/{chunk-JONXFAPO.js → chunk-CBOD7TXH.js} +5 -5
  87. package/dist/{chunk-JONXFAPO.js.map → chunk-CBOD7TXH.js.map} +1 -1
  88. package/dist/{chunk-FQPEMEWX.cjs → chunk-CRZ56SZU.cjs} +81 -32
  89. package/dist/chunk-CRZ56SZU.cjs.map +1 -0
  90. package/dist/{chunk-DO7SAMEK.cjs → chunk-D3GWARN7.cjs} +47 -47
  91. package/dist/{chunk-DO7SAMEK.cjs.map → chunk-D3GWARN7.cjs.map} +1 -1
  92. package/dist/{chunk-QTD6HX4O.js → chunk-D3OUDFU7.js} +5 -5
  93. package/dist/{chunk-QTD6HX4O.js.map → chunk-D3OUDFU7.js.map} +1 -1
  94. package/dist/{chunk-2QGYQBS2.cjs → chunk-DWUDZ66O.cjs} +10 -10
  95. package/dist/{chunk-2QGYQBS2.cjs.map → chunk-DWUDZ66O.cjs.map} +1 -1
  96. package/dist/chunk-EKG2UXNX.cjs +23 -0
  97. package/dist/chunk-EKG2UXNX.cjs.map +1 -0
  98. package/dist/chunk-FMMW3KX7.cjs +148 -0
  99. package/dist/chunk-FMMW3KX7.cjs.map +1 -0
  100. package/dist/{chunk-XVWOYKIK.js → chunk-FZHF5UWR.js} +3 -3
  101. package/dist/{chunk-XVWOYKIK.js.map → chunk-FZHF5UWR.js.map} +1 -1
  102. package/dist/chunk-H2VWDQWC.cjs +571 -0
  103. package/dist/chunk-H2VWDQWC.cjs.map +1 -0
  104. package/dist/chunk-H4FY6OZK.js +13 -0
  105. package/dist/chunk-H4FY6OZK.js.map +1 -0
  106. package/dist/{chunk-EDN4Y4ZG.cjs → chunk-H5IJSROF.cjs} +9 -15
  107. package/dist/chunk-H5IJSROF.cjs.map +1 -0
  108. package/dist/chunk-HZUB5CON.js +27 -0
  109. package/dist/chunk-HZUB5CON.js.map +1 -0
  110. package/dist/{chunk-NACVVDWB.js → chunk-I5IOSA27.js} +103 -105
  111. package/dist/chunk-I5IOSA27.js.map +1 -0
  112. package/dist/{chunk-OI2GQ25X.cjs → chunk-I7YAY2VQ.cjs} +7 -7
  113. package/dist/{chunk-OI2GQ25X.cjs.map → chunk-I7YAY2VQ.cjs.map} +1 -1
  114. package/dist/chunk-IRCWIA3R.js +20 -0
  115. package/dist/chunk-IRCWIA3R.js.map +1 -0
  116. package/dist/chunk-IVQBLXBK.cjs +55 -0
  117. package/dist/chunk-IVQBLXBK.cjs.map +1 -0
  118. package/dist/{chunk-7SQSZN2J.js → chunk-IZD4HTCP.js} +5 -5
  119. package/dist/{chunk-7SQSZN2J.js.map → chunk-IZD4HTCP.js.map} +1 -1
  120. package/dist/{chunk-3FPR224C.cjs → chunk-JHRUZ73O.cjs} +116 -107
  121. package/dist/chunk-JHRUZ73O.cjs.map +1 -0
  122. package/dist/{chunk-EZEEWCFJ.cjs → chunk-JQKMEKKW.cjs} +525 -298
  123. package/dist/chunk-JQKMEKKW.cjs.map +1 -0
  124. package/dist/chunk-JVA3KDEA.cjs +691 -0
  125. package/dist/chunk-JVA3KDEA.cjs.map +1 -0
  126. package/dist/{chunk-5K2BKEBD.js → chunk-K46SDNQD.js} +10 -4
  127. package/dist/chunk-K46SDNQD.js.map +1 -0
  128. package/dist/{chunk-7LZJNLA5.js → chunk-K67P5DLL.js} +108 -42
  129. package/dist/chunk-K67P5DLL.js.map +1 -0
  130. package/dist/{chunk-3G5W2U2L.cjs → chunk-KACEYDYV.cjs} +335 -258
  131. package/dist/chunk-KACEYDYV.cjs.map +1 -0
  132. package/dist/{chunk-JFRT7S3B.cjs → chunk-L6EVYIID.cjs} +318 -478
  133. package/dist/chunk-L6EVYIID.cjs.map +1 -0
  134. package/dist/{chunk-SHFBB23Q.js → chunk-LI4K2KEJ.js} +6 -4
  135. package/dist/chunk-LI4K2KEJ.js.map +1 -0
  136. package/dist/chunk-LKZDQ2B4.js +1581 -0
  137. package/dist/chunk-LKZDQ2B4.js.map +1 -0
  138. package/dist/{chunk-WODMN3Q2.cjs → chunk-LLFPQOBA.cjs} +27 -27
  139. package/dist/{chunk-WODMN3Q2.cjs.map → chunk-LLFPQOBA.cjs.map} +1 -1
  140. package/dist/{chunk-P6YLZTRE.js → chunk-LZMQ3SFK.js} +3 -3
  141. package/dist/{chunk-P6YLZTRE.js.map → chunk-LZMQ3SFK.js.map} +1 -1
  142. package/dist/{chunk-HEV35TGT.js → chunk-M3VTS3F6.js} +13 -4
  143. package/dist/chunk-M3VTS3F6.js.map +1 -0
  144. package/dist/{chunk-TQHGE7UC.cjs → chunk-M5MSP3BI.cjs} +18 -10
  145. package/dist/chunk-M5MSP3BI.cjs.map +1 -0
  146. package/dist/{chunk-D4QLTJSM.js → chunk-NBOS7BY3.js} +63 -23
  147. package/dist/chunk-NBOS7BY3.js.map +1 -0
  148. package/dist/chunk-NGQDGL5X.js +140 -0
  149. package/dist/chunk-NGQDGL5X.js.map +1 -0
  150. package/dist/{chunk-SIT26LAZ.cjs → chunk-NLX5OWK7.cjs} +33 -5
  151. package/dist/chunk-NLX5OWK7.cjs.map +1 -0
  152. package/dist/chunk-NUQ2YFFH.cjs +1637 -0
  153. package/dist/chunk-NUQ2YFFH.cjs.map +1 -0
  154. package/dist/{chunk-UMGZDVOA.cjs → chunk-OGL4X4PH.cjs} +206 -208
  155. package/dist/chunk-OGL4X4PH.cjs.map +1 -0
  156. package/dist/{chunk-LRQKXRXO.cjs → chunk-OTNTGEXR.cjs} +4 -4
  157. package/dist/{chunk-LRQKXRXO.cjs.map → chunk-OTNTGEXR.cjs.map} +1 -1
  158. package/dist/chunk-OTWE63BW.js +53 -0
  159. package/dist/chunk-OTWE63BW.js.map +1 -0
  160. package/dist/chunk-PC5NGH5A.js +549 -0
  161. package/dist/chunk-PC5NGH5A.js.map +1 -0
  162. package/dist/{chunk-26YKDNUD.cjs → chunk-PS3TUWJM.cjs} +12 -10
  163. package/dist/chunk-PS3TUWJM.cjs.map +1 -0
  164. package/dist/{chunk-OMZ37BM2.js → chunk-PVFFH7TL.js} +5 -5
  165. package/dist/{chunk-OMZ37BM2.js.map → chunk-PVFFH7TL.js.map} +1 -1
  166. package/dist/chunk-QCD5JKU4.cjs +15 -0
  167. package/dist/chunk-QCD5JKU4.cjs.map +1 -0
  168. package/dist/{chunk-UGHG7PGX.js → chunk-QG5VEOKX.js} +30 -4
  169. package/dist/chunk-QG5VEOKX.js.map +1 -0
  170. package/dist/{chunk-TUNPBZY3.cjs → chunk-QLLZM5I3.cjs} +4 -4
  171. package/dist/{chunk-TUNPBZY3.cjs.map → chunk-QLLZM5I3.cjs.map} +1 -1
  172. package/dist/{chunk-BRRP76WO.js → chunk-RCBG6YMT.js} +781 -375
  173. package/dist/chunk-RCBG6YMT.js.map +1 -0
  174. package/dist/{chunk-LTXQOEIC.js → chunk-RI7RJH4G.js} +281 -204
  175. package/dist/chunk-RI7RJH4G.js.map +1 -0
  176. package/dist/{chunk-GYEG3ZLZ.cjs → chunk-RJMHU2MG.cjs} +121 -18
  177. package/dist/chunk-RJMHU2MG.cjs.map +1 -0
  178. package/dist/{chunk-GLHXM7C4.js → chunk-RVUL2HXY.js} +61 -23
  179. package/dist/chunk-RVUL2HXY.js.map +1 -0
  180. package/dist/chunk-RWUWTJQY.cjs +30 -0
  181. package/dist/chunk-RWUWTJQY.cjs.map +1 -0
  182. package/dist/{chunk-2O4PCIZ6.cjs → chunk-S5GU4LUN.cjs} +13 -13
  183. package/dist/{chunk-2O4PCIZ6.cjs.map → chunk-S5GU4LUN.cjs.map} +1 -1
  184. package/dist/{chunk-JPD2CTC3.js → chunk-SDPWO2Z5.js} +7 -7
  185. package/dist/{chunk-JPD2CTC3.js.map → chunk-SDPWO2Z5.js.map} +1 -1
  186. package/dist/{chunk-OVI7IXYX.js → chunk-SLGGT2XD.js} +3 -3
  187. package/dist/{chunk-OVI7IXYX.js.map → chunk-SLGGT2XD.js.map} +1 -1
  188. package/dist/{chunk-ROR5ZR6A.cjs → chunk-TIJUA4I6.cjs} +45 -45
  189. package/dist/{chunk-ROR5ZR6A.cjs.map → chunk-TIJUA4I6.cjs.map} +1 -1
  190. package/dist/{chunk-AOSSQDVO.cjs → chunk-TM54OBHX.cjs} +13 -13
  191. package/dist/{chunk-AOSSQDVO.cjs.map → chunk-TM54OBHX.cjs.map} +1 -1
  192. package/dist/{chunk-KF6K7TGH.js → chunk-TYEYRCXL.js} +766 -433
  193. package/dist/chunk-TYEYRCXL.js.map +1 -0
  194. package/dist/{chunk-Z2JCLZFJ.js → chunk-UKOVGCRN.js} +2151 -570
  195. package/dist/chunk-UKOVGCRN.js.map +1 -0
  196. package/dist/chunk-UYKDYE5D.cjs +12 -0
  197. package/dist/{chunk-CICO5GXD.cjs.map → chunk-UYKDYE5D.cjs.map} +1 -1
  198. package/dist/{chunk-S5TERQVW.js → chunk-VAAC7L57.js} +284 -66
  199. package/dist/chunk-VAAC7L57.js.map +1 -0
  200. package/dist/{chunk-7UOLHNWC.cjs → chunk-VKHXYVN7.cjs} +22 -33
  201. package/dist/chunk-VKHXYVN7.cjs.map +1 -0
  202. package/dist/{chunk-6NGW27EO.cjs → chunk-VLBTRXA2.cjs} +10 -10
  203. package/dist/{chunk-6NGW27EO.cjs.map → chunk-VLBTRXA2.cjs.map} +1 -1
  204. package/dist/{chunk-YIURNGXI.js → chunk-VUQZNUHU.js} +22 -6
  205. package/dist/chunk-VUQZNUHU.js.map +1 -0
  206. package/dist/{chunk-YYUHLYM2.cjs → chunk-WDM5WQK4.cjs} +183 -143
  207. package/dist/chunk-WDM5WQK4.cjs.map +1 -0
  208. package/dist/{chunk-ZFMCDJGB.js → chunk-WFSYYU4W.js} +70 -220
  209. package/dist/chunk-WFSYYU4W.js.map +1 -0
  210. package/dist/{chunk-SR725PWF.cjs → chunk-WRBV2FNH.cjs} +2065 -1659
  211. package/dist/chunk-WRBV2FNH.cjs.map +1 -0
  212. package/dist/{chunk-MRDBBHIZ.cjs → chunk-X4GDXBOP.cjs} +2 -2
  213. package/dist/chunk-X4GDXBOP.cjs.map +1 -0
  214. package/dist/chunk-XORONCV3.js +202 -0
  215. package/dist/chunk-XORONCV3.js.map +1 -0
  216. package/dist/{chunk-D5R42W5D.js → chunk-XZW2CTNO.js} +115 -12
  217. package/dist/chunk-XZW2CTNO.js.map +1 -0
  218. package/dist/{chunk-ZLONH2UD.js → chunk-YDEJQWOL.js} +2 -2
  219. package/dist/chunk-YDEJQWOL.js.map +1 -0
  220. package/dist/{chunk-2TYSSBU5.js → chunk-YT2IVFAI.js} +30 -21
  221. package/dist/chunk-YT2IVFAI.js.map +1 -0
  222. package/dist/chunk-ZGVTNKTX.cjs +217 -0
  223. package/dist/chunk-ZGVTNKTX.cjs.map +1 -0
  224. package/dist/core/index.cjs +29 -28
  225. package/dist/core/index.d.cts +4 -4
  226. package/dist/core/index.d.ts +4 -4
  227. package/dist/core/index.js +9 -8
  228. package/dist/{ddl-D_oW-EVO.d.ts → ddl-BvcbgzHo.d.ts} +3 -3
  229. package/dist/{ddl-BL1NZLMY.d.cts → ddl-Ufebz5q5.d.cts} +3 -3
  230. package/dist/graph-extension/index.cjs +21 -20
  231. package/dist/graph-extension/index.d.cts +2 -4
  232. package/dist/graph-extension/index.d.ts +2 -4
  233. package/dist/graph-extension/index.js +5 -4
  234. package/dist/graph-merge/index.cjs +324 -307
  235. package/dist/graph-merge/index.cjs.map +1 -1
  236. package/dist/graph-merge/index.d.cts +8 -9
  237. package/dist/graph-merge/index.d.ts +8 -9
  238. package/dist/graph-merge/index.js +51 -34
  239. package/dist/graph-merge/index.js.map +1 -1
  240. package/dist/index.cjs +224 -222
  241. package/dist/index.cjs.map +1 -1
  242. package/dist/index.d.cts +11 -12
  243. package/dist/index.d.ts +11 -12
  244. package/dist/index.js +38 -36
  245. package/dist/index.js.map +1 -1
  246. package/dist/indexes/index.cjs +15 -13
  247. package/dist/indexes/index.d.cts +4 -4
  248. package/dist/indexes/index.d.ts +4 -4
  249. package/dist/indexes/index.js +8 -6
  250. package/dist/{ingestion-import-target-dNeL7iAv.d.ts → ingestion-import-target-CAs1OX-l.d.cts} +1 -1
  251. package/dist/{ingestion-import-target-XPxZYw89.d.cts → ingestion-import-target-DCQSPfNx.d.ts} +1 -1
  252. package/dist/interchange/index.cjs +57 -54
  253. package/dist/interchange/index.cjs.map +1 -1
  254. package/dist/interchange/index.d.cts +19 -8
  255. package/dist/interchange/index.d.ts +19 -8
  256. package/dist/interchange/index.js +21 -18
  257. package/dist/interchange/index.js.map +1 -1
  258. package/dist/local-store-impl-6DDTFM32.cjs +77 -0
  259. package/dist/local-store-impl-6DDTFM32.cjs.map +1 -0
  260. package/dist/local-store-impl-OXTOVU2J.js +75 -0
  261. package/dist/local-store-impl-OXTOVU2J.js.map +1 -0
  262. package/dist/{manager-CYaff3n3.d.cts → manager-B68OrPR2.d.ts} +29 -2
  263. package/dist/{manager-D9eRT_ns.d.ts → manager-D_t7oK69.d.cts} +29 -2
  264. package/dist/pglite-store-impl-6EMZGL7K.js +73 -0
  265. package/dist/pglite-store-impl-6EMZGL7K.js.map +1 -0
  266. package/dist/pglite-store-impl-GJG3Y7RP.cjs +75 -0
  267. package/dist/pglite-store-impl-GJG3Y7RP.cjs.map +1 -0
  268. package/dist/{postgres-CcL4bAHS.d.ts → postgres-BPLSVyHM.d.ts} +279 -2
  269. package/dist/{postgres-DMj39MEu.d.cts → postgres-CqvtFC2y.d.cts} +279 -2
  270. package/dist/profiler/index.d.cts +9 -9
  271. package/dist/profiler/index.d.ts +9 -9
  272. package/dist/provenance/index.cjs +59 -44
  273. package/dist/provenance/index.cjs.map +1 -1
  274. package/dist/provenance/index.d.cts +7 -7
  275. package/dist/provenance/index.d.ts +7 -7
  276. package/dist/provenance/index.js +28 -13
  277. package/dist/provenance/index.js.map +1 -1
  278. package/dist/{repair-validity-windows-BFNZvd_H.d.cts → repair-validity-windows-DEzCKAdy.d.cts} +7 -3
  279. package/dist/{repair-validity-windows-DlUSqwCg.d.ts → repair-validity-windows-GMdaS2AH.d.ts} +7 -3
  280. package/dist/resolve-D_H8MHtq.d.ts +1805 -0
  281. package/dist/resolve-WEW8gWws.d.cts +1805 -0
  282. package/dist/schema/index.cjs +48 -46
  283. package/dist/schema/index.d.cts +4 -6
  284. package/dist/schema/index.d.ts +4 -6
  285. package/dist/schema/index.js +21 -19
  286. package/dist/{searchable-bpE1bBfc.d.ts → searchable-C_UREI9K.d.ts} +1 -1
  287. package/dist/{searchable-DHJMh_nj.d.cts → searchable-ClgET_i7.d.cts} +1 -1
  288. package/dist/{sqlite-YppHrNFb.d.cts → sqlite-D1mXO9Kp.d.cts} +310 -2
  289. package/dist/{sqlite-D7Oz0SQh.d.ts → sqlite-MZA3oZNB.d.ts} +310 -2
  290. package/dist/{store-bphCSo7z.d.cts → store-CuFX7fCx.d.cts} +117 -31
  291. package/dist/{store-DRrFCx5x.d.ts → store-D-ZjXQpW.d.ts} +117 -31
  292. package/dist/{temporal-CbnLzTmM.d.ts → temporal-CpyEiRY8.d.cts} +1 -1
  293. package/dist/{temporal-5GqpYCk2.d.cts → temporal-y0Aep9Su.d.ts} +1 -1
  294. package/dist/{types-BqFZTQmV.d.cts → types-6yf0Vv-_.d.cts} +2016 -94
  295. package/dist/{types-BqFZTQmV.d.ts → types-6yf0Vv-_.d.ts} +2016 -94
  296. package/dist/{types-Bx74kaTt.d.ts → types-DzJ4dlzk.d.cts} +1 -1
  297. package/dist/{types-CXAhpW-c.d.cts → types-_vVSB9k-.d.ts} +1 -1
  298. package/dist/{where-O-k2wgYm.d.ts → where-DuG2LCLe.d.ts} +1 -1
  299. package/dist/{where-DI_Fqz-X.d.cts → where-Mhf_yyKX.d.cts} +1 -1
  300. package/package.json +7 -2
  301. package/dist/chunk-26YKDNUD.cjs.map +0 -1
  302. package/dist/chunk-2TYSSBU5.js.map +0 -1
  303. package/dist/chunk-3DMMGT6S.js.map +0 -1
  304. package/dist/chunk-3FPR224C.cjs.map +0 -1
  305. package/dist/chunk-3G5W2U2L.cjs.map +0 -1
  306. package/dist/chunk-3KOY4FH3.cjs +0 -934
  307. package/dist/chunk-3KOY4FH3.cjs.map +0 -1
  308. package/dist/chunk-3QNZ5SAJ.cjs +0 -3502
  309. package/dist/chunk-3QNZ5SAJ.cjs.map +0 -1
  310. package/dist/chunk-3U5ABFDW.cjs +0 -259
  311. package/dist/chunk-3U5ABFDW.cjs.map +0 -1
  312. package/dist/chunk-5K2BKEBD.js.map +0 -1
  313. package/dist/chunk-5PRKMB24.cjs +0 -124
  314. package/dist/chunk-5PRKMB24.cjs.map +0 -1
  315. package/dist/chunk-6LN7FIVU.js +0 -107
  316. package/dist/chunk-6LN7FIVU.js.map +0 -1
  317. package/dist/chunk-6SWPJEYN.js +0 -1126
  318. package/dist/chunk-6SWPJEYN.js.map +0 -1
  319. package/dist/chunk-7LZJNLA5.js.map +0 -1
  320. package/dist/chunk-7UOLHNWC.cjs.map +0 -1
  321. package/dist/chunk-BFUOME67.cjs.map +0 -1
  322. package/dist/chunk-BRRP76WO.js.map +0 -1
  323. package/dist/chunk-CICO5GXD.cjs +0 -12
  324. package/dist/chunk-D4QLTJSM.js.map +0 -1
  325. package/dist/chunk-D5R42W5D.js.map +0 -1
  326. package/dist/chunk-EDN4Y4ZG.cjs.map +0 -1
  327. package/dist/chunk-EZEEWCFJ.cjs.map +0 -1
  328. package/dist/chunk-FA2AFWLP.cjs.map +0 -1
  329. package/dist/chunk-FQPEMEWX.cjs.map +0 -1
  330. package/dist/chunk-GLHXM7C4.js.map +0 -1
  331. package/dist/chunk-GYEG3ZLZ.cjs.map +0 -1
  332. package/dist/chunk-HDL2ARHX.cjs +0 -1156
  333. package/dist/chunk-HDL2ARHX.cjs.map +0 -1
  334. package/dist/chunk-HEV35TGT.js.map +0 -1
  335. package/dist/chunk-I4GAZH5Z.js +0 -913
  336. package/dist/chunk-I4GAZH5Z.js.map +0 -1
  337. package/dist/chunk-JB6T4GLL.cjs.map +0 -1
  338. package/dist/chunk-JBQQ7THH.js +0 -20
  339. package/dist/chunk-JBQQ7THH.js.map +0 -1
  340. package/dist/chunk-JFRT7S3B.cjs.map +0 -1
  341. package/dist/chunk-KF6K7TGH.js.map +0 -1
  342. package/dist/chunk-L3LQNR34.cjs +0 -1254
  343. package/dist/chunk-L3LQNR34.cjs.map +0 -1
  344. package/dist/chunk-LTXQOEIC.js.map +0 -1
  345. package/dist/chunk-MKJ4KXL5.cjs +0 -12
  346. package/dist/chunk-MRDBBHIZ.cjs.map +0 -1
  347. package/dist/chunk-NACVVDWB.js.map +0 -1
  348. package/dist/chunk-NVY5CJFP.js +0 -244
  349. package/dist/chunk-NVY5CJFP.js.map +0 -1
  350. package/dist/chunk-PWLJ77UV.cjs +0 -23
  351. package/dist/chunk-PWLJ77UV.cjs.map +0 -1
  352. package/dist/chunk-S5TERQVW.js.map +0 -1
  353. package/dist/chunk-SHFBB23Q.js.map +0 -1
  354. package/dist/chunk-SIT26LAZ.cjs.map +0 -1
  355. package/dist/chunk-SR725PWF.cjs.map +0 -1
  356. package/dist/chunk-TQHGE7UC.cjs.map +0 -1
  357. package/dist/chunk-UGHG7PGX.js.map +0 -1
  358. package/dist/chunk-UGHQV7MP.cjs.map +0 -1
  359. package/dist/chunk-UMGZDVOA.cjs.map +0 -1
  360. package/dist/chunk-WIC7DRXW.js.map +0 -1
  361. package/dist/chunk-YIURNGXI.js.map +0 -1
  362. package/dist/chunk-YYUHLYM2.cjs.map +0 -1
  363. package/dist/chunk-Z2JCLZFJ.js.map +0 -1
  364. package/dist/chunk-ZDKTPBGV.js.map +0 -1
  365. package/dist/chunk-ZFMCDJGB.js.map +0 -1
  366. package/dist/chunk-ZLONH2UD.js.map +0 -1
  367. package/dist/index-COs_z6nV.d.cts +0 -1132
  368. package/dist/index-D7d1u2gr.d.ts +0 -1132
  369. package/dist/materialize-indexes-DJ3ykH59.d.ts +0 -266
  370. package/dist/materialize-indexes-DTtAnvfY.d.cts +0 -266
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/store/row-mappers.ts","../src/store/constraints.ts","../src/store/validity-end.ts","../src/store/operations/already-exists.ts","../src/store/operations/node-operations.ts"],"names":["row"],"mappings":";;;;;;;;;;;;;;;;;;AAiCA,SAAS,gBAAmB,KAAA,EAA4C;AACtE,EAAA,OAAO,KAAA,KAAU,OAAO,MAAA,GAAY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gB;AAAA,SAC1C;AAAA,MACF,CAAA,MAAO;AACL,QAAA,OAAA,CAAQ,KAAK,IAAI,EAAE,IAAA,EAAM,UAAU,WAAW,CAAA,EAAG,QAAQ,OAAA,EAAQ;AAAA,MACnE;AAAA,IACF;AAGA,IAAA,KAAA,MAAW,EAAE,KAAA,EAAO,WAAA,EAAY,IAAK,WAAA,EAAa;AAChD,MAAA,MAAM,YAAA,GAAe,cAAA,CAAe,OAAA,CAAQ,WAAW,CAAC,CAAA;AACxD,MAAA,OAAA,CAAQ,KAAK,CAAA,GAAI,EAAE,MAAM,YAAA,CAAa,IAAA,EAAM,QAAQ,OAAA,EAAQ;AAAA,IAC9D;AAEA,IAAA,OAAO,OAAA;AAAA,EACT;AAEA,EAAA,IAAI;AACF,IAAA,OAAO,MAAM,OAAA,EAAQ;AAAA,EACvB,SAAS,KAAA,EAAO;AACd,IAAA,IAAI,EAAE,KAAA,YAAiB,eAAA,CAAA,EAAkB,MAAM,KAAA;AAC/C,IAAA,OAAO,OAAA,EAAQ;AAAA,EACjB;AACF","file":"chunk-KF6K7TGH.js","sourcesContent":["/**\n * Row Mappers for Store\n *\n * Transforms database rows into typed Node and Edge objects.\n */\nimport {\n type EdgeRow as BackendEdgeRow,\n type NodeRow as BackendNodeRow,\n rowPropsToObject,\n} from \"../backend/types\";\nimport {\n filterReservedKeys,\n RESERVED_EDGE_KEYS,\n RESERVED_NODE_KEYS,\n} from \"./reserved-keys\";\nimport { type Edge, type EdgeMeta, type Node, type NodeMeta } from \"./types\";\n\n/**\n * Raw node row from database (without graph_id).\n * Derived from BackendNodeRow so BackendNodeRow is assignable without casts.\n */\nexport type NodeRow = Omit<BackendNodeRow, \"graph_id\">;\n\n/**\n * Raw edge row from database (without graph_id).\n * Derived from BackendEdgeRow so BackendEdgeRow is assignable without casts.\n */\nexport type EdgeRow = Omit<BackendEdgeRow, \"graph_id\">;\n\n/**\n * Converts null to undefined for consistent typing.\n * Database backends return null for missing values, but our types use undefined.\n */\nfunction nullToUndefined<T>(value: T | null | undefined): T | undefined {\n return value === null ? undefined : value;\n}\n\n/**\n * Transforms a database row into a typed Node object.\n *\n * Props are spread at top level, metadata goes under `meta`.\n * Reserved keys (id, kind, meta) in props are filtered out to prevent collisions.\n * Null values from database are normalized to undefined.\n */\nexport function rowToNode(row: NodeRow): Node {\n const rawProps = rowPropsToObject(row.props);\n const props = filterReservedKeys(rawProps, RESERVED_NODE_KEYS);\n return {\n kind: row.kind,\n id: row.id as Node[\"id\"],\n meta: rowToNodeMeta(row),\n ...props,\n };\n}\n\nexport function rowToNodeMeta(\n row: Pick<\n NodeRow,\n | \"version\"\n | \"valid_from\"\n | \"valid_to\"\n | \"created_at\"\n | \"updated_at\"\n | \"deleted_at\"\n >,\n): NodeMeta {\n return {\n version: row.version,\n validFrom: nullToUndefined(row.valid_from),\n validTo: nullToUndefined(row.valid_to),\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n deletedAt: nullToUndefined(row.deleted_at),\n };\n}\n\n/**\n * Transforms a database row into a typed Edge object.\n *\n * Props are spread at top level, metadata goes under `meta`.\n * Reserved keys in props are filtered out to prevent collisions.\n * Null values from database are normalized to undefined.\n */\nexport function rowToEdge(row: EdgeRow): Edge {\n const rawProps = rowPropsToObject(row.props);\n const props = filterReservedKeys(rawProps, RESERVED_EDGE_KEYS);\n return {\n id: row.id,\n kind: row.kind,\n fromKind: row.from_kind,\n fromId: row.from_id,\n toKind: row.to_kind,\n toId: row.to_id,\n meta: rowToEdgeMeta(row),\n ...props,\n } as Edge;\n}\n\nexport function rowToEdgeMeta(\n row: Pick<\n EdgeRow,\n \"valid_from\" | \"valid_to\" | \"created_at\" | \"updated_at\" | \"deleted_at\"\n >,\n): EdgeMeta {\n return {\n validFrom: nullToUndefined(row.valid_from),\n validTo: nullToUndefined(row.valid_to),\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n deletedAt: nullToUndefined(row.deleted_at),\n };\n}\n","/**\n * Constraint Checking for Store Operations\n *\n * Handles checking disjointness and cardinality constraints.\n *\n * ## The invariant these probes depend on\n *\n * **A declared constraint's probe and the write it guards commit under one\n * per-graph mutual exclusion, on every backend.** Every check in this module is\n * an APPLICATION probe: it reads, decides, and returns, and the caller then\n * writes. Nothing in the schema re-decides at write time, because for each of\n * these constraints the available key covers a different axis than the\n * constraint declares:\n *\n * - edge cardinality `one` / `unique` / `oneActive` is a predicate over\n * `(kind, from)` or `(kind, from, to)`, while the edges table's only\n * uniqueness is its `(graph_id, id)` primary key;\n * - disjointness is a predicate over `(graph_id, id)` ACROSS kinds, while the\n * nodes primary key is `(graph_id, kind, id)` — the same id under a disjoint\n * kind is a different row by construction;\n * - `scope: \"kindWithSubClasses\"` uniqueness probes the root kind and every\n * descendant, while `insertUniquenessEntries` reserves one row under the\n * node's OWN kind and the uniques primary key is\n * `(graph_id, node_kind, constraint_name, key)` — sibling kinds are distinct\n * rows that can never collide (see {@link file://./uniqueness.ts}).\n *\n * So the probe is only as good as the serialization around it. SQLite supplies\n * that for free (`BEGIN IMMEDIATE` admits one writer per database). PostgreSQL\n * supplied it only when history or revision tracking was enabled, because only\n * those took the per-graph advisory lock — leaving a default PostgreSQL store\n * open to two writers that both read \"no conflict\" and both commit.\n * {@link edgeWriteNeedsConstraintFence} / {@link nodeWriteNeedsConstraintFence}\n * are what the write paths ask so they take that same per-graph lock whenever\n * one of these probes is in play, and only then.\n */\nimport { type GraphBackend, type TransactionBackend } from \"../backend/types\";\nimport {\n checkCardinality,\n checkDisjointness,\n checkUniqueEdge,\n getKindsForUniquenessCheck,\n} from \"../constraints\";\nimport { type Cardinality, type UniqueConstraint } from \"../core/types\";\nimport { type KindRegistry } from \"../registry/kind-registry\";\n\n/**\n * Context for constraint operations.\n */\nexport type ConstraintContext = Readonly<{\n graphId: string;\n registry: KindRegistry;\n backend: GraphBackend | TransactionBackend;\n}>;\n\n/**\n * WHICH declared constraint makes a write constrained.\n *\n * The classification names the reason rather than answering yes/no, because\n * the reason is load-bearing twice over: it is what the fence is taken FOR, and\n * — on a backend that cannot hold the fence — it is what the refusal has to\n * tell the caller. \"This backend cannot fence constrained writes\" is unusable\n * advice; \"your `cardinality: 'one'` edge cannot be enforced here\" is\n * actionable, and only the classifier knows which it was.\n */\nexport type ConstraintFenceReason =\n /** Edge cardinality `one` / `unique` / `oneActive`. */\n | \"edgeCardinality\"\n /** `getOrCreateByEndpoints` converging on a match key no key backs. */\n | \"edgeMatchKeyConvergence\"\n /** A `disjointWith` axiom, probed across kinds the node PK cannot span. */\n | \"nodeDisjointness\"\n /** A unique constraint whose scope spans more than the node's own kind. */\n | \"nodeUniquenessScope\";\n\n/**\n * The constraint that makes an edge write of this cardinality constrained, or\n * `undefined` when it is not.\n *\n * `many` declares no constraint, so its create runs no cardinality probe and\n * must NOT pay for the lock — the fence is for writes that check something, not\n * for writes in general. Every other cardinality counts or existence-tests\n * sibling edges before inserting, and nothing in the schema repeats that test.\n *\n * The one owner of this classification: `checkCardinalityConstraint`'s `many`\n * arm and this predicate are the same decision seen from two sides, and a\n * second inline `!== \"many\"` at a write path would be the copy that drifts.\n */\nexport function edgeWriteNeedsConstraintFence(\n cardinality: Cardinality,\n): ConstraintFenceReason | undefined {\n return cardinality === \"many\" ? undefined : \"edgeCardinality\";\n}\n\n/**\n * The constraint that makes a node write of this kind constrained, or\n * `undefined` when it is not. A kind can qualify on both counts; the reason\n * reported is the first that applies, which is enough to name the class in a\n * refusal.\n *\n * Two probe families qualify, and they are reached by different operations:\n *\n * - **Disjointness** is probed only where a node comes into existence under a\n * kind — the create/resurrect preparation. An in-place update cannot change a\n * node's kind, so it re-derives no cross-kind verdict and needs no fence for\n * this reason.\n * - **Shared-scope uniqueness** is probed by create AND update. It qualifies\n * only when the constraint's scope actually spans more than the node's own\n * kind: a single-kind scope probes exactly the `(graph_id, node_kind,\n * constraint_name, key)` row that `insertUnique` then reserves, so the\n * uniques primary key IS the fence and the write needs no other. Deciding\n * this by expanding the scope — rather than by testing `scope !== \"kind\"` —\n * keeps the answer true for a `kindWithSubClasses` constraint on a kind that\n * has no hierarchy, which is backed by its own key exactly like a `kind`\n * scope.\n */\nexport function nodeWriteNeedsConstraintFence(\n registry: KindRegistry,\n kind: string,\n uniqueConstraints: readonly UniqueConstraint[],\n operation: \"create\" | \"update\",\n): ConstraintFenceReason | undefined {\n if (operation === \"create\" && registry.getDisjointKinds(kind).length > 0) {\n return \"nodeDisjointness\";\n }\n const sharedScope = uniqueConstraints.some(\n (constraint) =>\n getKindsForUniquenessCheck(kind, constraint.scope, registry).length > 1,\n );\n return sharedScope ? \"nodeUniquenessScope\" : undefined;\n}\n\n/**\n * Checks disjointness constraints for a node.\n *\n * Ensures that a node with a given ID doesn't exist in any disjoint kinds.\n *\n * @throws ValidationError if disjointness constraint is violated\n */\nexport async function checkDisjointnessConstraint(\n ctx: ConstraintContext,\n kind: string,\n id: string,\n): Promise<void> {\n // Get all kinds that are disjoint with this kind\n const disjointKinds = ctx.registry.getDisjointKinds(kind);\n\n // For each disjoint kind, check if a node with this ID exists\n for (const disjointKind of disjointKinds) {\n const existing = await ctx.backend.getNode(ctx.graphId, disjointKind, id);\n if (existing && !existing.deleted_at) {\n const error = checkDisjointness(id, kind, [disjointKind], ctx.registry);\n if (error) throw error;\n }\n }\n}\n\n/**\n * Checks cardinality constraints for an edge.\n *\n * @throws CardinalityError if cardinality constraint is violated\n */\nexport async function checkCardinalityConstraint(\n ctx: ConstraintContext,\n edgeKind: string,\n cardinality: \"many\" | \"one\" | \"unique\" | \"oneActive\",\n fromKind: string,\n fromId: string,\n toKind: string,\n toId: string,\n validTo: string | undefined,\n): Promise<void> {\n switch (cardinality) {\n case \"many\": {\n // No constraint - allow any number of edges\n return;\n }\n\n case \"one\": {\n // At most one edge of this kind from this source\n const count = await ctx.backend.countEdgesFrom({\n graphId: ctx.graphId,\n edgeKind,\n fromKind,\n fromId,\n });\n const error = checkCardinality(\n edgeKind,\n fromKind,\n fromId,\n \"one\",\n count,\n false,\n );\n if (error) throw error;\n return;\n }\n\n case \"unique\": {\n // At most one edge between this specific source-target pair\n const exists = await ctx.backend.edgeExistsBetween({\n graphId: ctx.graphId,\n edgeKind,\n fromKind,\n fromId,\n toKind,\n toId,\n });\n const error = checkUniqueEdge(\n edgeKind,\n fromKind,\n fromId,\n toKind,\n toId,\n exists ? 1 : 0,\n );\n if (error) throw error;\n return;\n }\n\n case \"oneActive\": {\n // At most one active edge (valid_to IS NULL) from this source\n // Only check if the new edge will be active (validTo is not set)\n if (validTo !== undefined) {\n // New edge is already ended, no active constraint to check\n return;\n }\n const count = await ctx.backend.countEdgesFrom({\n graphId: ctx.graphId,\n edgeKind,\n fromKind,\n fromId,\n activeOnly: true,\n });\n const error = checkCardinality(\n edgeKind,\n fromKind,\n fromId,\n \"oneActive\",\n count,\n count > 0,\n );\n if (error) throw error;\n return;\n }\n }\n}\n","import type { GraphBackend, TransactionBackend } from \"../backend/types\";\nimport type { KindEntity } from \"../core/types\";\nimport { ConfigurationError, ValidationError } from \"../errors\";\n\nexport type ValidityEndMutationInput = Readonly<{\n validTo?: string;\n clearValidTo?: true;\n}>;\n\n/** One owner for the mutually-exclusive validity-end write contract. */\nexport function assertValidityEndMutation(\n input: ValidityEndMutationInput,\n context: Readonly<{ entityType: KindEntity; kind: string; id?: string }>,\n): void {\n if (input.validTo === undefined || input.clearValidTo !== true) return;\n throw new ValidationError(\n '\"validTo\" and \"clearValidTo\" are mutually exclusive',\n {\n ...context,\n operation: \"update\",\n issues: [\n {\n path: \"clearValidTo\",\n message: 'Pass either \"validTo\" or \"clearValidTo\", not both',\n },\n ],\n },\n );\n}\n\n/** The end a row will hold after applying this mutation. */\nexport function validityEndAfterMutation(\n input: ValidityEndMutationInput,\n current: string | undefined,\n): string | undefined {\n if (input.clearValidTo === true) return undefined;\n return input.validTo ?? current;\n}\n\n/**\n * Custom backends explicitly opt in to clearing. The store refuses before\n * invoking a backend that has not promised to apply the new state.\n */\nexport function assertClearValidToSupported(\n backend: GraphBackend | TransactionBackend,\n entityType: KindEntity,\n): void {\n if (backend.capabilities.clearValidTo === true) return;\n throw new ConfigurationError(\n `This backend does not support clearing ${entityType} validTo`,\n {\n code: \"CLEAR_VALID_TO_UNSUPPORTED\",\n entityType,\n },\n );\n}\n","/**\n * The create API's \"this identity is already taken\" refusal, and the one\n * translation that turns a driver's duplicate-key report into it.\n *\n * A create learns an id is taken one of two ways: its own existence probe sees\n * the row, or the engine refuses the INSERT. The engine's report used to escape\n * as a `DrizzleQueryError` whose `.message` is the raw SQL text (issue #410), so\n * one condition surfaced as a typed user error down one path and an opaque system\n * error down the other, and a caller could not branch on it at all. Both paths\n * now raise the SAME error, carrying {@link ENTITY_ALREADY_EXISTS_CODE} on its\n * issue.\n *\n * The engine's path is reached two ways, and the second is not a race:\n *\n * - A NODE create probes first, but the probe and the INSERT are two statements.\n * PostgreSQL under its default READ COMMITTED does not serialize two write\n * transactions, so both can probe an absent row and both can then insert it,\n * and the loser finds out from the INSERT. SQLite cannot reach this shape:\n * `BEGIN IMMEDIATE` gives the writer slot to one transaction at a time (pinned\n * by the business-transaction write-lock cases in\n * `tests/backends/sqlite/sqlite-backend.test.ts`), so the loser's probe runs\n * after the winner committed and its verdict stands.\n * - An EDGE create has no existence probe at all — its id is caller-supplied or\n * freshly generated — so the engine's refusal is the ONLY report on EVERY\n * backend, race or no race. That is why the classification covers both\n * dialects and not just PostgreSQL.\n *\n * The backend does the classification (it owns the relation and constraint names\n * the engine reports); this module owns the store-level judgement of what that\n * classification means to a caller.\n */\nimport { type KindEntity } from \"../../core/types\";\nimport {\n DatabaseOperationError,\n ENTITY_ALREADY_EXISTS_CODE,\n ValidationError,\n} from \"../../errors\";\n\n/** An entity the refused statement tried to create. */\ntype AttemptedCreate = Readonly<{ kind: string; id: string }>;\n\n/** Sentence-initial and mid-sentence names for each entity. */\nconst ENTITY_LABELS = {\n node: { title: \"Node\", article: \"A node\" },\n edge: { title: \"Edge\", article: \"An edge\" },\n} as const satisfies Record<\n KindEntity,\n Readonly<{ title: string; article: string }>\n>;\n\nfunction alreadyExistsError(\n entity: KindEntity,\n kind: string,\n id: string | undefined,\n detail: string,\n cause: unknown,\n): ValidationError {\n const label = ENTITY_LABELS[entity];\n return new ValidationError(\n `${label.title} already exists: ${detail}`,\n {\n entityType: entity,\n kind,\n operation: \"create\",\n ...(id === undefined ? {} : { id }),\n issues: [\n {\n path: \"id\",\n code: ENTITY_ALREADY_EXISTS_CODE,\n message: `${label.article} with this ID already exists`,\n },\n ],\n },\n {\n suggestion: `Use a different ID or update the existing ${entity}.`,\n ...(cause === undefined ? {} : { cause }),\n },\n );\n}\n\n/**\n * The refusal a create raises for a taken id: the probe path's error, and the\n * target of the driver-report translation below.\n */\nexport function createAlreadyExistsError(\n entity: KindEntity,\n kind: string,\n id: string,\n): ValidationError {\n return alreadyExistsError(entity, kind, id, `${kind}/${id}`, undefined);\n}\n\nfunction isDuplicateKeyInsertError(\n error: unknown,\n entity: KindEntity,\n): error is DatabaseOperationError {\n return (\n error instanceof DatabaseOperationError &&\n error.details.operation === \"insert\" &&\n error.details.entity === entity &&\n error.details.reason === \"duplicate_key\"\n );\n}\n\n/**\n * Rethrows a classified duplicate-key insert as {@link createAlreadyExistsError},\n * and anything else untouched.\n *\n * A single insert names the row it lost on exactly. A multi-row one cannot: the\n * engine reports that the statement collided without saying which row did, and\n * the transaction is already aborted, so there is nothing left to probe. The\n * refusal then names the statement instead of inventing an attribution — same\n * error type, same issue code, `details.id` simply absent. The count is the\n * refused STATEMENT's rows, which is the caller's batch only until the backend\n * chunks it, so the message claims no more than that. Every batch here comes\n * from one collection, so the kind is always known.\n */\nfunction rethrowAsAlreadyExists(error: unknown, entity: KindEntity): never {\n if (!isDuplicateKeyInsertError(error, entity)) throw error;\n const attempted: readonly AttemptedCreate[] = error.details.attempted ?? [];\n const first = attempted[0];\n if (first === undefined) throw error;\n if (attempted.length === 1) {\n throw alreadyExistsError(\n entity,\n first.kind,\n first.id,\n `${first.kind}/${first.id}`,\n error,\n );\n }\n throw alreadyExistsError(\n entity,\n first.kind,\n undefined,\n `one of the ${attempted.length} ${first.kind} ids in the refused insert`,\n error,\n );\n}\n\n/**\n * Runs an insert (or a group of inserts issued as one unit) and converts a\n * duplicate-key refusal into the create API's already-exists error.\n */\nexport async function withAlreadyExistsTranslation<T>(\n entity: KindEntity,\n run: () => Promise<T>,\n): Promise<T> {\n try {\n return await run();\n } catch (error) {\n rethrowAsAlreadyExists(error, entity);\n }\n}\n","/**\n * Node Operations for Store\n *\n * Handles node CRUD operations: create, update, delete.\n *\n * ## A write asserts every component its verdict READ\n *\n * `performNodeUpdate` is a probe-and-write pair: it reads the row, decides from\n * what it finds, and then writes. Under PostgreSQL READ COMMITTED a concurrent\n * `hardDelete` + recreate re-resolves `(graph_id, kind, id)` between the two,\n * so anything the decision consumed and the statement does not restate is a\n * decision that can land on a row it was never computed for — and the write\n * reports success. Every value read off the probed row, and where it is\n * asserted:\n *\n * - `kind` / `id` — the write key itself, restated in every UPDATE's `WHERE`.\n * - `deleted_at` (which leg runs, and whether to sample a resurrection\n * instant) — asserted as `deleted_at IS NULL` on the in-place leg and\n * `IS NOT NULL` on the resurrecting one, so each leg can only hit a row in\n * the state it was chosen for.\n * - `valid_from` — asserted via `UpdateNodeParams.expectedValidFrom` WHEN the\n * window verdict read it ({@link ValidityWindowVerdict}): the caller stated\n * a `validFrom` to compare against the row's, or a lone `validTo` to invert\n * against it. A plain `update({ props })` states no window, so the verdict\n * is independent of the row's bound and the write carries no predicate for\n * it — the same \"only what it asserted\" rule the edge identity components\n * follow, and for the same reason: inventing a predicate for a component the\n * caller made no claim about refuses writes that are legitimate. A\n * resurrection is judged against the write instant rather than the row's\n * bound, so it asserts none either; its own tombstone predicate fences it.\n * - `props` — read twice, as the merge base for the caller's partial update\n * and as the `oldProps` side of the uniqueness diff — and NOT assertable: a\n * props blob is TEXT on SQLite and `jsonb` on PostgreSQL, and neither\n * comparison is stable under key reordering. Bounded instead, two ways: the\n * sidecar writes are gated on the primary UPDATE's rowcount (see\n * `applyNodeUpdate`), and\n * {@link performNodeUpdateWithResurrectionRecovery} re-reads and re-merges\n * whenever a predicate catches a replaced row.\n * - the uniques-table row behind `getOrCreateByConstraint` — read to resolve\n * WHICH node the key names. Not assertable by the node UPDATE (it is a\n * different table); bounded by the constraint write fence, which makes the\n * probe and the write it authorizes commit under one per-graph mutual\n * exclusion. Its `deleted_at`, however, is NOT the owner of \"does this write\n * resurrect\" — both the single and bulk paths read that from the node row\n * they are about to write, because one decision with two owners drifts.\n */\nimport { deriveBackend } from \"../../backend/derive-backend\";\nimport {\n type GraphBackend,\n type InsertNodeParams,\n isLiveNodeRow,\n type NodeRow as BackendNodeRow,\n rowPropsToObject,\n type TransactionBackend,\n type UniqueRow,\n} from \"../../backend/types\";\nimport {\n checkWherePredicate,\n computeUniqueKey,\n getKindsForUniquenessCheck,\n} from \"../../constraints\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport { assertJsonValue } from \"../../core/json-value\";\nimport {\n type JsonValue,\n type KindEntity,\n type NodeType,\n type UniqueConstraint,\n} from \"../../core/types\";\nimport {\n ConfigurationError,\n DatabaseOperationError,\n KindNotFoundError,\n NodeConstraintNotFoundError,\n NodeIndexNotFoundError,\n NodeNotFoundError,\n UniquenessError,\n ValidationError,\n} from \"../../errors\";\nimport { validateNodeProps } from \"../../errors/validation\";\nimport { refKey } from \"../../identity/service\";\nimport {\n compileIndexWhere,\n compileNodeIndexFieldKeys,\n type IndexCompilationContext,\n} from \"../../indexes/compiler\";\nimport { type NodeIndexDeclaration } from \"../../indexes/types\";\nimport { type ValueType } from \"../../query/ast\";\nimport {\n createSqlSchema,\n DEFAULT_SQL_SCHEMA,\n type SqlSchema,\n} from \"../../query/compiler/schema\";\nimport { getDialect } from \"../../query/dialect\";\nimport { type DialectAdapter } from \"../../query/dialect/types\";\nimport { type JsonPointer, resolveJsonPointer } from \"../../query/json-pointer\";\nimport { sql, type SqlFragment } from \"../../query/sql-fragment\";\nimport type { CompiledSelectSql } from \"../../query/sql-intent\";\nimport { asCompiledRowsSql } from \"../../query/sql-intent\";\nimport { type KindRegistry } from \"../../registry/kind-registry\";\nimport { canonicalEqual } from \"../../schema/canonical\";\nimport {\n assertOrderedValidityWindow,\n assertWritableValidityWindow,\n nowIso,\n preservesImmutableLowerBound,\n resolveStampedValidityLowerBound,\n validateOptionalCanonicalIsoDate,\n} from \"../../utils/date\";\nimport { generateId } from \"../../utils/id\";\nimport { createDataKeyedBag, hasOwnKey } from \"../../utils/object\";\nimport { requireDefined } from \"../../utils/presence\";\nimport { encodeTupleKey } from \"../../utils/tuple-key\";\nimport { type UpsertDirtyCheck } from \"../collections/coalesce\";\nimport { type UpsertUpdateNodeInput } from \"../collections/node-collection\";\nimport {\n checkDisjointnessConstraint,\n type ConstraintContext,\n type ConstraintFenceReason,\n nodeWriteNeedsConstraintFence,\n} from \"../constraints\";\nimport { getEmbeddingFields } from \"../embedding-sync\";\nimport { getSearchableFields } from \"../fulltext-sync\";\nimport {\n nodeInsertDispatch,\n runInsertBatch,\n runInsertBatchReturning,\n runInsertNoReturn,\n} from \"../insert-dispatch\";\nimport { getNodeRowsByIds } from \"../node-fetch\";\nimport { type GraphWriteLock } from \"../recorded-capture/clock\";\nimport { type NodeRow, rowToNode } from \"../row-mappers\";\nimport {\n type BulkOperationHookContext,\n type CreateNodeInput,\n type GetOrCreateAction,\n type Node,\n type NodeBulkFindByIndexOptions,\n type NodeGetOrCreateByConstraintOptions,\n type OperationHookContext,\n type UpdateNodeInput,\n} from \"../types\";\nimport {\n checkUniquenessConstraints,\n createUniquenessContext,\n validateResolvedNodeUniqueness,\n} from \"../uniqueness\";\nimport {\n assertClearValidToSupported,\n assertValidityEndMutation,\n} from \"../validity-end\";\nimport {\n createAlreadyExistsError,\n withAlreadyExistsTranslation,\n} from \"./already-exists\";\nimport {\n applyNodeHardDelete,\n applyNodeInsertSideEffects,\n applyNodeInsertSideEffectsBatch,\n applyNodeSoftDelete,\n applyNodeUpdate,\n createNodeWriteContext,\n} from \"./node-write-pipeline\";\nimport {\n runHookedWriteOperation,\n runInWriteTransaction,\n} from \"./write-transaction\";\n\n// ============================================================\n// Types\n// ============================================================\n\nexport type NodeOperationContext<G extends GraphDef> = Readonly<{\n graph: G;\n graphId: string;\n schemaVersion: number | undefined;\n historyEnabled: boolean;\n revisionTrackingEnabled: boolean;\n coalesceUnchangedUpsertsEnabled: boolean;\n revisionSchema: SqlSchema;\n registry: KindRegistry;\n createOperationContext: (\n operation: \"create\" | \"update\" | \"delete\",\n entity: KindEntity,\n kind: string,\n id: string,\n ) => OperationHookContext;\n withOperationHooks: <T>(\n ctx: OperationHookContext,\n fn: () => Promise<T>,\n ) => Promise<T>;\n createBulkOperationContext: (\n operation: \"updateWhere\",\n kind: string,\n ) => BulkOperationHookContext;\n withBulkOperationHooks: <T extends Readonly<{ affectedCount: number }>>(\n ctx: BulkOperationHookContext,\n fn: () => Promise<T>,\n ) => Promise<T>;\n identity?: Readonly<{\n lock: (target: GraphBackend | TransactionBackend) => Promise<void>;\n foldCreated: (\n target: GraphBackend | TransactionBackend,\n references: readonly Readonly<{ kind: string; id: string }>[],\n ) => Promise<void>;\n detachDeleted: (\n target: GraphBackend | TransactionBackend,\n ref: Readonly<{ kind: string; id: string }>,\n mode: \"soft\" | \"hard\",\n ) => Promise<void>;\n requireValidityEndCompatible: (\n target: GraphBackend | TransactionBackend,\n ref: Readonly<{ kind: string; id: string }>,\n validTo: string,\n ) => Promise<void>;\n }>;\n}>;\n\ntype NodeCreatePrepared = Readonly<{\n kind: string;\n id: string;\n nodeKind: NodeType;\n validatedProps: Record<string, unknown>;\n uniqueConstraints: readonly UniqueConstraint[];\n insertParams: InsertNodeParams;\n /**\n * `true` when the caller supplied `input.id`. A generated id cannot\n * already exist under another kind, so identity folding can skip its\n * cross-kind probe entirely for those rows.\n */\n idProvided: boolean;\n /**\n * The soft-deleted row occupying this id, or `undefined` when the id is\n * free. Named for what it can hold rather than what it was read as: the\n * duplicate-existence probe in {@link finishNodeCreatePreparation} throws\n * on a LIVE row, so what survives is always a tombstone awaiting\n * resurrection. Carrying it here is what lets the create path route\n * insert-vs-resurrect without re-reading the same (graph, kind, id).\n */\n tombstone: BackendNodeRow | undefined;\n}>;\n\ntype CachedNodeRow = Awaited<ReturnType<GraphBackend[\"getNode\"]>>;\ntype CachedUniqueRow = Awaited<ReturnType<GraphBackend[\"checkUnique\"]>>;\n\n// ============================================================\n// Helper Functions\n// ============================================================\n\n// Own-key membership, matching `store.getNodePropsSchema` and the collections\n// proxy: kind names are arbitrary identifiers, so a `toString`-named kind that\n// is NOT registered would otherwise read the inherited function as its\n// registration and fail with a `TypeError` off `registration.type` instead of\n// the `KindNotFoundError` this guard exists to raise.\nfunction getNodeRegistration<G extends GraphDef>(graph: G, kind: string) {\n if (!hasOwnKey(graph.nodes, kind)) throw new KindNotFoundError(kind, \"node\");\n const registration = graph.nodes[kind];\n if (registration === undefined) throw new KindNotFoundError(kind, \"node\");\n return registration;\n}\n\n/**\n * WHICH constraint makes this node write one whose probe no database key\n * repeats at write time, so it must take the per-graph write fence — or be\n * refused where no fence exists. The classification itself lives with the\n * constraints ({@link file://../constraints.ts nodeWriteNeedsConstraintFence});\n * this is only the graph-def lookup that feeds it.\n *\n * A kind this graph does not define answers `undefined`: choosing the fence\n * must not become the thing that reports an unknown kind, which the write path\n * raises from inside its hooked transaction where `onError` observes it.\n */\nfunction nodeFencesConstraintProbe<G extends GraphDef>(\n ctx: Pick<NodeOperationContext<G>, \"graph\" | \"registry\">,\n kind: string,\n operation: \"create\" | \"update\",\n): ConstraintFenceReason | undefined {\n if (!hasOwnKey(ctx.graph.nodes, kind)) return undefined;\n return nodeWriteNeedsConstraintFence(\n ctx.registry,\n kind,\n getNodeRegistration(ctx.graph, kind).unique ?? [],\n operation,\n );\n}\n\n/**\n * A batch fences when ANY item does — one transaction, so one constrained\n * member makes the whole write constrained, and the first such member names the\n * class a refusal would report.\n */\nfunction nodeBatchFencesConstraintProbe<G extends GraphDef>(\n ctx: Pick<NodeOperationContext<G>, \"graph\" | \"registry\">,\n inputs: readonly Readonly<{ kind: string }>[],\n operation: \"create\" | \"update\",\n): ConstraintFenceReason | undefined {\n for (const input of inputs) {\n const reason = nodeFencesConstraintProbe(ctx, input.kind, operation);\n if (reason !== undefined) return reason;\n }\n return undefined;\n}\n\nfunction buildNodeCacheKey(graphId: string, kind: string, id: string): string {\n return encodeTupleKey([graphId, kind, id]);\n}\n\nfunction buildUniqueCacheKey(\n graphId: string,\n nodeKind: string,\n constraintName: string,\n key: string,\n): string {\n return encodeTupleKey([graphId, nodeKind, constraintName, key]);\n}\n\nfunction buildInsertNodeParams(\n graphId: string,\n kind: string,\n id: string,\n props: Record<string, unknown>,\n validFrom: string | undefined,\n validTo: string | undefined,\n): InsertNodeParams {\n const insertParams: {\n graphId: string;\n kind: string;\n id: string;\n props: Record<string, unknown>;\n validFrom?: string;\n validTo?: string;\n } = {\n graphId,\n kind,\n id,\n props,\n };\n if (validFrom !== undefined) insertParams.validFrom = validFrom;\n if (validTo !== undefined) insertParams.validTo = validTo;\n return insertParams;\n}\n\nfunction createPendingUniqueRow(\n graphId: string,\n nodeKind: string,\n constraintName: string,\n key: string,\n nodeId: string,\n): UniqueRow {\n return {\n graph_id: graphId,\n node_kind: nodeKind,\n constraint_name: constraintName,\n key,\n node_id: nodeId,\n concrete_kind: nodeKind,\n deleted_at: undefined,\n };\n}\n\nfunction resolveConstraint<G extends GraphDef>(\n graph: G,\n kind: string,\n constraintName: string,\n): UniqueConstraint {\n const registration = getNodeRegistration(graph, kind);\n const constraints = registration.unique ?? [];\n const constraint = constraints.find(\n (candidate) => candidate.name === constraintName,\n );\n if (constraint === undefined) {\n throw new NodeConstraintNotFoundError(constraintName, kind);\n }\n return constraint;\n}\n\n// ============================================================\n// Batch Validation Cache\n//\n// During batch operations, multiple items may reference the same\n// nodes/unique keys. This cache avoids redundant backend lookups\n// and tracks pending (not-yet-flushed) inserts so that later items\n// in the batch can see earlier ones during validation.\n// ============================================================\n\nexport function createNodeBatchValidationBackend(\n graphId: string,\n registry: KindRegistry,\n backend: GraphBackend | TransactionBackend,\n): Readonly<{\n backend: GraphBackend | TransactionBackend;\n registerPendingNode: (params: InsertNodeParams) => void;\n registerPendingUniqueEntries: (\n kind: string,\n id: string,\n props: Record<string, unknown>,\n constraints: readonly UniqueConstraint[],\n ) => void;\n registerAppliedNodeUpdate: (\n kind: string,\n id: string,\n oldProps: Record<string, unknown>,\n newProps: Record<string, unknown>,\n constraints: readonly UniqueConstraint[],\n ) => void;\n seedNodeRow: (kind: string, id: string, row: CachedNodeRow) => void;\n seedUniqueRow: (\n kind: string,\n constraintName: string,\n key: string,\n row: CachedUniqueRow,\n ) => void;\n}> {\n const nodeCache = new Map<string, CachedNodeRow>();\n const pendingNodes = new Map<string, NonNullable<CachedNodeRow>>();\n const uniqueCache = new Map<string, CachedUniqueRow>();\n const pendingUniqueOwners = new Map<string, string>();\n\n async function getNodeCached(\n lookupGraphId: string,\n kind: string,\n id: string,\n ): Promise<CachedNodeRow> {\n const cacheKey = buildNodeCacheKey(lookupGraphId, kind, id);\n const pendingNode = pendingNodes.get(cacheKey);\n if (pendingNode !== undefined) return pendingNode;\n if (nodeCache.has(cacheKey)) return nodeCache.get(cacheKey);\n const existing = await backend.getNode(lookupGraphId, kind, id);\n nodeCache.set(cacheKey, existing);\n return existing;\n }\n\n async function checkUniqueCached(\n params: Parameters<GraphBackend[\"checkUnique\"]>[0],\n ): Promise<CachedUniqueRow> {\n const cacheKey = buildUniqueCacheKey(\n params.graphId,\n params.nodeKind,\n params.constraintName,\n params.key,\n );\n const pendingOwner = pendingUniqueOwners.get(cacheKey);\n if (pendingOwner !== undefined) {\n return createPendingUniqueRow(\n params.graphId,\n params.nodeKind,\n params.constraintName,\n params.key,\n pendingOwner,\n );\n }\n if (uniqueCache.has(cacheKey)) return uniqueCache.get(cacheKey);\n const existing = await backend.checkUnique(params);\n uniqueCache.set(cacheKey, existing);\n return existing;\n }\n\n function registerPendingNode(params: InsertNodeParams): void {\n const cacheKey = buildNodeCacheKey(params.graphId, params.kind, params.id);\n pendingNodes.set(cacheKey, {\n graph_id: params.graphId,\n kind: params.kind,\n id: params.id,\n props: JSON.stringify(params.props),\n version: 1,\n // The simulated cached row only needs a NodeRow-shaped valid_from\n // (string | undefined, never null) for existence/uniqueness checks,\n // which don't inspect its value — normalize import's explicit-NULL\n // sentinel away rather than widen this cache's row shape.\n valid_from: params.validFrom ?? undefined,\n valid_to: params.validTo,\n created_at: \"\",\n updated_at: \"\",\n deleted_at: undefined,\n });\n }\n\n function registerPendingUniqueEntries(\n kind: string,\n id: string,\n props: Record<string, unknown>,\n constraints: readonly UniqueConstraint[],\n ): void {\n for (const constraint of constraints) {\n if (!checkWherePredicate(constraint, props)) continue;\n\n const key = computeUniqueKey(\n props,\n constraint.fields,\n constraint.collation,\n );\n const concreteEntryKey = buildUniqueCacheKey(\n graphId,\n kind,\n constraint.name,\n key,\n );\n pendingUniqueOwners.set(concreteEntryKey, id);\n\n if (constraint.scope !== \"kind\") {\n const kindsToCheck = getKindsForUniquenessCheck(\n kind,\n constraint.scope,\n registry,\n );\n for (const kindToCheck of kindsToCheck) {\n const inheritedEntryKey = buildUniqueCacheKey(\n graphId,\n kindToCheck,\n constraint.name,\n key,\n );\n pendingUniqueOwners.set(inheritedEntryKey, id);\n }\n }\n }\n }\n\n // Reflects a completed in-slice node update in the uniqueness caches so a\n // later row's pre-check sees the post-update reservation state — the state\n // the sequential path's per-row backend read would observe. The batch path\n // primes the caches ONCE before routing, but an in-slice update mutates the\n // real backend's uniqueness rows directly; without reconciling here a later\n // create either (a) claims a value this update just freed yet gets rejected\n // against the stale reservation, or (b) passes the stale \"free\" cache for a\n // value this update just took and then violates the real constraint at\n // flush, aborting the whole import. Mirrors updateUniquenessEntries' key\n // diff: for each constraint whose key changed, the released old key becomes\n // free and the reserved new key becomes owned by this node, across every\n // kind the constraint's scope checks.\n function registerAppliedNodeUpdate(\n kind: string,\n id: string,\n oldProps: Record<string, unknown>,\n newProps: Record<string, unknown>,\n constraints: readonly UniqueConstraint[],\n ): void {\n for (const constraint of constraints) {\n const oldApplies = checkWherePredicate(constraint, oldProps);\n const newApplies = checkWherePredicate(constraint, newProps);\n const oldKey =\n oldApplies ?\n computeUniqueKey(oldProps, constraint.fields, constraint.collation)\n : undefined;\n const newKey =\n newApplies ?\n computeUniqueKey(newProps, constraint.fields, constraint.collation)\n : undefined;\n if (oldKey === newKey) continue;\n\n const kindsToCheck = getKindsForUniquenessCheck(\n kind,\n constraint.scope,\n registry,\n );\n\n if (oldKey !== undefined) {\n for (const kindToCheck of kindsToCheck) {\n const cacheKey = buildUniqueCacheKey(\n graphId,\n kindToCheck,\n constraint.name,\n oldKey,\n );\n // This node released the key on the real backend, so it is now\n // free. Clear any pending reservation and record the known-free\n // state (overwriting a stale seeded owner) so a later create's\n // pre-check sees a vacancy instead of a redundant backend read.\n pendingUniqueOwners.delete(cacheKey);\n uniqueCache.set(cacheKey, undefined);\n }\n }\n if (newKey !== undefined) {\n for (const kindToCheck of kindsToCheck) {\n const cacheKey = buildUniqueCacheKey(\n graphId,\n kindToCheck,\n constraint.name,\n newKey,\n );\n // This node now holds the key on the real backend. A pending owner\n // shadows the seeded uniqueCache entry (checkUniqueCached consults\n // it first), matching registerPendingUniqueEntries' reservation.\n pendingUniqueOwners.set(cacheKey, id);\n }\n }\n }\n }\n\n // Seed functions let batch preparation prime the caches from one\n // getNodes / checkUniqueBatch round trip instead of a per-row probe.\n // Seeding an absent result (`undefined`) is meaningful — it marks the\n // key as known-missing so the per-row check skips the backend read.\n // Existing entries are never overwritten: a pending registration or an\n // earlier lookup always wins.\n function seedNodeRow(kind: string, id: string, row: CachedNodeRow): void {\n const cacheKey = buildNodeCacheKey(graphId, kind, id);\n if (nodeCache.has(cacheKey)) return;\n nodeCache.set(cacheKey, row);\n }\n\n function seedUniqueRow(\n kind: string,\n constraintName: string,\n key: string,\n row: CachedUniqueRow,\n ): void {\n const cacheKey = buildUniqueCacheKey(graphId, kind, constraintName, key);\n if (uniqueCache.has(cacheKey)) return;\n uniqueCache.set(cacheKey, row);\n }\n\n const validationBackend = deriveBackend(backend, {\n getNode: getNodeCached,\n checkUnique: checkUniqueCached,\n } satisfies Partial<GraphBackend | TransactionBackend>);\n\n return {\n backend: validationBackend,\n registerPendingNode,\n registerPendingUniqueEntries,\n registerAppliedNodeUpdate,\n seedNodeRow,\n seedUniqueRow,\n };\n}\n\n// ============================================================\n// Shared Create Pipeline\n// ============================================================\n\n/**\n * The synchronous half of create preparation: kind resolution, Zod\n * validation, and date validation. Produces everything the async\n * constraint checks need, so batch preparation can validate every input\n * first and then prime the validation caches with batched reads before\n * running {@link finishNodeCreatePreparation} per row.\n */\n/**\n * Internal create options threaded from operations that validated props\n * BEFORE calling into the create path. Never exposed on the public store\n * surface.\n */\ntype NodeCreateInternalOptions = Readonly<{\n /** `input.props` is already the output of `validateNodeProps`. */\n propsPreValidated?: boolean;\n}>;\n\nexport type NodeCreateDraft = Readonly<{\n kind: string;\n id: string;\n idProvided: boolean;\n nodeKind: NodeType;\n uniqueConstraints: readonly UniqueConstraint[];\n validatedProps: Record<string, unknown>;\n validFrom: string | undefined;\n validTo: string | undefined;\n}>;\n\nfunction draftNodeCreate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: CreateNodeInput,\n id: string,\n options?: NodeCreateInternalOptions,\n): NodeCreateDraft {\n const kind = input.kind;\n const registration = getNodeRegistration(ctx.graph, kind);\n const nodeKind = registration.type;\n\n // getOrCreate / findByConstraint variants validate props up front (the\n // key computation needs the PARSED shape), then hand the validated\n // object here — re-running the full Zod parse on it would double the\n // validation cost of every create leg for no additional safety (hooks\n // wrap the transaction and cannot transform inputs in between).\n const validatedProps =\n options?.propsPreValidated === true ?\n input.props\n : validateNodeProps(nodeKind.schema, input.props, {\n kind,\n operation: \"create\",\n });\n\n const validFrom = validateOptionalCanonicalIsoDate(\n input.validFrom,\n \"validFrom\",\n );\n const validTo = validateOptionalCanonicalIsoDate(input.validTo, \"validTo\");\n // A stated pair must be ordered, and on an insert that is the COMPLETE rule.\n // A lone historical validTo is NOT an error — it means \"born already ended\"\n // (see assertWritableValidityWindow), and the insert stores no lower bound for\n // it rather than one past the stated end, so there is no effective bound left\n // for this layer to judge. Both create paths (single and batch) draft through\n // here, so this is the only insert-side check needed.\n assertOrderedValidityWindow(`${kind} \"${id}\"`, validFrom, validTo);\n\n return {\n kind,\n id,\n idProvided: input.id !== undefined,\n nodeKind,\n uniqueConstraints: registration.unique ?? [],\n validatedProps,\n validFrom,\n validTo,\n };\n}\n\n/**\n * The async half: existence, disjointness, and uniqueness checks.\n *\n * The existence probe's row is returned on the prepared record so fresh\n * inserts avoid a second read. Resurrection is the rare exception: it\n * re-checks the row immediately before writing because another transaction\n * may have resurrected it after preparation.\n */\nasync function finishNodeCreatePreparation<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n draft: NodeCreateDraft,\n backend: GraphBackend | TransactionBackend,\n): Promise<NodeCreatePrepared> {\n const { kind, id, validatedProps, uniqueConstraints } = draft;\n\n // This is the fast-path existence gate. Resurrection repeats it immediately\n // before the update because the row can change while constraints are checked.\n const existingNode = await backend.getNode(ctx.graphId, kind, id);\n if (existingNode && !existingNode.deleted_at) {\n throw createAlreadyExistsError(\"node\", kind, id);\n }\n\n const constraintContext: ConstraintContext = {\n graphId: ctx.graphId,\n registry: ctx.registry,\n backend,\n };\n await checkDisjointnessConstraint(constraintContext, kind, id);\n\n await checkUniquenessConstraints(\n createUniquenessContext(ctx.graphId, ctx.registry, backend),\n kind,\n id,\n validatedProps,\n uniqueConstraints,\n );\n\n return {\n kind,\n id,\n idProvided: draft.idProvided,\n tombstone: existingNode,\n nodeKind: draft.nodeKind,\n validatedProps,\n uniqueConstraints,\n insertParams: buildInsertNodeParams(\n ctx.graphId,\n kind,\n id,\n validatedProps,\n draft.validFrom,\n draft.validTo,\n ),\n };\n}\n\nasync function validateAndPrepareNodeCreate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: CreateNodeInput,\n id: string,\n backend: GraphBackend | TransactionBackend,\n options?: NodeCreateInternalOptions,\n): Promise<NodeCreatePrepared> {\n return finishNodeCreatePreparation(\n ctx,\n draftNodeCreate(ctx, input, id, options),\n backend,\n );\n}\n\n/**\n * Batched {@link finalizeNodeCreate}: applies every prepared create's\n * side effects through the batch pipeline (one uniqueness batch, one\n * fulltext/embedding batch per kind) instead of a per-row statement fan.\n */\nasync function finalizeNodeCreateBatch<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n preparedCreates: readonly NodeCreatePrepared[],\n backend: GraphBackend | TransactionBackend,\n lock: GraphWriteLock,\n): Promise<void> {\n await applyNodeInsertSideEffectsBatch(\n createNodeWriteContext(ctx.graphId, ctx.registry, lock),\n preparedCreates.map((prepared) => ({\n kind: prepared.kind,\n id: prepared.id,\n schema: prepared.nodeKind.schema,\n props: prepared.validatedProps,\n uniqueConstraints: prepared.uniqueConstraints,\n })),\n backend,\n );\n}\n\n/**\n * The created references identity folding actually has to consider.\n *\n * Folding looks for a live node carrying the SAME id under a DIFFERENT kind.\n * A generated id is fresh — nothing can already hold it — so only\n * caller-supplied ids can participate, and a batch of purely auto-id creates\n * needs no cross-kind probe at all.\n */\nfunction foldReferences(\n preparedCreates: readonly NodeCreatePrepared[],\n): readonly Readonly<{ kind: string; id: string }>[] {\n return preparedCreates\n .filter((prepared) => prepared.idProvided)\n .map((prepared) => ({ kind: prepared.kind, id: prepared.id }));\n}\n\nasync function finalizeNodeCreate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n prepared: NodeCreatePrepared,\n backend: GraphBackend | TransactionBackend,\n lock: GraphWriteLock,\n): Promise<void> {\n await applyNodeInsertSideEffects(\n createNodeWriteContext(ctx.graphId, ctx.registry, lock),\n {\n kind: prepared.kind,\n id: prepared.id,\n schema: prepared.nodeKind.schema,\n props: prepared.validatedProps,\n uniqueConstraints: prepared.uniqueConstraints,\n },\n backend,\n );\n}\n\n// ============================================================\n// Shared Update Pipeline\n//\n// executeNodeUpdate wraps this in operation hooks.\n// executeNodeUpsertUpdate calls it directly (no hooks) for\n// getOrCreate resurrections.\n// ============================================================\n\n/**\n * The exact props an update would persist: the caller's partial input merged\n * over the current props and run through the kind's Zod schema (defaults\n * applied, values normalized). Also returns the resolved registration so\n * callers need not look it up again. Operates on PARSED props so both the write\n * path (which parses the row) and the coalesce dirty-check (which may compare\n * against a batch-local running value, never a row) share one validation.\n */\nfunction computeNodeUpdate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n id: string,\n existingProps: Record<string, unknown>,\n inputProps: Partial<Record<string, unknown>>,\n) {\n const registration = getNodeRegistration(ctx.graph, kind);\n const validatedProps = validateNodeProps(\n registration.type.schema,\n { ...existingProps, ...inputProps },\n { kind, operation: \"update\", id },\n );\n return { registration, validatedProps };\n}\n\n/**\n * Row-based wrapper over {@link computeNodeUpdate} for the write path. Reads the\n * kind/id off the row (a `getNode(kind, id)` result always carries the\n * requested kind), matching {@link resolveEdgeUpdateProps}.\n */\nfunction resolveNodeUpdateProps<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n existing: Pick<NodeRow, \"kind\" | \"id\" | \"props\">,\n inputProps: Partial<Record<string, unknown>>,\n) {\n const existingProps = rowPropsToObject(existing.props);\n const { registration, validatedProps } = computeNodeUpdate(\n ctx,\n existing.kind,\n existing.id,\n existingProps,\n inputProps,\n );\n return { registration, existingProps, validatedProps };\n}\n\n/**\n * The coalesce dirty-check: returns the props an `upsertById` would persist and\n * whether they equal `existingProps` (so the write can be skipped). Compares on\n * the storage-normalized representation (validated, key-order-independent), so\n * it answers exactly \"would the persisted JSON differ?\". `existingProps` is the\n * PARSED current props — the row's, or the batch-local running value for a\n * repeated id in `bulkUpsertById`.\n */\nexport function nodeUpsertDirtyCheck<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n id: string,\n existingProps: Record<string, unknown>,\n inputProps: Record<string, unknown>,\n): UpsertDirtyCheck {\n const { validatedProps } = computeNodeUpdate(\n ctx,\n kind,\n id,\n existingProps,\n inputProps,\n );\n return {\n validatedProps,\n unchanged: canonicalEqual(validatedProps, existingProps),\n };\n}\n\nasync function performNodeUpdate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: UpsertUpdateNodeInput,\n backend: GraphBackend | TransactionBackend,\n lock: GraphWriteLock,\n options?: Readonly<{ clearDeleted?: boolean }>,\n): Promise<Node> {\n const { kind, id } = input;\n\n assertValidityEndMutation(input, { entityType: \"node\", kind, id });\n\n const existing = await backend.getNode(ctx.graphId, kind, id);\n if (!existing) throw new NodeNotFoundError(kind, id);\n\n const { registration, validatedProps } = resolveNodeUpdateProps(\n ctx,\n existing,\n input.props,\n );\n const nodeKind = registration.type;\n\n const validTo = validateOptionalCanonicalIsoDate(input.validTo, \"validTo\");\n // A node resurrection RESETS `valid_from` (see `buildUpdateNode`), so its\n // effective lower bound is one this write stamps rather than the row's stored\n // one. The instant is sampled HERE and the bound resolved from it travels to\n // the backend as an explicit `validFrom`, because the guard has to measure\n // the bound the write will actually store: left to default, the builder's own\n // `resolveStampedValidityLowerBound` call would judge the backend's strictly\n // later sample, and a `validTo` at this instant would pass the guard as\n // zero-width and land as a different shape a millisecond later (issue #413).\n // An in-place update keeps the row's stored bound, which no write rewrites and\n // so needs no prediction.\n const resurrectionInstant =\n options?.clearDeleted === true && existing.deleted_at !== undefined ?\n nowIso()\n : undefined;\n // Event materializers may state the source row's lower bound on every\n // delivery while asking a live update to preserve the bound already stored.\n // This is explicit create/resurrection-only input, not the old silent drop:\n // the default remains `\"refuse\"`, and a resurrection still validates and\n // stores the stated value below.\n const preservesLiveLowerBound =\n resurrectionInstant === undefined &&\n preservesImmutableLowerBound(input.onImmutableLowerBound);\n const statedValidFrom = validateOptionalCanonicalIsoDate(\n input.validFrom,\n \"validFrom\",\n );\n const validFrom = preservesLiveLowerBound ? undefined : statedValidFrom;\n // The bound this resurrection will STORE, decided by the same owner every\n // insert builder decides through, against the instant sampled above. Asking\n // the owner rather than assuming `resurrectionInstant` is what makes a\n // resurrection carrying only a historical `validTo` reach the shape a create\n // reaches — no lower bound, \"ended at T, start unknown\" — instead of being\n // refused for inverting against an instant the write would never have stored\n // (I12). `undefined` here means \"no bound\", which is nothing to invert\n // against, so the verdict below judges exactly what lands.\n const resurrectionBound =\n resurrectionInstant === undefined ? undefined : (\n resolveStampedValidityLowerBound(validFrom, validTo, resurrectionInstant)\n );\n // A resurrection STORES a stated `validFrom` (it rewrites the whole window);\n // an in-place update never does, so one that differs from the row's stored\n // bound is refused rather than accepted and dropped.\n const windowVerdict = assertWritableValidityWindow(\n `${kind} \"${id}\"`,\n validFrom,\n resurrectionInstant === undefined ?\n {\n effectiveValidFrom: existing.valid_from,\n appliesStatedValidFrom: false,\n effectiveBoundIsStored: true,\n }\n : {\n effectiveValidFrom: resurrectionBound,\n appliesStatedValidFrom: true,\n // The bound this write is about to stamp, not one the row holds.\n effectiveBoundIsStored: false,\n },\n validTo,\n );\n\n const writeContext = createNodeWriteContext(ctx.graphId, ctx.registry, lock);\n const shared = {\n schema: nodeKind.schema,\n validatedProps,\n uniqueConstraints: registration.unique ?? [],\n ...(validTo !== undefined && { validTo }),\n ...(input.clearValidTo === true && { clearValidTo: true as const }),\n // The bound the verdict above READ, carried into the UPDATE's own `WHERE`\n // so the row this writes is the row that was judged. The verdict hands over\n // the predicate rather than a flag, so both conditions that decide it — did\n // the verdict consult the effective bound, and WAS that bound the row's\n // stored one — are answered where they are known. A plain\n // `update({ props })` states no window, reads no bound, and stays unfenced:\n // the same rule `UpdateEdgeParams`'s identity components follow, for the\n // same reason. The resurrecting leg is judged against `resurrectionInstant`\n // and so fences on `deleted_at IS NOT NULL` alone, converging through the\n // recovery below.\n ...windowVerdict.storedLowerBoundFence,\n };\n\n // A resurrecting upsert (clearDeleted) may target a tombstoned row; a plain\n // update must prove the row live — see NodeUpdateTarget.\n if (options?.clearDeleted) {\n // Keyed on the SAME condition the verdict was, because only that condition\n // produces a verdict to state. With `resurrectionInstant` defined this is\n // the DECISION, never an absence: omitting the key would let\n // `buildUpdateNode` re-derive the bound against the backend's own, strictly\n // later `timestamp`, so the two layers would agree only while the two clocks\n // do — the #413 hazard, one layer out. `null` is how `UpdateNodeParams`\n // spells \"store no lower bound\", which is what this decision resolves to for\n // a resurrection that ends at or before the instant it judged.\n //\n // With it UNDEFINED this read found the row live — a peer resurrected it\n // between the collection's probe and here — so the verdict judged the row's\n // stored bound and stamped nothing. There is no decision to state, and\n // stating one anyway would write away a `validFrom` the guard just ACCEPTED\n // as equal to that stored bound. The statement usually matches no row\n // (`deleted_at IS NOT NULL`) and the recovery below re-reads, but a peer that\n // re-tombstones before the UPDATE makes it match, so this leg carries the\n // stated bound exactly as the in-place leg does.\n const resurrectionLowerBound =\n resurrectionInstant === undefined ?\n validFrom !== undefined && { validFrom }\n // eslint-disable-next-line unicorn/no-null -- `validFrom: null` means \"store NULL\"; omitting the key means \"decide for me\", and this path has already decided. See UpdateNodeParams.validFrom.\n : { validFrom: resurrectionBound ?? null };\n const row = await applyNodeUpdate(\n writeContext,\n { ...shared, existing, clearDeleted: true, ...resurrectionLowerBound },\n backend,\n );\n return rowToNode(row);\n }\n\n if (!isLiveNodeRow(existing)) throw new NodeNotFoundError(kind, id);\n const row = await applyNodeUpdate(\n writeContext,\n // An in-place update must not rewrite the stored bound, so it keeps the\n // conditional spread: `buildUpdateNode` ignores `validFrom` off the\n // resurrection leg, and stating one here would claim a rewrite that no\n // statement performs.\n { ...shared, existing, ...(validFrom !== undefined && { validFrom }) },\n backend,\n );\n return rowToNode(row);\n}\n\n/**\n * How many probe-and-write rounds a node update gets before it stops trying to\n * converge. One retry: enough to absorb a single concurrent recreate, bounded\n * so a peer that keeps replacing the row cannot livelock this caller (the same\n * shape, and the same reasoning, as `getOrCreateByEndpoints`'s bounded loop).\n */\nconst NODE_UPDATE_ATTEMPTS = 2;\n\n/**\n * Runs a node update and CONVERGES on the row that is actually there when a\n * predicated UPDATE matches nothing.\n *\n * `performNodeUpdate` is a probe-and-write pair, and both of the predicates its\n * statement carries beyond `(graph_id, kind, id)` can stop matching between the\n * two under PostgreSQL READ COMMITTED:\n *\n * - `deleted_at IS NOT NULL` on the resurrecting leg — a peer resurrected the\n * tombstone first;\n * - `expectedValidFrom` on the in-place leg — a peer hard-deleted and\n * recreated the row, so the bound this update's window verdict was computed\n * against is gone.\n *\n * Both are the SAME event from the caller's side: the row moved under a\n * decision already made. Neither may surface as the zero-row\n * `DatabaseOperationError` the backend raises, which is an internal sentinel\n * and names nothing a caller can act on. So this re-reads and re-derives:\n *\n * - row gone, or tombstoned where the leg needs a live one — `NodeNotFoundError`,\n * exactly what the pre-write probe would have thrown;\n * - row live — retry the whole thing. The retry re-reads, re-merges the\n * caller's partial props over the CURRENT props, and re-judges the window\n * against the CURRENT bound, so a stated window that no longer fits is\n * refused with the same typed `ValidationError` the first attempt would have\n * raised. A resurrection that lost its race converges to an ordinary update,\n * which is upsert's documented semantics: the peer owns the new window, this\n * late writer owns the properties — and a caller that STATED a lower bound\n * for the resurrection it lost is therefore refused rather than silently\n * updated without it.\n *\n * Retrying rather than refusing is what keeps the fence from being a behavior\n * regression: the losing writer still lands its properties, on the row that is\n * really there, judged against the bounds that row really carries.\n */\nasync function performNodeUpdateWithResurrectionRecovery<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: UpsertUpdateNodeInput,\n target: GraphBackend | TransactionBackend,\n lock: GraphWriteLock,\n options?: Readonly<{ clearDeleted?: boolean }>,\n): Promise<Node> {\n for (let attempt = 1; attempt <= NODE_UPDATE_ATTEMPTS; attempt += 1) {\n try {\n // Only the FIRST attempt may resurrect: reaching a retry means the row is\n // live, and an ordinary update is what converges on it.\n return await performNodeUpdate(\n ctx,\n input,\n target,\n lock,\n attempt === 1 ? options : undefined,\n );\n } catch (error) {\n if (!isNodeUpdateNoRowError(error) || attempt === NODE_UPDATE_ATTEMPTS) {\n throw nodeUpdateRaceError(input, error);\n }\n const current = await target.getNode(ctx.graphId, input.kind, input.id);\n if (current === undefined || current.deleted_at !== undefined) {\n throw new NodeNotFoundError(input.kind, input.id);\n }\n }\n }\n // Unreachable: the loop either returns or throws on its last attempt.\n throw new NodeNotFoundError(input.kind, input.id);\n}\n\n/**\n * The error a caller sees when a node update exhausts its attempts, or fails\n * with something that is not the zero-row sentinel.\n *\n * A non-sentinel error passes through untouched. The sentinel does not: it says\n * \"the statement matched nothing\", which after {@link NODE_UPDATE_ATTEMPTS}\n * rounds means a peer is replacing this row faster than this writer can read\n * it. That is a contention fact, and it is reported as one rather than as a\n * missing node — the node is present, it just is not staying still.\n */\nfunction nodeUpdateRaceError(\n input: UpsertUpdateNodeInput,\n error: unknown,\n): unknown {\n if (!isNodeUpdateNoRowError(error)) return error;\n return new DatabaseOperationError(\n `Node update for ${input.kind} \"${input.id}\" could not be applied to a stable row after ${NODE_UPDATE_ATTEMPTS} attempts: the row was removed and recreated between each read and its write. A concurrent writer is replacing this node faster than it can be read; serialize the writers, or retry.`,\n {\n operation: \"update\",\n entity: \"node\",\n attempted: [{ kind: input.kind, id: input.id }],\n },\n { cause: error },\n );\n}\n\n// ============================================================\n// Shared Batch Preparation\n//\n// Both returning and non-returning batch creates share the same\n// validate-and-register loop. This extracts it.\n// ============================================================\n\n/**\n * Primes the batch validation caches with batched reads: one `getNodes`\n * per kind for existence probes and one `checkUniqueBatch` per\n * (constraint, kind) for uniqueness pre-checks. The per-row checks in\n * {@link finishNodeCreatePreparation} then hit memory instead of issuing\n * one probe per row. Backends without the batch primitives skip priming\n * and keep the per-row fallback.\n */\nexport async function primeBatchValidationCaches(\n ctx: Readonly<{ graphId: string; registry: KindRegistry }>,\n drafts: readonly NodeCreateDraft[],\n backend: GraphBackend | TransactionBackend,\n seams: Readonly<{\n seedNodeRow: (kind: string, id: string, row: CachedNodeRow) => void;\n seedUniqueRow: (\n kind: string,\n constraintName: string,\n key: string,\n row: CachedUniqueRow,\n ) => void;\n }>,\n): Promise<void> {\n if (backend.getNodes !== undefined) {\n const idsByKind = new Map<string, Set<string>>();\n for (const draft of drafts) {\n const ids = idsByKind.get(draft.kind) ?? new Set<string>();\n ids.add(draft.id);\n idsByKind.set(draft.kind, ids);\n }\n for (const [kind, ids] of idsByKind) {\n const orderedIds = [...ids];\n const rows = await backend.getNodes(ctx.graphId, kind, orderedIds);\n const rowsById = new Map(rows.map((row) => [row.id, row]));\n for (const id of orderedIds) {\n seams.seedNodeRow(kind, id, rowsById.get(id));\n }\n }\n }\n\n if (backend.checkUniqueBatch !== undefined) {\n interface ProbeGroup {\n nodeKind: string;\n constraintName: string;\n keys: Set<string>;\n }\n const groups = new Map<string, ProbeGroup>();\n for (const draft of drafts) {\n for (const constraint of draft.uniqueConstraints) {\n if (!checkWherePredicate(constraint, draft.validatedProps)) continue;\n const key = computeUniqueKey(\n draft.validatedProps,\n constraint.fields,\n constraint.collation,\n );\n const kindsToCheck = getKindsForUniquenessCheck(\n draft.kind,\n constraint.scope,\n ctx.registry,\n );\n for (const kindToCheck of kindsToCheck) {\n const groupKey = encodeTupleKey([kindToCheck, constraint.name]);\n const group = groups.get(groupKey) ?? {\n nodeKind: kindToCheck,\n constraintName: constraint.name,\n keys: new Set<string>(),\n };\n group.keys.add(key);\n groups.set(groupKey, group);\n }\n }\n }\n for (const group of groups.values()) {\n const orderedKeys = [...group.keys];\n const rows = await backend.checkUniqueBatch({\n graphId: ctx.graphId,\n nodeKind: group.nodeKind,\n constraintName: group.constraintName,\n keys: orderedKeys,\n });\n const rowsByKey = new Map(rows.map((row) => [row.key, row]));\n for (const key of orderedKeys) {\n seams.seedUniqueRow(\n group.nodeKind,\n group.constraintName,\n key,\n rowsByKey.get(key),\n );\n }\n }\n }\n}\n\nasync function prepareBatchCreates<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n inputs: readonly CreateNodeInput[],\n backend: GraphBackend | TransactionBackend,\n options?: NodeCreateInternalOptions,\n): Promise<readonly NodeCreatePrepared[]> {\n const {\n backend: validationBackend,\n registerPendingNode,\n registerPendingUniqueEntries,\n seedNodeRow,\n seedUniqueRow,\n } = createNodeBatchValidationBackend(ctx.graphId, ctx.registry, backend);\n\n // Pass 1 (synchronous): validate every input and assign ids. This\n // surfaces a later row's validation error before an earlier row's\n // constraint error — both fail the whole batch, so ordering across\n // error categories is not part of the contract.\n const drafts = inputs.map((input) =>\n draftNodeCreate(ctx, input, input.id ?? generateId(), options),\n );\n\n await primeBatchValidationCaches(ctx, drafts, backend, {\n seedNodeRow,\n seedUniqueRow,\n });\n\n // Pass 2: per-row constraint checks against the primed caches, in input\n // order, registering pendings so later rows see earlier ones.\n const preparedCreates: NodeCreatePrepared[] = [];\n for (const draft of drafts) {\n const prepared = await finishNodeCreatePreparation(\n ctx,\n draft,\n validationBackend,\n );\n preparedCreates.push(prepared);\n registerPendingNode(prepared.insertParams);\n registerPendingUniqueEntries(\n prepared.kind,\n prepared.id,\n prepared.validatedProps,\n prepared.uniqueConstraints,\n );\n }\n\n return preparedCreates;\n}\n\ntype CreatePartition = Readonly<{\n inserts: readonly NodeCreatePrepared[];\n resurrections: readonly NodeCreatePrepared[];\n}>;\n\n/**\n * Splits prepared creates into fresh inserts and tombstone resurrections.\n *\n * Purely in-memory: preparation already read each id's row under this write\n * lock (batched through `getNodes` when the backend has it, per-row through\n * the validation cache otherwise) and carried it on the prepared record, so\n * routing costs no additional round trip.\n */\nfunction partitionCreates(\n preparedCreates: readonly NodeCreatePrepared[],\n): CreatePartition {\n const inserts: NodeCreatePrepared[] = [];\n const resurrections: NodeCreatePrepared[] = [];\n\n for (const prepared of preparedCreates) {\n if (prepared.tombstone === undefined) {\n inserts.push(prepared);\n } else {\n resurrections.push(prepared);\n }\n }\n return { inserts, resurrections };\n}\n\nfunction isNodeUpdateNoRowError(\n error: unknown,\n): error is DatabaseOperationError {\n return (\n error instanceof DatabaseOperationError &&\n error.details.operation === \"update\" &&\n error.details.entity === \"node\" &&\n error.details.reason === \"no_row_returned\"\n );\n}\n\nasync function resurrectPreparedNode<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n target: GraphBackend | TransactionBackend,\n lock: GraphWriteLock,\n prepared: NodeCreatePrepared,\n): Promise<BackendNodeRow> {\n const current = await target.getNode(ctx.graphId, prepared.kind, prepared.id);\n if (current === undefined) {\n throw new DatabaseOperationError(\n `Node tombstone disappeared before resurrection: ${prepared.kind} ${prepared.id}`,\n { operation: \"update\", entity: \"node\" },\n );\n }\n if (current.deleted_at === undefined) {\n throw createAlreadyExistsError(\"node\", prepared.kind, prepared.id);\n }\n // A create landing on a tombstone RESETS the window, so this leg stamps a\n // bound whenever the caller stated none — and it decides which one through\n // the same owner `performNodeUpdate`'s resurrection leg and every insert\n // builder use, against an instant sampled HERE. Two consequences. The stored\n // bound is the one this layer judged rather than the backend's strictly later\n // sample, so one write has one instant (issue #413). And a create carrying\n // only a historical `validTo` reaches the same stored shape on a tombstoned\n // id as on a fresh one — no lower bound (I12).\n const resurrectionInstant = nowIso();\n const resurrectionBound = resolveStampedValidityLowerBound(\n prepared.insertParams.validFrom,\n prepared.insertParams.validTo,\n resurrectionInstant,\n );\n try {\n return await applyNodeUpdate(\n createNodeWriteContext(ctx.graphId, ctx.registry, lock),\n {\n existing: current,\n clearDeleted: true,\n schema: prepared.nodeKind.schema,\n validatedProps: prepared.validatedProps,\n uniqueConstraints: prepared.uniqueConstraints,\n // The decision itself, never an absence — see the same spelling on\n // `performNodeUpdate`'s resurrection leg.\n // eslint-disable-next-line unicorn/no-null -- `validFrom: null` means \"store NULL\"; omitting the key means \"decide for me\", and this path has already decided. See UpdateNodeParams.validFrom.\n validFrom: resurrectionBound ?? null,\n ...(prepared.insertParams.validTo === undefined ?\n {}\n : { validTo: prepared.insertParams.validTo }),\n },\n target,\n );\n } catch (error) {\n if (!isNodeUpdateNoRowError(error)) throw error;\n // The UPDATE itself has a tombstone predicate, closing the remaining gap\n // between the re-read and write. Translate a peer resurrection into the\n // create API's stable duplicate error instead of leaking a 0-row update.\n const afterFailure = await target.getNode(\n ctx.graphId,\n prepared.kind,\n prepared.id,\n );\n if (afterFailure !== undefined && afterFailure.deleted_at === undefined) {\n throw createAlreadyExistsError(\"node\", prepared.kind, prepared.id);\n }\n throw error;\n }\n}\n\n// ============================================================\n// Shared Constraint Lookup\n//\n// Both single and bulk find/getOrCreate operations need to look up\n// unique constraint entries across all applicable kinds.\n// ============================================================\n\nasync function findUniqueRowAcrossKinds(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n constraintName: string,\n key: string,\n kindsToCheck: readonly string[],\n includeDeleted: boolean,\n): Promise<\n | { node_id: string; concrete_kind: string; deleted_at: string | undefined }\n | undefined\n> {\n for (const kindToCheck of kindsToCheck) {\n const row = await backend.checkUnique({\n graphId,\n nodeKind: kindToCheck,\n constraintName,\n key,\n includeDeleted,\n });\n if (row !== undefined) return row;\n }\n return undefined;\n}\n\ninterface UniqueMatchRow {\n node_id: string;\n concrete_kind: string;\n deleted_at: string | undefined;\n}\n\nasync function batchCheckUniqueAcrossKinds(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n constraintName: string,\n uniqueKeys: readonly string[],\n kindsToCheck: readonly string[],\n includeDeleted: boolean,\n): Promise<Map<string, UniqueMatchRow>> {\n const existingByKey = new Map<string, UniqueMatchRow>();\n\n for (const kindToCheck of kindsToCheck) {\n if (backend.checkUniqueBatch === undefined) {\n for (const key of uniqueKeys) {\n if (existingByKey.has(key)) continue;\n const row = await backend.checkUnique({\n graphId,\n nodeKind: kindToCheck,\n constraintName,\n key,\n includeDeleted,\n });\n if (row !== undefined) {\n existingByKey.set(row.key, row);\n }\n }\n } else {\n const rows = await backend.checkUniqueBatch({\n graphId,\n nodeKind: kindToCheck,\n constraintName,\n keys: uniqueKeys,\n includeDeleted,\n });\n for (const row of rows) {\n if (!existingByKey.has(row.key)) {\n existingByKey.set(row.key, row);\n }\n }\n }\n }\n\n return existingByKey;\n}\n\n// ============================================================\n// Node Create Operations\n// ============================================================\n\nasync function executeNodeCreateInternal<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: CreateNodeInput,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ returnRow?: boolean }> & NodeCreateInternalOptions,\n): Promise<Node | undefined> {\n const kind = input.kind;\n const id = input.id ?? generateId();\n const opContext = ctx.createOperationContext(\"create\", \"node\", kind, id);\n const shouldReturnRow = options?.returnRow ?? true;\n\n return runHookedWriteOperation(\n ctx,\n opContext,\n backend,\n async (target, lock) => {\n const identity = ctx.identity;\n if (identity !== undefined) await identity.lock(target);\n const prepared = await validateAndPrepareNodeCreate(\n ctx,\n input,\n id,\n target,\n options,\n );\n\n const existing = prepared.tombstone;\n if (existing !== undefined) {\n const resurrected = await resurrectPreparedNode(\n ctx,\n target,\n lock,\n prepared,\n );\n if (identity !== undefined) {\n await identity.foldCreated(target, foldReferences([prepared]));\n }\n return shouldReturnRow ? rowToNode(resurrected) : undefined;\n }\n\n // The existence probe above is not the last word: on an engine that does\n // not serialize the two writers, a concurrent create of the same new id\n // can commit between the probe and this INSERT, and only the engine's\n // refusal reports it. Both routes to that conclusion raise the same error.\n const row = await withAlreadyExistsTranslation(\"node\", async () => {\n if (shouldReturnRow) return target.insertNode(prepared.insertParams);\n await runInsertNoReturn(\n nodeInsertDispatch(target),\n prepared.insertParams,\n );\n return;\n });\n\n await finalizeNodeCreate(ctx, prepared, target, lock);\n if (identity !== undefined) {\n await identity.foldCreated(target, foldReferences([prepared]));\n }\n\n if (row === undefined) return;\n return rowToNode(row);\n },\n {\n fencesConstraintProbe: nodeFencesConstraintProbe(ctx, kind, \"create\"),\n },\n );\n}\n\nexport async function executeNodeCreate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: CreateNodeInput,\n backend: GraphBackend | TransactionBackend,\n options?: NodeCreateInternalOptions,\n): Promise<Node> {\n const result = await executeNodeCreateInternal(ctx, input, backend, {\n returnRow: true,\n ...options,\n });\n if (!result) {\n throw new DatabaseOperationError(\n \"Node create failed: expected created node row\",\n { operation: \"insert\", entity: \"node\" },\n );\n }\n return result;\n}\n\nexport async function executeNodeCreateNoReturn<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: CreateNodeInput,\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n await executeNodeCreateInternal(ctx, input, backend, { returnRow: false });\n}\n\n/**\n * Executes batched node creates without returning inserted node payloads.\n *\n * Note: `withOperationHooks` is intentionally skipped for batch throughput.\n * Per-item hooks would negate the performance benefit of batching.\n */\nexport async function executeNodeCreateNoReturnBatch<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n inputs: readonly CreateNodeInput[],\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n if (inputs.length === 0) return;\n\n await runInWriteTransaction(\n ctx,\n backend,\n async (target, lock) => {\n const identity = ctx.identity;\n if (identity !== undefined) await identity.lock(target);\n const preparedCreates = await prepareBatchCreates(ctx, inputs, target);\n\n const partition = partitionCreates(preparedCreates);\n await withAlreadyExistsTranslation(\"node\", () =>\n runInsertBatch(\n nodeInsertDispatch(target),\n partition.inserts.map((prepared) => prepared.insertParams),\n ),\n );\n for (const prepared of partition.resurrections) {\n await resurrectPreparedNode(ctx, target, lock, prepared);\n }\n await finalizeNodeCreateBatch(ctx, partition.inserts, target, lock);\n if (identity !== undefined) {\n await identity.foldCreated(target, foldReferences(preparedCreates));\n }\n },\n {\n fencesConstraintProbe: nodeBatchFencesConstraintProbe(\n ctx,\n inputs,\n \"create\",\n ),\n },\n );\n}\n\n/**\n * Executes batched node creates and returns the inserted node payloads.\n *\n * Uses batch validation caching and a single multi-row INSERT with RETURNING\n * when the backend supports it. Falls back to sequential inserts otherwise.\n *\n * Note: `withOperationHooks` is intentionally skipped for batch throughput.\n * Per-item hooks would negate the performance benefit of batching.\n */\nexport async function executeNodeCreateBatch<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n inputs: readonly CreateNodeInput[],\n backend: GraphBackend | TransactionBackend,\n options?: NodeCreateInternalOptions,\n): Promise<readonly Node[]> {\n if (inputs.length === 0) return [];\n\n return runInWriteTransaction(\n ctx,\n backend,\n async (target, lock) => {\n const identity = ctx.identity;\n if (identity !== undefined) await identity.lock(target);\n const preparedCreates = await prepareBatchCreates(\n ctx,\n inputs,\n target,\n options,\n );\n\n const partition = partitionCreates(preparedCreates);\n const inserted = await withAlreadyExistsTranslation(\"node\", () =>\n runInsertBatchReturning(\n nodeInsertDispatch(target),\n partition.inserts.map((prepared) => prepared.insertParams),\n ),\n );\n const resurrected: BackendNodeRow[] = [];\n for (const prepared of partition.resurrections) {\n resurrected.push(\n await resurrectPreparedNode(ctx, target, lock, prepared),\n );\n }\n await finalizeNodeCreateBatch(ctx, partition.inserts, target, lock);\n const byReference = new Map(\n [...inserted, ...resurrected].map((row) => [\n refKey({ kind: row.kind, id: row.id }),\n row,\n ]),\n );\n const rows = preparedCreates.map((prepared) =>\n requireDefined(\n byReference.get(refKey({ kind: prepared.kind, id: prepared.id })),\n `Missing written row for ${prepared.kind} ${prepared.id}`,\n ),\n );\n if (identity !== undefined) {\n await identity.foldCreated(target, foldReferences(preparedCreates));\n }\n\n return rows.map((row) => rowToNode(row));\n },\n {\n fencesConstraintProbe: nodeBatchFencesConstraintProbe(\n ctx,\n inputs,\n \"create\",\n ),\n },\n );\n}\n\n// ============================================================\n// Node Update Operations\n// ============================================================\n\nexport async function executeNodeUpdate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: UpsertUpdateNodeInput,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n): Promise<Node> {\n const opContext = ctx.createOperationContext(\n \"update\",\n \"node\",\n input.kind,\n input.id,\n );\n return runHookedWriteOperation(\n ctx,\n opContext,\n backend,\n async (target, lock) => {\n if (input.clearValidTo === true) {\n assertClearValidToSupported(backend, \"node\");\n }\n const validTo = validateOptionalCanonicalIsoDate(\n input.validTo,\n \"validTo\",\n );\n const identity = ctx.identity;\n if (\n identity !== undefined &&\n (options?.clearDeleted === true || input.validTo !== undefined)\n ) {\n await identity.lock(target);\n }\n if (identity !== undefined && validTo !== undefined) {\n await identity.requireValidityEndCompatible(\n target,\n { kind: input.kind, id: input.id },\n validTo,\n );\n }\n const node = await performNodeUpdateWithResurrectionRecovery(\n ctx,\n input,\n target,\n lock,\n options,\n );\n if (options?.clearDeleted && identity !== undefined) {\n await identity.foldCreated(target, [\n { kind: input.kind, id: input.id },\n ]);\n }\n return node;\n },\n {\n fencesConstraintProbe: nodeFencesConstraintProbe(\n ctx,\n input.kind,\n \"update\",\n ),\n },\n );\n}\n\n/**\n * Executes an atomic, set-based update of current nodes. The backend returns\n * every after-image so the Store can validate the complete rows before\n * rebuilding all derived sidecars inside the same transaction.\n */\nexport async function executeNodeUpdateWhere<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n inputPatch: Record<string, unknown>,\n candidateIds: CompiledSelectSql,\n candidateIdColumn: string,\n backend: GraphBackend | TransactionBackend,\n): Promise<Readonly<{ affectedCount: number }>> {\n const registration = getNodeRegistration(ctx.graph, kind);\n const schema = registration.type.schema;\n const uniqueConstraints = registration.unique ?? [];\n\n if (!backend.capabilities.transactions) {\n throw new ConfigurationError(\n \"updateWhere() requires a transactional backend so validation and sidecars are atomic\",\n { code: \"SET_UPDATE_TRANSACTIONS_REQUIRED\", kind },\n );\n }\n if (backend.updateNodeSet === undefined) {\n throw new ConfigurationError(\n \"This backend does not support set-based node updates\",\n { code: \"SET_UPDATE_UNSUPPORTED\", kind },\n );\n }\n if (Object.keys(inputPatch).length === 0) {\n throw new ValidationError(\"updateWhere() patch must not be empty\", {\n entityType: \"node\",\n kind,\n operation: \"update\",\n issues: [{ path: \"patch\", message: \"Provide at least one property\" }],\n });\n }\n const unknownProperty = Object.keys(inputPatch).find(\n (property) => !Object.hasOwn(schema.shape, property),\n );\n if (unknownProperty !== undefined) {\n throw new ValidationError(\n `Unknown ${kind} property in updateWhere() patch: ${unknownProperty}`,\n {\n entityType: \"node\",\n kind,\n operation: \"update\",\n issues: [\n {\n path: unknownProperty,\n message: \"Property is not declared by the node schema\",\n },\n ],\n },\n );\n }\n\n const parsedPatch = validateNodeProps(schema.partial(), inputPatch, {\n kind,\n operation: \"update\",\n });\n // Data-keyed: `property` comes from the caller's patch object.\n const patch = createDataKeyedBag<JsonValue>();\n const unsetProperties: string[] = [];\n for (const [property, value] of Object.entries(parsedPatch)) {\n if (value === undefined) {\n unsetProperties.push(property);\n continue;\n }\n assertJsonValue(value, property, `Node \"${kind}\" updateWhere patch`);\n patch[property] = value as JsonValue;\n }\n if (Object.keys(patch).length === 0 && unsetProperties.length === 0) {\n throw new ValidationError(\n \"updateWhere() patch has no recognized properties\",\n {\n entityType: \"node\",\n kind,\n operation: \"update\",\n issues: [\n { path: \"patch\", message: \"Provide a declared node property\" },\n ],\n },\n );\n }\n\n if (\n uniqueConstraints.length > 0 &&\n (backend.hardDeleteUniquesByNodeIds === undefined ||\n backend.insertUniqueBatch === undefined ||\n backend.checkUniqueBatch === undefined)\n ) {\n throw new ConfigurationError(\n \"updateWhere() requires batched uniqueness sidecar operations for constrained nodes\",\n { code: \"SET_UPDATE_UNIQUENESS_UNSUPPORTED\", kind },\n );\n }\n if (\n getSearchableFields(schema).length > 0 &&\n (backend.upsertFulltext === undefined ||\n backend.deleteFulltext === undefined ||\n backend.upsertFulltextBatch === undefined ||\n backend.deleteFulltextBatch === undefined)\n ) {\n throw new ConfigurationError(\n \"updateWhere() requires batched fulltext sidecar operations for searchable nodes\",\n { code: \"SET_UPDATE_FULLTEXT_UNSUPPORTED\", kind },\n );\n }\n if (\n getEmbeddingFields(schema).length > 0 &&\n (backend.upsertEmbedding === undefined ||\n backend.deleteEmbedding === undefined ||\n backend.upsertEmbeddingBatch === undefined ||\n backend.deleteEmbeddingBatch === undefined)\n ) {\n throw new ConfigurationError(\n \"updateWhere() requires batched vector sidecar operations for embedded nodes\",\n { code: \"SET_UPDATE_VECTOR_UNSUPPORTED\", kind },\n );\n }\n\n const hookContext = ctx.createBulkOperationContext(\"updateWhere\", kind);\n return ctx.withBulkOperationHooks(hookContext, () =>\n runInWriteTransaction(\n ctx,\n backend,\n async (target, lock) => {\n const updateNodeSet = target.updateNodeSet;\n if (updateNodeSet === undefined) {\n throw new ConfigurationError(\n \"The transaction backend does not support set-based node updates\",\n { code: \"SET_UPDATE_UNSUPPORTED\", kind },\n );\n }\n const hardDeleteUniquesByNodeIds = target.hardDeleteUniquesByNodeIds;\n if (\n uniqueConstraints.length > 0 &&\n (hardDeleteUniquesByNodeIds === undefined ||\n target.insertUniqueBatch === undefined ||\n target.checkUniqueBatch === undefined)\n ) {\n throw new ConfigurationError(\n \"The transaction backend lacks batched uniqueness operations\",\n { code: \"SET_UPDATE_UNIQUENESS_UNSUPPORTED\", kind },\n );\n }\n if (\n getSearchableFields(schema).length > 0 &&\n (target.upsertFulltext === undefined ||\n target.deleteFulltext === undefined ||\n target.upsertFulltextBatch === undefined ||\n target.deleteFulltextBatch === undefined)\n ) {\n throw new ConfigurationError(\n \"The transaction backend lacks batched fulltext operations\",\n { code: \"SET_UPDATE_FULLTEXT_UNSUPPORTED\", kind },\n );\n }\n if (\n getEmbeddingFields(schema).length > 0 &&\n (target.upsertEmbedding === undefined ||\n target.deleteEmbedding === undefined ||\n target.upsertEmbeddingBatch === undefined ||\n target.deleteEmbeddingBatch === undefined)\n ) {\n throw new ConfigurationError(\n \"The transaction backend lacks batched vector operations\",\n { code: \"SET_UPDATE_VECTOR_UNSUPPORTED\", kind },\n );\n }\n const result = await updateNodeSet({\n graphId: ctx.graphId,\n kind,\n patch,\n unsetProperties,\n candidateIds,\n candidateIdColumn,\n });\n if (result.affectedCount === 0) return { affectedCount: 0 };\n\n const sidecarItems = result.rows.map((row) => {\n const props = rowPropsToObject(row.props);\n const validatedProps = validateNodeProps(schema, props, {\n kind,\n operation: \"update\",\n id: row.id,\n });\n if (!canonicalEqual(validatedProps, props)) {\n throw new ValidationError(\n `Set update would persist a non-canonical ${kind} row`,\n {\n entityType: \"node\",\n kind,\n operation: \"update\",\n id: row.id,\n issues: [\n {\n path: \"props\",\n message: \"The complete row requires schema normalization\",\n },\n ],\n },\n );\n }\n return {\n kind,\n id: row.id,\n schema,\n props: validatedProps,\n uniqueConstraints,\n };\n });\n\n if (uniqueConstraints.length > 0) {\n await validateResolvedNodeUniqueness(\n createUniquenessContext(ctx.graphId, ctx.registry, target),\n sidecarItems.map((item) => ({\n kind: item.kind,\n id: item.id,\n props: item.props,\n constraints: item.uniqueConstraints,\n })),\n );\n await requireDefined(hardDeleteUniquesByNodeIds)({\n graphId: ctx.graphId,\n concreteKind: kind,\n nodeIds: result.rows.map((row) => row.id),\n });\n }\n await applyNodeInsertSideEffectsBatch(\n createNodeWriteContext(ctx.graphId, ctx.registry, lock),\n sidecarItems,\n target,\n );\n return { affectedCount: result.affectedCount };\n },\n {\n didWrite: (result) => result.affectedCount > 0,\n // The set update re-checks every changed unique key across the\n // constraint's scope before rebuilding the sidecars, so a shared-scope\n // constraint makes it a constrained write like any other update.\n fencesConstraintProbe: nodeFencesConstraintProbe(ctx, kind, \"update\"),\n },\n ),\n );\n}\n\n/**\n * Executes a node update for upsert — bypasses operation hooks\n * and allows updating soft-deleted nodes when clearDeleted is set.\n */\nexport async function executeNodeUpsertUpdate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: UpsertUpdateNodeInput,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n): Promise<Node> {\n if (input.clearValidTo === true) {\n assertClearValidToSupported(backend, \"node\");\n }\n return runInWriteTransaction(\n ctx,\n backend,\n async (target, lock) => {\n const validTo = validateOptionalCanonicalIsoDate(\n input.validTo,\n \"validTo\",\n );\n const identity = ctx.identity;\n if (\n identity !== undefined &&\n (options?.clearDeleted === true || input.validTo !== undefined)\n ) {\n await identity.lock(target);\n }\n if (identity !== undefined && validTo !== undefined) {\n await identity.requireValidityEndCompatible(\n target,\n { kind: input.kind, id: input.id },\n validTo,\n );\n }\n const node = await performNodeUpdateWithResurrectionRecovery(\n ctx,\n input,\n target,\n lock,\n options,\n );\n if (options?.clearDeleted && identity !== undefined) {\n await identity.foldCreated(target, [\n { kind: input.kind, id: input.id },\n ]);\n }\n return node;\n },\n {\n fencesConstraintProbe: nodeFencesConstraintProbe(\n ctx,\n input.kind,\n \"update\",\n ),\n },\n );\n}\n\n// ============================================================\n// Node Delete Operations\n// ============================================================\n\nexport async function executeNodeDelete<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n id: string,\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n // Gate outside hooks and transaction (matching edge deletes): an absent or\n // already-tombstoned node is a no-op, so it neither fires hooks nor opens a\n // write transaction (empty transactions are costly on libsql). The cascade\n // re-reads inside the transaction, so a node concurrently deleted between\n // this gate and the write lock is still handled correctly.\n const gate = await backend.getNode(ctx.graphId, kind, id);\n if (!gate || gate.deleted_at) return;\n\n const opContext = ctx.createOperationContext(\"delete\", \"node\", kind, id);\n\n return runHookedWriteOperation(\n ctx,\n opContext,\n backend,\n async (target, lock) => {\n const identity = ctx.identity;\n if (identity !== undefined) await identity.lock(target);\n const registration = getNodeRegistration(ctx.graph, kind);\n // This preflight is NOT removable round-trip fat: the soft-delete\n // pipeline consumes the pre-image (uniqueness entries are keyed by\n // props-derived constraint keys), and this in-transaction read is\n // the concurrency-correct source for it.\n const preflight = await target.getNode(ctx.graphId, kind, id);\n if (!preflight || !isLiveNodeRow(preflight)) return;\n\n // The cascade (connected edges, uniques, embeddings, fulltext, node) is\n // not individually atomic, so it runs in one write transaction. Under\n // recorded-time capture this also collapses the cascade into a single\n // recorded commit instant instead of one instant per sub-write.\n await applyNodeSoftDelete(\n createNodeWriteContext(ctx.graphId, ctx.registry, lock),\n {\n existing: preflight,\n schema: registration.type.schema,\n uniqueConstraints: registration.unique ?? [],\n onDelete: registration.onDelete,\n },\n target,\n );\n if (identity !== undefined) {\n await identity.detachDeleted(target, { kind, id }, \"soft\");\n }\n },\n );\n}\n\n/**\n * Soft-deletes a batch without per-item operation hooks.\n *\n * Batch collection methods deliberately omit per-item hooks for throughput.\n * Owning the write transaction here also prevents a per-item success from\n * being reported before the batch's outer COMMIT.\n */\nexport async function executeNodeDeleteBatch<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n ids: readonly string[],\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n await runInWriteTransaction(\n ctx,\n backend,\n async (target, lock) => {\n const identity = ctx.identity;\n if (identity !== undefined) await identity.lock(target);\n const registration = getNodeRegistration(ctx.graph, kind);\n const writeContext = createNodeWriteContext(\n ctx.graphId,\n ctx.registry,\n lock,\n );\n let affectedCount = 0;\n\n for (const id of ids) {\n // This is both the existence gate and the concurrency-correct\n // pre-image consumed by uniqueness cleanup. It must stay inside the\n // batch transaction after the graph write lock is held.\n const preflight = await target.getNode(ctx.graphId, kind, id);\n if (!preflight || !isLiveNodeRow(preflight)) continue;\n\n await applyNodeSoftDelete(\n writeContext,\n {\n existing: preflight,\n schema: registration.type.schema,\n uniqueConstraints: registration.unique ?? [],\n onDelete: registration.onDelete,\n },\n target,\n );\n if (identity !== undefined) {\n await identity.detachDeleted(target, { kind, id }, \"soft\");\n }\n affectedCount += 1;\n }\n\n return affectedCount;\n },\n { didWrite: (affectedCount) => affectedCount > 0 },\n );\n}\n\n/**\n * Executes a node hard delete operation (permanent removal).\n *\n * Unlike soft delete, this permanently removes the node and all\n * associated data (uniqueness entries, embeddings) from the database.\n */\nexport async function executeNodeHardDelete<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n id: string,\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n // Gate outside hooks and transaction so an absent node neither fires hooks\n // nor opens an empty transaction (see executeNodeDelete). The cascade\n // re-reads inside the transaction.\n const gate = await backend.getNode(ctx.graphId, kind, id);\n if (!gate) return;\n\n const opContext = ctx.createOperationContext(\"delete\", \"node\", kind, id);\n\n return runHookedWriteOperation(\n ctx,\n opContext,\n backend,\n async (target, lock) => {\n const identity = ctx.identity;\n if (identity !== undefined) await identity.lock(target);\n const registration = getNodeRegistration(ctx.graph, kind);\n // No in-transaction preflight (unlike soft delete, whose pipeline\n // consumes the pre-image for uniqueness-key cleanup): every hard\n // cascade member is id-keyed and idempotent — the delete-behavior\n // check re-reads edges itself, `hardDeleteNode` deletes by primary\n // key, and embeddings clean up by id — so a node concurrently\n // removed between the gate and the write lock makes each statement\n // a 0-row no-op.\n\n // The cascade (edges, node, embeddings) is not individually atomic, so\n // it runs in one write transaction. Embeddings live in strategy-owned\n // per-`(kind, field)` tables, so they are cleaned up here rather than\n // in the backend's graph-agnostic `hardDeleteNode` cascade.\n await applyNodeHardDelete(\n createNodeWriteContext(ctx.graphId, ctx.registry, lock),\n {\n kind,\n id,\n schema: registration.type.schema,\n onDelete: registration.onDelete,\n },\n target,\n );\n if (identity !== undefined) {\n await identity.detachDeleted(target, { kind, id }, \"hard\");\n }\n },\n );\n}\n\n// ============================================================\n// Get-Or-Create Operations\n// ============================================================\n\nexport async function executeNodeGetOrCreateByConstraint<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n constraintName: string,\n props: Record<string, unknown>,\n backend: GraphBackend | TransactionBackend,\n options?: NodeGetOrCreateByConstraintOptions,\n): Promise<Readonly<{ node: Node; action: GetOrCreateAction }>> {\n const ifExists = options?.ifExists ?? \"return\";\n\n const registration = getNodeRegistration(ctx.graph, kind);\n const nodeKind = registration.type;\n const validatedProps = validateNodeProps(nodeKind.schema, props, {\n kind,\n operation: \"create\",\n });\n\n const constraint = resolveConstraint(ctx.graph, kind, constraintName);\n\n if (!checkWherePredicate(constraint, validatedProps)) {\n const node = await executeNodeCreate(\n ctx,\n { kind, props: validatedProps },\n backend,\n { propsPreValidated: true },\n );\n return { node, action: \"created\" };\n }\n\n const key = computeUniqueKey(\n validatedProps,\n constraint.fields,\n constraint.collation,\n );\n\n const kindsToCheck = getKindsForUniquenessCheck(\n kind,\n constraint.scope,\n ctx.registry,\n );\n\n // The probe runs outside any transaction (the found path is a pure read),\n // and each write leg opens its own hooked transaction. A concurrent create\n // can therefore reserve the key between the probe and the create — that\n // surfaces as UniquenessError, and the caller retries the probe once to\n // converge on the row the winner created.\n async function attempt(): Promise<\n Readonly<{ node: Node; action: GetOrCreateAction }>\n > {\n const existingUniqueRow = await findUniqueRowAcrossKinds(\n backend,\n ctx.graphId,\n constraint.name,\n key,\n kindsToCheck,\n true,\n );\n\n if (existingUniqueRow === undefined) {\n const node = await executeNodeCreate(\n ctx,\n { kind, props: validatedProps },\n backend,\n { propsPreValidated: true },\n );\n return { node, action: \"created\" };\n }\n\n // Fetch using concrete_kind (may differ from requested kind\n // when scope is \"kindWithSubClasses\" and the match is on a sibling/parent kind)\n const existingRow = await backend.getNode(\n ctx.graphId,\n existingUniqueRow.concrete_kind,\n existingUniqueRow.node_id,\n );\n\n if (existingRow === undefined) {\n const node = await executeNodeCreate(\n ctx,\n { kind, props: validatedProps },\n backend,\n { propsPreValidated: true },\n );\n return { node, action: \"created\" };\n }\n\n const isSoftDeleted = existingRow.deleted_at !== undefined;\n\n if (isSoftDeleted || ifExists === \"update\") {\n const concreteKind = existingUniqueRow.concrete_kind;\n const node = await executeNodeUpsertUpdate(\n ctx,\n {\n kind: concreteKind,\n id: existingRow.id as UpdateNodeInput[\"id\"],\n props: validatedProps,\n },\n backend,\n { clearDeleted: isSoftDeleted },\n );\n return { node, action: isSoftDeleted ? \"resurrected\" : \"updated\" };\n }\n\n return { node: rowToNode(existingRow), action: \"found\" };\n }\n\n try {\n return await attempt();\n } catch (error) {\n if (!(error instanceof UniquenessError)) throw error;\n return attempt();\n }\n}\n\n// ============================================================\n// Find-By-Constraint Operations\n// ============================================================\n\nexport async function executeNodeFindByConstraint<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n constraintName: string,\n props: Record<string, unknown>,\n backend: GraphBackend | TransactionBackend,\n): Promise<Node | undefined> {\n const registration = getNodeRegistration(ctx.graph, kind);\n const nodeKind = registration.type;\n const validatedProps = validateNodeProps(nodeKind.schema, props, {\n kind,\n operation: \"create\",\n });\n\n const constraint = resolveConstraint(ctx.graph, kind, constraintName);\n if (!checkWherePredicate(constraint, validatedProps)) return undefined;\n\n const key = computeUniqueKey(\n validatedProps,\n constraint.fields,\n constraint.collation,\n );\n\n const kindsToCheck = getKindsForUniquenessCheck(\n kind,\n constraint.scope,\n ctx.registry,\n );\n\n const existingUniqueRow = await findUniqueRowAcrossKinds(\n backend,\n ctx.graphId,\n constraint.name,\n key,\n kindsToCheck,\n false,\n );\n\n if (existingUniqueRow === undefined) return undefined;\n\n const existingRow = await backend.getNode(\n ctx.graphId,\n existingUniqueRow.concrete_kind,\n existingUniqueRow.node_id,\n );\n\n if (existingRow === undefined || existingRow.deleted_at !== undefined)\n return undefined;\n\n return rowToNode(existingRow);\n}\n\n// ============================================================\n// Bulk Find-By-Constraint\n// ============================================================\n\n/**\n * Validates all items and computes unique constraint keys.\n * Shared by both bulk find and bulk getOrCreate.\n */\nfunction validateAndComputeKeys(\n nodeKind: NodeType,\n kind: string,\n constraint: UniqueConstraint,\n items: readonly Readonly<{ props: Record<string, unknown> }>[],\n): { validatedProps: Record<string, unknown>; key: string | undefined }[] {\n const validated: {\n validatedProps: Record<string, unknown>;\n key: string | undefined;\n }[] = [];\n\n for (const item of items) {\n const validatedProps = validateNodeProps(nodeKind.schema, item.props, {\n kind,\n operation: \"create\",\n });\n const applies = checkWherePredicate(constraint, validatedProps);\n const key =\n applies ?\n computeUniqueKey(\n validatedProps,\n constraint.fields,\n constraint.collation,\n )\n : undefined;\n validated.push({ validatedProps, key });\n }\n\n return validated;\n}\n\nfunction collectUniqueKeys(\n validated: readonly { key: string | undefined }[],\n): string[] {\n return [\n ...new Set(\n validated\n .map((entry) => entry.key)\n .filter((key): key is string => key !== undefined),\n ),\n ];\n}\n\nexport async function executeNodeBulkFindByConstraint<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n constraintName: string,\n items: readonly Readonly<{ props: Record<string, unknown> }>[],\n backend: GraphBackend | TransactionBackend,\n): Promise<(Node | undefined)[]> {\n if (items.length === 0) return [];\n\n const registration = getNodeRegistration(ctx.graph, kind);\n const nodeKind = registration.type;\n const constraint = resolveConstraint(ctx.graph, kind, constraintName);\n\n const validated = validateAndComputeKeys(nodeKind, kind, constraint, items);\n const uniqueKeys = collectUniqueKeys(validated);\n\n const kindsToCheck = getKindsForUniquenessCheck(\n kind,\n constraint.scope,\n ctx.registry,\n );\n\n const existingByKey =\n uniqueKeys.length > 0 ?\n await batchCheckUniqueAcrossKinds(\n backend,\n ctx.graphId,\n constraint.name,\n uniqueKeys,\n kindsToCheck,\n false,\n )\n : new Map<string, { node_id: string; concrete_kind: string }>();\n\n // Assemble results, deduplicating keys seen within the batch\n const results: (Node | undefined)[] = Array.from({ length: items.length });\n const seenKeys = new Map<string, number>();\n\n for (const [index, { key }] of validated.entries()) {\n if (key === undefined) {\n results[index] = undefined;\n continue;\n }\n\n const previousIndex = seenKeys.get(key);\n if (previousIndex !== undefined) {\n results[index] = results[previousIndex];\n continue;\n }\n seenKeys.set(key, index);\n\n const existing = existingByKey.get(key);\n if (existing === undefined) {\n results[index] = undefined;\n continue;\n }\n\n const existingRow = await backend.getNode(\n ctx.graphId,\n existing.concrete_kind,\n existing.node_id,\n );\n\n if (existingRow === undefined || existingRow.deleted_at !== undefined) {\n results[index] = undefined;\n continue;\n }\n\n results[index] = rowToNode(existingRow);\n }\n\n return results;\n}\n\n// ============================================================\n// Bulk Find-By-Index\n// ============================================================\n\n/**\n * Resolves a declared node index by name, validating the kind first.\n *\n * @throws {KindNotFoundError} when the node kind is not registered\n * @throws {NodeIndexNotFoundError} when no node index of that name exists\n */\nfunction resolveNodeIndex<G extends GraphDef>(\n graph: G,\n kind: string,\n indexName: string,\n): NodeIndexDeclaration {\n getNodeRegistration(graph, kind);\n\n const declaration = graph.indexes?.find(\n (candidate) =>\n candidate.entity === \"node\" &&\n candidate.kind === kind &&\n candidate.name === indexName,\n );\n\n if (declaration?.entity !== \"node\") {\n throw new NodeIndexNotFoundError(indexName, kind);\n }\n\n // GIN-family indexes serve containment / substring predicates, not the\n // equality probes bulkFindByIndex compiles — targeting one here would\n // silently probe with the wrong extraction semantics.\n if (declaration.method !== undefined) {\n throw new ConfigurationError(\n `bulkFindByIndex cannot probe index \"${indexName}\" (method ` +\n `\"${declaration.method}\"): only btree indexes serve equality probes.`,\n { indexName, kind, method: declaration.method },\n );\n }\n\n return declaration;\n}\n\nconst INDEX_PROBE_EXPECTED_TYPEOF: Partial<Record<ValueType, string>> = {\n string: \"string\",\n number: \"number\",\n boolean: \"boolean\",\n};\n\n/**\n * Validates a single probe value against its declared index-field type.\n * Missing/null values are valid (null probes); only a present, scalar\n * value of the wrong type is rejected.\n */\nfunction validateIndexProbeValue(\n value: unknown,\n valueType: ValueType | undefined,\n pointer: JsonPointer,\n kind: string,\n): void {\n if (value === undefined || value === null) return;\n\n // Index keys are scalar; a non-scalar probe can't be bound and must fail\n // with a typed error rather than a cryptic driver bind error downstream.\n if (\n typeof value !== \"string\" &&\n typeof value !== \"number\" &&\n typeof value !== \"boolean\" &&\n !(value instanceof Date)\n ) {\n throw indexProbeTypeError(\n pointer,\n kind,\n \"a scalar (string, number, boolean, or Date)\",\n value,\n );\n }\n\n if (valueType === \"date\") {\n if (value instanceof Date || typeof value === \"string\") return;\n throw indexProbeTypeError(\n pointer,\n kind,\n \"date (Date or ISO string)\",\n value,\n );\n }\n\n const expected = INDEX_PROBE_EXPECTED_TYPEOF[valueType ?? \"unknown\"];\n if (expected === undefined) return;\n if (typeof value !== expected) {\n throw indexProbeTypeError(pointer, kind, expected, value);\n }\n}\n\nfunction indexProbeTypeError(\n pointer: JsonPointer,\n kind: string,\n expected: string,\n value: unknown,\n): ValidationError {\n return new ValidationError(\n `Index probe value for \"${pointer}\" on node kind \"${kind}\" has an incompatible type`,\n {\n entityType: \"node\",\n kind,\n issues: [\n {\n path: pointer,\n message: `Expected ${expected}, received ${typeof value}`,\n code: \"invalid_type\",\n },\n ],\n },\n );\n}\n\n/** Coerces a non-null probe value into a driver-bindable scalar. */\nfunction coerceIndexProbeBind(\n value: unknown,\n adapter: DialectAdapter,\n): unknown {\n return adapter.bindValue(normalizeProbeScalar(value as ProbeScalar));\n}\n\ntype ProbeScalar = string | number | boolean | Date;\n\n/**\n * Canonical scalar form of a validated probe value, shared by the dedup key\n * and the bound SQL value so the two can never drift (a Date and its ISO\n * string normalize identically — and produce identical predicates).\n */\nfunction normalizeProbeScalar(value: ProbeScalar): string | number | boolean {\n return value instanceof Date ? value.toISOString() : value;\n}\n\nconst PROBE_NULL_TAG = 0;\nconst PROBE_VALUE_TAG = 1;\n\n/**\n * Stable dedup key for a probe tuple. Each slot is tagged so a null/undefined\n * value can never collide with a string that happens to equal a sentinel -\n * null maps to [0], a present scalar to [1, normalized].\n */\nfunction canonicalIndexProbeKey(probe: readonly unknown[]): string {\n return JSON.stringify(\n probe.map((value) =>\n value === undefined || value === null ?\n [PROBE_NULL_TAG]\n : [PROBE_VALUE_TAG, normalizeProbeScalar(value as ProbeScalar)],\n ),\n );\n}\n\n/**\n * Batched candidate retrieval against a declared node index.\n *\n * Emits a single query against the nodes table: each input's indexed-field\n * values become a probe predicate (null-safe equality, reusing the index's\n * own extraction expressions so the planner can use the physical index), and\n * a `CASE` selector tags each matched row with the deduped probe group it\n * satisfies. Rows are grouped back to input positions in order; each input's\n * candidate set is ordered by node id.\n */\nexport async function executeNodeBulkFindByIndex<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n indexName: string,\n items: readonly Readonly<{ props: Record<string, unknown> }>[],\n backend: GraphBackend | TransactionBackend,\n options?: NodeBulkFindByIndexOptions,\n): Promise<Node[][]> {\n if (items.length === 0) return [];\n\n const index = resolveNodeIndex(ctx.graph, kind, indexName);\n\n if (index.fields.length === 0) {\n throw new ConfigurationError(\n `bulkFindByIndex requires an index with at least one prop-based field on index \"${indexName}\" (node kind \"${kind}\")`,\n { indexName, kind },\n {\n suggestion:\n \"bulkFindByIndex probes by prop values from each item; an index declared with only keySystemColumns/coveringFields (no fields) has nothing to probe by.\",\n },\n );\n }\n\n // Date-typed lookup keys can't satisfy the cross-backend parity guarantee:\n // SQLite compares stored ISO text byte-wise while Postgres compares\n // timestamptz instants, so equal instants in different ISO forms diverge.\n // Declare the gap rather than return backend-dependent results.\n if (index.fieldValueTypes.includes(\"date\")) {\n throw new ConfigurationError(\n `bulkFindByIndex does not support date-typed key fields on index \"${indexName}\" (node kind \"${kind}\")`,\n { indexName, kind },\n {\n suggestion:\n \"Date index keys compare differently across SQLite and PostgreSQL. Use a string-encoded key field, or query date predicates via store.query(...).where(...).\",\n },\n );\n }\n\n const limitPerInput = options?.limitPerInput;\n if (\n limitPerInput !== undefined &&\n (!Number.isInteger(limitPerInput) || limitPerInput <= 0)\n ) {\n throw new ValidationError(\n \"bulkFindByIndex limitPerInput must be a positive integer\",\n {\n entityType: \"node\",\n kind,\n issues: [\n {\n path: \"limitPerInput\",\n message: `Expected a positive integer, received ${String(limitPerInput)}`,\n code: \"invalid_value\",\n },\n ],\n },\n );\n }\n\n const adapter = getDialect(backend.dialect);\n\n // 1. Extract + validate each input's indexed-field probe tuple.\n const probes: unknown[][] = items.map((item) =>\n index.fields.map((pointer, position) => {\n const value = resolveJsonPointer(item.props, pointer);\n validateIndexProbeValue(\n value,\n index.fieldValueTypes[position],\n pointer,\n kind,\n );\n return value;\n }),\n );\n\n // 2. Dedupe probe tuples; map each distinct tuple to its input positions.\n const groupByKey = new Map<string, number>();\n const groupProbes: unknown[][] = [];\n const groupToInputs: number[][] = [];\n for (const [inputIndex, probe] of probes.entries()) {\n const key = canonicalIndexProbeKey(probe);\n const existing = groupByKey.get(key);\n if (existing === undefined) {\n groupByKey.set(key, groupProbes.length);\n groupProbes.push(probe);\n groupToInputs.push([inputIndex]);\n continue;\n }\n groupToInputs[existing]?.push(inputIndex);\n }\n\n // 3. Build probe predicates shared by the CASE selector and WHERE filter.\n const schema =\n backend.tableNames ?\n createSqlSchema(backend.tableNames)\n : DEFAULT_SQL_SCHEMA;\n const compileContext: IndexCompilationContext = {\n dialect: backend.dialect,\n propsColumn: sql.raw(`\"props\"`),\n systemColumn: (column) => sql.raw(`\"${column}\"`),\n };\n const fieldKeys = compileNodeIndexFieldKeys(index, compileContext);\n\n const groupPredicates = groupProbes.map(\n (probe) =>\n sql`(${sql.join(\n fieldKeys.map((fieldKey, position) => {\n const value = probe[position];\n if (value === undefined || value === null) {\n return sql`${fieldKey} IS NULL`;\n }\n return adapter.nullSafeEquals(\n fieldKey,\n sql`${coerceIndexProbeBind(value, adapter)}`,\n );\n }),\n sql` AND `,\n )})`,\n );\n\n const caseBranches = groupPredicates.map(\n (predicate, group) => sql`WHEN ${predicate} THEN ${sql.raw(String(group))}`,\n );\n const probeIndexExpr = sql`CASE ${sql.join(caseBranches, sql` `)} ELSE NULL END`;\n\n const conditions: SqlFragment[] = [\n sql`\"graph_id\" = ${ctx.graphId}`,\n sql`\"kind\" = ${kind}`,\n sql`\"deleted_at\" IS NULL`,\n ];\n if (index.where !== undefined) {\n conditions.push(compileIndexWhere(compileContext, index.where));\n }\n conditions.push(sql`(${sql.join(groupPredicates, sql` OR `)})`);\n const whereClause = sql.join(conditions, sql` AND `);\n\n // The probe matching runs against the nodes table; rows are hydrated\n // separately via the backend's normalized node reads so the returned\n // shape is identical to every other node API (props/timestamp\n // normalization is backend-owned, not re-derived from raw driver rows).\n const probedSelect = sql`SELECT \"id\", ${probeIndexExpr} AS probe_idx FROM ${schema.nodesTable} WHERE ${whereClause}`;\n\n // limitPerInput caps each input's candidates per probe group. When the\n // backend supports window functions we cap in SQL (`ROW_NUMBER()`), which\n // also avoids transferring excess ids on low-selectivity keys. Otherwise we\n // degrade gracefully: fetch all matching ids and cap per group in JS before\n // hydration — the cap stays correct, only the id transfer is unbounded.\n const capInSql =\n limitPerInput !== undefined && backend.capabilities.windowFunctions;\n\n const query =\n capInSql ?\n sql`SELECT \"id\", probe_idx FROM (SELECT \"id\", probe_idx, ROW_NUMBER() OVER (PARTITION BY probe_idx ORDER BY \"id\") AS probe_rank FROM (${probedSelect}) AS probed) AS ranked WHERE probe_rank <= ${limitPerInput} ORDER BY probe_idx, \"id\"`\n : sql`${probedSelect} ORDER BY probe_idx, \"id\"`;\n\n // 4. Execute, hydrate matched nodes, and group back to input positions.\n const rawMatches = await backend.execute<ProbeMatch>(\n asCompiledRowsSql(query),\n );\n const matches =\n limitPerInput !== undefined && !capInSql ?\n capMatchesPerGroup(rawMatches, limitPerInput)\n : rawMatches;\n\n const nodesById = await hydrateNodesById(\n backend,\n ctx.graphId,\n kind,\n matches.map((match) => match.id),\n );\n\n const results: Node[][] = Array.from({ length: items.length }, () => []);\n for (const match of matches) {\n const node = nodesById.get(match.id);\n if (node === undefined) continue;\n const inputs = groupToInputs[match.probe_idx];\n if (inputs === undefined) continue;\n for (const inputIndex of inputs) {\n results[inputIndex]?.push(node);\n }\n }\n\n return results;\n}\n\ntype ProbeMatch = Readonly<{ id: string; probe_idx: number }>;\n\n/**\n * Caps matches to the first `limitPerInput` per probe group (the JS-side\n * equivalent of the `ROW_NUMBER()` window). Relies on `matches` already being\n * ordered by `(probe_idx, id)`, so the kept rows are the lowest ids per group.\n */\nfunction capMatchesPerGroup(\n matches: readonly ProbeMatch[],\n limitPerInput: number,\n): ProbeMatch[] {\n const perGroupCount = new Map<number, number>();\n const capped: ProbeMatch[] = [];\n for (const match of matches) {\n const count = perGroupCount.get(match.probe_idx) ?? 0;\n if (count >= limitPerInput) continue;\n perGroupCount.set(match.probe_idx, count + 1);\n capped.push(match);\n }\n return capped;\n}\n\n/** Hydrates live nodes by id via the backend's normalized node reads. */\nasync function hydrateNodesById(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n kind: string,\n ids: readonly string[],\n): Promise<Map<string, Node>> {\n const rowsById = await getNodeRowsByIds(backend, graphId, kind, ids);\n const nodesById = new Map<string, Node>();\n for (const [id, row] of rowsById) {\n if (row.deleted_at !== undefined) continue;\n nodesById.set(id, rowToNode(row));\n }\n return nodesById;\n}\n\n// ============================================================\n// Bulk Get-Or-Create-By-Constraint\n// ============================================================\n\nexport async function executeNodeBulkGetOrCreateByConstraint<\n G extends GraphDef,\n>(\n ctx: NodeOperationContext<G>,\n kind: string,\n constraintName: string,\n items: readonly Readonly<{ props: Record<string, unknown> }>[],\n backend: GraphBackend | TransactionBackend,\n options?: NodeGetOrCreateByConstraintOptions,\n): Promise<Readonly<{ node: Node; action: GetOrCreateAction }>[]> {\n if (items.length === 0) return [];\n\n const ifExists = options?.ifExists ?? \"return\";\n const registration = getNodeRegistration(ctx.graph, kind);\n const nodeKind = registration.type;\n const constraint = resolveConstraint(ctx.graph, kind, constraintName);\n\n // Step 1: Validate all props and compute keys\n const validated = validateAndComputeKeys(nodeKind, kind, constraint, items);\n const uniqueKeys = collectUniqueKeys(validated);\n\n const kindsToCheck = getKindsForUniquenessCheck(\n kind,\n constraint.scope,\n ctx.registry,\n );\n\n type Result = Readonly<{ node: Node; action: GetOrCreateAction }>;\n\n // Steps 2-6 are one convergence attempt: the batch probe runs outside any\n // transaction and each write leg opens its own, so a concurrent create can\n // reserve a key between them. The uniques primary key catches that and raises\n // `UniquenessError`; re-running the whole attempt converges on the winner's\n // row. Without this the single-item path retried and the batch failed\n // outright, which is the asymmetry #428 called out.\n async function attempt(): Promise<Result[]> {\n // Step 2: Batch-check existing keys\n const existingByKey =\n uniqueKeys.length > 0 ?\n await batchCheckUniqueAcrossKinds(\n backend,\n ctx.graphId,\n constraint.name,\n uniqueKeys,\n kindsToCheck,\n true,\n )\n : new Map<\n string,\n {\n node_id: string;\n concrete_kind: string;\n deleted_at: string | undefined;\n }\n >();\n\n // Step 3: Partition into toCreate, toFetch, and duplicates\n const toCreate: { index: number; input: CreateNodeInput }[] = [];\n const toFetch: {\n index: number;\n nodeId: string;\n concreteKind: string;\n validatedProps: Record<string, unknown>;\n }[] = [];\n const duplicateOf: { index: number; sourceIndex: number }[] = [];\n const seenKeys = new Map<string, number>();\n\n for (const [index, { validatedProps, key }] of validated.entries()) {\n if (key === undefined) {\n toCreate.push({ index, input: { kind, props: validatedProps } });\n continue;\n }\n\n const previousIndex = seenKeys.get(key);\n if (previousIndex !== undefined) {\n duplicateOf.push({ index, sourceIndex: previousIndex });\n continue;\n }\n\n seenKeys.set(key, index);\n\n const existing = existingByKey.get(key);\n if (existing === undefined) {\n toCreate.push({ index, input: { kind, props: validatedProps } });\n } else {\n toFetch.push({\n index,\n nodeId: existing.node_id,\n concreteKind: existing.concrete_kind,\n validatedProps,\n });\n }\n }\n\n const results: Result[] = Array.from({ length: items.length });\n\n // Step 4: Execute creates\n if (toCreate.length > 0) {\n const createInputs = toCreate.map((entry) => entry.input);\n const createdNodes = await executeNodeCreateBatch(\n ctx,\n createInputs,\n backend,\n { propsPreValidated: true },\n );\n for (const [batchIndex, entry] of toCreate.entries()) {\n results[entry.index] = {\n node: requireDefined(createdNodes[batchIndex]),\n action: \"created\",\n };\n }\n }\n\n // Step 5: Handle existing nodes (fetch/update/resurrect)\n for (const entry of toFetch) {\n const { index, concreteKind, validatedProps, nodeId } = entry;\n\n const existingRow = await backend.getNode(\n ctx.graphId,\n concreteKind,\n nodeId,\n );\n\n if (existingRow === undefined) {\n const node = await executeNodeCreate(\n ctx,\n { kind, props: validatedProps },\n backend,\n { propsPreValidated: true },\n );\n results[index] = { node, action: \"created\" };\n continue;\n }\n\n // Read from the NODE ROW this loop just fetched, not from the uniques row\n // the batch probe captured back in step 2 — the single-item path has\n // always derived it here (see `executeNodeGetOrCreateByConstraint`), and\n // one decision with two owners drifts. The uniques copy is also the\n // staler of the two: step 4's creates run between the probe and this\n // read, and a peer can soft-delete or resurrect the node in that window.\n // Whether this write RESURRECTS has to come from the row it will target.\n const isSoftDeleted = existingRow.deleted_at !== undefined;\n\n if (isSoftDeleted || ifExists === \"update\") {\n const node = await executeNodeUpsertUpdate(\n ctx,\n {\n kind: concreteKind,\n id: existingRow.id as UpdateNodeInput[\"id\"],\n props: validatedProps,\n },\n backend,\n { clearDeleted: isSoftDeleted },\n );\n results[index] = {\n node,\n action: isSoftDeleted ? \"resurrected\" : \"updated\",\n };\n } else {\n results[index] = { node: rowToNode(existingRow), action: \"found\" };\n }\n }\n\n // Step 6: Resolve within-batch duplicates by copying the first occurrence's result\n for (const { index, sourceIndex } of duplicateOf) {\n const sourceResult = requireDefined(results[sourceIndex]);\n results[index] = { node: sourceResult.node, action: \"found\" };\n }\n\n return results;\n }\n\n try {\n return await attempt();\n } catch (error) {\n if (!(error instanceof UniquenessError)) throw error;\n return attempt();\n }\n}\n"]}