@nicia-ai/typegraph 0.50.0 → 0.51.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -0
- package/dist/backend/drizzle/indexes.cjs +10 -8
- package/dist/backend/drizzle/indexes.d.cts +1 -1
- package/dist/backend/drizzle/indexes.d.ts +1 -1
- package/dist/backend/drizzle/indexes.js +6 -4
- package/dist/backend/index.cjs +183 -50
- package/dist/backend/index.d.cts +90 -4
- package/dist/backend/index.d.ts +90 -4
- package/dist/backend/index.js +6 -9
- package/dist/backend/postgres/index.cjs +30 -28
- package/dist/backend/postgres/index.d.cts +7 -7
- package/dist/backend/postgres/index.d.ts +7 -7
- package/dist/backend/postgres/index.js +16 -14
- package/dist/backend/postgres/pglite-store.cjs +6 -62
- package/dist/backend/postgres/pglite-store.cjs.map +1 -1
- package/dist/backend/postgres/pglite-store.d.cts +8 -8
- package/dist/backend/postgres/pglite-store.d.ts +8 -8
- package/dist/backend/postgres/pglite-store.js +6 -62
- package/dist/backend/postgres/pglite-store.js.map +1 -1
- package/dist/backend/postgres/pglite.cjs +18 -16
- package/dist/backend/postgres/pglite.d.cts +3 -3
- package/dist/backend/postgres/pglite.d.ts +3 -3
- package/dist/backend/postgres/pglite.js +17 -15
- package/dist/backend/sqlite/index.cjs +27 -25
- package/dist/backend/sqlite/index.d.cts +7 -7
- package/dist/backend/sqlite/index.d.ts +7 -7
- package/dist/backend/sqlite/index.js +14 -12
- package/dist/backend/sqlite/libsql.cjs +21 -19
- package/dist/backend/sqlite/libsql.cjs.map +1 -1
- package/dist/backend/sqlite/libsql.d.cts +3 -3
- package/dist/backend/sqlite/libsql.d.ts +3 -3
- package/dist/backend/sqlite/libsql.js +16 -14
- package/dist/backend/sqlite/libsql.js.map +1 -1
- package/dist/backend/sqlite/local-store.cjs +8 -64
- package/dist/backend/sqlite/local-store.cjs.map +1 -1
- package/dist/backend/sqlite/local-store.d.cts +8 -8
- package/dist/backend/sqlite/local-store.d.ts +8 -8
- package/dist/backend/sqlite/local-store.js +7 -64
- package/dist/backend/sqlite/local-store.js.map +1 -1
- package/dist/backend/sqlite/local.cjs +22 -19
- package/dist/backend/sqlite/local.d.cts +3 -3
- package/dist/backend/sqlite/local.d.ts +3 -3
- package/dist/backend/sqlite/local.js +18 -15
- package/dist/{chunk-TUVD4DFR.cjs → chunk-2CVDZCXH.cjs} +122 -51
- package/dist/chunk-2CVDZCXH.cjs.map +1 -0
- package/dist/{chunk-I5C6OTKR.js → chunk-2DWTBNSH.js} +3 -3
- package/dist/{chunk-I5C6OTKR.js.map → chunk-2DWTBNSH.js.map} +1 -1
- package/dist/{chunk-C76WFIVZ.cjs → chunk-2KCTP3U2.cjs} +180 -127
- package/dist/chunk-2KCTP3U2.cjs.map +1 -0
- package/dist/{chunk-BYBDM423.cjs → chunk-322TBTOQ.cjs} +48 -48
- package/dist/{chunk-BYBDM423.cjs.map → chunk-322TBTOQ.cjs.map} +1 -1
- package/dist/chunk-36SX6QXP.cjs +186 -0
- package/dist/chunk-36SX6QXP.cjs.map +1 -0
- package/dist/{chunk-H3XP6BAV.js → chunk-36VYWVQU.js} +3 -3
- package/dist/{chunk-H3XP6BAV.js.map → chunk-36VYWVQU.js.map} +1 -1
- package/dist/{chunk-VTJVMP4I.js → chunk-4DKY6RIU.js} +102 -31
- package/dist/chunk-4DKY6RIU.js.map +1 -0
- package/dist/chunk-4QKOZYMV.js +9 -0
- package/dist/chunk-4QKOZYMV.js.map +1 -0
- package/dist/{chunk-U3Z7XKAG.js → chunk-57JM6NW3.js} +8 -18
- package/dist/chunk-57JM6NW3.js.map +1 -0
- package/dist/{chunk-WCLMKNQE.cjs → chunk-5FVZSE3B.cjs} +1356 -1108
- package/dist/chunk-5FVZSE3B.cjs.map +1 -0
- package/dist/{chunk-XMY2SXOH.cjs → chunk-5WWEYV4H.cjs} +2208 -579
- package/dist/chunk-5WWEYV4H.cjs.map +1 -0
- package/dist/{chunk-WQBAQZHR.js → chunk-6NLYIMJO.js} +4 -4
- package/dist/{chunk-WQBAQZHR.js.map → chunk-6NLYIMJO.js.map} +1 -1
- package/dist/{chunk-G2TLHH6T.cjs → chunk-7B7I7YAW.cjs} +6 -6
- package/dist/{chunk-G2TLHH6T.cjs.map → chunk-7B7I7YAW.cjs.map} +1 -1
- package/dist/{chunk-EDLKIQRI.js → chunk-7G5IYROL.js} +6 -548
- package/dist/chunk-7G5IYROL.js.map +1 -0
- package/dist/{chunk-46UGOVRW.js → chunk-7QFRK6PU.js} +3 -7
- package/dist/chunk-7QFRK6PU.js.map +1 -0
- package/dist/chunk-A4C4NJ5U.cjs +12 -0
- package/dist/chunk-A4C4NJ5U.cjs.map +1 -0
- package/dist/{chunk-7CCMCMJO.cjs → chunk-AOGOC6JF.cjs} +77 -68
- package/dist/chunk-AOGOC6JF.cjs.map +1 -0
- package/dist/{chunk-TYGGUWMS.cjs → chunk-B3MN7EJR.cjs} +177 -137
- package/dist/chunk-B3MN7EJR.cjs.map +1 -0
- package/dist/{chunk-K6VKTBST.cjs → chunk-BZ5MVITP.cjs} +4 -4
- package/dist/{chunk-K6VKTBST.cjs.map → chunk-BZ5MVITP.cjs.map} +1 -1
- package/dist/{chunk-ZAQUKCUC.js → chunk-CBOD7TXH.js} +5 -5
- package/dist/{chunk-ZAQUKCUC.js.map → chunk-CBOD7TXH.js.map} +1 -1
- package/dist/{chunk-LLVOQOWE.cjs → chunk-CRZ56SZU.cjs} +6 -5
- package/dist/chunk-CRZ56SZU.cjs.map +1 -0
- package/dist/{chunk-ON47CBE4.cjs → chunk-D3GWARN7.cjs} +47 -47
- package/dist/{chunk-ON47CBE4.cjs.map → chunk-D3GWARN7.cjs.map} +1 -1
- package/dist/{chunk-W5SOCUBL.js → chunk-D3OUDFU7.js} +5 -5
- package/dist/{chunk-W5SOCUBL.js.map → chunk-D3OUDFU7.js.map} +1 -1
- package/dist/chunk-EKG2UXNX.cjs +23 -0
- package/dist/chunk-EKG2UXNX.cjs.map +1 -0
- package/dist/{chunk-2Q45FAIE.js → chunk-EVYW3532.js} +28 -19
- package/dist/chunk-EVYW3532.js.map +1 -0
- package/dist/{chunk-7PRMDZIA.cjs → chunk-FMMW3KX7.cjs} +21 -55
- package/dist/chunk-FMMW3KX7.cjs.map +1 -0
- package/dist/chunk-H2VWDQWC.cjs +571 -0
- package/dist/chunk-H2VWDQWC.cjs.map +1 -0
- package/dist/chunk-H4FY6OZK.js +13 -0
- package/dist/chunk-H4FY6OZK.js.map +1 -0
- package/dist/{chunk-OJHD3LXJ.cjs → chunk-H5IJSROF.cjs} +2 -8
- package/dist/chunk-H5IJSROF.cjs.map +1 -0
- package/dist/{chunk-U5EL6JUV.js → chunk-I5IOSA27.js} +101 -103
- package/dist/chunk-I5IOSA27.js.map +1 -0
- package/dist/{chunk-SHC7BCG5.cjs → chunk-I7YAY2VQ.cjs} +7 -7
- package/dist/{chunk-SHC7BCG5.cjs.map → chunk-I7YAY2VQ.cjs.map} +1 -1
- package/dist/chunk-IRCWIA3R.js +20 -0
- package/dist/chunk-IRCWIA3R.js.map +1 -0
- package/dist/chunk-IVQBLXBK.cjs +55 -0
- package/dist/chunk-IVQBLXBK.cjs.map +1 -0
- package/dist/{chunk-5PP4KRPV.js → chunk-IZD4HTCP.js} +5 -5
- package/dist/{chunk-5PP4KRPV.js.map → chunk-IZD4HTCP.js.map} +1 -1
- package/dist/{chunk-RDP6ZRSM.cjs → chunk-JQKMEKKW.cjs} +261 -204
- package/dist/chunk-JQKMEKKW.cjs.map +1 -0
- package/dist/chunk-JVA3KDEA.cjs +691 -0
- package/dist/chunk-JVA3KDEA.cjs.map +1 -0
- package/dist/{chunk-JG5XIJDY.js → chunk-K67P5DLL.js} +62 -22
- package/dist/chunk-K67P5DLL.js.map +1 -0
- package/dist/{chunk-MX7EKQPM.js → chunk-K6OZIHKI.js} +345 -97
- package/dist/chunk-K6OZIHKI.js.map +1 -0
- package/dist/{chunk-CS6JTQQ2.cjs → chunk-KACEYDYV.cjs} +94 -62
- package/dist/chunk-KACEYDYV.cjs.map +1 -0
- package/dist/{chunk-5OWHU7Z7.cjs → chunk-L6EVYIID.cjs} +248 -210
- package/dist/chunk-L6EVYIID.cjs.map +1 -0
- package/dist/{chunk-7OWE7WD6.js → chunk-LI4K2KEJ.js} +4 -4
- package/dist/{chunk-7OWE7WD6.js.map → chunk-LI4K2KEJ.js.map} +1 -1
- package/dist/chunk-LKZDQ2B4.js +1581 -0
- package/dist/chunk-LKZDQ2B4.js.map +1 -0
- package/dist/{chunk-45YZXI6X.cjs → chunk-LLFPQOBA.cjs} +27 -27
- package/dist/{chunk-45YZXI6X.cjs.map → chunk-LLFPQOBA.cjs.map} +1 -1
- package/dist/{chunk-ZRJTM7MT.js → chunk-LZMQ3SFK.js} +3 -3
- package/dist/{chunk-ZRJTM7MT.js.map → chunk-LZMQ3SFK.js.map} +1 -1
- package/dist/{chunk-DI6VC62F.js → chunk-M3VTS3F6.js} +3 -3
- package/dist/{chunk-DI6VC62F.js.map → chunk-M3VTS3F6.js.map} +1 -1
- package/dist/{chunk-MZ34E2GN.js → chunk-NBOS7BY3.js} +60 -21
- package/dist/chunk-NBOS7BY3.js.map +1 -0
- package/dist/{chunk-YA36ABIL.js → chunk-NGQDGL5X.js} +14 -48
- package/dist/chunk-NGQDGL5X.js.map +1 -0
- package/dist/{chunk-ZBFZGLZE.cjs → chunk-NLX5OWK7.cjs} +6 -2
- package/dist/chunk-NLX5OWK7.cjs.map +1 -0
- package/dist/chunk-NUQ2YFFH.cjs +1637 -0
- package/dist/chunk-NUQ2YFFH.cjs.map +1 -0
- package/dist/{chunk-TTCOPKUL.cjs → chunk-OGL4X4PH.cjs} +182 -184
- package/dist/chunk-OGL4X4PH.cjs.map +1 -0
- package/dist/{chunk-HY5BNOUN.cjs → chunk-OTNTGEXR.cjs} +4 -4
- package/dist/{chunk-HY5BNOUN.cjs.map → chunk-OTNTGEXR.cjs.map} +1 -1
- package/dist/chunk-OTWE63BW.js +53 -0
- package/dist/chunk-OTWE63BW.js.map +1 -0
- package/dist/chunk-PC5NGH5A.js +549 -0
- package/dist/chunk-PC5NGH5A.js.map +1 -0
- package/dist/{chunk-IPRP6TDL.cjs → chunk-PS3TUWJM.cjs} +7 -7
- package/dist/{chunk-IPRP6TDL.cjs.map → chunk-PS3TUWJM.cjs.map} +1 -1
- package/dist/{chunk-V76FGHY3.js → chunk-PVFFH7TL.js} +5 -5
- package/dist/{chunk-V76FGHY3.js.map → chunk-PVFFH7TL.js.map} +1 -1
- package/dist/chunk-QCD5JKU4.cjs +15 -0
- package/dist/chunk-QCD5JKU4.cjs.map +1 -0
- package/dist/{chunk-IRPYOHRC.js → chunk-QG5VEOKX.js} +6 -2
- package/dist/chunk-QG5VEOKX.js.map +1 -0
- package/dist/{chunk-2CYI5HRH.js → chunk-RI7RJH4G.js} +49 -17
- package/dist/chunk-RI7RJH4G.js.map +1 -0
- package/dist/{chunk-5LKOVCPP.js → chunk-RVUL2HXY.js} +6 -5
- package/dist/chunk-RVUL2HXY.js.map +1 -0
- package/dist/{chunk-WK23PGTP.cjs → chunk-S5GU4LUN.cjs} +11 -11
- package/dist/{chunk-WK23PGTP.cjs.map → chunk-S5GU4LUN.cjs.map} +1 -1
- package/dist/{chunk-S33YQEL7.js → chunk-SDPWO2Z5.js} +6 -6
- package/dist/{chunk-S33YQEL7.js.map → chunk-SDPWO2Z5.js.map} +1 -1
- package/dist/{chunk-6S3PTHL4.js → chunk-SLGGT2XD.js} +3 -3
- package/dist/{chunk-6S3PTHL4.js.map → chunk-SLGGT2XD.js.map} +1 -1
- package/dist/{chunk-HSEZ7X6Y.cjs → chunk-TIJUA4I6.cjs} +45 -45
- package/dist/{chunk-HSEZ7X6Y.cjs.map → chunk-TIJUA4I6.cjs.map} +1 -1
- package/dist/{chunk-CSNOYIB4.cjs → chunk-TM54OBHX.cjs} +13 -13
- package/dist/{chunk-CSNOYIB4.cjs.map → chunk-TM54OBHX.cjs.map} +1 -1
- package/dist/{chunk-MM3JHVKZ.cjs → chunk-TUWSVL6I.cjs} +4 -4
- package/dist/{chunk-MM3JHVKZ.cjs.map → chunk-TUWSVL6I.cjs.map} +1 -1
- package/dist/{chunk-2GIV5X4P.js → chunk-TYEYRCXL.js} +86 -33
- package/dist/chunk-TYEYRCXL.js.map +1 -0
- package/dist/{chunk-MJPZNEJZ.js → chunk-UKOVGCRN.js} +2095 -496
- package/dist/chunk-UKOVGCRN.js.map +1 -0
- package/dist/chunk-UYKDYE5D.cjs +12 -0
- package/dist/{chunk-KWNWG4RC.cjs.map → chunk-UYKDYE5D.cjs.map} +1 -1
- package/dist/{chunk-FX5ZW6PN.js → chunk-VAAC7L57.js} +95 -40
- package/dist/chunk-VAAC7L57.js.map +1 -0
- package/dist/{chunk-ISKCIQF2.cjs → chunk-VKHXYVN7.cjs} +14 -25
- package/dist/chunk-VKHXYVN7.cjs.map +1 -0
- package/dist/chunk-VUQZNUHU.js +171 -0
- package/dist/chunk-VUQZNUHU.js.map +1 -0
- package/dist/{chunk-K2XYLVVB.cjs → chunk-WDM5WQK4.cjs} +175 -136
- package/dist/chunk-WDM5WQK4.cjs.map +1 -0
- package/dist/{chunk-GVYVGGPJ.js → chunk-WFSYYU4W.js} +66 -28
- package/dist/chunk-WFSYYU4W.js.map +1 -0
- package/dist/{chunk-R7MRFE5P.js → chunk-WS5MT2UJ.js} +3 -3
- package/dist/{chunk-R7MRFE5P.js.map → chunk-WS5MT2UJ.js.map} +1 -1
- package/dist/chunk-XORONCV3.js +202 -0
- package/dist/chunk-XORONCV3.js.map +1 -0
- package/dist/chunk-ZGVTNKTX.cjs +217 -0
- package/dist/chunk-ZGVTNKTX.cjs.map +1 -0
- package/dist/core/index.cjs +20 -20
- package/dist/core/index.d.cts +4 -4
- package/dist/core/index.d.ts +4 -4
- package/dist/core/index.js +4 -4
- package/dist/{ddl-B49O7dB_.d.ts → ddl-BvcbgzHo.d.ts} +3 -3
- package/dist/{ddl-DcZG660s.d.cts → ddl-Ufebz5q5.d.cts} +3 -3
- package/dist/graph-extension/index.d.cts +2 -4
- package/dist/graph-extension/index.d.ts +2 -4
- package/dist/graph-merge/index.cjs +140 -125
- package/dist/graph-merge/index.cjs.map +1 -1
- package/dist/graph-merge/index.d.cts +8 -9
- package/dist/graph-merge/index.d.ts +8 -9
- package/dist/graph-merge/index.js +42 -27
- package/dist/graph-merge/index.js.map +1 -1
- package/dist/index.cjs +144 -143
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +11 -12
- package/dist/index.d.ts +11 -12
- package/dist/index.js +30 -29
- package/dist/index.js.map +1 -1
- package/dist/indexes/index.cjs +14 -12
- package/dist/indexes/index.d.cts +4 -4
- package/dist/indexes/index.d.ts +4 -4
- package/dist/indexes/index.js +7 -5
- package/dist/{ingestion-import-target-CI8OWIkM.d.ts → ingestion-import-target-CAs1OX-l.d.cts} +1 -1
- package/dist/{ingestion-import-target-DCpfM1PX.d.cts → ingestion-import-target-DCQSPfNx.d.ts} +1 -1
- package/dist/interchange/index.cjs +41 -39
- package/dist/interchange/index.cjs.map +1 -1
- package/dist/interchange/index.d.cts +8 -8
- package/dist/interchange/index.d.ts +8 -8
- package/dist/interchange/index.js +16 -14
- package/dist/interchange/index.js.map +1 -1
- package/dist/local-store-impl-JC7OBRAW.js +75 -0
- package/dist/local-store-impl-JC7OBRAW.js.map +1 -0
- package/dist/local-store-impl-UOS2LUIG.cjs +77 -0
- package/dist/local-store-impl-UOS2LUIG.cjs.map +1 -0
- package/dist/{manager-Cfg1ENj1.d.ts → manager-B68OrPR2.d.ts} +1 -2
- package/dist/{manager-D348fa6W.d.cts → manager-D_t7oK69.d.cts} +1 -2
- package/dist/pglite-store-impl-J5J5AA52.cjs +75 -0
- package/dist/pglite-store-impl-J5J5AA52.cjs.map +1 -0
- package/dist/pglite-store-impl-LDRH2DUH.js +73 -0
- package/dist/pglite-store-impl-LDRH2DUH.js.map +1 -0
- package/dist/{postgres-UStOycLI.d.ts → postgres-BPLSVyHM.d.ts} +1 -1
- package/dist/{postgres-CH1kkM5J.d.cts → postgres-CqvtFC2y.d.cts} +1 -1
- package/dist/profiler/index.d.cts +9 -9
- package/dist/profiler/index.d.ts +9 -9
- package/dist/provenance/index.cjs +33 -20
- package/dist/provenance/index.cjs.map +1 -1
- package/dist/provenance/index.d.cts +7 -7
- package/dist/provenance/index.d.ts +7 -7
- package/dist/provenance/index.js +24 -11
- package/dist/provenance/index.js.map +1 -1
- package/dist/{repair-validity-windows-aWX7VNvv.d.cts → repair-validity-windows-DEzCKAdy.d.cts} +7 -3
- package/dist/{repair-validity-windows-BtOEe2pS.d.ts → repair-validity-windows-GMdaS2AH.d.ts} +7 -3
- package/dist/resolve-D_H8MHtq.d.ts +1805 -0
- package/dist/resolve-WEW8gWws.d.cts +1805 -0
- package/dist/schema/index.cjs +42 -40
- package/dist/schema/index.d.cts +4 -6
- package/dist/schema/index.d.ts +4 -6
- package/dist/schema/index.js +15 -13
- package/dist/{searchable-z4BiFfHI.d.ts → searchable-C_UREI9K.d.ts} +1 -1
- package/dist/{searchable-C8-RrL3l.d.cts → searchable-ClgET_i7.d.cts} +1 -1
- package/dist/{sqlite-axLw5Lo5.d.ts → sqlite-D1mXO9Kp.d.cts} +2 -1
- package/dist/{sqlite-Cyx9j9o6.d.cts → sqlite-MZA3oZNB.d.ts} +2 -1
- package/dist/{store-CTfQ9taw.d.ts → store-CuFX7fCx.d.cts} +38 -41
- package/dist/{store-DR9J7JVB.d.cts → store-D-ZjXQpW.d.ts} +38 -41
- package/dist/{temporal-CBOrERz5.d.ts → temporal-CpyEiRY8.d.cts} +1 -1
- package/dist/{temporal-B4Ky4wzh.d.cts → temporal-y0Aep9Su.d.ts} +1 -1
- package/dist/{types-CWg4dTjj.d.ts → types-6yf0Vv-_.d.cts} +1672 -1
- package/dist/{types-CWg4dTjj.d.cts → types-6yf0Vv-_.d.ts} +1672 -1
- package/dist/{types-BScHXVM7.d.ts → types-DzJ4dlzk.d.cts} +1 -1
- package/dist/{types-BE921wRl.d.cts → types-_vVSB9k-.d.ts} +1 -1
- package/dist/{where-BWXUPV3C.d.ts → where-DuG2LCLe.d.ts} +1 -1
- package/dist/{where-CNtx1aLc.d.cts → where-Mhf_yyKX.d.cts} +1 -1
- package/package.json +5 -1
- package/dist/chunk-2CYI5HRH.js.map +0 -1
- package/dist/chunk-2GIV5X4P.js.map +0 -1
- package/dist/chunk-2Q45FAIE.js.map +0 -1
- package/dist/chunk-46UGOVRW.js.map +0 -1
- package/dist/chunk-5LKOVCPP.js.map +0 -1
- package/dist/chunk-5OWHU7Z7.cjs.map +0 -1
- package/dist/chunk-6LEOAIIB.js +0 -1160
- package/dist/chunk-6LEOAIIB.js.map +0 -1
- package/dist/chunk-7CCMCMJO.cjs.map +0 -1
- package/dist/chunk-7PRMDZIA.cjs.map +0 -1
- package/dist/chunk-C76WFIVZ.cjs.map +0 -1
- package/dist/chunk-CS6JTQQ2.cjs.map +0 -1
- package/dist/chunk-EDLKIQRI.js.map +0 -1
- package/dist/chunk-EH3JZJUM.cjs +0 -567
- package/dist/chunk-EH3JZJUM.cjs.map +0 -1
- package/dist/chunk-FX5ZW6PN.js.map +0 -1
- package/dist/chunk-GHZPZNFC.cjs +0 -132
- package/dist/chunk-GHZPZNFC.cjs.map +0 -1
- package/dist/chunk-GVYVGGPJ.js.map +0 -1
- package/dist/chunk-IHK5KA2Q.cjs +0 -262
- package/dist/chunk-IHK5KA2Q.cjs.map +0 -1
- package/dist/chunk-IRPYOHRC.js.map +0 -1
- package/dist/chunk-ISKCIQF2.cjs.map +0 -1
- package/dist/chunk-JG5XIJDY.js.map +0 -1
- package/dist/chunk-K2XYLVVB.cjs.map +0 -1
- package/dist/chunk-KWNWG4RC.cjs +0 -12
- package/dist/chunk-LLVOQOWE.cjs.map +0 -1
- package/dist/chunk-MJPZNEJZ.js.map +0 -1
- package/dist/chunk-MX7EKQPM.js.map +0 -1
- package/dist/chunk-MZ34E2GN.js.map +0 -1
- package/dist/chunk-OJHD3LXJ.cjs.map +0 -1
- package/dist/chunk-PALYTHGM.js +0 -114
- package/dist/chunk-PALYTHGM.js.map +0 -1
- package/dist/chunk-RDP6ZRSM.cjs.map +0 -1
- package/dist/chunk-S3SDEQMC.js +0 -532
- package/dist/chunk-S3SDEQMC.js.map +0 -1
- package/dist/chunk-TEC24ZDA.cjs +0 -1254
- package/dist/chunk-TEC24ZDA.cjs.map +0 -1
- package/dist/chunk-TP4NJTI3.cjs +0 -1192
- package/dist/chunk-TP4NJTI3.cjs.map +0 -1
- package/dist/chunk-TTCOPKUL.cjs.map +0 -1
- package/dist/chunk-TUVD4DFR.cjs.map +0 -1
- package/dist/chunk-TYGGUWMS.cjs.map +0 -1
- package/dist/chunk-U3Z7XKAG.js.map +0 -1
- package/dist/chunk-U5EL6JUV.js.map +0 -1
- package/dist/chunk-VTJVMP4I.js.map +0 -1
- package/dist/chunk-WCLMKNQE.cjs.map +0 -1
- package/dist/chunk-XMY2SXOH.cjs.map +0 -1
- package/dist/chunk-Y55DLLEG.js +0 -247
- package/dist/chunk-Y55DLLEG.js.map +0 -1
- package/dist/chunk-YA36ABIL.js.map +0 -1
- package/dist/chunk-ZBFZGLZE.cjs.map +0 -1
- package/dist/index-B0PrmE3K.d.cts +0 -1146
- package/dist/index-CwcXsL5R.d.ts +0 -1146
- package/dist/materialize-indexes-C9GG3O3C.d.ts +0 -266
- package/dist/materialize-indexes-CrSiW_lT.d.cts +0 -266
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/identity/row-codec.ts","../src/identity/reference.ts","../src/identity/different-assertion.ts","../src/identity/sql-target.ts","../src/identity/service-read.ts","../src/identity/interchange-read.ts","../src/identity/service-components.ts","../src/identity/separation.ts","../src/identity/validity-window.ts","../src/identity/service-mutation.ts","../src/identity/assertion-key.ts","../src/identity/service-facade.ts","../src/identity/service-interchange-write.ts","../src/identity/service-maintenance.ts"],"names":["canonicalizeDatabaseTimestamp","ConfigurationError","encodeTupleKey","compareCodePoints","recordedBindParamBudget","asCompiledStatementSql","isSqliteStaleSnapshotError","KindNotFoundError","resolveWriteFencePlan","requireWriteFence","asCompiledRowsSql","sql","identitySqlCoordinate","nowIso","identityNodeSnapshotSource","chunk","classes","identityNodeVisibilitySql","requireDefined","historicalIdentityReconstructionCtes","resolveRecursiveTraversal","identityAssertionSnapshotSource","IDENTITY_ASSERTION_COLUMNS","getDialect","ValidationError","NodeNotFoundError","isMissingTableError","IdentitySeparationViolationError","validateOptionalCanonicalIsoDate","IdentityValidityWindowError","IdentityContradictionError","generateId","IdentityEndpointValidityError","assertRecursiveTraversal","row","ids","runInWriteTransaction","withRecordedIdentityMutationTarget","firstClass","secondClass","kindList"],"mappings":";;;;;;;;;;;;;;;AAsBO,SAAS,6BAA6B,KAAA,EAAwB;AACnE,EAAA,MAAM,SAAA,GAAYA,gDAA8B,KAAK,CAAA;AACrD,EAAA,IAAI,cAAc,MAAA,EAAW;AAC3B,IAAA,MAAM,IAAIC,oCAAA;AAAA,MACR,6EAAA;AAAA,MACA,EAAE,KAAA,EAAM;AAAA,MACR;AAAA,QACE,UAAA,EACE;AAAA;AACJ,KACF;AAAA,EACF;AACA,EAAA,OAAO,SAAA;AACT;AAEO,SAAS,0BAA0B,KAAA,EAAoC;AAC5E,EAAA,OAAO,UAAU,MAAA,IAAa,KAAA,KAAU,IAAA,GACpC,MAAA,GACA,6BAA6B,KAAK,CAAA;AACxC;AAEO,SAAS,8BACd,GAAA,EAC6B;AAC7B,EAAA,OAAO;AAAA,IACL,UAAU,GAAA,CAAI,QAAA;AAAA,IACd,IAAI,GAAA,CAAI,EAAA;AAAA,IACR,KAAK,GAAA,CAAI,GAAA;AAAA,IACT,QAAQ,GAAA,CAAI,MAAA;AAAA,IACZ,MAAM,GAAA,CAAI,IAAA;AAAA,IACV,QAAQ,GAAA,CAAI,MAAA;AAAA,IACZ,MAAM,GAAA,CAAI,IAAA;AAAA,IACV,UAAA,EAAY,4BAAA,CAA6B,GAAA,CAAI,UAAU,CAAA;AAAA,IACvD,QAAA,EAA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A,CAAI;AAAA,SACnB;AACA,QAAA,MAAM,wBAAA;AAAA,UACJ,SAAA;AAAA,UACAA,qBAAA;AAAA,mBAAA,EACW,GAAA,CAAI,OAAO,uBAAuB;AAAA,2BAAA,EAC1B,OAAO,CAAA;AAAA,6BAAA,EACL,GAAG,CAAA;AAAA,gCAAA,EACA,IAAI,IAAI,CAAA;AAAA,8BAAA,EACV,IAAI,EAAE;AAAA,6BAAA,EACP,GAAA,CAAI,OAAO,CAAA,UAAA,EAAa,GAAA,CAAI,EAAE;AAAA,UAAA;AAAA,SAErD;AACA,QAAA,KAAA,CAAM,GAAA,CAAI,OAAA,EAAS,GAAA,CAAI,EAAA,EAAI,KAAK,CAAA;AAAA,MAClC;AAAA,IACF;AACA,IAAA,MAAM,sBAAA;AAAA,MACJ,SAAA;AAAA,MACA,GAAA,CAAI,MAAA;AAAA,MACJ,GAAA,CAAI,OAAA;AAAA,MACJ,CAAC,GAAG,CAAA;AAAA,MACJ,GAAA,CAAI;AAAA,KACN;AAAA,EACF,CAAC,CAAA;AACH","file":"chunk-L6EVYIID.cjs","sourcesContent":["import { ConfigurationError } from \"../errors\";\nimport { canonicalizeDatabaseTimestamp } from \"../utils/date\";\nimport { type IdentityTransferAssertion } from \"./service-types\";\nimport { type IdentityAssertionStorageRow } from \"./storage-types\";\n\nexport type RawIdentityAssertionRow = Readonly<{\n graph_id: string;\n id: string;\n rel: \"same\" | \"different\";\n a_kind: string;\n a_id: string;\n b_kind: string;\n b_id: string;\n valid_from: unknown;\n valid_to: unknown;\n created_at: unknown;\n updated_at: unknown;\n deleted_at: unknown;\n ended_by_kind: string | null | undefined;\n ended_by_id: string | null | undefined;\n}>;\n\nexport function toCanonicalIdentityTimestamp(value: unknown): string {\n const canonical = canonicalizeDatabaseTimestamp(value);\n if (canonical === undefined) {\n throw new ConfigurationError(\n \"Identity relation returned a timestamp that is not a representable instant.\",\n { value },\n {\n suggestion:\n \"Inspect the identity assertion rows for a corrupt timestamp column.\",\n },\n );\n }\n return canonical;\n}\n\nexport function optionalIdentityTimestamp(value: unknown): string | undefined {\n return value === undefined || value === null ?\n undefined\n : toCanonicalIdentityTimestamp(value);\n}\n\nexport function normalizeIdentityAssertionRow(\n row: RawIdentityAssertionRow,\n): IdentityAssertionStorageRow {\n return {\n graph_id: row.graph_id,\n id: row.id,\n rel: row.rel,\n a_kind: row.a_kind,\n a_id: row.a_id,\n b_kind: row.b_kind,\n b_id: row.b_id,\n valid_from: toCanonicalIdentityTimestamp(row.valid_from),\n valid_to: optionalIdentityTimestamp(row.valid_to),\n created_at: toCanonicalIdentityTimestamp(row.created_at),\n updated_at: toCanonicalIdentityTimestamp(row.updated_at),\n deleted_at: optionalIdentityTimestamp(row.deleted_at),\n ended_by_kind: row.ended_by_kind ?? undefined,\n ended_by_id: row.ended_by_id ?? undefined,\n };\n}\n\nexport function toTransferAssertion(\n row: IdentityAssertionStorageRow,\n): IdentityTransferAssertion {\n return {\n id: row.id,\n relation: row.rel,\n a: { kind: row.a_kind, id: row.a_id },\n b: { kind: row.b_kind, id: row.b_id },\n validFrom: row.valid_from,\n ...(row.valid_to === undefined ? {} : { validTo: row.valid_to }),\n ...(row.ended_by_kind === undefined || row.ended_by_id === undefined ?\n {}\n : { endedBy: { kind: row.ended_by_kind, id: row.ended_by_id } }),\n };\n}\n","import { compareCodePoints } from \"../utils/compare\";\nimport { encodeTupleKey } from \"../utils/tuple-key\";\nimport { type PlainNodeRef } from \"./sql-target\";\n\n/** Canonical, injective map key for a node reference. */\nexport function identityReferenceKey(ref: PlainNodeRef): string {\n return encodeTupleKey([ref.kind, ref.id]);\n}\n\n/** Orders identity references by kind, then id, using code-point order. */\nexport function compareIdentityReferences(\n left: PlainNodeRef,\n right: PlainNodeRef,\n): number {\n const kindOrder = compareCodePoints(left.kind, right.kind);\n return kindOrder === 0 ? compareCodePoints(left.id, right.id) : kindOrder;\n}\n\n/** Returns a pair in the canonical identity endpoint order. */\nexport function normalizeIdentityPair(\n first: PlainNodeRef,\n second: PlainNodeRef,\n): readonly [PlainNodeRef, PlainNodeRef] {\n return compareIdentityReferences(first, second) <= 0 ?\n [first, second]\n : [second, first];\n}\n\n/** Tests reference membership through the canonical key representation. */\nexport function identityReferencesContain(\n members: readonly PlainNodeRef[],\n ref: PlainNodeRef,\n): boolean {\n const key = identityReferenceKey(ref);\n return members.some((member) => identityReferenceKey(member) === key);\n}\n","import { identityReferenceKey } from \"./reference\";\nimport { type PlainNodeRef } from \"./sql-target\";\nimport { type IdentityAssertionStorageRow } from \"./storage-types\";\n\n/** Finds a negative assertion connecting two structural identity classes. */\nexport function spanningDifferentAssertion(\n assertions: readonly IdentityAssertionStorageRow[],\n first: readonly PlainNodeRef[],\n second: readonly PlainNodeRef[],\n): IdentityAssertionStorageRow | undefined {\n const firstKeys = new Set(\n first.map((reference) => identityReferenceKey(reference)),\n );\n const secondKeys = new Set(\n second.map((reference) => identityReferenceKey(reference)),\n );\n return assertions.find((assertion) => {\n if (assertion.rel !== \"different\") return false;\n const firstEndpoint = identityReferenceKey({\n kind: assertion.a_kind,\n id: assertion.a_id,\n });\n const secondEndpoint = identityReferenceKey({\n kind: assertion.b_kind,\n id: assertion.b_id,\n });\n return (\n (firstKeys.has(firstEndpoint) && secondKeys.has(secondEndpoint)) ||\n (firstKeys.has(secondEndpoint) && secondKeys.has(firstEndpoint))\n );\n });\n}\n","/**\n * The SQL-execution primitives every identity relation writer shares: the\n * target type identity statements run against, the bind-budget chunk math, and\n * the statement runner.\n *\n * Extracted so the derived-relation writers (`separation.ts`) and the identity\n * service can both use them without importing each other.\n */\nimport {\n type BackendIdentity,\n type GraphBackend,\n type GraphEntityReadBackend,\n type QueryExecutionBackend,\n type RawQueryExecutionBackend,\n type SchemaReadBackend,\n type SqlCompilationBackend,\n} from \"../backend/types\";\nimport { ConfigurationError } from \"../errors\";\nimport { type SqlFragment } from \"../query/sql-fragment\";\nimport { asCompiledStatementSql } from \"../query/sql-intent\";\nimport { recordedBindParamBudget } from \"../store/recorded-capture/relations\";\nimport { isSqliteStaleSnapshotError } from \"../utils/sql-errors\";\n\n/**\n * @internal\n *\n * What an identity statement runs against: reads, compiled execution, and the\n * optional raw-statement port {@link executeIdentityStatement} refuses without.\n *\n * An EXPLICIT FACET COMPOSITION rather than `GraphBackend | TransactionBackend`,\n * for the same reason `TransactionBackend` is one: identity writes touch the\n * identity relations through `executeStatement`, never through a graph-entity\n * write member, so naming the members states what identity may reach instead of\n * inheriting every mutation port a backend happens to expose.\n *\n * Both backend shapes are still assignable to it, so no existing caller\n * changes. What the composition additionally admits is the write pipeline's\n * row-work projection (`WriteTarget`): the store's identity fold and detach run\n * inside a write frame, whose handle exposes reads only, and `executeStatement`\n * is optional here exactly as it is on `GraphBackend` — so a target that cannot\n * run statements is refused by {@link executeIdentityStatement} with a named\n * error rather than excluded by a type nobody in row work can produce.\n */\nexport type IdentityTarget = Readonly<\n BackendIdentity &\n GraphEntityReadBackend &\n SchemaReadBackend &\n QueryExecutionBackend &\n SqlCompilationBackend &\n RawQueryExecutionBackend &\n Pick<GraphBackend, \"executeStatement\">\n>;\n\n/** A node reference stripped to the two columns identity relations store. */\nexport type PlainNodeRef = Readonly<{ kind: string; id: string }>;\n\n/**\n * Upper bound on how many node references one identity statement names. Kept\n * well below every backend's bind budget so the chunk math below, not the\n * driver, decides statement size on generous engines.\n */\nexport const MAX_REFERENCE_CHUNK_SIZE = 200;\n\n/**\n * How many items fit in one statement given the target's bind-parameter\n * budget, capped at `maxItems`.\n *\n * @throws {ConfigurationError} when even a single item cannot fit.\n */\nexport function identityChunkSize(\n target: IdentityTarget,\n input: Readonly<{\n fixedParameters: number;\n maxItems: number;\n parametersPerItem: number;\n }>,\n): number {\n const parameterLimit = recordedBindParamBudget(target);\n const chunkSize = Math.floor(\n (parameterLimit - input.fixedParameters) / input.parametersPerItem,\n );\n if (chunkSize < 1) {\n throw new ConfigurationError(\n \"Operational Identity cannot fit this statement within the backend bind-parameter limit.\",\n {\n code: \"IDENTITY_BIND_BUDGET_TOO_SMALL\",\n parameterLimit,\n fixedParameters: input.fixedParameters,\n parametersPerItem: input.parametersPerItem,\n },\n );\n }\n return Math.min(input.maxItems, chunkSize);\n}\n\nfunction requireStatementTarget(\n target: IdentityTarget,\n): asserts target is IdentityTarget & {\n executeStatement: NonNullable<GraphBackend[\"executeStatement\"]>;\n} {\n if (target.executeStatement === undefined) {\n throw new ConfigurationError(\n \"Operational Identity requires statement execution support.\",\n { code: \"IDENTITY_REQUIRES_STATEMENT_EXECUTION\" },\n {\n suggestion:\n \"Use a built-in transactional SQLite or PostgreSQL backend.\",\n },\n );\n }\n}\n\n/**\n * The refusal an identity write raises when SQLite would not let the enclosing\n * transaction become a writer (#447).\n *\n * The per-graph identity locks (`lockIdentityGraph`, `lockIdentityDdl`) are\n * no-ops on SQLite, on the premise that TypeGraph's own transactions open\n * `BEGIN IMMEDIATE` and therefore hold the database's single writer slot for\n * the whole read→write identity fold. `adoptTransaction` breaks exactly that\n * premise: it adopts a transaction the CALLER began, which may be DEFERRED, and\n * the adoption seam cannot observe how — SQLite exposes no frame-kind query\n * through any bundled driver. A deferred frame is a reader until its first\n * write, so the fold's write can find the snapshot stale and lose the upgrade.\n *\n * SQLite renders that as `SQLITE_BUSY_SNAPSHOT` / \"database is locked\", which\n * says nothing about the cause and names no remedy. It is not retryable in\n * place either — SQLite's own contract is that the transaction must be rolled\n * back — and the transaction boundary belongs to the caller, so identity cannot\n * restart it. What identity CAN guarantee is that the failure never surfaces as\n * a raw driver error: it names the adopted deferred frame and the fix.\n */\nfunction identityWriterSlotError(cause: unknown): ConfigurationError {\n return new ConfigurationError(\n \"Operational Identity could not take the SQLite writer slot: this transaction was begun DEFERRED and another connection committed before the identity write, so its read snapshot is stale.\",\n {\n code: \"IDENTITY_TRANSACTION_NOT_WRITE_FENCED\",\n sqliteCode: \"SQLITE_BUSY_SNAPSHOT\",\n },\n {\n cause,\n suggestion:\n \"Roll back and re-run the transaction (SQLite cannot upgrade a stale snapshot in place). Identity mutations serialize on the writer slot, so an adopted transaction must be opened with BEGIN IMMEDIATE — or run the writes through store.transaction(), which already does.\",\n },\n );\n}\n\n/** Runs one write statement against an identity target. */\nexport async function executeIdentityStatement(\n target: IdentityTarget,\n statement: SqlFragment,\n): Promise<void> {\n requireStatementTarget(target);\n try {\n await target.executeStatement(asCompiledStatementSql(statement));\n } catch (error) {\n // Every identity relation writer runs through here, so translating at this\n // one seam covers the whole surface — the fold, the derived-relation\n // writers, maintenance and the schema transition alike.\n if (!isSqliteStaleSnapshotError(error)) throw error;\n throw identityWriterSlotError(error);\n }\n}\n","import { resolveRecursiveTraversal } from \"../backend/capabilities/recursive-traversal\";\nimport {\n requireWriteFence,\n resolveWriteFencePlan,\n} from \"../backend/capabilities/write-fence\";\nimport { type GraphDef } from \"../core/define-graph\";\nimport { type ReadCoordinate } from \"../core/temporal\";\nimport { KindNotFoundError } from \"../errors\";\nimport { type SqlSchema } from \"../query/compiler/schema\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../query/sql-intent\";\nimport { chunk } from \"../utils/array\";\nimport { compareCodePoints } from \"../utils/compare\";\nimport { nowIso } from \"../utils/date\";\nimport { requireDefined } from \"../utils/presence\";\nimport { spanningDifferentAssertion } from \"./different-assertion\";\nimport {\n historicalIdentityReconstructionCtes,\n IDENTITY_ASSERTION_COLUMNS,\n identityAssertionSnapshotSource,\n identityNodeSnapshotSource,\n identityNodeVisibilitySql,\n identitySqlCoordinate,\n} from \"./historical-sql\";\nimport {\n compareIdentityReferences,\n identityReferenceKey,\n identityReferencesContain,\n normalizeIdentityPair,\n} from \"./reference\";\nimport {\n normalizeIdentityAssertionRow,\n optionalIdentityTimestamp,\n type RawIdentityAssertionRow,\n toCanonicalIdentityTimestamp,\n} from \"./row-codec\";\nimport { type IdentityServiceContext } from \"./service-types\";\nimport {\n executeIdentityStatement,\n identityChunkSize,\n type IdentityTarget,\n MAX_REFERENCE_CHUNK_SIZE,\n type PlainNodeRef,\n} from \"./sql-target\";\nimport { type IdentityAssertionStorageRow } from \"./storage-types\";\nimport {\n type IdentityAssertion,\n type IdentityAssertionId,\n type IdentityAssertionResult,\n type IdentityNodeReference,\n type IdentityNodeRefInput,\n type IdentityRelation,\n} from \"./types\";\n\nexport type Backend = IdentityTarget;\n\nexport type IdentityTouch = (\n graphId: string,\n id: string,\n afterImage?: IdentityAssertionStorageRow,\n) => void;\n\nexport const MAX_CLOSURE_INSERT_CHUNK_SIZE = 100;\n\nexport const MAX_ASSERTION_INSERT_CHUNK_SIZE = 50;\n\ntype RawNodeSnapshotRow = Readonly<{\n kind: string;\n id: string;\n valid_from: unknown;\n valid_to: unknown;\n created_at: unknown;\n deleted_at: unknown;\n}>;\n\nexport type RawClosureClassRow = Readonly<{\n member_kind: string;\n member_id: string;\n}>;\n\nexport type RawSeedClassAnchorRow = Readonly<{\n seed_kind: string;\n seed_id: string;\n class_kind: string;\n class_id: string;\n}>;\n\ntype RawSeedClassMemberRow = RawClosureClassRow &\n Readonly<{\n seed_kind: string;\n seed_id: string;\n }>;\n\ntype RawHistoricalClassMemberRow = RawSeedClassMemberRow &\n Readonly<{ is_visible: unknown }>;\n\nexport type NodeSnapshot = Readonly<{\n ref: PlainNodeRef;\n validFrom: string | undefined;\n validTo: string | undefined;\n createdAt: string;\n deletedAt: string | undefined;\n}>;\n\nexport type IdentitySnapshot = Readonly<{\n nodes: readonly NodeSnapshot[];\n structuralNodes: readonly PlainNodeRef[];\n assertions: readonly IdentityAssertionStorageRow[];\n components: ReadonlyMap<string, readonly PlainNodeRef[]>;\n}>;\n\nfunction plainRef<G extends GraphDef>(\n ref: IdentityNodeRefInput<G>,\n): PlainNodeRef {\n return { kind: ref.kind, id: ref.id };\n}\n\nexport function registeredPlainRef<G extends GraphDef>(\n ctx: Pick<IdentityServiceContext<G>, \"graphId\" | \"registry\">,\n ref: IdentityNodeRefInput<G>,\n): PlainNodeRef {\n const result = plainRef(ref);\n if (!ctx.registry.nodeKinds.has(result.kind)) {\n throw new KindNotFoundError(result.kind, \"node\", {\n graphId: ctx.graphId,\n });\n }\n return result;\n}\n\n/**\n * The canonical map key for a node reference. Every identity closure map —\n * structural classes, affected-closure sets, loaded-node lookups — is keyed\n * with it, so any caller building or probing one of those maps must produce\n * its keys through this helper rather than re-spelling the serialization.\n */\nexport function refKey(ref: PlainNodeRef): string {\n return identityReferenceKey(ref);\n}\n\n/**\n * Projects a stored assertion row into the interchange transfer shape. The row\n * must already be normalized (see `normalizeIdentityAssertionRow`); raw driver rows\n * carry dialect-specific timestamp and NULL spellings this shape does not.\n */\n/**\n * Whether `ref` is one of `members`.\n *\n * Keys the probe once instead of re-serializing it for every member, which\n * an inline `members.some((m) => refKey(m) === refKey(ref))` does.\n */\nexport function containsRef(\n members: readonly PlainNodeRef[],\n ref: PlainNodeRef,\n): boolean {\n return identityReferencesContain(members, ref);\n}\n\nexport function compareReferences(\n left: PlainNodeRef,\n right: PlainNodeRef,\n): number {\n return compareIdentityReferences(left, right);\n}\n\nexport function normalizePair(\n first: PlainNodeRef,\n second: PlainNodeRef,\n): readonly [PlainNodeRef, PlainNodeRef] {\n return normalizeIdentityPair(first, second);\n}\n\n// A retraction ends an assertion at \"now\", but a backward clock skew can make\n// now < the row's valid_from — minting an empty (valid_to < valid_from) window\n// that validateTransferShape rejects on archival re-import. Clamp the end to\n// valid_from so the closed window is at worst zero-width, never negative.\nexport function clampValidTo(timestamp: string, validFrom: string): string {\n return compareCodePoints(timestamp, validFrom) < 0 ? validFrom : timestamp;\n}\n\n/**\n * Canonicalizes a driver timestamp read back from an identity relation. Drivers\n * hand back `Date` objects or zoneless strings depending on dialect; identity\n * rows are compared as canonical UTC strings, so an unrepresentable value is a\n * storage-boundary fault rather than a silently skewed comparison.\n */\n\nexport function publicAssertion<G extends GraphDef>(\n row: IdentityAssertionStorageRow,\n): IdentityAssertion<G> {\n return {\n id: row.id as IdentityAssertionId,\n relation: row.rel,\n a: publicNodeRef<G>({ kind: row.a_kind, id: row.a_id }),\n b: publicNodeRef<G>({ kind: row.b_kind, id: row.b_id }),\n validFrom: row.valid_from,\n ...(row.valid_to === undefined ? {} : { validTo: row.valid_to }),\n };\n}\n\nexport function assertionResult<G extends GraphDef>(\n assertion: IdentityAssertion<G>,\n action: IdentityAssertionResult<G>[\"action\"],\n): IdentityAssertionResult<G> {\n return { assertion, action };\n}\n\nexport function publicNodeRef<G extends GraphDef>(\n ref: PlainNodeRef,\n): IdentityNodeReference<G> {\n // Every service entry point validates kinds against the graph registry, and\n // persisted assertion/closure rows are constrained to those same endpoints.\n // Reapply the public per-kind NodeId brand at this storage boundary.\n return ref as IdentityNodeReference<G>;\n}\n\n/**\n * Serializes identity-affecting writers on one graph.\n *\n * The lock is deliberately whole-graph rather than scoped to the kinds a write\n * touches. Identity closures are transitive: an assertion between two kinds\n * merges their classes, so a \"which kinds participate\" test would have to\n * evaluate the closure — the very thing the lock protects. A coarse lock is\n * the only scope that is correct without reading what it guards.\n *\n * The cost is a known throughput ceiling: concurrent writers on a single\n * identity-enabled graph serialize even when their kinds share no relation.\n * Scoping the lock to connected components of the assertion graph is the\n * refinement if that ceiling ever binds.\n *\n * SQLITE: no lock is taken because the engine's single writer slot already\n * serializes writers — a premise that holds for every transaction TypeGraph\n * opens itself (`BEGIN IMMEDIATE` takes the slot before the first read) but NOT\n * for one adopted through `store.withTransaction()`, which may have been begun\n * DEFERRED by the caller. There the fold's read→write can lose the upgrade and\n * SQLite refuses the write with a stale snapshot. That case is neither\n * serializable from here (the frame is already open, and its kind is not\n * observable) nor retryable in place (SQLite requires a rollback), so it is\n * refused with a typed error naming the cause and the remedy — see\n * `executeIdentityStatement` (#447).\n *\n * The dialect check above is now the `resolveWriteFencePlan`/\n * `requireWriteFence` pair (§5.3): the `lock` arm takes the advisory lock,\n * and the `engine-serialized` arm is the SQLite writer-slot case this doc\n * already describes.\n */\nexport async function lockIdentityGraph(\n target: Backend,\n graphId: string,\n): Promise<void> {\n const plan = resolveWriteFencePlan(target);\n const fence = requireWriteFence(plan, \"identity graph lock\", \"advisory-lock\");\n switch (fence.kind) {\n case \"lock\": {\n await target.execute(\n asCompiledRowsSql(sql`\n SELECT pg_advisory_xact_lock(\n hashtext('typegraph:identity'),\n hashtext(${graphId})\n )\n `),\n );\n return;\n }\n case \"engine-serialized\": {\n // No lock is taken because the engine's single writer slot already\n // serializes writers — see the DEFERRED-frame caveat above, which\n // `executeIdentityStatement` turns into a typed refusal (#447).\n return;\n }\n default: {\n fence satisfies never;\n }\n }\n}\n\n/**\n * Drains in-flight legacy node writes before the first identity snapshot.\n * Resolves a {@link resolveWriteFencePlan}; the `lock` arm takes the relation\n * lock (needs `tableLocks`), and the `engine-serialized` arm is the SQLite\n * writer-slot case, which has already drained every writer.\n */\nexport async function lockIdentityEnablementNodes(\n target: Backend,\n schema: SqlSchema,\n): Promise<void> {\n const plan = resolveWriteFencePlan(target);\n const fence = requireWriteFence(\n plan,\n \"identity enablement drain\",\n \"table-lock\",\n );\n switch (fence.kind) {\n case \"lock\": {\n await executeIdentityStatement(\n target,\n sql`LOCK TABLE ${schema.nodesTable} IN SHARE MODE`,\n );\n return;\n }\n case \"engine-serialized\": {\n // No lock is taken because the engine's single writer slot already\n // drained every writer before the fence opened.\n return;\n }\n default: {\n fence satisfies never;\n }\n }\n}\n\nexport async function loadNodeSnapshot(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n coordinate: ReadCoordinate | undefined,\n): Promise<readonly NodeSnapshot[]> {\n const sqlCoordinate = identitySqlCoordinate(coordinate, nowIso());\n const rows = await target.execute<RawNodeSnapshotRow>(\n asCompiledRowsSql(\n identityNodeSnapshotSource(schema, graphId, sqlCoordinate),\n ),\n );\n return rows.map((row) => ({\n ref: { kind: row.kind, id: row.id },\n validFrom: optionalIdentityTimestamp(row.valid_from),\n validTo: optionalIdentityTimestamp(row.valid_to),\n createdAt: toCanonicalIdentityTimestamp(row.created_at),\n deletedAt: optionalIdentityTimestamp(row.deleted_at),\n }));\n}\n\nexport function isCurrentClosureCoordinate(\n coordinate: ReadCoordinate | undefined,\n): boolean {\n return (\n coordinate?.recorded === undefined &&\n (coordinate?.valid.mode ?? \"current\") === \"current\"\n );\n}\n\nexport async function loadCurrentStructuralClasses(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n references: readonly PlainNodeRef[],\n): Promise<ReadonlyMap<string, readonly PlainNodeRef[]>> {\n const uniqueByKey = new Map<string, PlainNodeRef>();\n for (const ref of references) uniqueByKey.set(refKey(ref), ref);\n const uniqueReferences = [...uniqueByKey.values()];\n if (uniqueReferences.length === 0) return new Map();\n const chunkSize = identityChunkSize(target, {\n fixedParameters: 2,\n maxItems: MAX_REFERENCE_CHUNK_SIZE,\n parametersPerItem: 2,\n });\n if (uniqueReferences.length > chunkSize) {\n const combined = new Map<string, readonly PlainNodeRef[]>();\n for (const refChunk of chunk(uniqueReferences, chunkSize)) {\n const classes = await loadCurrentStructuralClasses(\n target,\n schema,\n graphId,\n refChunk,\n );\n for (const [key, members] of classes) combined.set(key, members);\n }\n return combined;\n }\n const seedRows = sql.join(\n uniqueReferences.map((ref) => sql`(${ref.kind}, ${ref.id})`),\n sql`, `,\n );\n const rows = await target.execute<RawSeedClassMemberRow>(\n asCompiledRowsSql(sql`\n WITH seeds(seed_kind, seed_id) AS (\n VALUES ${seedRows}\n ), anchors AS (\n SELECT seeds.seed_kind, seeds.seed_id,\n COALESCE(anchor.class_kind, seeds.seed_kind) AS class_kind,\n COALESCE(anchor.class_id, seeds.seed_id) AS class_id\n FROM seeds\n LEFT JOIN ${schema.identityClosureTable} anchor\n ON anchor.graph_id = ${graphId}\n AND anchor.member_kind = seeds.seed_kind\n AND anchor.member_id = seeds.seed_id\n )\n SELECT anchors.seed_kind, anchors.seed_id,\n COALESCE(member.member_kind, anchors.seed_kind) AS member_kind,\n COALESCE(member.member_id, anchors.seed_id) AS member_id\n FROM anchors\n LEFT JOIN ${schema.identityClosureTable} member\n ON member.graph_id = ${graphId}\n AND member.class_kind = anchors.class_kind\n AND member.class_id = anchors.class_id\n `),\n );\n const classes = new Map<string, PlainNodeRef[]>();\n for (const row of rows) {\n const seedKey = refKey({ kind: row.seed_kind, id: row.seed_id });\n const members = classes.get(seedKey) ?? [];\n members.push({ kind: row.member_kind, id: row.member_id });\n classes.set(seedKey, members);\n }\n return new Map(\n [...classes].map(([seedKey, members]) => [\n seedKey,\n members.toSorted((left, right) => compareReferences(left, right)),\n ]),\n );\n}\n\nexport async function loadCurrentVisibleMembers(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n ref: PlainNodeRef,\n): Promise<readonly PlainNodeRef[]> {\n const now = nowIso();\n const coordinate = identitySqlCoordinate(undefined, now);\n // Two deliberate deviations keep this read O(class size) instead of\n // O(graph size) on SQLite. A row-value `(class_kind, class_id) IN\n // (subquery)` defeats the closure's class index, so the members CTE joins\n // the anchor row instead. And SQLite's planner, estimating without\n // statistics, likes to drive the visibility join from the nodes table via\n // the `(graph_id, deleted_at)` index — a scan of every live node per call.\n // CROSS JOIN pins the join order on SQLite (a documented planner control)\n // while remaining an ordinary inner join on PostgreSQL, whose planner\n // orders freely from real statistics either way.\n // Only the endpoint identity is projected: the visibility predicate below\n // already consumed this row's timestamps in SQL, so hydrating them into JS\n // would validate columns nothing downstream reads.\n const rows = await target.execute<PlainNodeRef>(\n asCompiledRowsSql(sql`\n WITH anchor AS (\n SELECT class_kind, class_id\n FROM ${schema.identityClosureTable}\n WHERE graph_id = ${graphId}\n AND member_kind = ${ref.kind}\n AND member_id = ${ref.id}\n ), members(kind, id) AS (\n SELECT closure.member_kind, closure.member_id\n FROM anchor\n JOIN ${schema.identityClosureTable} closure\n ON closure.graph_id = ${graphId}\n AND closure.class_kind = anchor.class_kind\n AND closure.class_id = anchor.class_id\n UNION ALL\n SELECT ${ref.kind}, ${ref.id}\n WHERE NOT EXISTS (SELECT 1 FROM anchor)\n )\n SELECT n.kind, n.id\n FROM members m\n CROSS JOIN ${schema.nodesTable} n\n WHERE n.graph_id = ${graphId}\n AND n.kind = m.kind\n AND n.id = m.id\n AND ${identityNodeVisibilitySql(coordinate, \"n\")}\n `),\n );\n const members = rows\n .map((row) => ({ kind: row.kind, id: row.id }))\n .toSorted((left, right) => compareReferences(left, right));\n return containsRef(members, ref) ? members : [];\n}\n\nasync function loadHistoricalVisibleMembers(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n ref: PlainNodeRef,\n coordinate: ReadCoordinate,\n sameIdAcrossKinds: \"fold\" | \"ignore\",\n): Promise<readonly PlainNodeRef[]> {\n const classes = await loadHistoricalClasses(\n target,\n schema,\n graphId,\n [ref],\n coordinate,\n sameIdAcrossKinds,\n );\n return requireDefined(classes.get(refKey(ref))).visible;\n}\n\nexport type HistoricalClass = Readonly<{\n structural: readonly PlainNodeRef[];\n visible: readonly PlainNodeRef[];\n}>;\n\nexport async function loadHistoricalClasses(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n references: readonly PlainNodeRef[],\n coordinate: ReadCoordinate,\n sameIdAcrossKinds: \"fold\" | \"ignore\",\n): Promise<ReadonlyMap<string, HistoricalClass>> {\n const uniqueByKey = new Map<string, PlainNodeRef>();\n for (const ref of references) uniqueByKey.set(refKey(ref), ref);\n const uniqueReferences = [...uniqueByKey.values()];\n const emptyClasses = new Map(\n uniqueReferences.map((ref) => [\n refKey(ref),\n { structural: [], visible: [] } satisfies HistoricalClass,\n ]),\n );\n if (uniqueReferences.length === 0) return emptyClasses;\n const chunkSize = identityChunkSize(target, {\n fixedParameters: 24,\n maxItems: MAX_REFERENCE_CHUNK_SIZE,\n parametersPerItem: 2,\n });\n if (uniqueReferences.length > chunkSize) {\n const combined = new Map<string, HistoricalClass>();\n for (const refChunk of chunk(uniqueReferences, chunkSize)) {\n const classes = await loadHistoricalClasses(\n target,\n schema,\n graphId,\n refChunk,\n coordinate,\n sameIdAcrossKinds,\n );\n for (const [key, value] of classes) combined.set(key, value);\n }\n return combined;\n }\n const currentInstant = nowIso();\n const sqlCoordinate = identitySqlCoordinate(coordinate, currentInstant);\n const seeds = sql.join(\n uniqueReferences.map((ref) => sql`(${ref.kind}, ${ref.id})`),\n sql`, `,\n );\n const reconstruction = historicalIdentityReconstructionCtes({\n schema,\n graphId,\n coordinate: sqlCoordinate,\n seedSource: sql`VALUES ${seeds}`,\n sameIdAcrossKinds,\n recursiveTraversal: resolveRecursiveTraversal(target.capabilities),\n });\n const rows = await target.execute<RawHistoricalClassMemberRow>(\n asCompiledRowsSql(sql`\n WITH RECURSIVE\n ${reconstruction}\n SELECT member.seed_kind, member.seed_id,\n member.kind AS member_kind, member.id AS member_id,\n CASE WHEN ${identityNodeVisibilitySql(sqlCoordinate, \"n\")}\n THEN 1 ELSE 0 END AS is_visible\n FROM identity_members member\n JOIN node_snapshot n ON n.kind = member.kind AND n.id = member.id\n `),\n );\n const structuralBySeed = new Map<string, PlainNodeRef[]>();\n const visibleBySeed = new Map<string, PlainNodeRef[]>();\n for (const row of rows) {\n const seedKey = refKey({ kind: row.seed_kind, id: row.seed_id });\n const member = { kind: row.member_kind, id: row.member_id };\n const structural = structuralBySeed.get(seedKey) ?? [];\n structural.push(member);\n structuralBySeed.set(seedKey, structural);\n if (!row.is_visible) continue;\n const visible = visibleBySeed.get(seedKey) ?? [];\n visible.push(member);\n visibleBySeed.set(seedKey, visible);\n }\n return new Map(\n uniqueReferences.map((ref) => {\n const key = refKey(ref);\n return [\n key,\n {\n structural: (structuralBySeed.get(key) ?? []).toSorted(\n (left, right) => compareReferences(left, right),\n ),\n visible: (visibleBySeed.get(key) ?? []).toSorted((left, right) =>\n compareReferences(left, right),\n ),\n },\n ];\n }),\n );\n}\n\nexport function visibleMembersAtCoordinate<G extends GraphDef>(\n ctx: IdentityServiceContext<G>,\n ref: PlainNodeRef,\n): Promise<readonly PlainNodeRef[]> {\n const { coordinate } = ctx;\n if (coordinate === undefined || isCurrentClosureCoordinate(coordinate)) {\n return loadCurrentVisibleMembers(ctx.backend, ctx.schema, ctx.graphId, ref);\n }\n return loadHistoricalVisibleMembers(\n ctx.backend,\n ctx.schema,\n ctx.graphId,\n ref,\n coordinate,\n ctx.sameIdAcrossKinds,\n );\n}\n\nexport async function loadAssertions(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n coordinate: ReadCoordinate | undefined,\n currentInstant: string,\n): Promise<readonly IdentityAssertionStorageRow[]> {\n const source = identityAssertionSnapshotSource(\n schema,\n graphId,\n identitySqlCoordinate(coordinate, currentInstant),\n undefined,\n );\n const rows = await target.execute<RawIdentityAssertionRow>(\n asCompiledRowsSql(source),\n );\n return rows.map((row) => normalizeIdentityAssertionRow(row));\n}\n\nexport function referenceCondition(\n kindColumn: SqlFragment,\n idColumn: SqlFragment,\n references: readonly PlainNodeRef[],\n): SqlFragment {\n if (references.length === 0) return sql`1 = 0`;\n return sql`(${sql.join(\n references.map(\n (ref) => sql`(${kindColumn} = ${ref.kind} AND ${idColumn} = ${ref.id})`,\n ),\n sql` OR `,\n )})`;\n}\n\nexport async function loadAssertionsTouching(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n references: readonly PlainNodeRef[],\n coordinate: ReadCoordinate | undefined,\n relation?: IdentityRelation,\n): Promise<readonly IdentityAssertionStorageRow[]> {\n if (references.length === 0) return [];\n const chunkSize = identityChunkSize(target, {\n fixedParameters: 16,\n maxItems: MAX_REFERENCE_CHUNK_SIZE,\n parametersPerItem: 4,\n });\n if (references.length > chunkSize) {\n const byId = new Map<string, IdentityAssertionStorageRow>();\n for (const refChunk of chunk(references, chunkSize)) {\n const assertions = await loadAssertionsTouching(\n target,\n schema,\n graphId,\n refChunk,\n coordinate,\n relation,\n );\n for (const assertion of assertions) byId.set(assertion.id, assertion);\n }\n return [...byId.values()];\n }\n const source = identityAssertionSnapshotSource(\n schema,\n graphId,\n identitySqlCoordinate(coordinate, nowIso()),\n relation,\n );\n const aMatches = referenceCondition(\n sql`identity_assertions.a_kind`,\n sql`identity_assertions.a_id`,\n references,\n );\n const bMatches = referenceCondition(\n sql`identity_assertions.b_kind`,\n sql`identity_assertions.b_id`,\n references,\n );\n const rows = await target.execute<RawIdentityAssertionRow>(\n asCompiledRowsSql(sql`\n SELECT ${IDENTITY_ASSERTION_COLUMNS}\n FROM (${source}) identity_assertions\n WHERE ${aMatches} OR ${bMatches}\n `),\n );\n return rows.map((row) => normalizeIdentityAssertionRow(row));\n}\n\nexport async function loadSpanningDifferentAssertion(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n firstClass: readonly PlainNodeRef[],\n secondClass: readonly PlainNodeRef[],\n coordinate?: ReadCoordinate,\n): Promise<IdentityAssertionStorageRow | undefined> {\n const assertions = await loadAssertionsTouching(\n target,\n schema,\n graphId,\n firstClass,\n coordinate,\n \"different\",\n );\n return spanningDifferentAssertion(assertions, firstClass, secondClass);\n}\n","import { type GraphDef } from \"../core/define-graph\";\nimport { ConfigurationError } from \"../errors\";\nimport { getDialect } from \"../query/dialect\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../query/sql-intent\";\nimport {\n normalizeIdentityAssertionRow,\n type RawIdentityAssertionRow,\n toTransferAssertion,\n} from \"./row-codec\";\nimport {\n type IdentityAssertionPage,\n type IdentityAssertionPageOptions,\n type IdentityInterchangeReadOptions,\n type IdentityServiceContext,\n type IdentityTransferAssertion,\n} from \"./service-types\";\nimport {\n identityChunkSize,\n type IdentityTarget,\n MAX_REFERENCE_CHUNK_SIZE,\n} from \"./sql-target\";\n\n/**\n * The assertion-id expression this read scans and paginates by, pinned to\n * code-point order on every engine.\n *\n * Ordering is part of this read's contract, not an incidental detail. Two\n * consumers depend on it: the interchange export walks pages by an\n * `id > after` keyset cursor, and `computeContentComponent` hashes the\n * returned assertion list in READ order into a base-version content token.\n * The read seam is the only owner of that order — nothing downstream re-sorts.\n *\n * Left bare, `ORDER BY identity_assertions.id` sorts under the column's\n * collation, which on PostgreSQL is the database's locale (`en_US.utf8`\n * orders `a, B, c` case-insensitively) while SQLite's `BINARY` is code-point\n * order. Mixed-case ids — every nanoid, plus any caller-supplied id an\n * importer accepts — therefore paged differently on the two backends, and a\n * `base@V` token minted before this read carried an `ORDER BY` (which sorted\n * in JavaScript by code point) stopped matching its recomputation on\n * PostgreSQL.\n *\n * Both the scan order AND the keyset comparison go through the same\n * expression: a JavaScript re-sort would fix neither, and pinning only the\n * `ORDER BY` would leave the cursor comparing under a different collation\n * than the scan, which skips and duplicates rows across page boundaries.\n *\n * The `binaryText` member of the dialect adapter is the repo's existing seam\n * for this (`COLLATE \"C\"` on PostgreSQL, identity on SQLite), so SQLite's\n * emitted SQL is unchanged.\n */\nfunction codePointOrderedAssertionId(target: IdentityTarget): SqlFragment {\n return getDialect(target.dialect).binaryText(sql`identity_assertions.id`);\n}\n\nexport async function readIdentityAssertionPageAtTarget<G extends GraphDef>(\n ctx: IdentityServiceContext<G>,\n target: IdentityTarget,\n mode: \"state\" | \"archival\",\n options: IdentityAssertionPageOptions,\n): Promise<IdentityAssertionPage> {\n if (!Number.isSafeInteger(options.limit) || options.limit <= 0) {\n throw new ConfigurationError(\n \"Identity assertion page limit must be a positive safe integer.\",\n { limit: options.limit },\n );\n }\n const nodeKinds =\n options.nodeKinds === undefined ?\n undefined\n : [...new Set(options.nodeKinds)];\n const kindFilterChunkSize =\n nodeKinds === undefined || nodeKinds.length === 0 ?\n MAX_REFERENCE_CHUNK_SIZE\n : identityChunkSize(target, {\n fixedParameters: 16,\n maxItems: MAX_REFERENCE_CHUNK_SIZE,\n parametersPerItem: 2,\n });\n const filterKindsInMemory =\n nodeKinds !== undefined && nodeKinds.length > kindFilterChunkSize;\n const kindFilter =\n nodeKinds === undefined ? sql``\n : nodeKinds.length === 0 ? sql`AND 1 = 0`\n : filterKindsInMemory ? sql``\n : sql`\n AND identity_assertions.a_kind IN (${sql.join(\n nodeKinds.map((kind) => sql`${kind}`),\n sql`, `,\n )})\n AND identity_assertions.b_kind IN (${sql.join(\n nodeKinds.map((kind) => sql`${kind}`),\n sql`, `,\n )})\n `;\n const liveEndpointJoins =\n options.includeDeleted === false ?\n sql`\n JOIN ${ctx.schema.nodesTable} identity_a_node\n ON identity_a_node.graph_id = identity_assertions.graph_id\n AND identity_a_node.kind = identity_assertions.a_kind\n AND identity_a_node.id = identity_assertions.a_id\n AND identity_a_node.deleted_at IS NULL\n JOIN ${ctx.schema.nodesTable} identity_b_node\n ON identity_b_node.graph_id = identity_assertions.graph_id\n AND identity_b_node.kind = identity_assertions.b_kind\n AND identity_b_node.id = identity_assertions.b_id\n AND identity_b_node.deleted_at IS NULL\n `\n : sql``;\n const assertionIdKey = codePointOrderedAssertionId(target);\n const rows = await target.execute<RawIdentityAssertionRow>(\n asCompiledRowsSql(sql`\n SELECT identity_assertions.graph_id AS graph_id,\n identity_assertions.id AS id,\n identity_assertions.rel AS rel,\n identity_assertions.a_kind AS a_kind,\n identity_assertions.a_id AS a_id,\n identity_assertions.b_kind AS b_kind,\n identity_assertions.b_id AS b_id,\n identity_assertions.valid_from AS valid_from,\n identity_assertions.valid_to AS valid_to,\n identity_assertions.created_at AS created_at,\n identity_assertions.updated_at AS updated_at,\n identity_assertions.deleted_at AS deleted_at,\n identity_assertions.ended_by_kind AS ended_by_kind,\n identity_assertions.ended_by_id AS ended_by_id\n FROM ${ctx.schema.identityAssertionsTable} identity_assertions\n ${liveEndpointJoins}\n WHERE identity_assertions.graph_id = ${ctx.graphId}\n AND identity_assertions.deleted_at IS NULL\n ${\n options.after === undefined ?\n sql``\n : sql`AND ${assertionIdKey} > ${options.after}`\n }\n ${\n mode === \"state\" ?\n sql`AND identity_assertions.valid_to IS NULL`\n : sql``\n }\n ${kindFilter}\n ORDER BY ${assertionIdKey} ASC\n LIMIT ${options.limit}\n `),\n );\n const allowedKinds = filterKindsInMemory ? new Set(nodeKinds) : undefined;\n const assertions = rows\n .filter(\n (row) =>\n allowedKinds === undefined ||\n (allowedKinds.has(row.a_kind) && allowedKinds.has(row.b_kind)),\n )\n .map((row) => toTransferAssertion(normalizeIdentityAssertionRow(row)));\n const nextAfter = rows.at(-1)?.id;\n return {\n assertions,\n ...(nextAfter === undefined ? {} : { nextAfter }),\n done: rows.length < options.limit,\n };\n}\n\nexport async function readIdentityAssertionsForInterchange<G extends GraphDef>(\n ctx: IdentityServiceContext<G>,\n mode: \"state\" | \"archival\",\n options?: IdentityInterchangeReadOptions,\n): Promise<readonly IdentityTransferAssertion[]> {\n const page = await readIdentityAssertionPageAtTarget(ctx, ctx.backend, mode, {\n ...options,\n limit: 2_147_483_647,\n });\n return page.assertions;\n}\n","import { type ReadCoordinate } from \"../core/temporal\";\nimport {\n ConfigurationError,\n NodeNotFoundError,\n ValidationError,\n} from \"../errors\";\nimport { type SqlSchema } from \"../query/compiler/schema\";\nimport { sql } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../query/sql-intent\";\nimport { type KindRegistry } from \"../registry/kind-registry\";\nimport { chunk } from \"../utils/array\";\nimport { nowIso } from \"../utils/date\";\nimport { requireDefined } from \"../utils/presence\";\nimport type {\n Backend,\n IdentitySnapshot,\n RawClosureClassRow,\n} from \"./service-read\";\nimport {\n compareReferences,\n containsRef,\n loadAssertions,\n loadNodeSnapshot,\n referenceCondition,\n refKey,\n} from \"./service-read\";\nimport {\n identityChunkSize,\n MAX_REFERENCE_CHUNK_SIZE,\n type PlainNodeRef,\n} from \"./sql-target\";\nimport { type IdentityAssertionStorageRow } from \"./storage-types\";\nimport { type IdentityRelation } from \"./types\";\n\n/** @internal Exported for the stack-safety / union-by-size regression test. */\nexport class UnionFind {\n readonly #parents = new Map<string, string>();\n readonly #sizes = new Map<string, number>();\n readonly #refs = new Map<string, PlainNodeRef>();\n\n add(ref: PlainNodeRef): void {\n const key = refKey(ref);\n if (this.#parents.has(key)) return;\n this.#parents.set(key, key);\n this.#sizes.set(key, 1);\n this.#refs.set(key, ref);\n }\n\n // Iterative walk-then-compress: an adversarially ordered chain of unions can\n // build O(N) depth, which a recursive find would blow the stack on.\n #find(key: string): string {\n let root = key;\n for (;;) {\n const parent = this.#parents.get(root);\n if (parent === undefined) {\n throw new Error(`Unknown identity member ${root}`);\n }\n if (parent === root) break;\n root = parent;\n }\n let cursor = key;\n while (cursor !== root) {\n const next = requireDefined(\n this.#parents.get(cursor),\n `Unknown identity member ${cursor}`,\n );\n this.#parents.set(cursor, root);\n cursor = next;\n }\n return root;\n }\n\n // Union by size keeps trees shallow. Canonical member selection is\n // independent of root identity — components() sorts each group and takes the\n // code-point-least member — so linking by size never changes the closure.\n union(first: PlainNodeRef, second: PlainNodeRef): void {\n this.add(first);\n this.add(second);\n const firstRoot = this.#find(refKey(first));\n const secondRoot = this.#find(refKey(second));\n if (firstRoot === secondRoot) return;\n const firstSize = requireDefined(this.#sizes.get(firstRoot));\n const secondSize = requireDefined(this.#sizes.get(secondRoot));\n const [root, child] =\n firstSize >= secondSize ?\n [firstRoot, secondRoot]\n : [secondRoot, firstRoot];\n this.#parents.set(child, root);\n this.#sizes.set(root, firstSize + secondSize);\n }\n\n // Public root accessor for callers that maintain their own member index\n // incrementally (bulkAssertPairs) rather than re-deriving components().\n root(ref: PlainNodeRef): string {\n return this.#find(refKey(ref));\n }\n\n components(): ReadonlyMap<string, readonly PlainNodeRef[]> {\n const groups = new Map<string, PlainNodeRef[]>();\n for (const [key, ref] of this.#refs) {\n const root = this.#find(key);\n const group = groups.get(root) ?? [];\n group.push(ref);\n groups.set(root, group);\n }\n const byMember = new Map<string, readonly PlainNodeRef[]>();\n for (const group of groups.values()) {\n const sorted = group.toSorted((left, right) =>\n compareReferences(left, right),\n );\n for (const member of sorted) byMember.set(refKey(member), sorted);\n }\n return byMember;\n }\n}\n\nexport function buildComponents(\n structuralNodes: readonly PlainNodeRef[],\n assertions: readonly Pick<\n IdentityAssertionStorageRow,\n \"rel\" | \"a_kind\" | \"a_id\" | \"b_kind\" | \"b_id\"\n >[],\n sameIdAcrossKinds: \"fold\" | \"ignore\",\n): ReadonlyMap<string, readonly PlainNodeRef[]> {\n const unionFind = new UnionFind();\n const byId = new Map<string, PlainNodeRef[]>();\n for (const ref of structuralNodes) {\n unionFind.add(ref);\n const group = byId.get(ref.id) ?? [];\n group.push(ref);\n byId.set(ref.id, group);\n }\n if (sameIdAcrossKinds === \"fold\") {\n for (const group of byId.values()) {\n const first = group[0];\n if (first === undefined) continue;\n for (const member of group.slice(1)) unionFind.union(first, member);\n }\n }\n for (const assertion of assertions) {\n if (assertion.rel !== \"same\") continue;\n unionFind.union(\n { kind: assertion.a_kind, id: assertion.a_id },\n { kind: assertion.b_kind, id: assertion.b_id },\n );\n }\n return unionFind.components();\n}\n\n/**\n * Which node kinds an identity derivation is allowed to see: exactly the kinds\n * the graph's registry declares.\n *\n * The single owner of that filter, next to the {@link loadSnapshot} scoping it\n * feeds. Every derivation applies it, so an assertion naming a kind this schema\n * does not register is part of neither the closure nor the separation\n * projection. Anything that PREDICTS what a derivation will produce —\n * `separationRebuildRequired`, which decides whether a graph still owes\n * separation rows — has to apply the same filter, or it predicts rows the fill\n * will never write and asks for a rebuild that cannot converge.\n */\nexport function identityActiveKinds(\n registry: KindRegistry,\n): ReadonlySet<string> {\n return new Set(registry.nodeKinds.keys());\n}\n\nexport async function loadSnapshot(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n coordinate?: ReadCoordinate,\n allowedKinds?: ReadonlySet<string>,\n sameIdAcrossKinds: \"fold\" | \"ignore\" = \"fold\",\n): Promise<IdentitySnapshot> {\n const currentInstant = nowIso();\n const [nodes, assertions] = await Promise.all([\n loadNodeSnapshot(target, schema, graphId, coordinate),\n loadAssertions(target, schema, graphId, coordinate, currentInstant),\n ]);\n const scopedNodes =\n allowedKinds === undefined ? nodes : (\n nodes.filter((node) => allowedKinds.has(node.ref.kind))\n );\n const scopedAssertions =\n allowedKinds === undefined ? assertions : (\n assertions.filter(\n (assertion) =>\n allowedKinds.has(assertion.a_kind) &&\n allowedKinds.has(assertion.b_kind),\n )\n );\n const structuralNodes = scopedNodes\n .filter((node) => node.deletedAt === undefined)\n .map((node) => node.ref);\n return {\n nodes: scopedNodes,\n structuralNodes,\n assertions: scopedAssertions,\n components: buildComponents(\n structuralNodes,\n scopedAssertions,\n sameIdAcrossKinds,\n ),\n };\n}\n\nexport function componentFor(\n snapshot: IdentitySnapshot,\n ref: PlainNodeRef,\n): readonly PlainNodeRef[] {\n return snapshot.components.get(refKey(ref)) ?? [ref];\n}\n\nfunction sameComponent(\n snapshot: IdentitySnapshot,\n first: PlainNodeRef,\n second: PlainNodeRef,\n): boolean {\n return containsRef(componentFor(snapshot, first), second);\n}\n\nfunction kindsOf(members: readonly PlainNodeRef[]): ReadonlySet<string> {\n return new Set(members.map((member) => member.kind));\n}\n\n/**\n * Disjointness is a property of kinds, not of members, so an identity class of\n * n members carries at most as many distinct kinds as the registry declares.\n * Collapsing each class to its kind set before the pairwise scan keeps the check\n * quadratic in kinds instead of in class size. `Set` preserves first-insertion\n * order, so the reported pair is the same one the member-pair scan found.\n */\nexport function classHasDisjointKinds(\n registry: KindRegistry,\n first: readonly PlainNodeRef[],\n second: readonly PlainNodeRef[],\n): readonly [string, string] | undefined {\n return kindSetsHaveDisjointKinds(registry, kindsOf(first), kindsOf(second));\n}\n\nexport function kindSetsHaveDisjointKinds(\n registry: KindRegistry,\n first: ReadonlySet<string>,\n second: ReadonlySet<string>,\n): readonly [string, string] | undefined {\n for (const left of first) {\n for (const right of second) {\n if (registry.areDisjoint(left, right)) return [left, right];\n }\n }\n return undefined;\n}\n\nexport type DifferentAssertionIndex = Map<\n string,\n Map<string, IdentityAssertionStorageRow>\n>;\n\nexport function indexDifferentAssertion(\n index: DifferentAssertionIndex,\n firstRoot: string,\n secondRoot: string,\n assertion: IdentityAssertionStorageRow,\n): void {\n const firstNeighbors =\n index.get(firstRoot) ?? new Map<string, IdentityAssertionStorageRow>();\n const secondNeighbors =\n index.get(secondRoot) ?? new Map<string, IdentityAssertionStorageRow>();\n if (!firstNeighbors.has(secondRoot)) {\n firstNeighbors.set(secondRoot, assertion);\n }\n if (!secondNeighbors.has(firstRoot)) {\n secondNeighbors.set(firstRoot, assertion);\n }\n index.set(firstRoot, firstNeighbors);\n index.set(secondRoot, secondNeighbors);\n}\n\nexport function mergeDifferentAssertionRoots(\n index: DifferentAssertionIndex,\n survivingRoot: string,\n retiredRoot: string,\n): void {\n const survivingNeighbors =\n index.get(survivingRoot) ?? new Map<string, IdentityAssertionStorageRow>();\n const retiredNeighbors = index.get(retiredRoot);\n survivingNeighbors.delete(retiredRoot);\n if (retiredNeighbors !== undefined) {\n for (const [neighborRoot, assertion] of retiredNeighbors) {\n if (neighborRoot === survivingRoot) continue;\n const canonicalAssertion =\n survivingNeighbors.get(neighborRoot) ?? assertion;\n survivingNeighbors.set(neighborRoot, canonicalAssertion);\n const neighborMap = index.get(neighborRoot);\n if (neighborMap !== undefined) {\n neighborMap.delete(retiredRoot);\n neighborMap.set(survivingRoot, canonicalAssertion);\n }\n }\n }\n index.delete(retiredRoot);\n if (survivingNeighbors.size === 0) {\n index.delete(survivingRoot);\n } else {\n index.set(survivingRoot, survivingNeighbors);\n }\n}\n\nexport function validateSnapshotIntegrity(\n snapshot: IdentitySnapshot,\n registry: KindRegistry,\n graphId: string,\n): void {\n const structuralKeys = new Set(\n snapshot.structuralNodes.map((ref) => refKey(ref)),\n );\n for (const assertion of snapshot.assertions) {\n const a = { kind: assertion.a_kind, id: assertion.a_id };\n const b = { kind: assertion.b_kind, id: assertion.b_id };\n if (!structuralKeys.has(refKey(a)) || !structuralKeys.has(refKey(b))) {\n throw new ConfigurationError(\n \"Operational Identity contains a current assertion with a missing or deleted endpoint.\",\n {\n code: \"IDENTITY_SCHEMA_CONTRADICTION\",\n graphId,\n assertionId: assertion.id,\n a,\n b,\n },\n );\n }\n if (assertion.rel === \"different\" && sameComponent(snapshot, a, b)) {\n throw new ConfigurationError(\n \"Operational Identity contains a different assertion within one identity class.\",\n {\n code: \"IDENTITY_SCHEMA_CONTRADICTION\",\n graphId,\n assertionId: assertion.id,\n a,\n b,\n },\n );\n }\n }\n\n const visited = new Set<string>();\n for (const [memberKey, component] of snapshot.components) {\n if (visited.has(memberKey)) continue;\n for (const member of component) visited.add(refKey(member));\n // Self-pairs are safe to include: `areDisjoint(kind, kind)` is false by\n // construction, so scanning the component's kind set against itself finds\n // exactly the member pairs an upper-triangle member scan would.\n const conflictingKinds = classHasDisjointKinds(\n registry,\n component,\n component,\n );\n if (conflictingKinds !== undefined) {\n throw new ConfigurationError(\n \"Operational Identity class conflicts with ontology disjointness.\",\n {\n code: \"IDENTITY_SCHEMA_CONTRADICTION\",\n graphId,\n classMembers: component,\n conflictingKinds,\n },\n );\n }\n }\n}\n\ntype RawClosureRow = RawClosureClassRow &\n Readonly<{ class_kind: string; class_id: string }>;\n\nexport function closureMismatchError(\n graphId: string,\n detail: Record<string, unknown>,\n): ConfigurationError {\n return new ConfigurationError(\n \"Operational Identity materialized closure does not match computed identity components.\",\n { code: \"IDENTITY_SCHEMA_CONTRADICTION\", graphId, ...detail },\n {\n suggestion:\n \"Run rebuildIdentityClosure(store) to rebuild the materialized identity closure.\",\n },\n );\n}\n\n/**\n * Asserts the persisted `identityClosureTable` matches the closure the engine\n * derives from the current snapshot, so a stale or corrupted materialized\n * closure — which every current read trusts — cannot pass verification\n * silently. The expected rows are emitted by the same rule as\n * {@link insertClosureComponents}: only components with two or more members\n * carry rows, each member labeled with the component's code-point-least member;\n * singletons carry none.\n */\nexport async function assertClosureMatchesComponents(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n components: ReadonlyMap<string, readonly PlainNodeRef[]>,\n): Promise<void> {\n const expected = new Map<\n string,\n Readonly<{ member: PlainNodeRef; classRef: PlainNodeRef }>\n >();\n const emitted = new Set<string>();\n for (const [memberKey, component] of components) {\n if (emitted.has(memberKey) || component.length < 2) continue;\n const canonical = requireDefined(component[0]);\n for (const member of component) {\n const key = refKey(member);\n emitted.add(key);\n expected.set(key, { member, classRef: canonical });\n }\n }\n\n const rows = await target.execute<RawClosureRow>(\n asCompiledRowsSql(sql`\n SELECT member_kind, member_id, class_kind, class_id\n FROM ${schema.identityClosureTable}\n WHERE graph_id = ${graphId}\n `),\n );\n const seen = new Set<string>();\n for (const row of rows) {\n const member = { kind: row.member_kind, id: row.member_id };\n const memberKey = refKey(member);\n const match = expected.get(memberKey);\n if (\n match?.classRef.kind !== row.class_kind ||\n match.classRef.id !== row.class_id\n ) {\n throw closureMismatchError(graphId, {\n member,\n class: { kind: row.class_kind, id: row.class_id },\n expectedClass: match?.classRef,\n });\n }\n seen.add(memberKey);\n }\n for (const [memberKey, { member, classRef }] of expected) {\n if (seen.has(memberKey)) continue;\n throw closureMismatchError(graphId, {\n member,\n expectedClass: classRef,\n reason: \"missing-closure-row\",\n });\n }\n}\n\nexport function selfAssertionError(\n relation: IdentityRelation,\n): ValidationError {\n return new ValidationError(\n `Identity ${relation} assertions require two distinct node references.`,\n {\n issues: [\n {\n path: \"pair\",\n message: \"Identity self-assertions are not allowed\",\n code: \"IDENTITY_SELF_ASSERTION\",\n },\n ],\n },\n {\n suggestion:\n \"Filter reflexive pairs before calling an identity assertion method.\",\n },\n );\n}\n\nexport async function requireLiveEndpoint(\n target: Backend,\n graphId: string,\n ref: PlainNodeRef,\n): Promise<void> {\n const row = await target.getNode(graphId, ref.kind, ref.id);\n if (row === undefined || row.deleted_at !== undefined) {\n throw new NodeNotFoundError(ref.kind, ref.id);\n }\n}\n\nexport async function loadLiveReferences(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n references: readonly PlainNodeRef[],\n): Promise<readonly PlainNodeRef[]> {\n if (references.length === 0) return [];\n const chunkSize = identityChunkSize(target, {\n fixedParameters: 1,\n maxItems: MAX_REFERENCE_CHUNK_SIZE,\n parametersPerItem: 2,\n });\n if (references.length > chunkSize) {\n const byKey = new Map<string, PlainNodeRef>();\n for (const refChunk of chunk(references, chunkSize)) {\n const live = await loadLiveReferences(target, schema, graphId, refChunk);\n for (const ref of live) byKey.set(refKey(ref), ref);\n }\n return [...byKey.values()];\n }\n const matches = referenceCondition(sql`kind`, sql`id`, references);\n const rows = await target.execute<Readonly<{ kind: string; id: string }>>(\n asCompiledRowsSql(sql`\n SELECT kind, id\n FROM ${schema.nodesTable}\n WHERE graph_id = ${graphId}\n AND deleted_at IS NULL\n AND ${matches}\n `),\n );\n return rows.map((row) => ({ kind: row.kind, id: row.id }));\n}\n\nexport async function requireLiveEndpoints(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n references: readonly PlainNodeRef[],\n): Promise<void> {\n const uniqueByKey = new Map<string, PlainNodeRef>();\n for (const ref of references) uniqueByKey.set(refKey(ref), ref);\n const live = await loadLiveReferences(target, schema, graphId, references);\n const liveKeys = new Set(live.map((ref) => refKey(ref)));\n for (const [key, ref] of uniqueByKey) {\n if (!liveKeys.has(key)) throw new NodeNotFoundError(ref.kind, ref.id);\n }\n}\n\n/**\n * Requires every reference to name a node ROW — deleted or not. Ended\n * assertions take the raw-INSERT import branch and never touch the closure,\n * but historical reconstruction still conducts identity through them, so an\n * endpoint that never existed would become a phantom bridge: two real nodes\n * reporting `areSame` at an `asOf` coordinate via a node no one ever wrote.\n * The store's own archival exports satisfy this by construction (hard\n * deletion removes the assertions touching the node), so only hand-built\n * documents are refused.\n */\nexport async function requireStructuralEndpoints(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n references: readonly PlainNodeRef[],\n): Promise<void> {\n if (references.length === 0) return;\n const uniqueByKey = new Map<string, PlainNodeRef>();\n for (const ref of references) uniqueByKey.set(refKey(ref), ref);\n const unique = [...uniqueByKey.values()];\n const chunkSize = identityChunkSize(target, {\n fixedParameters: 1,\n maxItems: MAX_REFERENCE_CHUNK_SIZE,\n parametersPerItem: 2,\n });\n const presentKeys = new Set<string>();\n for (const refChunk of chunk(unique, chunkSize)) {\n const matches = referenceCondition(sql`kind`, sql`id`, refChunk);\n const rows = await target.execute<Readonly<{ kind: string; id: string }>>(\n asCompiledRowsSql(sql`\n SELECT kind, id\n FROM ${schema.nodesTable}\n WHERE graph_id = ${graphId}\n AND ${matches}\n `),\n );\n for (const row of rows) {\n presentKeys.add(refKey({ kind: row.kind, id: row.id }));\n }\n }\n for (const [key, ref] of uniqueByKey) {\n if (!presentKeys.has(key)) throw new NodeNotFoundError(ref.kind, ref.id);\n }\n}\n","/**\n * The identity SEPARATION relation: the `different` half of the assertion\n * ledger lifted from node pairs to whole identity classes, one row per\n * separated pair of classes.\n *\n * WHY IT EXISTS. Two code-level layers already refuse a contradictory identity\n * write — the plan-time simulation and the applier's own validation — and both\n * decide by reading state and comparing. A bug in either decides wrongly and\n * commits a ledger where a current `different` assertion sits inside one\n * identity class. This relation removes the decision: every class-fusing\n * transaction relabels the affected separation rows, and relabelling both sides\n * of a row to the same class key produces `class_key_low = class_key_high`,\n * which the relation's CHECK constraint rejects. The transaction aborts in the\n * engine, on a rule no application code can be talked out of.\n *\n * The writers below therefore never test for the contradictory row and skip it.\n * They project the ledger, emit what the projection says, and let the database\n * answer. {@link buildSeparationProjection} does record which assertion\n * produced a collapsed pair, but only so the abort can be reported as a typed\n * error naming the real cause instead of a driver constraint message.\n *\n * SHAPE. A class key is the code-point-least member of the class, encoded by\n * {@link identityClassKey} — a singleton class is keyed by its own node, so\n * nothing has to be materialized for nodes that carry no assertions. The pair\n * is stored ordered (`low < high`) under {@link compareCodePoints}, which is\n * exactly the order SQLite's BINARY collation and PostgreSQL's `C` collation\n * apply, so the writer and the CHECK constraint agree on every input.\n *\n * READABLE STATES. Because an empty relation answers \"not separated\" for every\n * pair, the relation's only safe states are ABSENT (every read raises\n * `IDENTITY_STORAGE_MISSING` — loud, never a wrong answer) and PRESENT AND\n * COMPLETE. {@link separationRebuildRequired} is how every provisioning path\n * tells those apart for one graph, and it is what makes a relation left empty\n * by a refused upgrade heal on the next open instead of under-reporting\n * forever. {@link isSeparated} consults the same predicate, because healing\n * happens at an OPEN and a handle opened before the relation existed cannot\n * heal itself — it refuses loudly until it is reopened. See\n * `schema-transition.ts` for the paths that own the invariant.\n */\nimport {\n ConfigurationError,\n IdentitySeparationViolationError,\n} from \"../errors\";\nimport { type SqlSchema } from \"../query/compiler/schema\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../query/sql-intent\";\nimport { type KindRegistry } from \"../registry/kind-registry\";\nimport { chunk } from \"../utils/array\";\nimport { compareCodePoints } from \"../utils/compare\";\nimport { nowIso } from \"../utils/date\";\nimport { isMissingTableError } from \"../utils/sql-errors\";\nimport { encodeTupleKey } from \"../utils/tuple-key\";\nimport {\n identityAssertionSnapshotSource,\n identitySqlCoordinate,\n} from \"./historical-sql\";\nimport { identityActiveKinds } from \"./service-components\";\nimport {\n executeIdentityStatement,\n identityChunkSize,\n type IdentityTarget,\n MAX_REFERENCE_CHUNK_SIZE,\n type PlainNodeRef,\n} from \"./sql-target\";\nimport { type IdentityAssertionStorageRow } from \"./storage-types\";\n\nconst MAX_SEPARATION_INSERT_CHUNK_SIZE = 100;\n\n/**\n * The PERSISTED encoding of an identity class key.\n *\n * Deliberately its own function rather than a reuse of the service's in-memory\n * `refKey`: this string lives in the database, so changing it is a migration,\n * while an in-memory map key is free to change with its map.\n */\nexport function identityClassKey(ref: PlainNodeRef): string {\n return encodeTupleKey([ref.kind, ref.id]);\n}\n\n/** One separated pair of identity classes, ordered by code point. */\nexport type SeparationPair = Readonly<{ low: string; high: string }>;\n\n/**\n * A `different` assertion whose two endpoints resolved to ONE class key — the\n * contradiction the separation relation exists to reject.\n */\ntype CollapsedSeparation = Readonly<{\n classKey: string;\n assertionId: string;\n a: PlainNodeRef;\n b: PlainNodeRef;\n}>;\n\nexport type SeparationProjection = Readonly<{\n pairs: readonly SeparationPair[];\n collapsed: readonly CollapsedSeparation[];\n}>;\n\n// NUL separator: `identityClassKey` is JSON, which escapes NUL to a `\\u0000`\n// sequence, so no encoded key can contain one and no two distinct pairs can\n// share a joined key.\nconst PAIR_KEY_SEPARATOR = \"\\u0000\";\n\nfunction pairKey(pair: SeparationPair): string {\n return `${pair.low}${PAIR_KEY_SEPARATOR}${pair.high}`;\n}\n\nfunction orderedPair(first: string, second: string): SeparationPair {\n return compareCodePoints(first, second) <= 0 ?\n { low: first, high: second }\n : { low: second, high: first };\n}\n\n/**\n * Projects `different` assertions onto their endpoints' identity classes.\n *\n * Duplicate pairs collapse to one row: several assertions can separate the same\n * two classes, and the relation records the separation, not its witnesses.\n * A pair whose endpoints share a class key is emitted UNCHANGED — rejecting it\n * is the database's job, not this function's — and additionally reported in\n * `collapsed` so the resulting abort can name the assertion behind it.\n */\nexport function buildSeparationProjection(\n assertions: readonly IdentityAssertionStorageRow[],\n classKeyOf: (ref: PlainNodeRef) => string,\n): SeparationProjection {\n const pairs = new Map<string, SeparationPair>();\n const collapsed: CollapsedSeparation[] = [];\n for (const assertion of assertions) {\n if (assertion.rel !== \"different\") continue;\n const a = { kind: assertion.a_kind, id: assertion.a_id };\n const b = { kind: assertion.b_kind, id: assertion.b_id };\n const pair = orderedPair(classKeyOf(a), classKeyOf(b));\n pairs.set(pairKey(pair), pair);\n if (pair.low === pair.high) {\n collapsed.push({\n classKey: pair.low,\n assertionId: assertion.id,\n a,\n b,\n });\n }\n }\n return { pairs: [...pairs.values()], collapsed };\n}\n\n/** Drops every separation row for the graph, ahead of a full recompute. */\nexport async function deleteSeparationForGraph(\n target: IdentityTarget,\n schema: SqlSchema,\n graphId: string,\n): Promise<void> {\n await executeIdentityStatement(\n target,\n sql`DELETE FROM ${schema.identitySeparationTable} WHERE graph_id = ${graphId}`,\n );\n}\n\n/**\n * Drops every separation row naming one of `classKeys` on either side.\n *\n * Callers pass the keys of ALL members of the affected classes, not just the\n * classes' current keys: a fuse retires one of the two keys, and the retired\n * key's rows are only reachable by its own member key.\n */\nexport async function deleteSeparationForClassKeys(\n target: IdentityTarget,\n schema: SqlSchema,\n graphId: string,\n classKeys: readonly string[],\n): Promise<void> {\n const unique = [...new Set(classKeys)];\n if (unique.length === 0) return;\n const chunkSize = identityChunkSize(target, {\n fixedParameters: 1,\n maxItems: MAX_REFERENCE_CHUNK_SIZE,\n parametersPerItem: 2,\n });\n for (const keyChunk of chunk(unique, chunkSize)) {\n const keyList = sql.join(\n keyChunk.map((key) => sql`${key}`),\n sql`, `,\n );\n await executeIdentityStatement(\n target,\n sql`\n DELETE FROM ${schema.identitySeparationTable}\n WHERE graph_id = ${graphId}\n AND (class_key_low IN (${keyList}) OR class_key_high IN (${keyList}))\n `,\n );\n }\n}\n\ntype RawSeparationRow = Readonly<{\n class_key_low: string;\n class_key_high: string;\n}>;\n\n/**\n * Whether the relation records two CURRENT classes as separated.\n *\n * One primary-key probe against `(graph_id, class_key_low, class_key_high)`,\n * standing in for resolving both classes' `different` assertions out of the\n * ledger and scanning them for one that spans the pair. Callers pass the class\n * keys in any order; putting them in the relation's `low < high` order is this\n * module's business, since it is the same ordering the writer applies.\n *\n * Valid only for a current-mode read: the relation projects CURRENT assertions\n * onto CURRENT classes, so a valid-time or recorded coordinate has to\n * reconstruct from the ledger instead.\n *\n * NEVER ANSWERS \"not separated\" WHEN IT COULD NOT READ. A missing relation\n * raises `IDENTITY_STORAGE_MISSING` and any other driver failure propagates\n * unchanged — and one more state answers loudly rather than falsely: the\n * relation is PRESENT but holds no row for this graph while the ledger holds a\n * live `different` assertion, which means this graph's fill never ran. A store\n * handle opened while the relation was ABSENT fails loudly on every read; if\n * another graph's upgrade then creates the shared relation mid-session, that\n * handle would otherwise transition from loud failure to a confident, wrong\n * \"not separated\" — {@link separationRebuildRequired} is what keeps it loud\n * until the handle is reopened (the reopen runs the fill).\n *\n * WHAT IT COSTS. The pair lookup and \"does this graph have ANY row\" travel in\n * ONE statement — a second seek on the same primary key, in the same round\n * trip — so a graph that uses separations pays nothing beyond that seek and the\n * ledger is not read at all. The ledger probe runs only when the graph has NO\n * separation rows AND the pair missed, which is also the only state where a\n * \"false\" could be an unfilled relation rather than an absent separation. Both\n * callers reach here having already resolved two identity classes through the\n * closure (a recursive CTE each), so the bounded `LIMIT 1` this adds in that\n * state is small against what the answer already cost.\n *\n * @throws {ConfigurationError} `IDENTITY_STORAGE_MISSING` when the relation the\n * probe reads does not exist, or exists without this graph's fill.\n */\nexport async function isSeparated(\n target: IdentityTarget,\n schema: SqlSchema,\n graphId: string,\n firstClassKey: string,\n secondClassKey: string,\n registry: KindRegistry,\n): Promise<boolean> {\n // A class is never separated from itself: `low = high` is what the relation's\n // CHECK exists to reject, so the probe is a guaranteed miss and the round\n // trip buys nothing.\n if (firstClassKey === secondClassKey) return false;\n const probe = await probeSeparationPair(\n target,\n schema,\n graphId,\n orderedPair(firstClassKey, secondClassKey),\n );\n if (probe.pairSeparated) return true;\n // The fast path, unchanged: rows exist for this graph, so the relation is not\n // in the unfilled state and the ledger is not read at all. This statement is\n // exactly the one the guard inherited — no proof rides along, no kind binds.\n if (probe.graphHasRows) return false;\n // Zero rows is not an exceptional state: it is the STEADY state of every\n // graph that holds only `same` assertions, so this is the path whose cost\n // decides whether the guard is affordable. The proof runs at most once per\n // Store handle.\n if (separationReadinessProven(registry, graphId)) return false;\n if (await hasLiveDifferentAssertions(target, schema, graphId, registry)) {\n throw separationUnfilledError(graphId, schema);\n }\n proveSeparationReadiness(registry, graphId);\n return false;\n}\n\n/**\n * Graphs whose separation relation has already been proven readable and\n * complete for a given registry: \"the relation holds rows for this graph, or\n * the ledger owes it none\".\n *\n * WHY THE PROOF IS WORTH KEEPING. The state it settles is not a corner case: a\n * graph holding only `same` assertions has zero separation rows FOREVER, so\n * without a memo every validated pair re-asks the ledger — and that question\n * has no index to answer it from (the ledger's partial unique index covers\n * `valid_to IS NULL`, which the live-window predicate does not imply), so it\n * scans. Measured on SQLite: +23% on a 50-assertion import, +32% at 200, +56%\n * on eight concurrent `assertSame`. The memo makes the proof O(1) per handle\n * instead of O(pairs).\n *\n * WHY THE REGISTRY IS THE KEY. It is the graph's kind registry — one per Store\n * handle, and the very filter the proof was taken under. A proof is therefore\n * reused only where the filter that produced it still applies, and two handles\n * over the same graph hold separate registries and prove independently.\n * A transaction target cannot be the key: every write opens its own, so a\n * per-target memo would never be reused by the single-assertion path at all.\n *\n * WHY IT IS SOUND. Nothing a validated write does turns a proven relation back\n * into an unfilled one: the writes that follow ADD separation rows (an accepted\n * `different`), or relabel rows that already exist (an accepted `same`), and a\n * retraction removes an assertion together with the row it produced. Across\n * processes the ledger and the relation move together too — every sanctioned\n * path writes both in one transaction.\n *\n * WHAT IT GIVES UP, stated plainly. The window this guard exists for is\n * UNAFFECTED: a handle opened while the relation was ABSENT fails loudly on\n * every read (it cannot read the relation at all), so it never records a proof,\n * and its FIRST successful read — the one right after another graph's upgrade\n * publishes the shared relation — still runs the proof and still refuses. What\n * a kept proof no longer re-detects is a relation dropped or truncated OUT OF\n * BAND midway through a handle's life, after that handle had already read it\n * successfully. That is the corruption class `validateIdentity()` reports and\n * the CHECK constraint still refuses at the next fusing write — not the\n * storage-provisioning gap this guard was added for.\n *\n * Keyed weakly, exactly as the recorded-write lock memo is, so a memo entry\n * cannot outlive the handle that earned it.\n */\nconst provenSeparationReadiness = new WeakMap<KindRegistry, Set<string>>();\n\nfunction separationReadinessProven(\n registry: KindRegistry,\n graphId: string,\n): boolean {\n return provenSeparationReadiness.get(registry)?.has(graphId) === true;\n}\n\nfunction proveSeparationReadiness(\n registry: KindRegistry,\n graphId: string,\n): void {\n const proven = provenSeparationReadiness.get(registry) ?? new Set<string>();\n proven.add(graphId);\n provenSeparationReadiness.set(registry, proven);\n}\n\n/** What one probe of the relation establishes about a pair AND its graph. */\ntype SeparationProbe = Readonly<{\n pairSeparated: boolean;\n graphHasRows: boolean;\n}>;\n\n/**\n * The pair lookup and \"does this graph hold ANY row\", in one statement.\n *\n * The readiness proof deliberately does NOT ride along here. Folding it in as a\n * `CASE`-guarded scalar subquery was measured and rejected: it made the\n * eight-concurrent-`assertSame` workload SLOWER than leaving it as a second\n * statement (0.873 vs 0.793 ms/op), because a fresh transaction cannot reuse a\n * memo and every statement then carries the join, the kind binds, and a bigger\n * plan to prepare — while the graphs that DO hold rows would have paid the same\n * binds for a subquery whose arm is never taken. Cheap on paper, not on the\n * engine.\n */\nasync function probeSeparationPair(\n target: IdentityTarget,\n schema: SqlSchema,\n graphId: string,\n pair: SeparationPair,\n): Promise<SeparationProbe> {\n try {\n const rows = await target.execute<Readonly<Record<string, unknown>>>(\n asCompiledRowsSql(sql`\n SELECT\n (\n SELECT COUNT(*) FROM ${schema.identitySeparationTable}\n WHERE graph_id = ${graphId}\n AND class_key_low = ${pair.low}\n AND class_key_high = ${pair.high}\n ) AS pair_rows,\n (\n SELECT COUNT(*) FROM (\n SELECT 1 AS present FROM ${schema.identitySeparationTable}\n WHERE graph_id = ${graphId}\n LIMIT 1\n ) graph_probe\n ) AS graph_rows\n `),\n );\n const row = rows[0];\n return {\n graphHasRows: countOf(row, \"graph_rows\") > 0,\n pairSeparated: countOf(row, \"pair_rows\") > 0,\n };\n } catch (error) {\n // Never degrade to \"not separated\": a caller that cannot read the relation\n // has no basis for an answer, and the wrong answer here is the one that\n // lets a contradiction through. Both branches below therefore throw.\n //\n // A missing relation is the one failure this seam can describe better than\n // the driver can, so it is translated — through the shared structural\n // classifier (SQLSTATE 42P01, SQLite `no such table`), never this module's\n // own wording match. Everything else — a deadlock, a serialization failure,\n // a lock timeout, a dropped connection — is transient or unrelated, and\n // relabelling it \"storage missing\" would send an operator to rebuild a\n // relation that is intact and would hide a retryable conflict from callers\n // that classify it (graph-merge's commit retry reads the driver SQLSTATE).\n if (!isMissingTableError(error)) throw error;\n throw separationUnreadableError(graphId, schema, error);\n }\n}\n\n/**\n * `COUNT(*)` as a number, whatever the driver hands back.\n *\n * PostgreSQL's `count` is `bigint`, which node-postgres returns as a string\n * rather than losing precision; SQLite returns a number. A truthiness test on\n * the raw value would read the string `\"0\"` as separated.\n */\nfunction countOf(\n row: Readonly<Record<string, unknown>> | undefined,\n column: string,\n): number {\n return Number(row?.[column] ?? 0);\n}\n\nfunction separationUnreadableError(\n graphId: string,\n schema: SqlSchema,\n cause: unknown,\n): ConfigurationError {\n return new ConfigurationError(\n \"Operational Identity could not read the materialized separation relation.\",\n {\n code: \"IDENTITY_STORAGE_MISSING\",\n graphId,\n tables: [schema.tables.identitySeparation],\n },\n {\n cause,\n suggestion:\n \"Recreate the identity separation relation with the standard TypeGraph DDL, open the Store, and run rebuildIdentityClosure(store) before serving traffic.\",\n },\n );\n}\n\n/**\n * The relation exists but holds no row for this graph while the ledger holds a\n * live `different` assertion — this graph's fill never ran.\n *\n * Reported under the same code as an absent relation, because it is the same\n * fact for an operator (this graph's derived separation storage is not\n * readable) with the same remedy. Reopening the Store runs the fill; a handle\n * that predates the relation's creation cannot, which is exactly the window\n * this refusal exists to keep loud.\n */\nfunction separationUnfilledError(\n graphId: string,\n schema: SqlSchema,\n): ConfigurationError {\n return new ConfigurationError(\n \"Operational Identity found the separation relation present but never filled for this graph.\",\n {\n code: \"IDENTITY_STORAGE_MISSING\",\n graphId,\n reason: \"unfilled\",\n tables: [schema.tables.identitySeparation],\n },\n {\n suggestion:\n \"Reopen the Store (createStoreWithSchema rebuilds the derived identity relations when they are missing rows), or run rebuildIdentityClosure(store) before serving traffic. A Store handle opened while the relation did not exist keeps failing until it is reopened.\",\n },\n );\n}\n\n/**\n * The persisted relation holds a separated pair the assertion ledger does not\n * project — the same `rebuild != recompute(ledger)` divergence\n * {@link assertSeparationMatchesProjection} refuses, discovered by a probe\n * whose answer the ledger could not corroborate.\n */\nexport function unexpectedSeparationError(\n graphId: string,\n firstClassKey: string,\n secondClassKey: string,\n): ConfigurationError {\n return separationMismatchError(graphId, {\n unexpected: orderedPair(firstClassKey, secondClassKey),\n });\n}\n\n/**\n * Whether THIS GRAPH's separation relation still owes rows to the ledger —\n * the per-graph fill decision every provisioning path keys on.\n *\n * The decision it replaces was \"the separation TABLE is missing\", and that\n * question has the wrong scope in two ways. Identity DDL is database-global\n * while the ledger is per-graph, so graph B creating the relation made graph A\n * skip its own fill; and a relation created by a schema commit that was then\n * refused stayed present-and-empty forever, because \"present\" is exactly what\n * suppressed the next open's rebuild. Keying on this graph's own derived state\n * fixes both, and makes a stranded empty relation SELF-HEALING: the next open\n * of the graph that owns the assertions sees assertions-without-rows and\n * rebuilds.\n *\n * `true` means: the ledger holds at least one live `different` assertion for\n * the graph while the relation holds no row for it. Those are precisely the\n * states in which the relation would under-report a separation — the answer\n * that lets `assertSame` fuse two classes a `different` assertion separates.\n * A graph with no live `different` assertion projects to zero rows, so an\n * empty relation is not merely safe there, it is CORRECT, and no rebuild is\n * owed.\n *\n * `relationExists: false` skips the row probe (the relation cannot be read\n * before it is created) and answers purely from the ledger, so a caller can\n * distinguish \"create it empty\" from \"create it and fill it in one fence\".\n *\n * EXACTNESS IS THE POINT, in both directions: \"a fill is owed\" has to be true\n * exactly when the fill would write a ROW, not merely when the ledger holds an\n * assertion. Three conditions get it there, and each one is a state that\n * over-answering would misdiagnose — see {@link hasLiveDifferentAssertions}:\n * the current-coordinate filter ({@link identityAssertionSnapshotSource}), the\n * registry filter ({@link identityActiveKinds}), and \"the endpoints are in\n * different classes\", without which a contradicted ledger — whose projection is\n * a degenerate pair the CHECK constraint refuses — reads as a relation that was\n * never filled. Over-answering does not merely waste work: it re-runs the\n * fenced CREATE+FILL under the database-scoped DDL lock at every open without\n * converging, and on the read path it reports storage-missing for a fault that\n * is neither. Under-answering leaves the relation under-reporting.\n */\nexport async function separationRebuildRequired(\n target: IdentityTarget,\n schema: SqlSchema,\n graphId: string,\n options: Readonly<{ relationExists: boolean; registry: KindRegistry }>,\n): Promise<boolean> {\n if (\n options.relationExists &&\n (await hasSeparationRows(target, schema, graphId))\n ) {\n return false;\n }\n return hasLiveDifferentAssertions(target, schema, graphId, options.registry);\n}\n\nasync function hasSeparationRows(\n target: IdentityTarget,\n schema: SqlSchema,\n graphId: string,\n): Promise<boolean> {\n const rows = await target.execute<Readonly<Record<string, unknown>>>(\n asCompiledRowsSql(sql`\n SELECT 1 AS present\n FROM ${schema.identitySeparationTable}\n WHERE graph_id = ${graphId}\n LIMIT 1\n `),\n );\n return rows.length > 0;\n}\n\n/**\n * Whether the ledger holds a live `different` assertion the relation OWES A ROW\n * FOR — one the fill would turn into a row the relation can actually hold.\n *\n * Two conditions separate that from \"a live `different` exists\", and both are\n * load-bearing:\n *\n * - THE REGISTRY FILTER. An assertion naming a kind this schema does not\n * register is dropped by `loadSnapshot` before the projection, so the fill\n * would never write it. Counting it asks for a rebuild that cannot converge.\n * - THE CLASSES MUST DIFFER. An assertion whose two endpoints are in the SAME\n * identity class projects to a DEGENERATE pair (`low = high`), which is\n * exactly what the relation's CHECK constraint exists to reject — the fill\n * would abort rather than write a row. Zero rows is then not an unfilled\n * relation, it is the only content the relation can hold, and the real fault\n * is a self-contradictory ledger. That fault has its own typed error, raised\n * by the writer and the CHECK ({@link IdentitySeparationViolationError});\n * reporting it here as storage-missing would name the wrong cause and send\n * an operator to a rebuild that cannot succeed.\n *\n * Two steps, because both conditions are the expensive half and almost never\n * change the answer. The first probe binds no kinds, joins nothing, and settles\n * the common case — no live `different` at all — in one statement. Only when\n * one exists does the exact probe run.\n *\n * Class membership comes from the materialized closure, the same authority the\n * callers of {@link isSeparated} resolved their class keys through. The fill\n * instead recomputes classes from the ledger, so a closure that is itself stale\n * could make this answer `false` where the fill would have written a row —\n * a database whose closure is corrupt, which `validateIdentity()` reports and\n * which the CHECK still refuses at the next fusing write.\n */\nasync function hasLiveDifferentAssertions(\n target: IdentityTarget,\n schema: SqlSchema,\n graphId: string,\n registry: KindRegistry,\n): Promise<boolean> {\n if (!(await probeAnyLiveDifferent(target, schema, graphId))) return false;\n const activeKinds = [...identityActiveKinds(registry)];\n if (activeKinds.length === 0) return false;\n // Both endpoints are filtered, so each kind is bound twice. Chunking the\n // cartesian product keeps the statement inside the backend's bind budget for\n // a registry too large to name in one; a single chunk is the normal case and\n // the loop then runs exactly one probe.\n const kindChunks = chunk(activeKinds, owedProbeChunkSize(target));\n for (const first of kindChunks) {\n for (const second of kindChunks) {\n if (await probeOwedSeparation(target, schema, graphId, [first, second])) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * How many binds {@link identityAssertionSnapshotSource} contributes at the\n * CURRENT coordinate: `graph_id`, `rel`, and the validity instant twice\n * (`valid_from <=` and `valid_to >`). A recorded coordinate binds two more, and\n * no caller here uses one.\n */\nconst IDENTITY_SNAPSHOT_PARAMETERS = 4;\n\n/**\n * Fixed binds in {@link probeOwedSeparation}'s STATEMENT — the snapshot\n * subquery's own, plus the `graph_id` each of the two closure `LEFT JOIN`s\n * binds.\n *\n * The chunk math budgets for the whole statement, so it must count every bind\n * the statement carries, not just the subquery's. Budgeting only the subquery's\n * four left the two join binds unfunded, so on a backend at its bind ceiling the\n * probe could be built one kind too wide and overrun the limit it was chunked to\n * respect. Asserted against the rendered statement in\n * `identity-separation-probe-cost.test.ts`.\n */\nconst OWED_SEPARATION_PROBE_PARAMETERS = IDENTITY_SNAPSHOT_PARAMETERS + 2;\n\n/** The cheap half: does the graph hold ANY live `different` assertion. */\nasync function probeAnyLiveDifferent(\n target: IdentityTarget,\n schema: SqlSchema,\n graphId: string,\n): Promise<boolean> {\n const rows = await target.execute<Readonly<Record<string, unknown>>>(\n asCompiledRowsSql(sql`\n SELECT 1 AS present\n FROM (${liveDifferentSource(schema, graphId)}) live_different\n LIMIT 1\n `),\n );\n return rows.length > 0;\n}\n\n/**\n * The exact half: a live `different` whose endpoints are in DIFFERENT classes\n * and whose kinds this schema registers — the assertions that become rows.\n *\n * A member absent from the closure is a singleton class keyed by itself, which\n * is what the `COALESCE` reconstructs: the closure materializes only classes\n * with more than one member.\n */\nasync function probeOwedSeparation(\n target: IdentityTarget,\n schema: SqlSchema,\n graphId: string,\n kinds: readonly [readonly string[], readonly string[]],\n): Promise<boolean> {\n const rows = await target.execute<Readonly<Record<string, unknown>>>(\n asCompiledRowsSql(sql`\n SELECT 1 AS present\n FROM (${liveDifferentSource(schema, graphId)}) live_different\n LEFT JOIN ${schema.identityClosureTable} class_a\n ON class_a.graph_id = ${graphId}\n AND class_a.member_kind = live_different.a_kind\n AND class_a.member_id = live_different.a_id\n LEFT JOIN ${schema.identityClosureTable} class_b\n ON class_b.graph_id = ${graphId}\n AND class_b.member_kind = live_different.b_kind\n AND class_b.member_id = live_different.b_id\n WHERE live_different.a_kind IN (${kindList(kinds[0])})\n AND live_different.b_kind IN (${kindList(kinds[1])})\n AND (\n COALESCE(class_a.class_kind, live_different.a_kind)\n <> COALESCE(class_b.class_kind, live_different.b_kind)\n OR COALESCE(class_a.class_id, live_different.a_id)\n <> COALESCE(class_b.class_id, live_different.b_id)\n )\n LIMIT 1\n `),\n );\n return rows.length > 0;\n}\n\n/**\n * How wide the kind lists may be in ONE owed-separation statement: a registry\n * that does not fit is asked about in chunks rather than silently truncated.\n */\nfunction owedProbeChunkSize(target: IdentityTarget): number {\n return identityChunkSize(target, {\n fixedParameters: OWED_SEPARATION_PROBE_PARAMETERS,\n maxItems: MAX_REFERENCE_CHUNK_SIZE,\n parametersPerItem: 2,\n });\n}\n\nfunction liveDifferentSource(schema: SqlSchema, graphId: string): SqlFragment {\n return identityAssertionSnapshotSource(\n schema,\n graphId,\n identitySqlCoordinate(undefined, nowIso()),\n \"different\",\n );\n}\n\nfunction kindList(kinds: readonly string[]): SqlFragment {\n return sql.join(\n kinds.map((kind) => sql`${kind}`),\n sql`, `,\n );\n}\n\n/** Every persisted separation pair for the graph. */\nexport async function readSeparationForGraph(\n target: IdentityTarget,\n schema: SqlSchema,\n graphId: string,\n): Promise<readonly SeparationPair[]> {\n const rows = await target.execute<RawSeparationRow>(\n asCompiledRowsSql(sql`\n SELECT class_key_low, class_key_high\n FROM ${schema.identitySeparationTable}\n WHERE graph_id = ${graphId}\n `),\n );\n return rows.map((row) => ({\n low: row.class_key_low,\n high: row.class_key_high,\n }));\n}\n\n/**\n * Writes a projection's pairs.\n *\n * The insert is issued as-is, collapsed rows included; the relation's CHECK\n * constraint is what refuses them. A rejected insert is re-thrown as\n * {@link IdentitySeparationViolationError} naming the assertion behind the\n * collapse — and if the insert is instead ACCEPTED while the projection holds a\n * collapsed pair, the constraint is missing from this database, which the same\n * error reports with `enforcedBy: \"writer\"` rather than letting the\n * contradiction commit.\n */\nexport async function insertSeparationRows(\n target: IdentityTarget,\n schema: SqlSchema,\n graphId: string,\n projection: SeparationProjection,\n): Promise<void> {\n const chunkSize = identityChunkSize(target, {\n fixedParameters: 0,\n maxItems: MAX_SEPARATION_INSERT_CHUNK_SIZE,\n parametersPerItem: 3,\n });\n for (const pairChunk of chunk(projection.pairs, chunkSize)) {\n const values = pairChunk.map(\n (pair) => sql`(${graphId}, ${pair.low}, ${pair.high})`,\n );\n try {\n await executeIdentityStatement(\n target,\n sql`\n INSERT INTO ${schema.identitySeparationTable} (\n graph_id, class_key_low, class_key_high\n ) VALUES ${sql.join(values, sql`, `)}\n `,\n );\n } catch (error) {\n const collapsed = collapsedIn(projection, pairChunk);\n if (collapsed === undefined) throw error;\n throw new IdentitySeparationViolationError(\n { graphId, enforcedBy: \"database\", ...collapsed },\n { cause: error },\n );\n }\n }\n const accepted = projection.collapsed[0];\n if (accepted === undefined) return;\n throw new IdentitySeparationViolationError({\n graphId,\n enforcedBy: \"writer\",\n ...accepted,\n });\n}\n\n/** The collapsed assertion whose row is in `pairChunk`, if the chunk has one. */\nfunction collapsedIn(\n projection: SeparationProjection,\n pairChunk: readonly SeparationPair[],\n): CollapsedSeparation | undefined {\n const keys = new Set(pairChunk.map((pair) => pairKey(pair)));\n return projection.collapsed.find((collapsed) =>\n keys.has(pairKey({ low: collapsed.classKey, high: collapsed.classKey })),\n );\n}\n\n/**\n * Asserts the persisted separation relation equals the projection of the given\n * assertions — the `rebuild == recompute(ledger)` oracle, run by identity\n * validation the same way the closure is checked against its components.\n */\nexport function assertSeparationMatchesProjection(\n graphId: string,\n persisted: readonly SeparationPair[],\n projection: SeparationProjection,\n): void {\n const expected = new Map(\n projection.pairs.map((pair) => [pairKey(pair), pair] as const),\n );\n const seen = new Set<string>();\n for (const pair of persisted) {\n const key = pairKey(pair);\n if (!expected.has(key)) {\n throw separationMismatchError(graphId, { unexpected: pair });\n }\n seen.add(key);\n }\n for (const [key, pair] of expected) {\n if (seen.has(key)) continue;\n throw separationMismatchError(graphId, { missing: pair });\n }\n}\n\nfunction separationMismatchError(\n graphId: string,\n detail: Readonly<Record<string, unknown>>,\n): ConfigurationError {\n return new ConfigurationError(\n \"Operational Identity materialized separation relation does not match the assertion ledger.\",\n { code: \"IDENTITY_SCHEMA_CONTRADICTION\", graphId, ...detail },\n {\n suggestion:\n \"Run rebuildIdentityClosure(store) to rebuild the materialized identity relations.\",\n },\n );\n}\n","import { IdentityValidityWindowError } from \"../errors\";\nimport { compareCodePoints } from \"../utils/compare\";\nimport { validateOptionalCanonicalIsoDate } from \"../utils/date\";\nimport { type IdentityValidityWindow } from \"./types\";\n\nexport type ResolvedIdentityValidityWindow = Readonly<{\n validFrom: string;\n validTo?: string;\n effective: \"current\" | \"historical\" | \"empty\";\n}>;\n\n/** Whether a caller stated either bound, as opposed to passing an empty object. */\nexport function hasExplicitIdentityValidityWindow(\n window: IdentityValidityWindow | undefined,\n): boolean {\n return window?.validFrom !== undefined || window?.validTo !== undefined;\n}\n\n/**\n * Validates, defaults, and classifies one identity assertion window against the\n * operation's single captured clock. Every writer and replay path shares this\n * owner so acceptance and current-state materialization cannot drift.\n */\nexport function resolveIdentityValidityWindow(\n window: IdentityValidityWindow | undefined,\n operationInstant: string,\n): ResolvedIdentityValidityWindow {\n const validFrom =\n validateOptionalCanonicalIsoDate(window?.validFrom, \"validFrom\") ??\n operationInstant;\n const validTo = validateOptionalCanonicalIsoDate(window?.validTo, \"validTo\");\n if (compareCodePoints(validFrom, operationInstant) > 0) {\n throw new IdentityValidityWindowError({\n reason: \"future-valid-from\",\n validFrom,\n ...(validTo === undefined ? {} : { validTo }),\n operationInstant,\n });\n }\n if (\n validTo !== undefined &&\n compareCodePoints(validTo, operationInstant) > 0\n ) {\n throw new IdentityValidityWindowError({\n reason: \"future-valid-to\",\n validFrom,\n validTo,\n operationInstant,\n });\n }\n if (validTo !== undefined && compareCodePoints(validTo, validFrom) < 0) {\n throw new IdentityValidityWindowError({\n reason: \"inverted\",\n validFrom,\n validTo,\n operationInstant,\n });\n }\n const effective =\n validTo === validFrom ? \"empty\"\n : validTo === undefined ? \"current\"\n : \"historical\";\n return {\n validFrom,\n ...(validTo === undefined ? {} : { validTo }),\n effective,\n };\n}\n\n/** Half-open overlap for canonical identity assertion windows. */\nexport function identityValidityWindowsOverlap(\n left: Readonly<{ validFrom: string; validTo?: string | undefined }>,\n right: Readonly<{ validFrom: string; validTo?: string | undefined }>,\n): boolean {\n if (left.validFrom === left.validTo || right.validFrom === right.validTo) {\n return false;\n }\n return (\n (right.validTo === undefined || left.validFrom < right.validTo) &&\n (left.validTo === undefined || right.validFrom < left.validTo)\n );\n}\n","import {\n assertRecursiveTraversal,\n type RecursiveTraversalVerdict,\n resolveRecursiveTraversal,\n} from \"../backend/capabilities/recursive-traversal\";\nimport { type GraphDef } from \"../core/define-graph\";\nimport {\n IdentityContradictionError,\n type IdentityContradictionErrorDetails,\n IdentityEndpointValidityError,\n IdentityValidityWindowError,\n NodeNotFoundError,\n} from \"../errors\";\nimport { type SqlSchema } from \"../query/compiler/schema\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../query/sql-intent\";\nimport { chunk } from \"../utils/array\";\nimport { canonicalizeDatabaseTimestamp } from \"../utils/date\";\nimport { generateId } from \"../utils/id\";\nimport { requireDefined } from \"../utils/presence\";\nimport { spanningDifferentAssertion } from \"./different-assertion\";\nimport { IDENTITY_ASSERTION_COLUMNS } from \"./historical-sql\";\nimport {\n normalizeIdentityAssertionRow,\n type RawIdentityAssertionRow,\n} from \"./row-codec\";\nimport {\n buildSeparationProjection,\n deleteSeparationForClassKeys,\n deleteSeparationForGraph,\n identityClassKey,\n insertSeparationRows,\n isSeparated,\n unexpectedSeparationError,\n} from \"./separation\";\nimport {\n buildComponents,\n classHasDisjointKinds,\n componentFor,\n loadLiveReferences,\n loadSnapshot,\n requireLiveEndpoint,\n selfAssertionError,\n} from \"./service-components\";\nimport type {\n Backend,\n IdentitySnapshot,\n IdentityTouch,\n RawSeedClassAnchorRow,\n} from \"./service-read\";\nimport {\n assertionResult,\n compareReferences,\n containsRef,\n loadAssertionsTouching,\n loadCurrentStructuralClasses,\n loadSpanningDifferentAssertion,\n MAX_ASSERTION_INSERT_CHUNK_SIZE,\n MAX_CLOSURE_INSERT_CHUNK_SIZE,\n normalizePair,\n publicAssertion,\n referenceCondition,\n refKey,\n registeredPlainRef,\n} from \"./service-read\";\nimport { type IdentityServiceContext } from \"./service-types\";\nimport {\n executeIdentityStatement,\n identityChunkSize,\n MAX_REFERENCE_CHUNK_SIZE,\n type PlainNodeRef,\n} from \"./sql-target\";\nimport { type IdentityAssertionStorageRow } from \"./storage-types\";\nimport {\n type IdentityAssertionResult,\n type IdentityNodeRefInput,\n type IdentityRelation,\n type IdentityValidityWindow,\n} from \"./types\";\nimport {\n type ResolvedIdentityValidityWindow,\n resolveIdentityValidityWindow,\n} from \"./validity-window\";\n\nexport async function validateCurrentRelation(\n ctx: Pick<\n IdentityServiceContext<GraphDef>,\n \"graphId\" | \"registry\" | \"schema\"\n >,\n target: Backend,\n relation: IdentityRelation,\n operation: IdentityContradictionErrorDetails[\"operation\"],\n a: PlainNodeRef,\n b: PlainNodeRef,\n): Promise<void> {\n const classes = await loadCurrentStructuralClasses(\n target,\n ctx.schema,\n ctx.graphId,\n [a, b],\n );\n const aClass = requireDefined(classes.get(refKey(a)));\n const bClass = requireDefined(classes.get(refKey(b)));\n if (relation === \"different\") {\n if (!containsRef(aClass, b)) return;\n throw new IdentityContradictionError({\n operation,\n a,\n b,\n reason: \"same-class\",\n });\n }\n\n // Whether the two classes are held apart is a single index probe on the\n // derived separation relation. Every caller reaches here with the relation in\n // step with the ledger: each one repairs it inside the same transaction as\n // the write it validates, before the next validation runs.\n const aKey = currentClassKey(aClass);\n const bKey = currentClassKey(bClass);\n if (\n await isSeparated(target, ctx.schema, ctx.graphId, aKey, bKey, ctx.registry)\n ) {\n // The relation records THAT the classes are separated, not which assertion\n // separates them, and the typed error names one — so the ledger answers\n // that single question, on the refusal path only.\n const different = await loadSpanningDifferentAssertion(\n target,\n ctx.schema,\n ctx.graphId,\n aClass,\n bClass,\n );\n if (different === undefined)\n throw unexpectedSeparationError(ctx.graphId, aKey, bKey);\n throw new IdentityContradictionError({\n operation,\n a,\n b,\n reason: \"different-assertion\",\n conflictingAssertionId: different.id,\n });\n }\n const disjointKinds = classHasDisjointKinds(ctx.registry, aClass, bClass);\n if (disjointKinds === undefined) return;\n throw new IdentityContradictionError({\n operation,\n a,\n b,\n reason: \"disjoint-kinds\",\n conflictingKinds: disjointKinds,\n });\n}\n\nexport async function currentAssertionForPair(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n relation: IdentityRelation,\n a: PlainNodeRef,\n b: PlainNodeRef,\n): Promise<IdentityAssertionStorageRow | undefined> {\n const rows = await target.execute<RawIdentityAssertionRow>(\n asCompiledRowsSql(sql`\n SELECT ${IDENTITY_ASSERTION_COLUMNS}\n FROM ${schema.identityAssertionsTable}\n WHERE graph_id = ${graphId}\n AND rel = ${relation}\n AND a_kind = ${a.kind}\n AND a_id = ${a.id}\n AND b_kind = ${b.kind}\n AND b_id = ${b.id}\n AND valid_to IS NULL\n AND deleted_at IS NULL\n LIMIT 1\n `),\n );\n return rows[0] === undefined ?\n undefined\n : normalizeIdentityAssertionRow(rows[0]);\n}\n\nexport async function assertionForExactWindow(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n relation: IdentityRelation,\n a: PlainNodeRef,\n b: PlainNodeRef,\n window: ResolvedIdentityValidityWindow,\n): Promise<IdentityAssertionStorageRow | undefined> {\n const validToMatch =\n window.validTo === undefined ?\n sql`valid_to IS NULL`\n : sql`valid_to = ${window.validTo}`;\n const rows = await target.execute<RawIdentityAssertionRow>(\n asCompiledRowsSql(sql`\n SELECT ${IDENTITY_ASSERTION_COLUMNS}\n FROM ${schema.identityAssertionsTable}\n WHERE graph_id = ${graphId}\n AND rel = ${relation}\n AND a_kind = ${a.kind}\n AND a_id = ${a.id}\n AND b_kind = ${b.kind}\n AND b_id = ${b.id}\n AND valid_from = ${window.validFrom}\n AND ${validToMatch}\n AND deleted_at IS NULL\n LIMIT 1\n `),\n );\n return rows[0] === undefined ?\n undefined\n : normalizeIdentityAssertionRow(rows[0]);\n}\n\nexport async function insertAssertion(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n relation: IdentityRelation,\n a: PlainNodeRef,\n b: PlainNodeRef,\n operationInstant: string,\n touch: IdentityTouch,\n options?: Readonly<{\n id?: string;\n validFrom?: string;\n validTo?: string;\n }>,\n): Promise<IdentityAssertionStorageRow> {\n const row = buildAssertionRow(\n graphId,\n relation,\n a,\n b,\n operationInstant,\n options,\n );\n await insertAssertionRows(target, schema, [row]);\n touch(graphId, row.id, row);\n return row;\n}\n\nexport function buildAssertionRow(\n graphId: string,\n relation: IdentityRelation,\n a: PlainNodeRef,\n b: PlainNodeRef,\n timestamp: string,\n options?: Readonly<{\n id?: string;\n validFrom?: string;\n validTo?: string;\n }>,\n): IdentityAssertionStorageRow {\n return {\n graph_id: graphId,\n id: options?.id ?? generateId(),\n rel: relation,\n a_kind: a.kind,\n a_id: a.id,\n b_kind: b.kind,\n b_id: b.id,\n valid_from: options?.validFrom ?? timestamp,\n valid_to: options?.validTo,\n created_at: timestamp,\n updated_at: timestamp,\n deleted_at: undefined,\n ended_by_kind: undefined,\n ended_by_id: undefined,\n };\n}\n\nfunction canonicalEndpointTimestamp(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined;\n return canonicalizeDatabaseTimestamp(value);\n}\n\nexport async function requireEndpointsCoverIdentityWindow(\n target: Backend,\n graphId: string,\n references: readonly PlainNodeRef[],\n window: ResolvedIdentityValidityWindow,\n): Promise<void> {\n for (const ref of references) {\n const row = await target.getNode(graphId, ref.kind, ref.id);\n if (row === undefined) throw new NodeNotFoundError(ref.kind, ref.id);\n if (window.effective === \"empty\") continue;\n const validFrom = canonicalEndpointTimestamp(row.valid_from);\n const validTo = canonicalEndpointTimestamp(row.valid_to);\n const deletedAt = canonicalEndpointTimestamp(row.deleted_at);\n const endpointWindow = {\n ...(validFrom === undefined ? {} : { validFrom }),\n ...(validTo === undefined ? {} : { validTo }),\n ...(deletedAt === undefined ? {} : { deletedAt }),\n };\n const startsTooLate =\n endpointWindow.validFrom !== undefined &&\n endpointWindow.validFrom > window.validFrom;\n const effectiveEnd = [endpointWindow.validTo, endpointWindow.deletedAt]\n .filter((value): value is string => value !== undefined)\n .toSorted()[0];\n const endsTooEarly =\n window.validTo === undefined ?\n effectiveEnd !== undefined\n : effectiveEnd !== undefined && effectiveEnd < window.validTo;\n if (!startsTooLate && !endsTooEarly) continue;\n throw new IdentityEndpointValidityError({\n endpoint: ref,\n assertionWindow: {\n validFrom: window.validFrom,\n ...(window.validTo === undefined ? {} : { validTo: window.validTo }),\n },\n endpointWindow,\n });\n }\n}\n\ntype RawIdentityWindowLedgerRow = RawIdentityAssertionRow &\n Readonly<{\n row_type: \"assertion\" | \"node\";\n node_kind?: unknown;\n node_id?: unknown;\n node_created_at?: unknown;\n node_deleted_at?: unknown;\n }>;\n\ntype IdentityWindowNode = Readonly<{\n ref: PlainNodeRef;\n createdAt: string;\n deletedAt?: string;\n}>;\n\nexport type IdentityWindowValidationRequest = Readonly<{\n references: readonly PlainNodeRef[];\n window: ResolvedIdentityValidityWindow;\n}>;\n\nexport type IdentityWindowValidator = Readonly<{\n validate: (\n relation: IdentityRelation,\n operation: IdentityContradictionErrorDetails[\"operation\"],\n a: PlainNodeRef,\n b: PlainNodeRef,\n window: ResolvedIdentityValidityWindow,\n ) => void;\n record: (assertion: IdentityAssertionStorageRow) => void;\n}>;\n\nfunction windowOverlapSql(\n alias: string,\n lowerBoundary: string,\n upperBoundary: string,\n): SqlFragment {\n const column = (name: string) =>\n sql`${sql.identifier(alias)}.${sql.identifier(name)}`;\n return sql`\n ${column(\"deleted_at\")} IS NULL\n AND ${column(\"valid_from\")} <= ${upperBoundary}\n AND (${column(\"valid_to\")} IS NULL OR ${column(\"valid_to\")} > ${lowerBoundary})\n `;\n}\n\n/**\n * @internal Exported only so the T3 type test can witness that the branded\n * verdict is REQUIRED here. Not re-exported from any entrypoint.\n */\nexport type IdentityWindowLedgerInput = Readonly<{\n target: Backend;\n schema: SqlSchema;\n graphId: string;\n requests: readonly IdentityWindowValidationRequest[];\n operationInstant: string;\n sameIdAcrossKinds: \"fold\" | \"ignore\";\n recursiveTraversal: RecursiveTraversalVerdict;\n}>;\n\nasync function loadIdentityWindowLedger(\n input: IdentityWindowLedgerInput,\n): Promise<\n Readonly<{\n nodes: readonly IdentityWindowNode[];\n assertions: IdentityAssertionStorageRow[];\n }>\n> {\n // The verdict is applied or refused, never skipped — including on the path\n // below that ends up needing no rows. Asserting before the early return\n // keeps a stated capability from being silently ignored just because this\n // particular call happens to have nothing active to validate.\n assertRecursiveTraversal(\n input.recursiveTraversal,\n \"identity window ledger read\",\n );\n const {\n target,\n schema,\n graphId,\n requests,\n operationInstant,\n sameIdAcrossKinds,\n } = input;\n const activeRequests = requests.filter(\n (request) => request.window.effective !== \"empty\",\n );\n if (activeRequests.length === 0) return { nodes: [], assertions: [] };\n const referencesByKey = new Map<string, PlainNodeRef>();\n for (const request of activeRequests) {\n for (const reference of request.references) {\n referencesByKey.set(refKey(reference), reference);\n }\n }\n const references = [...referencesByKey.values()];\n const lowerBoundary = requireDefined(\n activeRequests.map((request) => request.window.validFrom).toSorted()[0],\n );\n const upperBoundary = requireDefined(\n activeRequests\n .map((request) => request.window.validTo ?? operationInstant)\n .toSorted()\n .at(-1),\n );\n const seedChunkSize = identityChunkSize(target, {\n fixedParameters: 20,\n maxItems: MAX_REFERENCE_CHUNK_SIZE,\n parametersPerItem: 2,\n });\n const rows: RawIdentityWindowLedgerRow[] = [];\n for (const referenceChunk of chunk(references, seedChunkSize)) {\n const seedRows = sql.join(\n referenceChunk.map(\n (reference) => sql`(${reference.kind}, ${reference.id})`,\n ),\n sql`, `,\n );\n const component =\n sameIdAcrossKinds === \"fold\" ?\n sql`\n neighbor_modes(mode) AS (\n VALUES ('assertion'), ('fold')\n ),\n component(kind, id) AS (\n SELECT seed_kind, seed_id FROM seeds\n UNION\n SELECT CASE\n WHEN neighbor_modes.mode = 'fold' THEN folded.kind\n WHEN assertion.a_kind = component.kind AND assertion.a_id = component.id\n THEN assertion.b_kind\n ELSE assertion.a_kind\n END,\n CASE\n WHEN neighbor_modes.mode = 'fold' THEN folded.id\n WHEN assertion.a_kind = component.kind AND assertion.a_id = component.id\n THEN assertion.b_id\n ELSE assertion.a_id\n END\n FROM component\n JOIN neighbor_modes ON 1 = 1\n LEFT JOIN ${schema.identityAssertionsTable} assertion\n ON neighbor_modes.mode = 'assertion'\n AND assertion.graph_id = ${graphId}\n AND assertion.rel = 'same'\n AND ${windowOverlapSql(\"assertion\", lowerBoundary, upperBoundary)}\n AND ((assertion.a_kind = component.kind AND assertion.a_id = component.id)\n OR (assertion.b_kind = component.kind AND assertion.b_id = component.id))\n LEFT JOIN ${schema.nodesTable} folded\n ON neighbor_modes.mode = 'fold'\n AND folded.graph_id = ${graphId}\n AND folded.id = component.id\n WHERE assertion.id IS NOT NULL OR folded.id IS NOT NULL\n )\n `\n : sql`\n component(kind, id) AS (\n SELECT seed_kind, seed_id FROM seeds\n UNION\n SELECT CASE\n WHEN assertion.a_kind = component.kind AND assertion.a_id = component.id\n THEN assertion.b_kind\n ELSE assertion.a_kind\n END,\n CASE\n WHEN assertion.a_kind = component.kind AND assertion.a_id = component.id\n THEN assertion.b_id\n ELSE assertion.a_id\n END\n FROM component\n JOIN ${schema.identityAssertionsTable} assertion\n ON assertion.graph_id = ${graphId}\n AND assertion.rel = 'same'\n AND ${windowOverlapSql(\"assertion\", lowerBoundary, upperBoundary)}\n AND ((assertion.a_kind = component.kind AND assertion.a_id = component.id)\n OR (assertion.b_kind = component.kind AND assertion.b_id = component.id))\n )\n `;\n rows.push(\n ...(await target.execute<RawIdentityWindowLedgerRow>(\n asCompiledRowsSql(sql`\n WITH RECURSIVE\n seeds(seed_kind, seed_id) AS (VALUES ${seedRows}),\n ${component},\n selected_assertions AS (\n SELECT DISTINCT assertion.*\n FROM ${schema.identityAssertionsTable} assertion\n JOIN component\n ON (assertion.a_kind = component.kind AND assertion.a_id = component.id)\n OR (assertion.b_kind = component.kind AND assertion.b_id = component.id)\n WHERE assertion.graph_id = ${graphId}\n AND ${windowOverlapSql(\"assertion\", lowerBoundary, upperBoundary)}\n )\n SELECT 'assertion' AS row_type, ${IDENTITY_ASSERTION_COLUMNS},\n NULL AS node_kind, NULL AS node_id,\n NULL AS node_created_at, NULL AS node_deleted_at\n FROM selected_assertions\n UNION ALL\n SELECT 'node', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,\n NULL, NULL, NULL, NULL, NULL,\n node.kind, node.id, node.created_at, node.deleted_at\n FROM ${schema.nodesTable} node\n JOIN component ON component.kind = node.kind AND component.id = node.id\n WHERE node.graph_id = ${graphId}\n `),\n )),\n );\n }\n const nodesByKey = new Map<string, IdentityWindowNode>();\n const assertionsById = new Map<string, IdentityAssertionStorageRow>();\n for (const row of rows) {\n if (row.row_type === \"assertion\") {\n const assertion = normalizeIdentityAssertionRow(row);\n assertionsById.set(assertion.id, assertion);\n continue;\n }\n if (typeof row.node_kind !== \"string\" || typeof row.node_id !== \"string\")\n continue;\n const createdAt = canonicalEndpointTimestamp(row.node_created_at);\n if (createdAt === undefined) continue;\n const deletedAt = canonicalEndpointTimestamp(row.node_deleted_at);\n const node = {\n ref: { kind: row.node_kind, id: row.node_id },\n createdAt,\n ...(deletedAt === undefined ? {} : { deletedAt }),\n } satisfies IdentityWindowNode;\n nodesByKey.set(refKey(node.ref), node);\n }\n return {\n nodes: [...nodesByKey.values()],\n assertions: [...assertionsById.values()],\n };\n}\n\nfunction identityWindowCheckpoints(\n window: ResolvedIdentityValidityWindow,\n operationInstant: string,\n nodes: readonly IdentityWindowNode[],\n assertions: readonly IdentityAssertionStorageRow[],\n): readonly string[] {\n if (window.effective === \"empty\") return [];\n const checkpoints = new Set([window.validFrom]);\n if (window.validTo === undefined) checkpoints.add(operationInstant);\n for (const row of [...assertions, ...nodes]) {\n for (const value of [\n \"valid_from\" in row ? row.valid_from : undefined,\n \"valid_to\" in row ? row.valid_to : undefined,\n \"createdAt\" in row ? row.createdAt : undefined,\n \"deletedAt\" in row ? row.deletedAt : undefined,\n ]) {\n const boundary = canonicalEndpointTimestamp(value);\n if (boundary === undefined || boundary < window.validFrom) continue;\n if (window.validTo !== undefined && boundary >= window.validTo) continue;\n if (boundary > operationInstant) continue;\n checkpoints.add(boundary);\n }\n }\n return [...checkpoints].toSorted();\n}\n\nfunction validateRelationAgainstLedger(\n ctx: Pick<IdentityServiceContext<GraphDef>, \"registry\" | \"sameIdAcrossKinds\">,\n nodes: readonly IdentityWindowNode[],\n assertions: readonly IdentityAssertionStorageRow[],\n relation: IdentityRelation,\n operation: IdentityContradictionErrorDetails[\"operation\"],\n a: PlainNodeRef,\n b: PlainNodeRef,\n window: ResolvedIdentityValidityWindow,\n operationInstant: string,\n): void {\n const checkpoints = identityWindowCheckpoints(\n window,\n operationInstant,\n nodes,\n assertions,\n );\n for (const instant of checkpoints) {\n const structuralNodes = nodes.map((node) => node.ref);\n const activeAssertions = assertions.filter(\n (assertion) =>\n assertion.deleted_at === undefined &&\n assertion.valid_from <= instant &&\n (assertion.valid_to === undefined || assertion.valid_to > instant),\n );\n const activeFoldReferences = nodes\n .filter(\n (node) =>\n node.createdAt <= instant &&\n (node.deletedAt === undefined || node.deletedAt > instant),\n )\n .map((node) => node.ref);\n const foldAssertions: Pick<\n IdentityAssertionStorageRow,\n \"rel\" | \"a_kind\" | \"a_id\" | \"b_kind\" | \"b_id\"\n >[] = [];\n if (ctx.sameIdAcrossKinds === \"fold\") {\n const byId = new Map<string, PlainNodeRef[]>();\n for (const reference of activeFoldReferences) {\n const sameId = byId.get(reference.id) ?? [];\n sameId.push(reference);\n byId.set(reference.id, sameId);\n }\n for (const sameId of byId.values()) {\n const first = sameId[0];\n if (first === undefined) continue;\n for (const other of sameId.slice(1)) {\n foldAssertions.push({\n rel: \"same\",\n a_kind: first.kind,\n a_id: first.id,\n b_kind: other.kind,\n b_id: other.id,\n });\n }\n }\n }\n const components = buildComponents(\n structuralNodes,\n [...activeAssertions, ...foldAssertions],\n \"ignore\",\n );\n const aClass = components.get(refKey(a)) ?? [];\n const bClass = components.get(refKey(b)) ?? [];\n if (relation === \"different\") {\n if (!containsRef(aClass, b)) continue;\n throw new IdentityContradictionError({\n operation,\n a,\n b,\n reason: \"same-class\",\n });\n }\n const different = spanningDifferentAssertion(\n activeAssertions,\n aClass,\n bClass,\n );\n if (different !== undefined) {\n throw new IdentityContradictionError({\n operation,\n a,\n b,\n reason: \"different-assertion\",\n conflictingAssertionId: different.id,\n });\n }\n const disjointKinds = classHasDisjointKinds(ctx.registry, aClass, bClass);\n if (disjointKinds === undefined) continue;\n throw new IdentityContradictionError({\n operation,\n a,\n b,\n reason: \"disjoint-kinds\",\n conflictingKinds: disjointKinds,\n });\n }\n}\n\nexport async function createIdentityWindowValidator(\n ctx: Pick<\n IdentityServiceContext<GraphDef>,\n \"graphId\" | \"registry\" | \"sameIdAcrossKinds\" | \"schema\"\n >,\n target: Backend,\n requests: readonly IdentityWindowValidationRequest[],\n operationInstant: string,\n ignoredAssertionIds: ReadonlySet<string> = new Set(),\n): Promise<IdentityWindowValidator> {\n const ledger = await loadIdentityWindowLedger({\n target,\n schema: ctx.schema,\n graphId: ctx.graphId,\n requests,\n operationInstant,\n sameIdAcrossKinds: ctx.sameIdAcrossKinds,\n recursiveTraversal: resolveRecursiveTraversal(target.capabilities),\n });\n if (ignoredAssertionIds.size > 0) {\n const retained = ledger.assertions.filter(\n (assertion) => !ignoredAssertionIds.has(assertion.id),\n );\n ledger.assertions.splice(0, ledger.assertions.length, ...retained);\n }\n return {\n validate(relation, operation, a, b, window) {\n validateRelationAgainstLedger(\n ctx,\n ledger.nodes,\n ledger.assertions,\n relation,\n operation,\n a,\n b,\n window,\n operationInstant,\n );\n },\n record(assertion) {\n ledger.assertions.push(assertion);\n },\n };\n}\n\nasync function validateRelationThroughoutIdentityWindow(\n ctx: Pick<\n IdentityServiceContext<GraphDef>,\n \"graphId\" | \"registry\" | \"sameIdAcrossKinds\" | \"schema\"\n >,\n target: Backend,\n relation: IdentityRelation,\n operation: IdentityContradictionErrorDetails[\"operation\"],\n a: PlainNodeRef,\n b: PlainNodeRef,\n window: ResolvedIdentityValidityWindow,\n operationInstant: string,\n): Promise<void> {\n const validator = await createIdentityWindowValidator(\n ctx,\n target,\n [{ references: [a, b], window }],\n operationInstant,\n );\n validator.validate(relation, operation, a, b, window);\n}\n\n/**\n * A nullable assertion column. An absent value inlines a literal `NULL` rather\n * than binding one, so the tuple's worst-case bind count is what\n * `parametersPerItem` below assumes.\n */\nfunction nullableAssertionValue(value: string | undefined): SqlFragment {\n return value === undefined ? sql`NULL` : sql`${value}`;\n}\n\nexport async function insertAssertionRows(\n target: Backend,\n schema: SqlSchema,\n rows: readonly IdentityAssertionStorageRow[],\n): Promise<void> {\n if (rows.length === 0) return;\n const chunkSize = identityChunkSize(target, {\n fixedParameters: 0,\n maxItems: MAX_ASSERTION_INSERT_CHUNK_SIZE,\n parametersPerItem: 14,\n });\n for (const rowChunk of chunk(rows, chunkSize)) {\n // Tuple order follows IDENTITY_ASSERTION_COLUMNS, which is also the INSERT's\n // column clause below.\n const values = rowChunk.map(\n (row) => sql`\n (\n ${row.graph_id}, ${row.id}, ${row.rel}, ${row.a_kind}, ${row.a_id},\n ${row.b_kind}, ${row.b_id}, ${row.valid_from},\n ${nullableAssertionValue(row.valid_to)},\n ${row.created_at}, ${row.updated_at},\n ${nullableAssertionValue(row.deleted_at)},\n ${nullableAssertionValue(row.ended_by_kind)},\n ${nullableAssertionValue(row.ended_by_id)}\n )\n `,\n );\n await executeIdentityStatement(\n target,\n sql`\n INSERT INTO ${schema.identityAssertionsTable} (${IDENTITY_ASSERTION_COLUMNS}) VALUES ${sql.join(values, sql`, `)}\n `,\n );\n }\n}\n\nexport async function loadAssertionsByIds(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n ids: readonly string[],\n): Promise<Map<string, IdentityAssertionStorageRow>> {\n const uniqueIds = [...new Set(ids)];\n const byId = new Map<string, IdentityAssertionStorageRow>();\n if (uniqueIds.length === 0) return byId;\n const chunkSize = identityChunkSize(target, {\n fixedParameters: 1,\n maxItems: MAX_REFERENCE_CHUNK_SIZE,\n parametersPerItem: 1,\n });\n for (const idChunk of chunk(uniqueIds, chunkSize)) {\n const idList = sql.join(\n idChunk.map((id) => sql`${id}`),\n sql`, `,\n );\n const rows = await target.execute<RawIdentityAssertionRow>(\n asCompiledRowsSql(sql`\n SELECT ${IDENTITY_ASSERTION_COLUMNS}\n FROM ${schema.identityAssertionsTable}\n WHERE graph_id = ${graphId} AND id IN (${idList})\n `),\n );\n for (const row of rows) {\n byId.set(row.id, normalizeIdentityAssertionRow(row));\n }\n }\n return byId;\n}\n\n/**\n * The class REPRESENTATIVE of each reference — the closure anchor row, or the\n * reference itself when it is a singleton.\n *\n * {@link loadCurrentStructuralClasses} answers the same question but also\n * materializes every member of every class; the separation projection needs\n * only the label, so this stops at the anchor join.\n */\nasync function loadCurrentClassAnchors(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n references: readonly PlainNodeRef[],\n): Promise<ReadonlyMap<string, PlainNodeRef>> {\n const uniqueByKey = new Map<string, PlainNodeRef>();\n for (const ref of references) uniqueByKey.set(refKey(ref), ref);\n const uniqueReferences = [...uniqueByKey.values()];\n const anchors = new Map<string, PlainNodeRef>();\n if (uniqueReferences.length === 0) return anchors;\n const chunkSize = identityChunkSize(target, {\n fixedParameters: 1,\n maxItems: MAX_REFERENCE_CHUNK_SIZE,\n parametersPerItem: 2,\n });\n for (const refChunk of chunk(uniqueReferences, chunkSize)) {\n const seedRows = sql.join(\n refChunk.map((ref) => sql`(${ref.kind}, ${ref.id})`),\n sql`, `,\n );\n const rows = await target.execute<RawSeedClassAnchorRow>(\n asCompiledRowsSql(sql`\n WITH seeds(seed_kind, seed_id) AS (\n VALUES ${seedRows}\n )\n SELECT seeds.seed_kind, seeds.seed_id,\n COALESCE(anchor.class_kind, seeds.seed_kind) AS class_kind,\n COALESCE(anchor.class_id, seeds.seed_id) AS class_id\n FROM seeds\n LEFT JOIN ${schema.identityClosureTable} anchor\n ON anchor.graph_id = ${graphId}\n AND anchor.member_kind = seeds.seed_kind\n AND anchor.member_id = seeds.seed_id\n `),\n );\n for (const row of rows) {\n anchors.set(refKey({ kind: row.seed_kind, id: row.seed_id }), {\n kind: row.class_kind,\n id: row.class_id,\n });\n }\n }\n return anchors;\n}\n\n/**\n * The separation class key of an already-RESOLVED current class.\n *\n * A class is labelled by its code-point-least member: `insertClosureComponents`\n * and `mergeCurrentClasses` both anchor a class on the first member of its\n * `compareReferences` ordering, and {@link loadCurrentStructuralClasses}\n * returns members in that same ordering — so `members[0]` is the anchor\n * {@link loadCurrentClassAnchors} hands the separation writer, without a second\n * round trip to fetch it. {@link snapshotClassKey} reads a snapshot the same\n * way.\n */\nexport function currentClassKey(members: readonly PlainNodeRef[]): string {\n return identityClassKey(requireDefined(members[0]));\n}\n\n/** The class key a full snapshot assigns to a reference. */\nexport function snapshotClassKey(\n snapshot: IdentitySnapshot,\n ref: PlainNodeRef,\n): string {\n return identityClassKey(requireDefined(componentFor(snapshot, ref)[0]));\n}\n\n/**\n * Rewrites every separation row whose class pair could have moved, given the\n * members of the classes a mutation touched.\n *\n * Deleting by MEMBER key rather than by class key is what makes this complete:\n * a fuse retires one of the two class keys, and rows carrying the retired key\n * are reachable only through the member it used to label.\n */\nasync function replaceSeparationForMembers(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n members: readonly PlainNodeRef[],\n): Promise<void> {\n const uniqueByKey = new Map<string, PlainNodeRef>();\n for (const member of members) uniqueByKey.set(refKey(member), member);\n const unique = [...uniqueByKey.values()];\n if (unique.length === 0) return;\n await deleteSeparationForClassKeys(\n target,\n schema,\n graphId,\n unique.map((member) => identityClassKey(member)),\n );\n const assertions = await loadAssertionsTouching(\n target,\n schema,\n graphId,\n unique,\n undefined,\n \"different\",\n );\n if (assertions.length === 0) return;\n const endpoints = assertions.flatMap((assertion) => [\n { kind: assertion.a_kind, id: assertion.a_id },\n { kind: assertion.b_kind, id: assertion.b_id },\n ]);\n const anchors = await loadCurrentClassAnchors(\n target,\n schema,\n graphId,\n endpoints,\n );\n await insertSeparationRows(\n target,\n schema,\n graphId,\n buildSeparationProjection(assertions, (ref) =>\n identityClassKey(requireDefined(anchors.get(refKey(ref)))),\n ),\n );\n}\n\n/**\n * The separation repair for a mutation that changed no identity class — a\n * `different` assertion arriving or ending. The classes stay put, so the\n * affected members are simply the members of the endpoints' current classes.\n */\nexport async function replaceSeparationForReferences(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n references: readonly PlainNodeRef[],\n): Promise<void> {\n if (references.length === 0) return;\n const classes = await loadCurrentStructuralClasses(\n target,\n schema,\n graphId,\n references,\n );\n await replaceSeparationForMembers(\n target,\n schema,\n graphId,\n [...classes.values()].flat(),\n );\n}\n\nexport async function replaceClosure(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n allowedKinds?: ReadonlySet<string>,\n sameIdAcrossKinds: \"fold\" | \"ignore\" = \"fold\",\n): Promise<void> {\n const snapshot = await loadSnapshot(\n target,\n schema,\n graphId,\n undefined,\n allowedKinds,\n sameIdAcrossKinds,\n );\n await executeIdentityStatement(\n target,\n sql`DELETE FROM ${schema.identityClosureTable} WHERE graph_id = ${graphId}`,\n );\n await insertClosureComponents(target, schema, graphId, snapshot.components);\n await deleteSeparationForGraph(target, schema, graphId);\n await insertSeparationRows(\n target,\n schema,\n graphId,\n buildSeparationProjection(snapshot.assertions, (ref) =>\n snapshotClassKey(snapshot, ref),\n ),\n );\n}\n\nasync function insertClosureComponents(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n components: ReadonlyMap<string, readonly PlainNodeRef[]>,\n): Promise<void> {\n const emitted = new Set<string>();\n const values: SqlFragment[] = [];\n for (const [memberKey, component] of components) {\n if (emitted.has(memberKey) || component.length < 2) continue;\n const canonical = requireDefined(component[0]);\n for (const member of component) {\n emitted.add(refKey(member));\n values.push(\n sql`(${graphId}, ${member.kind}, ${member.id}, ${canonical.kind}, ${canonical.id})`,\n );\n }\n }\n if (values.length === 0) return;\n const chunkSize = identityChunkSize(target, {\n fixedParameters: 0,\n maxItems: MAX_CLOSURE_INSERT_CHUNK_SIZE,\n parametersPerItem: 5,\n });\n for (const valueChunk of chunk(values, chunkSize)) {\n await executeIdentityStatement(\n target,\n sql`\n INSERT INTO ${schema.identityClosureTable} (\n graph_id, member_kind, member_id, class_kind, class_id\n ) VALUES ${sql.join(valueChunk, sql`, `)}\n `,\n );\n }\n}\n\nexport async function replaceAffectedClosure(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n references: readonly PlainNodeRef[],\n sameIdAcrossKinds: \"fold\" | \"ignore\" = \"fold\",\n): Promise<void> {\n if (references.length === 0) return;\n const affectedByKey = new Map<string, PlainNodeRef>();\n const classes = await loadCurrentStructuralClasses(\n target,\n schema,\n graphId,\n references,\n );\n for (const ref of references) {\n for (const member of requireDefined(classes.get(refKey(ref)))) {\n affectedByKey.set(refKey(member), member);\n }\n }\n const affected = [...affectedByKey.values()];\n const structuralNodes = await loadLiveReferences(\n target,\n schema,\n graphId,\n affected,\n );\n const assertions = await loadAssertionsTouching(\n target,\n schema,\n graphId,\n affected,\n undefined,\n \"same\",\n );\n const chunkSize = identityChunkSize(target, {\n fixedParameters: 1,\n maxItems: MAX_REFERENCE_CHUNK_SIZE,\n parametersPerItem: 2,\n });\n for (const affectedChunk of chunk(affected, chunkSize)) {\n const matches = referenceCondition(\n sql`member_kind`,\n sql`member_id`,\n affectedChunk,\n );\n await executeIdentityStatement(\n target,\n sql`\n DELETE FROM ${schema.identityClosureTable}\n WHERE graph_id = ${graphId} AND ${matches}\n `,\n );\n }\n const components = buildComponents(\n structuralNodes,\n assertions,\n sameIdAcrossKinds,\n );\n await insertClosureComponents(target, schema, graphId, components);\n // A recomputed component can ABSORB a member that was outside the affected\n // set — only when the ledger disagrees with the materialized closure, which\n // is exactly the state the separation relation exists to catch. Its old\n // singleton class is gone, so its rows must be rewritten too.\n const separationMembers = [...affected, ...[...components.values()].flat()];\n await replaceSeparationForMembers(target, schema, graphId, separationMembers);\n}\n\nexport async function mergeCurrentClasses(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n a: PlainNodeRef,\n b: PlainNodeRef,\n): Promise<void> {\n const classes = await loadCurrentStructuralClasses(target, schema, graphId, [\n a,\n b,\n ]);\n const aClass = requireDefined(classes.get(refKey(a)));\n const bClass = requireDefined(classes.get(refKey(b)));\n if (containsRef(aClass, b)) return;\n\n const fusedMembers = [...aClass, ...bClass];\n const [smaller, larger] =\n aClass.length <= bClass.length ? [aClass, bClass] : [bClass, aClass];\n const canonical = requireDefined(\n [...aClass, ...bClass].toSorted((left, right) =>\n compareReferences(left, right),\n )[0],\n );\n\n async function relabelExistingClass(\n members: readonly PlainNodeRef[],\n ): Promise<void> {\n if (members.length < 2) return;\n const previousCanonical = requireDefined(members[0]);\n if (refKey(previousCanonical) === refKey(canonical)) return;\n await executeIdentityStatement(\n target,\n sql`\n UPDATE ${schema.identityClosureTable}\n SET class_kind = ${canonical.kind}, class_id = ${canonical.id}\n WHERE graph_id = ${graphId}\n AND class_kind = ${previousCanonical.kind}\n AND class_id = ${previousCanonical.id}\n `,\n );\n }\n\n await relabelExistingClass(smaller);\n await relabelExistingClass(larger);\n const singletonMembers = [smaller, larger].flatMap((members) =>\n members.length === 1 ? members : [],\n );\n if (singletonMembers.length > 0) {\n const values = singletonMembers.map(\n (member) =>\n sql`(${graphId}, ${member.kind}, ${member.id}, ${canonical.kind}, ${canonical.id})`,\n );\n await executeIdentityStatement(\n target,\n sql`\n INSERT INTO ${schema.identityClosureTable} (\n graph_id, member_kind, member_id, class_kind, class_id\n ) VALUES ${sql.join(values, sql`, `)}\n `,\n );\n }\n // Relabelled in the SAME statement batch as the closure: if the two fused\n // classes were separated, both sides of their row become `canonical` and the\n // relation's CHECK aborts the transaction.\n await replaceSeparationForMembers(target, schema, graphId, fusedMembers);\n}\n\nexport async function assertPair<G extends GraphDef>(\n ctx: IdentityServiceContext<G>,\n target: Backend,\n relation: IdentityRelation,\n firstInput: IdentityNodeRefInput<G>,\n secondInput: IdentityNodeRefInput<G>,\n touch: IdentityTouch,\n windowInput: IdentityValidityWindow | undefined,\n operationInstant: string,\n windowValidator?: IdentityWindowValidator,\n): Promise<IdentityAssertionResult<G>> {\n const first = registeredPlainRef(ctx, firstInput);\n const second = registeredPlainRef(ctx, secondInput);\n if (refKey(first) === refKey(second)) throw selfAssertionError(relation);\n const [a, b] = normalizePair(first, second);\n if (windowInput === undefined) {\n const current = await currentAssertionForPair(\n target,\n ctx.schema,\n ctx.graphId,\n relation,\n a,\n b,\n );\n if (current !== undefined) {\n return assertionResult(publicAssertion(current), \"existing\");\n }\n await Promise.all([\n requireLiveEndpoint(target, ctx.graphId, a),\n requireLiveEndpoint(target, ctx.graphId, b),\n ]);\n await validateCurrentRelation(\n ctx,\n target,\n relation,\n relation === \"same\" ? \"assertSame\" : \"assertDifferent\",\n a,\n b,\n );\n const row = await insertAssertion(\n target,\n ctx.schema,\n ctx.graphId,\n relation,\n a,\n b,\n operationInstant,\n touch,\n );\n windowValidator?.record(row);\n if (relation === \"same\") {\n await mergeCurrentClasses(target, ctx.schema, ctx.graphId, a, b);\n } else {\n await replaceSeparationForReferences(target, ctx.schema, ctx.graphId, [\n a,\n b,\n ]);\n }\n return assertionResult(publicAssertion(row), \"created\");\n }\n const window = resolveIdentityValidityWindow(windowInput, operationInstant);\n await requireEndpointsCoverIdentityWindow(\n target,\n ctx.graphId,\n [a, b],\n window,\n );\n const existing = await assertionForExactWindow(\n target,\n ctx.schema,\n ctx.graphId,\n relation,\n a,\n b,\n window,\n );\n if (existing !== undefined) {\n return assertionResult(publicAssertion(existing), \"existing\");\n }\n if (window.effective === \"current\") {\n const current = await currentAssertionForPair(\n target,\n ctx.schema,\n ctx.graphId,\n relation,\n a,\n b,\n );\n if (current !== undefined) {\n throw new IdentityValidityWindowError({\n reason: \"overlapping-open-window\",\n validFrom: window.validFrom,\n operationInstant,\n });\n }\n }\n\n const operation = relation === \"same\" ? \"assertSame\" : \"assertDifferent\";\n if (windowValidator === undefined) {\n await validateRelationThroughoutIdentityWindow(\n ctx,\n target,\n relation,\n operation,\n a,\n b,\n window,\n operationInstant,\n );\n } else {\n windowValidator.validate(relation, operation, a, b, window);\n }\n const row = await insertAssertion(\n target,\n ctx.schema,\n ctx.graphId,\n relation,\n a,\n b,\n operationInstant,\n touch,\n {\n validFrom: window.validFrom,\n ...(window.validTo === undefined ? {} : { validTo: window.validTo }),\n },\n );\n windowValidator?.record(row);\n if (window.effective !== \"current\") {\n return assertionResult(publicAssertion(row), \"created\");\n }\n if (relation === \"same\") {\n await mergeCurrentClasses(target, ctx.schema, ctx.graphId, a, b);\n } else {\n await replaceSeparationForReferences(target, ctx.schema, ctx.graphId, [\n a,\n b,\n ]);\n }\n return assertionResult(publicAssertion(row), \"created\");\n}\n","import { encodeTupleKey } from \"../utils/tuple-key\";\nimport { type IdentityRelation } from \"./types\";\n\ntype IdentityKeyReference = Readonly<{ kind: string; id: string }>;\n\n/** Injective semantic identity for an assertion, excluding its ledger row id. */\nexport function identityAssertionSemanticKey(\n relation: IdentityRelation,\n a: IdentityKeyReference,\n b: IdentityKeyReference,\n): string {\n return encodeTupleKey([relation, a.kind, a.id, b.kind, b.id]);\n}\n","import { type GraphDef } from \"../core/define-graph\";\nimport {\n ConfigurationError,\n IdentityContradictionError,\n type IdentityContradictionErrorDetails,\n} from \"../errors\";\nimport { type SqlSchema } from \"../query/compiler/schema\";\nimport { sql } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../query/sql-intent\";\nimport { runInWriteTransaction } from \"../store/operations/write-transaction\";\nimport { withRecordedIdentityMutationTarget } from \"../store/recorded-capture\";\nimport { chunk } from \"../utils/array\";\nimport { compareCodePoints } from \"../utils/compare\";\nimport { nowIso } from \"../utils/date\";\nimport { requireDefined } from \"../utils/presence\";\nimport { identityAssertionSemanticKey } from \"./assertion-key\";\nimport { IDENTITY_ASSERTION_COLUMNS } from \"./historical-sql\";\nimport {\n normalizeIdentityAssertionRow,\n type RawIdentityAssertionRow,\n} from \"./row-codec\";\nimport { isSeparated } from \"./separation\";\nimport type { DifferentAssertionIndex } from \"./service-components\";\nimport {\n classHasDisjointKinds,\n indexDifferentAssertion,\n kindSetsHaveDisjointKinds,\n mergeDifferentAssertionRoots,\n requireLiveEndpoints,\n selfAssertionError,\n UnionFind,\n} from \"./service-components\";\nimport {\n assertPair,\n buildAssertionRow,\n createIdentityWindowValidator,\n currentAssertionForPair,\n currentClassKey,\n insertAssertionRows,\n replaceAffectedClosure,\n replaceSeparationForReferences,\n} from \"./service-mutation\";\nimport type { Backend, IdentityTouch } from \"./service-read\";\nimport {\n assertionResult,\n clampValidTo,\n containsRef,\n isCurrentClosureCoordinate,\n loadAssertionsTouching,\n loadCurrentStructuralClasses,\n loadCurrentVisibleMembers,\n loadHistoricalClasses,\n loadSpanningDifferentAssertion,\n lockIdentityGraph,\n normalizePair,\n publicAssertion,\n publicNodeRef,\n refKey,\n registeredPlainRef,\n visibleMembersAtCoordinate,\n} from \"./service-read\";\nimport {\n type IdentityServiceContext,\n type IdentityTransferAssertion,\n} from \"./service-types\";\nimport {\n executeIdentityStatement,\n identityChunkSize,\n MAX_REFERENCE_CHUNK_SIZE,\n type PlainNodeRef,\n} from \"./sql-target\";\nimport { type IdentityAssertionStorageRow } from \"./storage-types\";\nimport {\n type IdentityAssertionResult,\n type IdentityFacade,\n type IdentityNodeRefInput,\n type IdentityReadFacade,\n type IdentityRelation,\n type IdentityValidityWindow,\n} from \"./types\";\nimport {\n hasExplicitIdentityValidityWindow,\n resolveIdentityValidityWindow,\n} from \"./validity-window\";\n\ntype WindowedIdentityPair<G extends GraphDef> = Readonly<{\n a: IdentityNodeRefInput<G>;\n b: IdentityNodeRefInput<G>;\n}> &\n IdentityValidityWindow;\n\nfunction assertionSemanticKey(\n relation: IdentityRelation,\n a: PlainNodeRef,\n b: PlainNodeRef,\n): string {\n return identityAssertionSemanticKey(relation, a, b);\n}\n\nasync function bulkAssertPairs<G extends GraphDef>(\n ctx: IdentityServiceContext<G>,\n target: Backend,\n relation: IdentityRelation,\n pairs: readonly Readonly<{\n a: IdentityNodeRefInput<G>;\n b: IdentityNodeRefInput<G>;\n }>[],\n touch: IdentityTouch,\n): Promise<readonly IdentityAssertionResult<G>[]> {\n if (pairs.length === 0) return [];\n const normalizedPairs = pairs.map((pair) => {\n const first = registeredPlainRef(ctx, pair.a);\n const second = registeredPlainRef(ctx, pair.b);\n if (refKey(first) === refKey(second)) throw selfAssertionError(relation);\n return normalizePair(first, second);\n });\n const endpoints = normalizedPairs.flatMap(([a, b]) => [a, b]);\n await requireLiveEndpoints(target, ctx.schema, ctx.graphId, endpoints);\n\n const classes = await loadCurrentStructuralClasses(\n target,\n ctx.schema,\n ctx.graphId,\n endpoints,\n );\n const structuralByKey = new Map<string, PlainNodeRef>();\n for (const members of classes.values()) {\n for (const member of members) structuralByKey.set(refKey(member), member);\n }\n const structuralNodes = [...structuralByKey.values()];\n const persistedAssertions = await loadAssertionsTouching(\n target,\n ctx.schema,\n ctx.graphId,\n structuralNodes,\n undefined,\n );\n const bySemanticKey = new Map(\n persistedAssertions.map((assertion) => [\n assertionSemanticKey(\n assertion.rel,\n { kind: assertion.a_kind, id: assertion.a_id },\n { kind: assertion.b_kind, id: assertion.b_id },\n ),\n assertion,\n ]),\n );\n\n // Build the union-find ONCE (structural nodes + same-id groups + persisted\n // same-assertions), then union each accepted same pair into it. Per-root kind\n // sets make disjointness independent of class cardinality, and the symmetric\n // different-root index avoids rescanning every persisted assertion per pair.\n const unionFind = new UnionFind();\n const allReferences = new Map<string, PlainNodeRef>();\n const byId = new Map<string, PlainNodeRef[]>();\n for (const ref of structuralNodes) {\n unionFind.add(ref);\n allReferences.set(refKey(ref), ref);\n const group = byId.get(ref.id) ?? [];\n group.push(ref);\n byId.set(ref.id, group);\n }\n if (ctx.sameIdAcrossKinds === \"fold\") {\n for (const group of byId.values()) {\n const first = group[0];\n if (first === undefined) continue;\n for (const member of group.slice(1)) unionFind.union(first, member);\n }\n }\n for (const assertion of persistedAssertions) {\n const endpointA = { kind: assertion.a_kind, id: assertion.a_id };\n const endpointB = { kind: assertion.b_kind, id: assertion.b_id };\n if (assertion.rel === \"same\") {\n unionFind.union(endpointA, endpointB);\n } else {\n unionFind.add(endpointA);\n unionFind.add(endpointB);\n }\n allReferences.set(refKey(endpointA), endpointA);\n allReferences.set(refKey(endpointB), endpointB);\n }\n const kindsByRoot = new Map<string, Set<string>>();\n for (const ref of allReferences.values()) {\n const root = unionFind.root(ref);\n const kinds = kindsByRoot.get(root) ?? new Set<string>();\n kinds.add(ref.kind);\n kindsByRoot.set(root, kinds);\n }\n const differentByRoot: DifferentAssertionIndex = new Map();\n for (const assertion of persistedAssertions) {\n if (assertion.rel !== \"different\") continue;\n const rootA = unionFind.root({\n kind: assertion.a_kind,\n id: assertion.a_id,\n });\n const rootB = unionFind.root({\n kind: assertion.b_kind,\n id: assertion.b_id,\n });\n indexDifferentAssertion(differentByRoot, rootA, rootB, assertion);\n }\n\n const createdRows: IdentityAssertionStorageRow[] = [];\n const results: IdentityAssertionResult<G>[] = [];\n const closureReferences: PlainNodeRef[] = [];\n const timestamp = nowIso();\n const operation: IdentityContradictionErrorDetails[\"operation\"] =\n relation === \"same\" ? \"assertSame\" : \"assertDifferent\";\n\n for (const [a, b] of normalizedPairs) {\n const semanticKey = assertionSemanticKey(relation, a, b);\n const existing = bySemanticKey.get(semanticKey);\n if (existing !== undefined) {\n results.push(assertionResult(publicAssertion(existing), \"existing\"));\n continue;\n }\n const rootA = unionFind.root(a);\n const rootB = unionFind.root(b);\n if (relation === \"different\") {\n if (rootA === rootB) {\n throw new IdentityContradictionError({\n operation,\n a,\n b,\n reason: \"same-class\",\n });\n }\n } else {\n const spanning = differentByRoot.get(rootA)?.get(rootB);\n if (spanning !== undefined) {\n throw new IdentityContradictionError({\n operation,\n a,\n b,\n reason: \"different-assertion\",\n conflictingAssertionId: spanning.id,\n });\n }\n const disjointKinds = kindSetsHaveDisjointKinds(\n ctx.registry,\n kindsByRoot.get(rootA) ?? new Set([a.kind]),\n kindsByRoot.get(rootB) ?? new Set([b.kind]),\n );\n if (disjointKinds !== undefined) {\n throw new IdentityContradictionError({\n operation,\n a,\n b,\n reason: \"disjoint-kinds\",\n conflictingKinds: disjointKinds,\n });\n }\n }\n const row = buildAssertionRow(ctx.graphId, relation, a, b, timestamp);\n createdRows.push(row);\n bySemanticKey.set(semanticKey, row);\n results.push(assertionResult(publicAssertion(row), \"created\"));\n if (relation === \"same\") {\n closureReferences.push(a, b);\n if (rootA !== rootB) {\n unionFind.union(a, b);\n const survivingRoot = unionFind.root(a);\n const retiredRoot = survivingRoot === rootA ? rootB : rootA;\n const survivingKinds =\n kindsByRoot.get(survivingRoot) ?? new Set<string>();\n const retiredKinds = kindsByRoot.get(retiredRoot);\n if (retiredKinds !== undefined) {\n for (const kind of retiredKinds) survivingKinds.add(kind);\n }\n kindsByRoot.delete(retiredRoot);\n kindsByRoot.set(survivingRoot, survivingKinds);\n mergeDifferentAssertionRoots(\n differentByRoot,\n survivingRoot,\n retiredRoot,\n );\n }\n }\n }\n\n await insertAssertionRows(target, ctx.schema, createdRows);\n for (const row of createdRows) touch(ctx.graphId, row.id, row);\n if (closureReferences.length > 0) {\n await replaceAffectedClosure(\n target,\n ctx.schema,\n ctx.graphId,\n closureReferences,\n ctx.sameIdAcrossKinds,\n );\n } else {\n await replaceSeparationForReferences(\n target,\n ctx.schema,\n ctx.graphId,\n createdRows.flatMap((row) => [\n { kind: row.a_kind, id: row.a_id },\n { kind: row.b_kind, id: row.b_id },\n ]),\n );\n }\n return results;\n}\n\nasync function bulkAssertWindowedPairs<G extends GraphDef>(\n ctx: IdentityServiceContext<G>,\n target: Backend,\n relation: IdentityRelation,\n pairs: readonly WindowedIdentityPair<G>[],\n touch: IdentityTouch,\n operationInstant: string,\n): Promise<readonly IdentityAssertionResult<G>[]> {\n const windowRequests = pairs.map((pair) => {\n const first = registeredPlainRef(ctx, pair.a);\n const second = registeredPlainRef(ctx, pair.b);\n return {\n references: normalizePair(first, second),\n window: resolveIdentityValidityWindow(pair, operationInstant),\n };\n });\n const windowValidator = await createIdentityWindowValidator(\n ctx,\n target,\n windowRequests,\n operationInstant,\n );\n const results: IdentityAssertionResult<G>[] = [];\n for (const pair of pairs) {\n const window = hasExplicitIdentityValidityWindow(pair) ? pair : undefined;\n results.push(\n await assertPair(\n ctx,\n target,\n relation,\n pair.a,\n pair.b,\n touch,\n window,\n operationInstant,\n windowValidator,\n ),\n );\n }\n return results;\n}\n\nasync function findCurrentAssertionById(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n id: string,\n): Promise<IdentityAssertionStorageRow | undefined> {\n const rows = await target.execute<RawIdentityAssertionRow>(\n asCompiledRowsSql(sql`\n SELECT ${IDENTITY_ASSERTION_COLUMNS}\n FROM ${schema.identityAssertionsTable}\n WHERE graph_id = ${graphId}\n AND id = ${id}\n AND valid_to IS NULL\n AND deleted_at IS NULL\n LIMIT 1\n `),\n );\n return rows[0] === undefined ?\n undefined\n : normalizeIdentityAssertionRow(rows[0]);\n}\n\n/**\n * Ends the currently-open assertion with the given id, returning the ended\n * pre-image (so callers reuse its endpoints for closure repair instead of\n * re-reading the same row) or `undefined` when no open row matched.\n */\nasync function retractById(\n ctx: IdentityServiceContext<GraphDef>,\n target: Backend,\n id: string,\n touch: IdentityTouch,\n): Promise<IdentityAssertionStorageRow | undefined> {\n const existing = await findCurrentAssertionById(\n target,\n ctx.schema,\n ctx.graphId,\n id,\n );\n if (existing === undefined) return undefined;\n const now = nowIso();\n const validTo = clampValidTo(now, existing.valid_from);\n const ended = { ...existing, valid_to: validTo, updated_at: now };\n await executeIdentityStatement(\n target,\n sql`\n UPDATE ${ctx.schema.identityAssertionsTable}\n SET valid_to = ${validTo}, updated_at = ${now}\n WHERE graph_id = ${ctx.graphId}\n AND id = ${id}\n AND valid_to IS NULL\n `,\n );\n touch(ctx.graphId, id, ended);\n return ended;\n}\n\nasync function retractCurrentAssertions(\n ctx: IdentityServiceContext<GraphDef>,\n target: Backend,\n ids: readonly string[],\n touch: IdentityTouch,\n resolveValidTo: (\n row: IdentityAssertionStorageRow,\n operationInstant: string,\n ) => string,\n): Promise<readonly IdentityAssertionStorageRow[]> {\n const uniqueIds = [...new Set(ids)];\n if (uniqueIds.length === 0) return [];\n const current: IdentityAssertionStorageRow[] = [];\n const readChunkSize = identityChunkSize(target, {\n fixedParameters: 1,\n maxItems: MAX_REFERENCE_CHUNK_SIZE,\n parametersPerItem: 1,\n });\n for (const idChunk of chunk(uniqueIds, readChunkSize)) {\n const placeholders = sql.join(\n idChunk.map((id) => sql`${id}`),\n sql`, `,\n );\n const rows = await target.execute<RawIdentityAssertionRow>(\n asCompiledRowsSql(sql`\n SELECT ${IDENTITY_ASSERTION_COLUMNS}\n FROM ${ctx.schema.identityAssertionsTable}\n WHERE graph_id = ${ctx.graphId}\n AND id IN (${placeholders})\n AND valid_to IS NULL\n AND deleted_at IS NULL\n `),\n );\n current.push(...rows.map((row) => normalizeIdentityAssertionRow(row)));\n }\n if (current.length === 0) return [];\n const operationInstant = nowIso();\n // A single UPDATE cannot clamp per-row against each row's own valid_from, so\n // group ids by the valid_to they need. Ordinary API retractions share the\n // operation clock; merge retractions preserve each reviewed plan boundary.\n const byValidTo = new Map<string, string[]>();\n const endedById = new Map<string, string>();\n for (const row of current) {\n const validTo = resolveValidTo(row, operationInstant);\n endedById.set(row.id, validTo);\n const group = byValidTo.get(validTo) ?? [];\n group.push(row.id);\n byValidTo.set(validTo, group);\n }\n const updateChunkSize = identityChunkSize(target, {\n fixedParameters: 3,\n maxItems: MAX_REFERENCE_CHUNK_SIZE,\n parametersPerItem: 1,\n });\n for (const [validTo, ids] of byValidTo) {\n for (const idChunk of chunk(ids, updateChunkSize)) {\n const placeholders = sql.join(\n idChunk.map((id) => sql`${id}`),\n sql`, `,\n );\n await executeIdentityStatement(\n target,\n sql`\n UPDATE ${ctx.schema.identityAssertionsTable}\n SET valid_to = ${validTo}, updated_at = ${operationInstant}\n WHERE graph_id = ${ctx.graphId}\n AND id IN (${placeholders})\n AND valid_to IS NULL\n `,\n );\n }\n }\n const currentById = new Map(current.map((row) => [row.id, row]));\n const ended = uniqueIds.flatMap((id) => {\n const row = currentById.get(id);\n if (row === undefined) return [];\n return [\n {\n ...row,\n valid_to: requireDefined(endedById.get(row.id)),\n updated_at: operationInstant,\n },\n ];\n });\n for (const row of ended) {\n touch(ctx.graphId, row.id, { ...row });\n }\n return ended;\n}\n\nasync function retractByIds(\n ctx: IdentityServiceContext<GraphDef>,\n target: Backend,\n ids: readonly string[],\n touch: IdentityTouch,\n): Promise<readonly IdentityAssertionStorageRow[]> {\n return retractCurrentAssertions(\n ctx,\n target,\n ids,\n touch,\n (row, operationInstant) => clampValidTo(operationInstant, row.valid_from),\n );\n}\n\n/** Ends merge assertions at the exact valid-time boundaries in the reviewed plan. */\nexport async function retractPlannedAssertions(\n ctx: IdentityServiceContext<GraphDef>,\n target: Backend,\n retractions: readonly IdentityTransferAssertion[],\n touch: IdentityTouch,\n): Promise<readonly IdentityAssertionStorageRow[]> {\n const retractionById = new Map(\n retractions.map((retraction) => [retraction.id, retraction]),\n );\n return retractCurrentAssertions(\n ctx,\n target,\n retractions.map((retraction) => retraction.id),\n touch,\n (row, operationInstant) => {\n const retraction = requireDefined(retractionById.get(row.id));\n if (retraction.validTo === undefined) {\n throw new ConfigurationError(\n `Identity merge retraction ${retraction.id} is missing validTo.`,\n {\n code: \"IDENTITY_MERGE_RETRACTION_REQUIRES_END\",\n assertionId: retraction.id,\n },\n );\n }\n return requireDefined(\n resolveIdentityValidityWindow(\n { validFrom: row.valid_from, validTo: retraction.validTo },\n operationInstant,\n ).validTo,\n );\n },\n );\n}\n\nexport async function runIdentityMutation<G extends GraphDef, T>(\n ctx: IdentityServiceContext<G>,\n fn: (\n target: Backend,\n touch: IdentityTouch,\n markWritten: () => void,\n ) => Promise<T>,\n): Promise<T> {\n // Track whether the mutation actually touched a row: a successful no-op\n // (retracting an unknown id, an idempotent reassert) must not advance the\n // durable revision clock on revision-tracking stores. `markWritten` is for\n // sub-operations that record their capture touches through their OWN\n // recorded binding (the interchange import does) — the wrapped touch never\n // sees those rows, so the sub-operation must mark the write explicitly or\n // the clock stays unmoved and base@V tokens go stale.\n let touched = false;\n return runInWriteTransaction(\n {\n graphId: ctx.graphId,\n schemaVersion: ctx.schemaVersion,\n historyEnabled: ctx.historyEnabled,\n revisionTrackingEnabled: ctx.revisionTrackingEnabled,\n revisionSchema: ctx.schema,\n },\n ctx.backend,\n async (target) => {\n await lockIdentityGraph(target, ctx.graphId);\n return withRecordedIdentityMutationTarget(target, (rawTarget, touch) =>\n fn(\n rawTarget,\n (graphId, id, afterImage) => {\n touched = true;\n touch(graphId, id, afterImage);\n },\n () => {\n touched = true;\n },\n ),\n );\n },\n { didWrite: () => touched },\n );\n}\n\nexport function createIdentityReadFacade<G extends GraphDef>(\n ctx: IdentityServiceContext<G>,\n): IdentityReadFacade<G> {\n return {\n async representativeOf(input) {\n const members = await visibleMembersAtCoordinate(\n ctx,\n registeredPlainRef(ctx, input),\n );\n return members[0] === undefined ? undefined : publicNodeRef(members[0]);\n },\n\n async membersOf(input) {\n const members = await visibleMembersAtCoordinate(\n ctx,\n registeredPlainRef(ctx, input),\n );\n return members.map((member) => publicNodeRef<G>(member));\n },\n\n async nodesOf(input) {\n const members = await visibleMembersAtCoordinate(\n ctx,\n registeredPlainRef(ctx, input),\n );\n const nodes = await ctx.loadNodes(members, ctx.coordinate);\n return nodes.filter((node) => node !== undefined);\n },\n\n async areSame(firstInput, secondInput) {\n const first = registeredPlainRef(ctx, firstInput);\n const second = registeredPlainRef(ctx, secondInput);\n const members = await visibleMembersAtCoordinate(ctx, first);\n return containsRef(members, second);\n },\n\n async areDifferent(firstInput, secondInput) {\n const first = registeredPlainRef(ctx, firstInput);\n const second = registeredPlainRef(ctx, secondInput);\n const { coordinate } = ctx;\n if (coordinate === undefined || isCurrentClosureCoordinate(coordinate)) {\n const [firstVisible, secondVisible] = await Promise.all([\n loadCurrentVisibleMembers(\n ctx.backend,\n ctx.schema,\n ctx.graphId,\n first,\n ),\n loadCurrentVisibleMembers(\n ctx.backend,\n ctx.schema,\n ctx.graphId,\n second,\n ),\n ]);\n if (firstVisible.length === 0 || secondVisible.length === 0)\n return false;\n const classes = await loadCurrentStructuralClasses(\n ctx.backend,\n ctx.schema,\n ctx.graphId,\n [first, second],\n );\n const firstClass = requireDefined(classes.get(refKey(first)));\n const secondClass = requireDefined(classes.get(refKey(second)));\n // A boolean is the whole answer here, and the separation relation holds\n // exactly that boolean for a pair of current classes — no assertion has\n // to be named, so the ledger is not read at all.\n const separated = await isSeparated(\n ctx.backend,\n ctx.schema,\n ctx.graphId,\n currentClassKey(firstClass),\n currentClassKey(secondClass),\n ctx.registry,\n );\n return (\n separated ||\n classHasDisjointKinds(ctx.registry, firstClass, secondClass) !==\n undefined\n );\n }\n const classes = await loadHistoricalClasses(\n ctx.backend,\n ctx.schema,\n ctx.graphId,\n [first, second],\n coordinate,\n ctx.sameIdAcrossKinds,\n );\n const firstClass = requireDefined(classes.get(refKey(first)));\n const secondClass = requireDefined(classes.get(refKey(second)));\n if (firstClass.visible.length === 0 || secondClass.visible.length === 0)\n return false;\n const different = await loadSpanningDifferentAssertion(\n ctx.backend,\n ctx.schema,\n ctx.graphId,\n firstClass.structural,\n secondClass.structural,\n ctx.coordinate,\n );\n return (\n different !== undefined ||\n classHasDisjointKinds(\n ctx.registry,\n firstClass.structural,\n secondClass.structural,\n ) !== undefined\n );\n },\n\n async assertionsOf(input) {\n const ref = registeredPlainRef(ctx, input);\n const members = await visibleMembersAtCoordinate(ctx, ref);\n if (members.length === 0) return [];\n const assertions = await loadAssertionsTouching(\n ctx.backend,\n ctx.schema,\n ctx.graphId,\n [ref],\n ctx.coordinate,\n );\n return assertions\n .filter(\n (assertion) =>\n (assertion.a_kind === ref.kind && assertion.a_id === ref.id) ||\n (assertion.b_kind === ref.kind && assertion.b_id === ref.id),\n )\n .toSorted((left, right) => compareCodePoints(left.id, right.id))\n .map((assertion) => publicAssertion<G>(assertion));\n },\n };\n}\n\n/**\n * Splits ended assertions by which derived relation their repair belongs to: a\n * `same` retraction splits identity classes (closure repair, which carries the\n * separation repair with it), a `different` retraction removes a separation.\n */\nexport function partitionRetractedEndpoints(\n retracted: readonly IdentityAssertionStorageRow[],\n): Readonly<{\n closureReferences: readonly PlainNodeRef[];\n separationReferences: readonly PlainNodeRef[];\n}> {\n const closureReferences: PlainNodeRef[] = [];\n const separationReferences: PlainNodeRef[] = [];\n for (const ended of retracted) {\n const endpoints = [\n { kind: ended.a_kind, id: ended.a_id },\n { kind: ended.b_kind, id: ended.b_id },\n ];\n if (ended.rel === \"same\") {\n closureReferences.push(...endpoints);\n } else {\n separationReferences.push(...endpoints);\n }\n }\n return { closureReferences, separationReferences };\n}\n\nexport function createIdentityFacade<G extends GraphDef>(\n ctx: IdentityServiceContext<G>,\n): IdentityFacade<G> {\n return {\n ...createIdentityReadFacade(ctx),\n\n assertSame(a, b, window) {\n return runIdentityMutation(ctx, (target, touch) => {\n const operationInstant = nowIso();\n return assertPair(\n ctx,\n target,\n \"same\",\n a,\n b,\n touch,\n hasExplicitIdentityValidityWindow(window) ? window : undefined,\n operationInstant,\n );\n });\n },\n\n assertDifferent(a, b, window) {\n return runIdentityMutation(ctx, (target, touch) => {\n const operationInstant = nowIso();\n return assertPair(\n ctx,\n target,\n \"different\",\n a,\n b,\n touch,\n hasExplicitIdentityValidityWindow(window) ? window : undefined,\n operationInstant,\n );\n });\n },\n\n bulkAssertSame(pairs) {\n return runIdentityMutation(ctx, (target, touch) => {\n if (!pairs.some((pair) => hasExplicitIdentityValidityWindow(pair))) {\n return bulkAssertPairs(ctx, target, \"same\", pairs, touch);\n }\n return bulkAssertWindowedPairs(\n ctx,\n target,\n \"same\",\n pairs,\n touch,\n nowIso(),\n );\n });\n },\n\n bulkAssertDifferent(pairs) {\n return runIdentityMutation(ctx, (target, touch) => {\n if (!pairs.some((pair) => hasExplicitIdentityValidityWindow(pair))) {\n return bulkAssertPairs(ctx, target, \"different\", pairs, touch);\n }\n return bulkAssertWindowedPairs(\n ctx,\n target,\n \"different\",\n pairs,\n touch,\n nowIso(),\n );\n });\n },\n\n retractAssertion(id) {\n return runIdentityMutation(ctx, async (target, touch) => {\n const ended = await retractById(ctx, target, id, touch);\n if (ended !== undefined) {\n const endpoints = [\n { kind: ended.a_kind, id: ended.a_id },\n { kind: ended.b_kind, id: ended.b_id },\n ];\n if (ended.rel === \"same\") {\n await replaceAffectedClosure(\n target,\n ctx.schema,\n ctx.graphId,\n endpoints,\n ctx.sameIdAcrossKinds,\n );\n } else {\n await replaceSeparationForReferences(\n target,\n ctx.schema,\n ctx.graphId,\n endpoints,\n );\n }\n }\n return ended === undefined ? undefined : publicAssertion<G>(ended);\n });\n },\n\n retractSameAssertion(firstInput, secondInput) {\n return runIdentityMutation(ctx, async (target, touch) => {\n const [a, b] = normalizePair(\n registeredPlainRef(ctx, firstInput),\n registeredPlainRef(ctx, secondInput),\n );\n const existing = await currentAssertionForPair(\n target,\n ctx.schema,\n ctx.graphId,\n \"same\",\n a,\n b,\n );\n if (existing === undefined) return;\n const ended = await retractById(ctx, target, existing.id, touch);\n await replaceAffectedClosure(\n target,\n ctx.schema,\n ctx.graphId,\n [a, b],\n ctx.sameIdAcrossKinds,\n );\n return ended === undefined ? undefined : publicAssertion<G>(ended);\n });\n },\n\n retractDifferentAssertion(firstInput, secondInput) {\n return runIdentityMutation(ctx, async (target, touch) => {\n const [a, b] = normalizePair(\n registeredPlainRef(ctx, firstInput),\n registeredPlainRef(ctx, secondInput),\n );\n const existing = await currentAssertionForPair(\n target,\n ctx.schema,\n ctx.graphId,\n \"different\",\n a,\n b,\n );\n if (existing === undefined) return;\n const ended = await retractById(ctx, target, existing.id, touch);\n await replaceSeparationForReferences(target, ctx.schema, ctx.graphId, [\n a,\n b,\n ]);\n return ended === undefined ? undefined : publicAssertion<G>(ended);\n });\n },\n\n bulkRetractAssertions(ids) {\n return runIdentityMutation(ctx, async (target, touch) => {\n const retracted = await retractByIds(ctx, target, ids, touch);\n const { closureReferences, separationReferences } =\n partitionRetractedEndpoints(retracted);\n if (closureReferences.length > 0) {\n await replaceAffectedClosure(\n target,\n ctx.schema,\n ctx.graphId,\n closureReferences,\n ctx.sameIdAcrossKinds,\n );\n }\n await replaceSeparationForReferences(\n target,\n ctx.schema,\n ctx.graphId,\n separationReferences,\n );\n return retracted.map((assertion) => publicAssertion<G>(assertion));\n });\n },\n };\n}\n","import { type GraphDef } from \"../core/define-graph\";\nimport {\n ConfigurationError,\n IdentityValidityWindowError,\n NodeNotFoundError,\n ValidationError,\n} from \"../errors\";\nimport { withRecordedIdentityMutationTarget } from \"../store/recorded-capture\";\nimport { nowIso } from \"../utils/date\";\nimport {\n requireLiveEndpoints,\n requireStructuralEndpoints,\n} from \"./service-components\";\nimport {\n partitionRetractedEndpoints,\n retractPlannedAssertions,\n runIdentityMutation,\n} from \"./service-facade\";\nimport {\n assertionForExactWindow,\n createIdentityWindowValidator,\n currentAssertionForPair,\n insertAssertion,\n insertAssertionRows,\n loadAssertionsByIds,\n mergeCurrentClasses,\n replaceAffectedClosure,\n replaceSeparationForReferences,\n requireEndpointsCoverIdentityWindow,\n validateCurrentRelation,\n} from \"./service-mutation\";\nimport type { Backend } from \"./service-read\";\nimport { normalizePair, refKey } from \"./service-read\";\nimport {\n type IdentityImportSummary,\n type IdentityServiceContext,\n type IdentityTransferAssertion,\n} from \"./service-types\";\nimport { type PlainNodeRef } from \"./sql-target\";\nimport { type IdentityAssertionStorageRow } from \"./storage-types\";\nimport {\n type ResolvedIdentityValidityWindow,\n resolveIdentityValidityWindow,\n} from \"./validity-window\";\n\n/**\n * What importing a ledger of assertions reads off the service context: the\n * graph it writes for, the registry it validates kinds against, the SQL schema\n * its statements are built from, and the folding mode.\n *\n * A SLICE, not the whole context, because the target these statements run\n * against is passed separately — and the caller that passes it may hold only a\n * write frame's read projection, which cannot supply the context's backend (the\n * transaction opener). The same idiom `validateCurrentRelation` already uses.\n */\ntype IdentityAssertionImportContext = Pick<\n IdentityServiceContext<GraphDef>,\n \"graphId\" | \"registry\" | \"schema\" | \"sameIdAcrossKinds\"\n>;\n\n/**\n * Every transfer-shape rejection reports the same way: one issue against the\n * `identity.assertions` path, attributed to the offending assertion id.\n */\nfunction transferShapeError(\n assertion: IdentityTransferAssertion,\n message: string,\n issue: Readonly<{ message: string; code: string }>,\n): ValidationError {\n return new ValidationError(message, {\n issues: [\n {\n path: \"identity.assertions\",\n assertionId: assertion.id,\n message: issue.message,\n code: issue.code,\n },\n ],\n });\n}\n\nfunction validateTransferShape(\n ctx: IdentityAssertionImportContext,\n assertion: IdentityTransferAssertion,\n mode: \"state\" | \"archival\",\n operationInstant: string,\n): Readonly<{\n endpoints: readonly [PlainNodeRef, PlainNodeRef];\n window: ResolvedIdentityValidityWindow;\n}> {\n if (\n !ctx.registry.nodeKinds.has(assertion.a.kind) ||\n !ctx.registry.nodeKinds.has(assertion.b.kind)\n ) {\n throw transferShapeError(\n assertion,\n \"Identity import references an unknown node kind.\",\n {\n message: `Unknown identity endpoint kind in assertion ${assertion.id}`,\n code: \"IDENTITY_IMPORT_UNKNOWN_KIND\",\n },\n );\n }\n if (refKey(assertion.a) === refKey(assertion.b)) {\n throw transferShapeError(\n assertion,\n `Identity ${assertion.relation} assertions require two distinct node references.`,\n {\n message: `Assertion ${assertion.id} relates a node to itself`,\n code: \"IDENTITY_SELF_ASSERTION\",\n },\n );\n }\n const normalized = normalizePair(assertion.a, assertion.b);\n if (\n refKey(normalized[0]) !== refKey(assertion.a) ||\n refKey(normalized[1]) !== refKey(assertion.b)\n ) {\n throw transferShapeError(\n assertion,\n \"Identity import pairs must be normalized.\",\n {\n message: `Assertion ${assertion.id} endpoints are not in code-point order`,\n code: \"IDENTITY_IMPORT_PAIR_NOT_NORMALIZED\",\n },\n );\n }\n if (mode === \"state\" && assertion.validTo !== undefined) {\n throw transferShapeError(\n assertion,\n \"State identity import cannot contain ended assertions.\",\n {\n message: `Assertion ${assertion.id} is ended`,\n code: \"IDENTITY_STATE_IMPORT_ENDED_ASSERTION\",\n },\n );\n }\n let window: ResolvedIdentityValidityWindow;\n try {\n window = resolveIdentityValidityWindow(\n {\n validFrom: assertion.validFrom,\n ...(assertion.validTo === undefined ?\n {}\n : { validTo: assertion.validTo }),\n },\n operationInstant,\n );\n } catch (error) {\n if (!(error instanceof IdentityValidityWindowError)) throw error;\n const issue =\n error.details.reason === \"future-valid-from\" ?\n {\n code: \"IDENTITY_IMPORT_FUTURE_VALID_FROM\",\n message: `Assertion ${assertion.id} validFrom is in the future`,\n }\n : error.details.reason === \"future-valid-to\" ?\n {\n code: \"IDENTITY_IMPORT_FUTURE_VALID_TO\",\n message: `Assertion ${assertion.id} validTo is in the future`,\n }\n : {\n code: \"IDENTITY_IMPORT_INVALID_WINDOW\",\n message: `Assertion ${assertion.id} validTo must not precede validFrom`,\n };\n throw transferShapeError(\n assertion,\n \"Identity import contains an unsupported validity window.\",\n issue,\n );\n }\n // A cascade cause is only meaningful on an ENDED row, and only ever names\n // that row's own endpoint — the cascade ends assertions BECAUSE they touch\n // the deleted node. The relation carries the same rule as a CHECK; rejecting\n // it here turns an opaque constraint violation into an attributed one.\n if (assertion.endedBy !== undefined) {\n if (assertion.validTo === undefined) {\n throw transferShapeError(\n assertion,\n \"Identity import cannot name an ending cause on an open assertion.\",\n {\n message: `Assertion ${assertion.id} carries endedBy without validTo`,\n code: \"IDENTITY_IMPORT_ENDED_BY_WITHOUT_END\",\n },\n );\n }\n const endedByKey = refKey(assertion.endedBy);\n if (\n endedByKey !== refKey(assertion.a) &&\n endedByKey !== refKey(assertion.b)\n ) {\n throw transferShapeError(\n assertion,\n \"Identity import ending cause must name one of the assertion's endpoints.\",\n {\n message: `Assertion ${assertion.id} endedBy is not an endpoint of the assertion`,\n code: \"IDENTITY_IMPORT_ENDED_BY_NOT_ENDPOINT\",\n },\n );\n }\n }\n return { endpoints: normalized, window };\n}\n\n/**\n * Attribution tag the import coordinator attaches to an error it rethrows:\n * the id of the assertion it was APPLYING when the failure surfaced. Interchange\n * error reporting reads it so an `IdentityContradictionError` or\n * `NodeNotFoundError` is attributed to the failing assertion, not to whichever\n * earlier assertion happens to touch the same endpoints. A non-enumerable\n * symbol so the original error class, message, and details stay byte-identical\n * for direct callers.\n */\nexport const IDENTITY_IMPORT_FAILED_ASSERTION: unique symbol = Symbol(\n \"typegraph.identity.failedAssertionId\",\n);\n\n/** Committed import work recorded on an attributed import failure. */\nexport const IDENTITY_IMPORT_PROGRESS: unique symbol = Symbol(\n \"typegraph.identity.importProgress\",\n);\n\nfunction rethrowTaggedWithAssertion(\n error: unknown,\n assertionId: string,\n progress: IdentityImportSummary,\n): never {\n if (typeof error === \"object\" && error !== null) {\n Object.defineProperty(error, IDENTITY_IMPORT_FAILED_ASSERTION, {\n value: assertionId,\n enumerable: false,\n configurable: true,\n });\n Object.defineProperty(error, IDENTITY_IMPORT_PROGRESS, {\n value: progress,\n enumerable: false,\n configurable: true,\n });\n }\n throw error;\n}\n\n/**\n * Applies interchange identity rows inside the caller-owned write transaction.\n * The caller owns import conflict policy and acquires the graph identity lock;\n * this coordinator owns integrity, persistence, capture, and closure repair.\n */\nexport async function importIdentityAssertionsIntoTarget(\n ctx: IdentityAssertionImportContext,\n target: Backend,\n assertions: readonly IdentityTransferAssertion[],\n mode: \"state\" | \"archival\",\n ignoredAssertionIds: ReadonlySet<string> = new Set(),\n): Promise<IdentityImportSummary> {\n let created = 0;\n let skipped = 0;\n await withRecordedIdentityMutationTarget(target, async (rawTarget, touch) => {\n const operationInstant = nowIso();\n // Pre-pass: validate every shape in input order and normalize endpoints,\n // then batch the two reads the loop would otherwise issue per item — the\n // existing-row-by-id lookup and the current-endpoint liveness check.\n const normalized = assertions.map((assertion) => ({\n assertion,\n ...validateTransferShape(ctx, assertion, mode, operationInstant),\n }));\n const existingById = await loadAssertionsByIds(\n rawTarget,\n ctx.schema,\n ctx.graphId,\n assertions.map((assertion) => assertion.id),\n );\n const currentEndpoints: PlainNodeRef[] = [];\n const endedEndpoints: PlainNodeRef[] = [];\n for (const { assertion, endpoints } of normalized) {\n const [a, b] = endpoints;\n if (assertion.validTo === undefined) {\n currentEndpoints.push(a, b);\n } else {\n endedEndpoints.push(a, b);\n }\n }\n const attributeMissingEndpoint = (\n error: unknown,\n ended: boolean,\n ): never => {\n // The batch checks lose per-assertion context; the first assertion of\n // the checked kind touching the missing ref is the failing candidate.\n if (error instanceof NodeNotFoundError) {\n const missing = { kind: error.details.kind, id: error.details.id };\n const failing = normalized.find(\n ({ assertion, endpoints }) =>\n (assertion.validTo !== undefined) === ended &&\n endpoints.some(\n (endpoint) =>\n endpoint.kind === missing.kind && endpoint.id === missing.id,\n ),\n );\n if (failing !== undefined) {\n rethrowTaggedWithAssertion(error, failing.assertion.id, {\n created,\n skipped,\n });\n }\n }\n throw error;\n };\n try {\n await requireLiveEndpoints(\n rawTarget,\n ctx.schema,\n ctx.graphId,\n currentEndpoints,\n );\n } catch (error) {\n attributeMissingEndpoint(error, false);\n }\n try {\n await requireStructuralEndpoints(\n rawTarget,\n ctx.schema,\n ctx.graphId,\n endedEndpoints,\n );\n } catch (error) {\n attributeMissingEndpoint(error, true);\n }\n const windowValidator = await createIdentityWindowValidator(\n ctx,\n rawTarget,\n normalized.map(({ endpoints, window }) => ({\n references: endpoints,\n window,\n })),\n operationInstant,\n ignoredAssertionIds,\n );\n\n for (const { assertion, endpoints, window } of normalized) {\n const [a, b] = endpoints;\n try {\n const sameId = existingById.get(assertion.id);\n if (sameId !== undefined) {\n const exact =\n sameId.rel === assertion.relation &&\n sameId.a_kind === a.kind &&\n sameId.a_id === a.id &&\n sameId.b_kind === b.kind &&\n sameId.b_id === b.id &&\n sameId.valid_from === assertion.validFrom &&\n sameId.valid_to === assertion.validTo &&\n sameId.ended_by_kind === assertion.endedBy?.kind &&\n sameId.ended_by_id === assertion.endedBy?.id;\n if (exact) {\n skipped += 1;\n continue;\n }\n throw new ConfigurationError(\n `Identity assertion id ${assertion.id} already identifies different truth.`,\n {\n code: \"IDENTITY_IMPORT_ID_CONFLICT\",\n graphId: ctx.graphId,\n assertionId: assertion.id,\n },\n );\n }\n\n const exactWindow = await assertionForExactWindow(\n rawTarget,\n ctx.schema,\n ctx.graphId,\n assertion.relation,\n a,\n b,\n window,\n );\n if (exactWindow !== undefined) {\n skipped += 1;\n continue;\n }\n if (window.effective === \"current\") {\n const current = await currentAssertionForPair(\n rawTarget,\n ctx.schema,\n ctx.graphId,\n assertion.relation,\n a,\n b,\n );\n if (current !== undefined) {\n skipped += 1;\n continue;\n }\n await requireEndpointsCoverIdentityWindow(\n rawTarget,\n ctx.graphId,\n [a, b],\n window,\n );\n windowValidator.validate(assertion.relation, \"import\", a, b, window);\n // The temporal check owns historical correctness. The current check\n // also exercises the materialized separation backstop/readiness guard\n // before this row changes current derived state.\n await validateCurrentRelation(\n ctx,\n rawTarget,\n assertion.relation,\n \"import\",\n a,\n b,\n );\n const inserted = await insertAssertion(\n rawTarget,\n ctx.schema,\n ctx.graphId,\n assertion.relation,\n a,\n b,\n operationInstant,\n touch,\n { id: assertion.id, validFrom: window.validFrom },\n );\n existingById.set(inserted.id, inserted);\n windowValidator.record(inserted);\n created += 1;\n if (assertion.relation === \"same\") {\n await mergeCurrentClasses(rawTarget, ctx.schema, ctx.graphId, a, b);\n } else {\n await replaceSeparationForReferences(\n rawTarget,\n ctx.schema,\n ctx.graphId,\n [a, b],\n );\n }\n continue;\n }\n\n await requireEndpointsCoverIdentityWindow(\n rawTarget,\n ctx.graphId,\n [a, b],\n window,\n );\n windowValidator.validate(assertion.relation, \"import\", a, b, window);\n\n const timestamp = window.validFrom;\n const row: IdentityAssertionStorageRow = {\n graph_id: ctx.graphId,\n id: assertion.id,\n rel: assertion.relation,\n a_kind: a.kind,\n a_id: a.id,\n b_kind: b.kind,\n b_id: b.id,\n valid_from: window.validFrom,\n valid_to: window.validTo,\n created_at: timestamp,\n updated_at: window.validTo ?? window.validFrom,\n deleted_at: undefined,\n ended_by_kind: assertion.endedBy?.kind,\n ended_by_id: assertion.endedBy?.id,\n };\n await insertAssertionRows(rawTarget, ctx.schema, [row]);\n touch(ctx.graphId, row.id, row);\n existingById.set(row.id, row);\n windowValidator.record(row);\n created += 1;\n } catch (error) {\n rethrowTaggedWithAssertion(error, assertion.id, { created, skipped });\n }\n }\n });\n return { created, skipped };\n}\n\nexport async function applyIdentityChangesForContext<G extends GraphDef>(\n ctx: IdentityServiceContext<G>,\n retractions: readonly IdentityTransferAssertion[],\n assertions: readonly IdentityTransferAssertion[],\n): Promise<Readonly<{ created: number; retracted: number }>> {\n if (retractions.length === 0 && assertions.length === 0) {\n return { created: 0, retracted: 0 };\n }\n return runIdentityMutation(ctx, async (target, touch, markWritten) => {\n const retracted = await retractPlannedAssertions(\n ctx,\n target,\n retractions,\n touch,\n );\n const { closureReferences, separationReferences } =\n partitionRetractedEndpoints(retracted);\n // Repair the closure from the retractions BEFORE importing: a batch that\n // retracts same(a,b) and then asserts different(a,b) must validate the new\n // assertion against a closure that already reflects the split, not the\n // stale merged class the import validation would otherwise reject against.\n if (closureReferences.length > 0) {\n await replaceAffectedClosure(\n target,\n ctx.schema,\n ctx.graphId,\n closureReferences,\n ctx.sameIdAcrossKinds,\n );\n }\n await replaceSeparationForReferences(\n target,\n ctx.schema,\n ctx.graphId,\n separationReferences,\n );\n const summary = await importIdentityAssertionsIntoTarget(\n ctx,\n target,\n assertions,\n \"archival\",\n new Set(retracted.map((assertion) => assertion.id)),\n );\n // The import records capture touches through its OWN recorded binding, so\n // the mutation's wrapped touch never fires for created rows — an\n // identity-only merge would otherwise leave the durable revision clock\n // unmoved and every base@V token stale.\n if (summary.created > 0) markWritten();\n // ACTUAL ledger effects, not planned intents: rows the import created\n // (idempotent exact/pair matches excluded) and rows the retraction ended\n // (already-ended or unknown ids excluded).\n return { created: summary.created, retracted: retracted.length };\n });\n}\n","import { type GraphBackend, type TransactionBackend } from \"../backend/types\";\nimport { type GraphDef } from \"../core/define-graph\";\nimport {\n ConfigurationError,\n IdentityContradictionError,\n IdentityEndpointValidityError,\n} from \"../errors\";\nimport { type SqlSchema } from \"../query/compiler/schema\";\nimport { sql } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../query/sql-intent\";\nimport { withRecordedIdentityMutationTarget } from \"../store/recorded-capture\";\nimport { chunk } from \"../utils/array\";\nimport { nowIso } from \"../utils/date\";\nimport { requireDefined } from \"../utils/presence\";\nimport { IDENTITY_ASSERTION_COLUMNS } from \"./historical-sql\";\nimport {\n normalizeIdentityAssertionRow,\n optionalIdentityTimestamp,\n type RawIdentityAssertionRow,\n} from \"./row-codec\";\nimport {\n assertSeparationMatchesProjection,\n buildSeparationProjection,\n readSeparationForGraph,\n} from \"./separation\";\nimport {\n assertClosureMatchesComponents,\n classHasDisjointKinds,\n closureMismatchError,\n identityActiveKinds,\n loadLiveReferences,\n loadSnapshot,\n validateSnapshotIntegrity,\n} from \"./service-components\";\nimport { runIdentityMutation } from \"./service-facade\";\nimport {\n replaceAffectedClosure,\n replaceClosure,\n snapshotClassKey,\n validateCurrentRelation,\n} from \"./service-mutation\";\nimport type { Backend, RawClosureClassRow } from \"./service-read\";\nimport {\n clampValidTo,\n loadAssertionsTouching,\n loadCurrentStructuralClasses,\n lockIdentityGraph,\n refKey,\n} from \"./service-read\";\nimport { type IdentityServiceContext } from \"./service-types\";\nimport {\n executeIdentityStatement,\n identityChunkSize,\n MAX_REFERENCE_CHUNK_SIZE,\n type PlainNodeRef,\n} from \"./sql-target\";\nimport { type IdentityAssertionStorageRow } from \"./storage-types\";\n\n/**\n * The context slice a closure rebuild reads. Narrower than the full\n * {@link IdentityServiceContext} so a schema-transition preflight — which runs\n * below the Store layer and has no node loader or write-transaction settings to\n * offer — can drive the same rebuild the Store drives.\n */\nexport type IdentityRebuildContext<G extends GraphDef> = Pick<\n IdentityServiceContext<G>,\n \"backend\" | \"graphId\" | \"registry\" | \"schema\" | \"sameIdAcrossKinds\"\n>;\n\nfunction requireAtomicIdentityBackend(backend: Backend, graphId: string): void {\n if (!backend.capabilities.transactions) {\n throw new ConfigurationError(\n \"Operational Identity requires atomic transaction support.\",\n { code: \"IDENTITY_REQUIRES_ATOMIC_BACKEND\", graphId },\n );\n }\n}\n\n/**\n * Runs `fn` against a transactional target. A top-level `GraphBackend` opens\n * one; a `TransactionBackend` is already inside the caller's transaction and\n * has no `transaction` method to nest with, so it runs as-is.\n */\nasync function runOnTransactionIfSupported(\n backend: GraphBackend | TransactionBackend,\n fn: (target: Backend) => Promise<void>,\n): Promise<void> {\n if (\"transaction\" in backend) {\n await backend.transaction(async (target) => fn(target));\n return;\n }\n await fn(backend);\n}\n\nexport async function rebuildIdentityClosureForContext<G extends GraphDef>(\n ctx: IdentityRebuildContext<G>,\n): Promise<void> {\n requireAtomicIdentityBackend(ctx.backend, ctx.graphId);\n\n async function rebuildAtTarget(target: Backend): Promise<void> {\n await lockIdentityGraph(target, ctx.graphId);\n await withRecordedIdentityMutationTarget(target, async (rawTarget) => {\n const activeKinds = identityActiveKinds(ctx.registry);\n const snapshot = await loadSnapshot(\n rawTarget,\n ctx.schema,\n ctx.graphId,\n undefined,\n activeKinds,\n ctx.sameIdAcrossKinds,\n );\n validateSnapshotIntegrity(snapshot, ctx.registry, ctx.graphId);\n await replaceClosure(\n rawTarget,\n ctx.schema,\n ctx.graphId,\n activeKinds,\n ctx.sameIdAcrossKinds,\n );\n });\n }\n\n await runOnTransactionIfSupported(ctx.backend, async (target) =>\n rebuildAtTarget(target),\n );\n}\n\nexport async function validateIdentityForContext<G extends GraphDef>(\n ctx: IdentityServiceContext<G>,\n): Promise<void> {\n requireAtomicIdentityBackend(ctx.backend, ctx.graphId);\n\n async function validateAtTarget(target: Backend): Promise<void> {\n await lockIdentityGraph(target, ctx.graphId);\n const activeKinds = identityActiveKinds(ctx.registry);\n const snapshot = await loadSnapshot(\n target,\n ctx.schema,\n ctx.graphId,\n undefined,\n activeKinds,\n ctx.sameIdAcrossKinds,\n );\n validateSnapshotIntegrity(snapshot, ctx.registry, ctx.graphId);\n await assertClosureMatchesComponents(\n target,\n ctx.schema,\n ctx.graphId,\n snapshot.components,\n );\n assertSeparationMatchesProjection(\n ctx.graphId,\n await readSeparationForGraph(target, ctx.schema, ctx.graphId),\n buildSeparationProjection(snapshot.assertions, (ref) =>\n snapshotClassKey(snapshot, ref),\n ),\n );\n }\n\n await runOnTransactionIfSupported(ctx.backend, async (target) =>\n validateAtTarget(target),\n );\n}\n\n/**\n * The context slice the affected-class assertion reads. Narrower than the full\n * {@link IdentityServiceContext} because the assertion runs inside a\n * caller-owned write transaction and therefore takes its target explicitly\n * instead of opening one from `backend`.\n */\nexport type IdentityConsistencyContext<G extends GraphDef> = Pick<\n IdentityServiceContext<G>,\n \"graphId\" | \"registry\" | \"schema\" | \"sameIdAcrossKinds\"\n>;\n\n/** The affected identity classes, indexed for the assertion's three scans. */\ntype AffectedIdentityClasses = Readonly<{\n /** Each distinct affected class, keyed by its code-point-least member. */\n byClassKey: ReadonlyMap<string, readonly PlainNodeRef[]>;\n /** The class key of every affected member, for endpoint lookups. */\n classKeyByMember: ReadonlyMap<string, string>;\n /** Every member of every affected class, deduplicated. */\n members: readonly PlainNodeRef[];\n}>;\n\n/**\n * The identity classes the seeds belong to, read through the SAME materialized\n * closure every current identity read resolves through\n * ({@link loadCurrentStructuralClasses}), so the assertion judges the state\n * readers will actually see rather than a private reconstruction of it.\n */\nasync function loadAffectedIdentityClasses<G extends GraphDef>(\n ctx: IdentityConsistencyContext<G>,\n target: Backend,\n seeds: readonly PlainNodeRef[],\n): Promise<AffectedIdentityClasses> {\n const classes = await loadCurrentStructuralClasses(\n target,\n ctx.schema,\n ctx.graphId,\n seeds,\n );\n const byClassKey = new Map<string, readonly PlainNodeRef[]>();\n const classKeyByMember = new Map<string, string>();\n const members = new Map<string, PlainNodeRef>();\n for (const classMembers of classes.values()) {\n // Members come back in {@link compareReferences} order, so the first is\n // the class's code-point-least member — the same canonical label\n // {@link insertClosureComponents} writes, which makes two seeds of one\n // class collapse onto one entry here.\n const classKey = refKey(requireDefined(classMembers[0]));\n byClassKey.set(classKey, classMembers);\n for (const member of classMembers) {\n const memberKey = refKey(member);\n classKeyByMember.set(memberKey, classKey);\n members.set(memberKey, member);\n }\n }\n return { byClassKey, classKeyByMember, members: [...members.values()] };\n}\n\n/**\n * What an affected-class scan found: a genuine identity contradiction, or\n * evidence that the materialized closure lags the ledger it is derived from.\n * The two are indistinguishable to a caller reading a stale closure, which is\n * why {@link assertAffectedIdentityClassesConsistent} rebuilds before it\n * believes either.\n */\ntype AffectedClassInconsistency =\n | Readonly<{ kind: \"contradiction\"; error: IdentityContradictionError }>\n | Readonly<{\n kind: \"stale-closure\";\n detail: Readonly<Record<string, unknown>>;\n }>;\n\nfunction firstMemberOfKind(\n members: readonly PlainNodeRef[],\n kind: string,\n): PlainNodeRef {\n return requireDefined(\n members.find((member) => member.kind === kind),\n `Identity class carries no ${kind} member`,\n );\n}\n\n/**\n * The first inconsistency in the affected classes, or `undefined` when they\n * are consistent. Three scans, all scoped to the affected members:\n *\n * - a class whose member kinds the ontology declares disjoint;\n * - a CURRENT `different` assertion whose endpoints share one class;\n * - closure lag, as a current `same` assertion (or, under `\"fold\"`, a live\n * same-id row) whose endpoints the closure has NOT merged — the one shape\n * that could hide a contradiction from the two scans above, because both\n * resolve classes through that same closure.\n */\nasync function findAffectedClassInconsistency<G extends GraphDef>(\n ctx: IdentityConsistencyContext<G>,\n target: Backend,\n seeds: readonly PlainNodeRef[],\n): Promise<AffectedClassInconsistency | undefined> {\n const classes = await loadAffectedIdentityClasses(ctx, target, seeds);\n for (const members of classes.byClassKey.values()) {\n // Self-pairs are safe: `areDisjoint(kind, kind)` is false by construction.\n const conflictingKinds = classHasDisjointKinds(\n ctx.registry,\n members,\n members,\n );\n if (conflictingKinds === undefined) continue;\n const [leftKind, rightKind] = conflictingKinds;\n return {\n kind: \"contradiction\",\n error: new IdentityContradictionError({\n operation: \"merge\",\n a: firstMemberOfKind(members, leftKind),\n b: firstMemberOfKind(members, rightKind),\n reason: \"disjoint-kinds\",\n conflictingKinds,\n }),\n };\n }\n\n const assertions = await loadAssertionsTouching(\n target,\n ctx.schema,\n ctx.graphId,\n classes.members,\n undefined,\n );\n // Current `same` rows the closure has NOT merged into one class. An endpoint\n // outside every affected class is only evidence of lag when its node is\n // live — a class legitimately excludes a deleted member — so the liveness of\n // those endpoints is read once, after the scan, instead of per row.\n const unmerged: Readonly<{\n assertionId: string;\n a: PlainNodeRef;\n b: PlainNodeRef;\n outside: PlainNodeRef;\n }>[] = [];\n for (const assertion of assertions) {\n const a = { kind: assertion.a_kind, id: assertion.a_id };\n const b = { kind: assertion.b_kind, id: assertion.b_id };\n const aClassKey = classes.classKeyByMember.get(refKey(a));\n const bClassKey = classes.classKeyByMember.get(refKey(b));\n if (assertion.rel === \"different\") {\n if (aClassKey === undefined || aClassKey !== bClassKey) continue;\n return {\n kind: \"contradiction\",\n error: new IdentityContradictionError({\n operation: \"merge\",\n a,\n b,\n reason: \"same-class\",\n conflictingAssertionId: assertion.id,\n }),\n };\n }\n if (aClassKey !== undefined && bClassKey !== undefined) {\n if (aClassKey === bClassKey) continue;\n return {\n kind: \"stale-closure\",\n detail: { assertionId: assertion.id, a, b },\n };\n }\n // The row reached this scan by touching an affected member, so exactly one\n // endpoint can be outside the affected classes.\n unmerged.push({\n assertionId: assertion.id,\n a,\n b,\n outside: aClassKey === undefined ? a : b,\n });\n }\n if (unmerged.length > 0) {\n const liveOutside = await loadLiveReferences(\n target,\n ctx.schema,\n ctx.graphId,\n unmerged.map((row) => row.outside),\n );\n const liveKeys = new Set(liveOutside.map((ref) => refKey(ref)));\n const lagging = unmerged.find((row) => liveKeys.has(refKey(row.outside)));\n if (lagging !== undefined) {\n return {\n kind: \"stale-closure\",\n detail: {\n assertionId: lagging.assertionId,\n a: lagging.a,\n b: lagging.b,\n },\n };\n }\n }\n\n if (ctx.sameIdAcrossKinds !== \"fold\") return undefined;\n // The structural half of closure truth: under `\"fold\"` every live row\n // sharing an affected member's id belongs to that member's class. A row the\n // closure never folded reads as `undefined` here, which is the lag this\n // scan exists to catch.\n const liveKindsById = await liveNodeKindsSharingIds(\n ctx,\n target,\n classes.members.map((member) => member.id),\n );\n for (const [id, kinds] of liveKindsById) {\n const classKeys = new Set<string | undefined>();\n for (const kind of kinds) {\n classKeys.add(classes.classKeyByMember.get(refKey({ kind, id })));\n }\n if (classKeys.size > 1) {\n return {\n kind: \"stale-closure\",\n detail: { sharedId: id, kinds: [...kinds] },\n };\n }\n }\n return undefined;\n}\n\n/**\n * Asserts that the identity classes a write TOUCHED are contradiction-free, in\n * the caller's write transaction and against the state the write just left\n * behind. Scoped to the affected classes — the seeds plus everything the\n * closure links them to — so the cost is O(affected classes), not O(graph).\n *\n * This is the applier-owned half of identity correctness: unlike a caller's\n * plan-time simulation, it reads the post-write database, so a plan validated\n * against state that has since moved cannot commit a contradictory ledger. Any\n * refusal propagates out of the caller's transaction, which rolls the whole\n * write back — there is no partial commit.\n *\n * Both failure kinds go through ONE rebuild-and-recheck: the scans resolve\n * classes through the materialized closure, so a lagging closure can invent a\n * contradiction as easily as it can hide one. On any inconsistency the closure\n * is rebuilt from the base relations INSIDE the caller's transaction and the\n * scans re-run against it. A clean second pass means the closure was stale and\n * is now repaired (atomically with the caller's write); a repeated\n * contradiction is real and aborts; a repeated lag means the closure and the\n * ledger disagree in a way a rebuild cannot fix, which is corruption.\n */\nexport async function assertAffectedIdentityClassesConsistent<\n G extends GraphDef,\n>(\n ctx: IdentityConsistencyContext<G>,\n target: Backend,\n seeds: readonly PlainNodeRef[],\n): Promise<void> {\n if (seeds.length === 0) return;\n await lockIdentityGraph(target, ctx.graphId);\n const observed = await findAffectedClassInconsistency(ctx, target, seeds);\n if (observed === undefined) return;\n await withRecordedIdentityMutationTarget(target, async (rawTarget) => {\n await replaceClosure(\n rawTarget,\n ctx.schema,\n ctx.graphId,\n identityActiveKinds(ctx.registry),\n ctx.sameIdAcrossKinds,\n );\n });\n const rebuilt = await findAffectedClassInconsistency(ctx, target, seeds);\n if (rebuilt === undefined) return;\n if (rebuilt.kind === \"contradiction\") throw rebuilt.error;\n throw closureMismatchError(ctx.graphId, rebuilt.detail);\n}\n\n/**\n * Hard-deletes every assertion row (current AND ended) touching any of the\n * given node kinds, touching each removed row for recorded capture. Shared by\n * {@link removeIdentityKindsForContext} (Store.removeKinds) and the schema\n * commit preflight for kind-dropping migrations — the closure rebuild those\n * paths run afterwards silently FILTERS rows with unregistered kinds, so\n * without this cascade a dropped kind's assertions would survive as current\n * orphans: invisible to closure and live-endpoint interchange reads, yet\n * still present to raw ledger reads and merge staging.\n *\n * @internal\n */\nexport async function deleteAssertionsTouchingKinds(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n kinds: readonly string[],\n touch: (graphId: string, id: string) => void,\n): Promise<void> {\n const removedKinds = [...new Set(kinds)];\n if (removedKinds.length === 0) return;\n const matched = new Map<string, IdentityAssertionStorageRow>();\n const kindChunkSize = identityChunkSize(target, {\n fixedParameters: 1,\n maxItems: MAX_REFERENCE_CHUNK_SIZE,\n parametersPerItem: 2,\n });\n for (const kindChunk of chunk(removedKinds, kindChunkSize)) {\n const kindList = sql.join(\n kindChunk.map((kind) => sql`${kind}`),\n sql`, `,\n );\n const rows = await target.execute<RawIdentityAssertionRow>(\n asCompiledRowsSql(sql`\n SELECT ${IDENTITY_ASSERTION_COLUMNS}\n FROM ${schema.identityAssertionsTable}\n WHERE graph_id = ${graphId}\n AND (a_kind IN (${kindList}) OR b_kind IN (${kindList}))\n `),\n );\n for (const rawRow of rows) {\n matched.set(rawRow.id, normalizeIdentityAssertionRow(rawRow));\n }\n }\n const ids = [...matched.keys()];\n if (ids.length > 0) {\n const idChunkSize = identityChunkSize(target, {\n fixedParameters: 1,\n maxItems: MAX_REFERENCE_CHUNK_SIZE,\n parametersPerItem: 1,\n });\n for (const idChunk of chunk(ids, idChunkSize)) {\n const idList = sql.join(\n idChunk.map((id) => sql`${id}`),\n sql`, `,\n );\n await executeIdentityStatement(\n target,\n sql`\n DELETE FROM ${schema.identityAssertionsTable}\n WHERE graph_id = ${graphId} AND id IN (${idList})\n `,\n );\n }\n }\n for (const row of matched.values()) touch(graphId, row.id);\n}\n\n/**\n * Whether the ledger holds any assertion — current or ended — touching one of\n * the given node kinds. Lets a caller decide whether a cascade is needed at all\n * before it commits to a code path that can run one.\n *\n * @internal\n */\nexport async function hasAssertionsTouchingKinds(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n kinds: readonly string[],\n): Promise<boolean> {\n const probedKinds = [...new Set(kinds)];\n if (probedKinds.length === 0) return false;\n const kindChunkSize = identityChunkSize(target, {\n fixedParameters: 1,\n maxItems: MAX_REFERENCE_CHUNK_SIZE,\n parametersPerItem: 2,\n });\n for (const kindChunk of chunk(probedKinds, kindChunkSize)) {\n const kindList = sql.join(\n kindChunk.map((kind) => sql`${kind}`),\n sql`, `,\n );\n const rows = await target.execute<Readonly<{ id: string }>>(\n asCompiledRowsSql(sql`\n SELECT id\n FROM ${schema.identityAssertionsTable}\n WHERE graph_id = ${graphId}\n AND (a_kind IN (${kindList}) OR b_kind IN (${kindList}))\n LIMIT 1\n `),\n );\n if (rows.length > 0) return true;\n }\n return false;\n}\n\n/**\n * Hard-deletes every assertion row touching a node kind that is not registered\n * on the graph, so a first enablement (or a profile re-enablement) never adopts\n * orphans it cannot see. The closure rebuild that follows FILTERS unregistered\n * kinds, which would leave such rows current but invisible — the same stranding\n * {@link deleteAssertionsTouchingKinds} prevents on the drop path, arriving\n * instead from a database that already contained strays.\n *\n * @internal\n */\nexport async function purgeAssertionsWithUnregisteredKinds(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n registeredKinds: ReadonlySet<string>,\n touch: (graphId: string, id: string) => void,\n): Promise<void> {\n const pairs = await target.execute<\n Readonly<{ a_kind: string; b_kind: string }>\n >(\n asCompiledRowsSql(sql`\n SELECT DISTINCT a_kind, b_kind\n FROM ${schema.identityAssertionsTable}\n WHERE graph_id = ${graphId}\n `),\n );\n const unregistered = new Set<string>();\n for (const pair of pairs) {\n if (!registeredKinds.has(pair.a_kind)) unregistered.add(pair.a_kind);\n if (!registeredKinds.has(pair.b_kind)) unregistered.add(pair.b_kind);\n }\n if (unregistered.size === 0) return;\n await deleteAssertionsTouchingKinds(\n target,\n schema,\n graphId,\n [...unregistered],\n touch,\n );\n}\n\n/**\n * Cascades removed node kinds through the assertion ledger.\n *\n * `repairClosure: false` is for a graph whose identity profile is absent while\n * the ledger storage still exists (identity was disabled without dropping the\n * rows). There is no closure contract to restore without a profile, so the\n * cascade runs alone — the ledger must not keep rows for a kind the schema no\n * longer registers, whether or not identity is currently switched on.\n */\nexport async function removeIdentityKindsForContext<G extends GraphDef>(\n ctx: IdentityServiceContext<G>,\n kinds: readonly string[],\n options?: Readonly<{ repairClosure?: boolean }>,\n): Promise<void> {\n if (kinds.length === 0) return;\n const removedKinds = [...new Set(kinds)];\n await runIdentityMutation(ctx, async (target, touch) => {\n await deleteAssertionsTouchingKinds(\n target,\n ctx.schema,\n ctx.graphId,\n removedKinds,\n touch,\n );\n if (options?.repairClosure === false) return;\n await replaceClosure(\n target,\n ctx.schema,\n ctx.graphId,\n identityActiveKinds(ctx.registry),\n ctx.sameIdAcrossKinds,\n );\n });\n}\n\n/**\n * One chunked bare-id SELECT over ALL requested ids, not one per node kind:\n * `typegraph_nodes_id_idx (graph_id, id)` makes the kind-free probe an indexed\n * seek, so the whole cross-kind live peer set comes back in a single round\n * trip. Rows whose kind is outside the registry are dropped — they never\n * participate in identity.\n */\nexport async function liveNodeKindsSharingIds(\n ctx: Pick<\n IdentityServiceContext<GraphDef>,\n \"graphId\" | \"registry\" | \"schema\"\n >,\n target: Backend,\n ids: readonly string[],\n): Promise<ReadonlyMap<string, ReadonlySet<string>>> {\n const uniqueIds = [...new Set(ids)];\n const liveKindsById = new Map<string, Set<string>>();\n if (uniqueIds.length === 0) return liveKindsById;\n const chunkSize = identityChunkSize(target, {\n fixedParameters: 1,\n maxItems: MAX_REFERENCE_CHUNK_SIZE,\n parametersPerItem: 1,\n });\n for (const idChunk of chunk(uniqueIds, chunkSize)) {\n const idList = sql.join(\n idChunk.map((id) => sql`${id}`),\n sql`, `,\n );\n const rows = await target.execute<Readonly<{ kind: string; id: string }>>(\n asCompiledRowsSql(sql`\n SELECT kind, id\n FROM ${ctx.schema.nodesTable}\n WHERE graph_id = ${ctx.graphId}\n AND id IN (${idList})\n AND deleted_at IS NULL\n `),\n );\n for (const row of rows) {\n if (!ctx.registry.nodeKinds.has(row.kind)) continue;\n const kinds = liveKindsById.get(row.id) ?? new Set<string>();\n kinds.add(row.kind);\n liveKindsById.set(row.id, kinds);\n }\n }\n return liveKindsById;\n}\n\nexport async function foldIdentityForCreatedNodes(\n ctx: Pick<\n IdentityServiceContext<GraphDef>,\n \"graphId\" | \"registry\" | \"sameIdAcrossKinds\" | \"schema\"\n >,\n target: Backend,\n references: readonly PlainNodeRef[],\n): Promise<void> {\n if (references.length === 0 || ctx.sameIdAcrossKinds === \"ignore\") return;\n await lockIdentityGraph(target, ctx.graphId);\n await withRecordedIdentityMutationTarget(target, async (rawTarget) => {\n const liveKindsById = await liveNodeKindsSharingIds(\n ctx,\n rawTarget,\n references.map((ref) => ref.id),\n );\n const closureReferences: PlainNodeRef[] = [];\n for (const ref of references) {\n // Registry order, not row-arrival order: which conflicting peer\n // `validateCurrentRelation` reports first must not depend on how the\n // engine happened to return rows. Iterating the registry also drops\n // rows whose kind is outside it — those never participate in identity.\n const liveKinds = liveKindsById.get(ref.id);\n const peers: PlainNodeRef[] = [];\n if (liveKinds !== undefined) {\n for (const kind of ctx.registry.nodeKinds.keys()) {\n if (kind === ref.kind || !liveKinds.has(kind)) continue;\n peers.push({ kind, id: ref.id });\n }\n }\n if (peers.length === 0) continue;\n for (const peer of peers) {\n await validateCurrentRelation(\n ctx,\n rawTarget,\n \"same\",\n \"fold\",\n ref,\n peer,\n );\n }\n closureReferences.push(ref, ...peers);\n }\n await replaceAffectedClosure(\n rawTarget,\n ctx.schema,\n ctx.graphId,\n closureReferences,\n ctx.sameIdAcrossKinds,\n );\n });\n}\n\n/**\n * Reports whether the node carries a materialized identity class row.\n *\n * {@link insertClosureComponents} emits rows only for components with two or\n * more members, and every current-class read resolves through that table\n * ({@link loadCurrentStructuralClasses} anchors on it and coalesces a missing\n * row to the node itself), so no row means the node is a singleton under every\n * source of identity — assertions AND the same-id structural fold, which\n * `foldIdentityForCreatedNodes` materializes at create time.\n */\nasync function hasMaterializedIdentityClass(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n ref: PlainNodeRef,\n): Promise<boolean> {\n const rows = await target.execute<RawClosureClassRow>(\n asCompiledRowsSql(sql`\n SELECT member_kind, member_id\n FROM ${schema.identityClosureTable}\n WHERE graph_id = ${graphId}\n AND member_kind = ${ref.kind}\n AND member_id = ${ref.id}\n LIMIT 1\n `),\n );\n return rows.length > 0;\n}\n\n/**\n * Reads the instant a node was soft-deleted, as stored on its own row.\n *\n * The soft-delete cascade ends the node's open assertions AT THIS INSTANT\n * rather than at a second wall-clock read, so the assertion stops holding at\n * exactly the moment its endpoint stopped existing: a valid-time read at any\n * instant sees the node and its assertions agree. Two `nowIso()` reads inside\n * one transaction can straddle a millisecond boundary, so the instant has to\n * come from the stored value, not from a fresh clock read.\n *\n * Returns `undefined` when the row is gone or still live; callers fall back to\n * their own instant.\n */\nasync function readNodeDeletionInstant(\n target: Backend,\n schema: SqlSchema,\n graphId: string,\n ref: PlainNodeRef,\n): Promise<string | undefined> {\n const rows = await target.execute<Readonly<{ deleted_at: unknown }>>(\n asCompiledRowsSql(sql`\n SELECT deleted_at\n FROM ${schema.nodesTable}\n WHERE graph_id = ${graphId}\n AND kind = ${ref.kind}\n AND id = ${ref.id}\n LIMIT 1\n `),\n );\n const row = rows.at(0);\n return row === undefined ? undefined : (\n optionalIdentityTimestamp(row.deleted_at)\n );\n}\n\n/** Refuses a finite node window that would strand identity assertion history. */\nexport async function requireNodeValidityEndCompatible(\n ctx: Pick<IdentityServiceContext<GraphDef>, \"graphId\" | \"schema\">,\n target: Backend,\n ref: PlainNodeRef,\n validTo: string,\n): Promise<void> {\n const rows = await target.execute<RawIdentityAssertionRow>(\n asCompiledRowsSql(sql`\n SELECT ${IDENTITY_ASSERTION_COLUMNS}\n FROM ${ctx.schema.identityAssertionsTable}\n WHERE graph_id = ${ctx.graphId}\n AND deleted_at IS NULL\n AND (valid_to IS NULL OR valid_to > ${validTo})\n AND (\n (a_kind = ${ref.kind} AND a_id = ${ref.id})\n OR (b_kind = ${ref.kind} AND b_id = ${ref.id})\n )\n ORDER BY id\n LIMIT 1\n `),\n );\n const row = rows.at(0);\n if (row === undefined) return;\n const assertion = normalizeIdentityAssertionRow(row);\n throw new IdentityEndpointValidityError({\n endpoint: ref,\n assertionWindow: {\n validFrom: assertion.valid_from,\n ...(assertion.valid_to === undefined ?\n {}\n : { validTo: assertion.valid_to }),\n },\n endpointWindow: { validTo },\n });\n}\n\nexport async function detachIdentityForNode(\n ctx: Pick<\n IdentityServiceContext<GraphDef>,\n \"graphId\" | \"sameIdAcrossKinds\" | \"schema\"\n >,\n target: Backend,\n ref: PlainNodeRef,\n mode: \"soft\" | \"hard\",\n): Promise<void> {\n await lockIdentityGraph(target, ctx.graphId);\n await withRecordedIdentityMutationTarget(target, async (rawTarget, touch) => {\n const touchesNode = sql`\n (\n (a_kind = ${ref.kind} AND a_id = ${ref.id})\n OR (b_kind = ${ref.kind} AND b_id = ${ref.id})\n )\n `;\n // Hard delete physically removes the node, so EVERY assertion touching it —\n // including already-ended and previously soft-deleted rows — must be\n // removed, or a node soft-deleted before its hard delete would leave\n // archival assertions referencing a row that no longer exists. Soft delete\n // only ends the currently-open rows.\n const scope =\n mode === \"hard\" ?\n sql``\n : sql`AND valid_to IS NULL AND deleted_at IS NULL`;\n const rows = await rawTarget.execute<RawIdentityAssertionRow>(\n asCompiledRowsSql(sql`\n SELECT ${IDENTITY_ASSERTION_COLUMNS}\n FROM ${ctx.schema.identityAssertionsTable}\n WHERE graph_id = ${ctx.graphId}\n ${scope}\n AND ${touchesNode}\n `),\n );\n // Most deletes are of nodes that never participated in identity. Such a\n // node has no assertion rows in scope and no materialized class row, so its\n // component is itself and the closure repair below would delete and\n // reinsert nothing — one indexed lookup replaces its five statements.\n if (\n rows.length === 0 &&\n !(await hasMaterializedIdentityClass(\n rawTarget,\n ctx.schema,\n ctx.graphId,\n ref,\n ))\n ) {\n return;\n }\n const now = nowIso();\n // A soft delete ends its node's open assertions at the node's OWN deletion\n // instant (see readNodeDeletionInstant): the caller has already written\n // `deleted_at` inside this transaction, and reusing it keeps the node and\n // its assertions agreeing at every valid-time instant. The read is skipped\n // when there is nothing to end.\n const cascadeInstant =\n mode === \"hard\" || rows.length === 0 ?\n now\n : ((await readNodeDeletionInstant(\n rawTarget,\n ctx.schema,\n ctx.graphId,\n ref,\n )) ?? now);\n for (const rawRow of rows) {\n const row = normalizeIdentityAssertionRow(rawRow);\n if (mode === \"hard\") {\n await executeIdentityStatement(\n rawTarget,\n sql`\n DELETE FROM ${ctx.schema.identityAssertionsTable}\n WHERE graph_id = ${ctx.graphId} AND id = ${row.id}\n `,\n );\n touch(ctx.graphId, row.id);\n } else {\n const validTo = clampValidTo(cascadeInstant, row.valid_from);\n // Stamp the CAUSE of the ending alongside it, in the same statement:\n // this row stopped holding because `ref` was deleted, not because\n // anyone retracted it. Downstream (graph-merge's state-diff) reads the\n // stamp instead of trying to infer the cause from timestamps, which\n // cannot separate a retraction issued in the delete's own millisecond\n // from the cascade itself.\n const ended = {\n ...row,\n valid_to: validTo,\n updated_at: now,\n ended_by_kind: ref.kind,\n ended_by_id: ref.id,\n };\n await executeIdentityStatement(\n rawTarget,\n sql`\n UPDATE ${ctx.schema.identityAssertionsTable}\n SET valid_to = ${validTo},\n updated_at = ${now},\n ended_by_kind = ${ref.kind},\n ended_by_id = ${ref.id}\n WHERE graph_id = ${ctx.graphId} AND id = ${row.id}\n `,\n );\n touch(ctx.graphId, row.id, ended);\n }\n }\n await replaceAffectedClosure(\n rawTarget,\n ctx.schema,\n ctx.graphId,\n [ref],\n ctx.sameIdAcrossKinds,\n );\n });\n}\n"]}
|