@sixb/core 0.1.10 → 0.1.12
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/dist/actions/builders/params.d.ts +1 -22
- package/dist/actions/builders/params.d.ts.map +1 -1
- package/dist/actions/index.js +29 -28
- package/dist/actions/index.js.map +1 -1
- package/dist/actions/types/params.d.ts +10 -44
- package/dist/actions/types/params.d.ts.map +1 -1
- package/dist/actions/validation.d.ts.map +1 -1
- package/dist/actions/worker.js +3 -2
- package/dist/actions/worker.js.map +2 -2
- package/dist/agents/errors.d.ts +1 -1
- package/dist/agents/errors.d.ts.map +1 -1
- package/dist/agents/execution.d.ts +15 -9
- package/dist/agents/execution.d.ts.map +1 -1
- package/dist/agents/ids.d.ts +2 -0
- package/dist/agents/ids.d.ts.map +1 -1
- package/dist/agents/index.d.ts +1 -1
- package/dist/agents/index.d.ts.map +1 -1
- package/dist/agents/index.js +48 -42
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/request.d.ts.map +1 -1
- package/dist/agents/sandbox.d.ts +5 -0
- package/dist/agents/sandbox.d.ts.map +1 -0
- package/dist/agents/streams/index.js +4 -3
- package/dist/agents/streams/index.js.map +1 -1
- package/dist/agents/streams/internal.js +4 -3
- package/dist/agents/streams/internal.js.map +1 -1
- package/dist/agents/validation.d.ts.map +1 -1
- package/dist/auth/index.js +8 -6
- package/dist/auth/index.js.map +1 -1
- package/dist/authorization/index.js +5 -4
- package/dist/authorization/index.js.map +1 -1
- package/dist/blob-storage/types.d.ts +4 -1
- package/dist/blob-storage/types.d.ts.map +1 -1
- package/dist/bootstrap/index.js +50 -46
- package/dist/bootstrap/index.js.map +1 -1
- package/dist/{chunk-17kfctj6.js → chunk-0mza4xb2.js} +2 -2
- package/dist/chunk-2c4j899j.js.map +1 -1
- package/dist/{chunk-g00bfdq6.js → chunk-2cxv584m.js} +12 -56
- package/dist/{chunk-g00bfdq6.js.map → chunk-2cxv584m.js.map} +3 -3
- package/dist/{chunk-e0d1rzef.js → chunk-2h63nrde.js} +380 -97
- package/dist/chunk-2h63nrde.js.map +20 -0
- package/dist/{chunk-rtk71jzp.js → chunk-3bnt2wna.js} +2 -2
- package/dist/{chunk-awbhdqyc.js → chunk-3ghw2t5q.js} +1 -1
- package/dist/{chunk-b19g04jk.js → chunk-3h7ctayx.js} +1 -1
- package/dist/{chunk-wjasrj67.js → chunk-3qpcrcj8.js} +1 -1
- package/dist/{chunk-5hz0fnca.js → chunk-4k53sm9e.js} +6 -2
- package/dist/chunk-4k53sm9e.js.map +12 -0
- package/dist/chunk-4ph94nhd.js +81 -0
- package/dist/chunk-4ph94nhd.js.map +10 -0
- package/dist/chunk-58geavnf.js +29 -0
- package/dist/chunk-58geavnf.js.map +10 -0
- package/dist/{chunk-0y39rgsb.js → chunk-5tetw4hn.js} +1 -1
- package/dist/{chunk-7bs40fe1.js → chunk-69266efg.js} +83 -2
- package/dist/chunk-69266efg.js.map +12 -0
- package/dist/{chunk-g7knyczr.js → chunk-6ma8dvzc.js} +121 -53
- package/dist/chunk-6ma8dvzc.js.map +15 -0
- package/dist/{chunk-skz0hst3.js → chunk-7c2g3sz9.js} +6 -86
- package/dist/{chunk-skz0hst3.js.map → chunk-7c2g3sz9.js.map} +3 -3
- package/dist/{chunk-976rxdpx.js → chunk-7qnvhtcd.js} +93 -17
- package/dist/{chunk-976rxdpx.js.map → chunk-7qnvhtcd.js.map} +7 -6
- package/dist/{chunk-c5rkjrgp.js → chunk-7ytf06d3.js} +1 -1
- package/dist/{chunk-mrp7k0pw.js → chunk-91kcnbf0.js} +9 -14
- package/dist/chunk-91kcnbf0.js.map +10 -0
- package/dist/{chunk-yv79ncbv.js → chunk-96yw3pwd.js} +3 -3
- package/dist/chunk-96yw3pwd.js.map +10 -0
- package/dist/chunk-98cw09sw.js.map +2 -2
- package/dist/{chunk-93csa55g.js → chunk-axndsymr.js} +10 -4
- package/dist/chunk-axndsymr.js.map +11 -0
- package/dist/{chunk-r7fj830t.js → chunk-b768c93y.js} +100 -29
- package/dist/chunk-b768c93y.js.map +36 -0
- package/dist/{chunk-dz5h08xv.js → chunk-bbaa1fet.js} +24 -9
- package/dist/{chunk-dz5h08xv.js.map → chunk-bbaa1fet.js.map} +4 -4
- package/dist/{chunk-7apz6hg4.js → chunk-bet1rb9h.js} +8 -4
- package/dist/chunk-bet1rb9h.js.map +10 -0
- package/dist/{chunk-358caqf5.js → chunk-bfjv1adk.js} +2 -2
- package/dist/{chunk-b0ec55a1.js → chunk-bg2bs62d.js} +5 -5
- package/dist/{chunk-860dwwy0.js → chunk-cd234ba4.js} +22 -12
- package/dist/chunk-cd234ba4.js.map +14 -0
- package/dist/chunk-d62kjtbg.js.map +1 -1
- package/dist/chunk-dmn70ztd.js.map +2 -2
- package/dist/{chunk-28ja2cjs.js → chunk-e1f1sqba.js} +39 -53
- package/dist/{chunk-28ja2cjs.js.map → chunk-e1f1sqba.js.map} +5 -6
- package/dist/{chunk-ap0g1g74.js → chunk-eyjzgav0.js} +39 -4
- package/dist/chunk-eyjzgav0.js.map +12 -0
- package/dist/{chunk-rb1xx120.js → chunk-f06sf7rr.js} +9 -5
- package/dist/chunk-f06sf7rr.js.map +11 -0
- package/dist/{chunk-g6cke204.js → chunk-f85hpqnm.js} +1 -1
- package/dist/{chunk-vsj3mdfj.js → chunk-fc5zfxy1.js} +1 -1
- package/dist/{chunk-38zv5rkr.js → chunk-g2gezsg5.js} +1 -1
- package/dist/{chunk-38zv5rkr.js.map → chunk-g2gezsg5.js.map} +2 -2
- package/dist/{chunk-nmbxcaqx.js → chunk-g50nxqs5.js} +53 -66
- package/dist/chunk-g50nxqs5.js.map +18 -0
- package/dist/{chunk-1824gssz.js → chunk-gswwr35f.js} +4 -4
- package/dist/{chunk-92vk7gta.js → chunk-gzt6v1ja.js} +1 -1
- package/dist/{chunk-aa6z4a19.js → chunk-hgqpcmyr.js} +2 -1
- package/dist/chunk-hgqpcmyr.js.map +12 -0
- package/dist/{chunk-gqh45d2n.js → chunk-hkw8rykk.js} +2 -2
- package/dist/{chunk-f4w3yp4f.js → chunk-hzw7yv5g.js} +104 -21
- package/dist/chunk-hzw7yv5g.js.map +13 -0
- package/dist/{chunk-5c7ga8zz.js → chunk-jjwhy3rs.js} +5 -5
- package/dist/chunk-kept9cdd.js +29 -0
- package/dist/chunk-kept9cdd.js.map +10 -0
- package/dist/{chunk-ftv470j8.js → chunk-m7cx05vp.js} +247 -16
- package/dist/{chunk-ftv470j8.js.map → chunk-m7cx05vp.js.map} +14 -10
- package/dist/{chunk-qyeptdyv.js → chunk-mdnw7nj8.js} +10 -6
- package/dist/chunk-mdnw7nj8.js.map +15 -0
- package/dist/{chunk-5p1v802y.js → chunk-nzsy3xrp.js} +253 -86
- package/dist/chunk-nzsy3xrp.js.map +46 -0
- package/dist/chunk-p1683c0v.js +104 -0
- package/dist/chunk-p1683c0v.js.map +11 -0
- package/dist/chunk-p6r1ex7t.js +93 -0
- package/dist/chunk-p6r1ex7t.js.map +10 -0
- package/dist/{chunk-p5vcsw9c.js → chunk-qm535afa.js} +10 -10
- package/dist/{chunk-p5vcsw9c.js.map → chunk-qm535afa.js.map} +4 -4
- package/dist/chunk-r5zythxp.js +552 -0
- package/dist/chunk-r5zythxp.js.map +17 -0
- package/dist/{chunk-9qsh3p5y.js → chunk-rb143ggb.js} +1 -1
- package/dist/{chunk-653vwrzr.js → chunk-rdghfsss.js} +1 -1
- package/dist/{chunk-t1f4f1ve.js → chunk-sfypc7mk.js} +18 -13
- package/dist/{chunk-t1f4f1ve.js.map → chunk-sfypc7mk.js.map} +3 -3
- package/dist/{chunk-f0rwz2vh.js → chunk-t6f3tdnr.js} +2 -54
- package/dist/chunk-t6f3tdnr.js.map +10 -0
- package/dist/{chunk-bn138h9w.js → chunk-t7dzd1tm.js} +3 -3
- package/dist/{chunk-pr2h4bv4.js → chunk-tg4g4zh0.js} +3 -3
- package/dist/chunk-vpxss818.js +56 -0
- package/dist/chunk-vpxss818.js.map +10 -0
- package/dist/{chunk-ms2tmn1k.js → chunk-vsg0g7h9.js} +53 -57
- package/dist/chunk-vsg0g7h9.js.map +17 -0
- package/dist/{chunk-8vj0rjgs.js → chunk-wjffn5m4.js} +1 -1
- package/dist/{chunk-nt99sxd6.js → chunk-x9tmx3fc.js} +18 -24
- package/dist/chunk-x9tmx3fc.js.map +14 -0
- package/dist/{chunk-agbbygvh.js → chunk-xn686q2e.js} +8 -8
- package/dist/{chunk-g53f0e4j.js → chunk-xnx96gfy.js} +45 -17
- package/dist/{chunk-g53f0e4j.js.map → chunk-xnx96gfy.js.map} +3 -3
- package/dist/{chunk-v2vcg0w6.js → chunk-xtfryrfb.js} +2 -2
- package/dist/chunk-y0v18c2j.js +363 -0
- package/dist/chunk-y0v18c2j.js.map +14 -0
- package/dist/{chunk-72w2pxk7.js → chunk-y1ahv8b7.js} +11 -3
- package/dist/{chunk-72w2pxk7.js.map → chunk-y1ahv8b7.js.map} +3 -3
- package/dist/chunk-y3ev53cq.js +84 -0
- package/dist/chunk-y3ev53cq.js.map +10 -0
- package/dist/{chunk-p6a4npdx.js → chunk-ybhz3j9g.js} +362 -60
- package/dist/chunk-ybhz3j9g.js.map +63 -0
- package/dist/{chunk-z30bv4ga.js → chunk-yxb4c62x.js} +3 -2
- package/dist/{chunk-z30bv4ga.js.map → chunk-yxb4c62x.js.map} +3 -3
- package/dist/chunk-z3y5kg1x.js +14 -0
- package/dist/chunk-z3y5kg1x.js.map +10 -0
- package/dist/connectors/connections/command-context.d.ts +2 -0
- package/dist/connectors/connections/command-context.d.ts.map +1 -1
- package/dist/connectors/connections/contracts.d.ts +1 -1
- package/dist/connectors/connections/contracts.d.ts.map +1 -1
- package/dist/connectors/connections/execution.d.ts +1 -0
- package/dist/connectors/connections/execution.d.ts.map +1 -1
- package/dist/connectors/connections/runs.d.ts +1 -0
- package/dist/connectors/connections/runs.d.ts.map +1 -1
- package/dist/connectors/connections/service.d.ts +2 -0
- package/dist/connectors/connections/service.d.ts.map +1 -1
- package/dist/datasets/validation.d.ts +4 -0
- package/dist/datasets/validation.d.ts.map +1 -1
- package/dist/datasets/write.d.ts.map +1 -1
- package/dist/datasets/write.js +5 -4
- package/dist/datasets/write.js.map +1 -1
- package/dist/error-reporting/capability.d.ts +3 -2
- package/dist/error-reporting/capability.d.ts.map +1 -1
- package/dist/error-reporting/internal.js +5 -4
- package/dist/error-reporting/internal.js.map +1 -1
- package/dist/error-reporting/reports.d.ts +10 -0
- package/dist/error-reporting/reports.d.ts.map +1 -1
- package/dist/error-reporting/types.d.ts +10 -2
- package/dist/error-reporting/types.d.ts.map +1 -1
- package/dist/errors/catalog.d.ts +12 -0
- package/dist/errors/catalog.d.ts.map +1 -1
- package/dist/errors/failure-message.d.ts +8 -0
- package/dist/errors/failure-message.d.ts.map +1 -0
- package/dist/errors/internal.d.ts.map +1 -1
- package/dist/errors/internal.js +3 -2
- package/dist/errors/internal.js.map +1 -1
- package/dist/events/index.js +5 -4
- package/dist/events/index.js.map +1 -1
- package/dist/events/outbox-dispatcher.d.ts +2 -2
- package/dist/events/outbox-dispatcher.d.ts.map +1 -1
- package/dist/execution/agent.js +44 -41
- package/dist/execution/agent.js.map +1 -1
- package/dist/execution/authorization.d.ts.map +1 -1
- package/dist/execution/authorized-object-reader.d.ts +3 -0
- package/dist/execution/authorized-object-reader.d.ts.map +1 -1
- package/dist/execution/kernel-operation.d.ts +4 -0
- package/dist/execution/kernel-operation.d.ts.map +1 -0
- package/dist/execution/primitive.js +44 -41
- package/dist/execution/primitive.js.map +2 -2
- package/dist/execution/request.js +45 -42
- package/dist/execution/request.js.map +2 -2
- package/dist/execution/types.d.ts +6 -0
- package/dist/execution/types.d.ts.map +1 -1
- package/dist/index.d.ts +15 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +68 -59
- package/dist/index.js.map +1 -1
- package/dist/lake-storage/in-memory.d.ts.map +1 -1
- package/dist/lake-storage/index.js +5 -4
- package/dist/lake-storage/index.js.map +1 -1
- package/dist/lake-storage/types.d.ts +2 -0
- package/dist/lake-storage/types.d.ts.map +1 -1
- package/dist/maintenance/ontology-maintenance.d.ts.map +1 -1
- package/dist/maintenance/types.d.ts +1 -1
- package/dist/maintenance/types.d.ts.map +1 -1
- package/dist/materialization/errors.d.ts +1 -1
- package/dist/materialization/errors.d.ts.map +1 -1
- package/dist/materialization/index.d.ts +1 -0
- package/dist/materialization/index.d.ts.map +1 -1
- package/dist/materialization/index.js +3 -3
- package/dist/materialization/model.d.ts +2 -0
- package/dist/materialization/model.d.ts.map +1 -1
- package/dist/materialization/vectors.d.ts +19 -0
- package/dist/materialization/vectors.d.ts.map +1 -0
- package/dist/materializer/context.d.ts.map +1 -1
- package/dist/materializer/edits/commit.d.ts.map +1 -1
- package/dist/materializer/edits/vector-authority.d.ts +6 -0
- package/dist/materializer/edits/vector-authority.d.ts.map +1 -0
- package/dist/materializer/edits/vectors.d.ts +6 -0
- package/dist/materializer/edits/vectors.d.ts.map +1 -0
- package/dist/materializer/effective/validate.d.ts.map +1 -1
- package/dist/materializer/effective/vector-indexing.d.ts +7 -0
- package/dist/materializer/effective/vector-indexing.d.ts.map +1 -0
- package/dist/materializer/effective/vectors.d.ts +6 -0
- package/dist/materializer/effective/vectors.d.ts.map +1 -0
- package/dist/materializer/execution/work-executor.d.ts +2 -1
- package/dist/materializer/execution/work-executor.d.ts.map +1 -1
- package/dist/materializer/index.js +26 -25
- package/dist/materializer/index.js.map +1 -1
- package/dist/materializer/shared/normalize.d.ts.map +1 -1
- package/dist/models/catalog-index.d.ts +15 -0
- package/dist/models/catalog-index.d.ts.map +1 -0
- package/dist/models/catalog.d.ts +27 -6
- package/dist/models/catalog.d.ts.map +1 -1
- package/dist/models/decision/catalog.d.ts +12 -0
- package/dist/models/decision/catalog.d.ts.map +1 -0
- package/dist/models/decision/errors.d.ts +7 -0
- package/dist/models/decision/errors.d.ts.map +1 -0
- package/dist/models/decision/output.d.ts +50 -0
- package/dist/models/decision/output.d.ts.map +1 -0
- package/dist/models/decision/questions.d.ts +14 -0
- package/dist/models/decision/questions.d.ts.map +1 -0
- package/dist/models/decision/runtime.d.ts +7 -0
- package/dist/models/decision/runtime.d.ts.map +1 -0
- package/dist/models/decision/types.d.ts +92 -0
- package/dist/models/decision/types.d.ts.map +1 -0
- package/dist/models/decision/validation.d.ts +7 -0
- package/dist/models/decision/validation.d.ts.map +1 -0
- package/dist/models/definitions.d.ts +8 -1
- package/dist/models/definitions.d.ts.map +1 -1
- package/dist/models/embedding-model.d.ts +60 -0
- package/dist/models/embedding-model.d.ts.map +1 -0
- package/dist/models/execution/binding.d.ts +2 -0
- package/dist/models/execution/binding.d.ts.map +1 -1
- package/dist/models/execution/embedding.d.ts +5 -0
- package/dist/models/execution/embedding.d.ts.map +1 -0
- package/dist/models/execution/index.js +29 -26
- package/dist/models/execution/index.js.map +1 -1
- package/dist/models/execution/model-call-recorder.d.ts +5 -1
- package/dist/models/execution/model-call-recorder.d.ts.map +1 -1
- package/dist/models/execution/session.d.ts +21 -0
- package/dist/models/execution/session.d.ts.map +1 -0
- package/dist/models/execution.d.ts.map +1 -1
- package/dist/models/generation-types.d.ts +2 -0
- package/dist/models/generation-types.d.ts.map +1 -1
- package/dist/models/index.d.ts +9 -1
- package/dist/models/index.d.ts.map +1 -1
- package/dist/models/index.js +17 -7
- package/dist/models/index.js.map +1 -1
- package/dist/models/pricing.d.ts +3 -2
- package/dist/models/pricing.d.ts.map +1 -1
- package/dist/objects/authorized-ontology-view.d.ts.map +1 -1
- package/dist/objects/execution.d.ts +1 -0
- package/dist/objects/execution.d.ts.map +1 -1
- package/dist/objects/index.js +29 -28
- package/dist/objects/index.js.map +1 -1
- package/dist/objects/query/executor.d.ts +3 -0
- package/dist/objects/query/executor.d.ts.map +1 -1
- package/dist/objects/query/index.d.ts +2 -0
- package/dist/objects/query/index.d.ts.map +1 -1
- package/dist/objects/query/index.js +34 -24
- package/dist/objects/query/index.js.map +1 -1
- package/dist/objects/query/ir.d.ts +6 -2
- package/dist/objects/query/ir.d.ts.map +1 -1
- package/dist/objects/query/normalize.d.ts.map +1 -1
- package/dist/objects/query/validate.d.ts.map +1 -1
- package/dist/objects/sdk/object-handle.d.ts +5 -0
- package/dist/objects/sdk/object-handle.d.ts.map +1 -1
- package/dist/objects/sdk/object-set.d.ts.map +1 -1
- package/dist/objects/sdk/query-executor.d.ts +2 -0
- package/dist/objects/sdk/query-executor.d.ts.map +1 -1
- package/dist/objects/sdk/runtime-query-executor.d.ts.map +1 -1
- package/dist/objects/vectors/handle.d.ts +4 -0
- package/dist/objects/vectors/handle.d.ts.map +1 -0
- package/dist/objects/vectors/indexing-batch.d.ts +6 -0
- package/dist/objects/vectors/indexing-batch.d.ts.map +1 -0
- package/dist/objects/vectors/indexing-generate.d.ts +11 -0
- package/dist/objects/vectors/indexing-generate.d.ts.map +1 -0
- package/dist/objects/vectors/indexing-runtime.d.ts +7 -0
- package/dist/objects/vectors/indexing-runtime.d.ts.map +1 -0
- package/dist/objects/vectors/indexing-shared.d.ts +17 -0
- package/dist/objects/vectors/indexing-shared.d.ts.map +1 -0
- package/dist/objects/vectors/indexing-single.d.ts +4 -0
- package/dist/objects/vectors/indexing-single.d.ts.map +1 -0
- package/dist/objects/vectors/indexing-store-batch.d.ts +6 -0
- package/dist/objects/vectors/indexing-store-batch.d.ts.map +1 -0
- package/dist/objects/vectors/indexing.d.ts +7 -0
- package/dist/objects/vectors/indexing.d.ts.map +1 -0
- package/dist/objects/vectors/profile.d.ts +13 -0
- package/dist/objects/vectors/profile.d.ts.map +1 -0
- package/dist/objects/vectors/query.d.ts +5 -0
- package/dist/objects/vectors/query.d.ts.map +1 -0
- package/dist/objects/vectors/resolve-query.d.ts +6 -0
- package/dist/objects/vectors/resolve-query.d.ts.map +1 -0
- package/dist/objects/vectors/types.d.ts +11 -0
- package/dist/objects/vectors/types.d.ts.map +1 -0
- package/dist/ontology/index.d.ts +2 -1
- package/dist/ontology/index.d.ts.map +1 -1
- package/dist/ontology/index.js +5 -5
- package/dist/ontology/index.js.map +1 -1
- package/dist/ontology/internal.js +5 -4
- package/dist/ontology/internal.js.map +1 -1
- package/dist/ontology/registry.d.ts.map +1 -1
- package/dist/ontology/types.d.ts +8 -9
- package/dist/ontology/types.d.ts.map +1 -1
- package/dist/ontology/validation/definition.d.ts +3 -0
- package/dist/ontology/validation/definition.d.ts.map +1 -0
- package/dist/ontology/validation/properties.d.ts.map +1 -1
- package/dist/ontology/validation/query.d.ts.map +1 -1
- package/dist/ontology/validation/schema.d.ts +1 -1
- package/dist/ontology/validation/schema.d.ts.map +1 -1
- package/dist/ontology/vector-profiles.d.ts +4 -0
- package/dist/ontology/vector-profiles.d.ts.map +1 -0
- package/dist/pipelines/index.js +28 -27
- package/dist/pipelines/index.js.map +1 -1
- package/dist/projections/internal.js +24 -23
- package/dist/projections/internal.js.map +1 -1
- package/dist/query.js +2 -2
- package/dist/queues/in-memory.d.ts +2 -1
- package/dist/queues/in-memory.d.ts.map +1 -1
- package/dist/queues/index.d.ts +1 -1
- package/dist/queues/index.d.ts.map +1 -1
- package/dist/queues/index.js +1 -1
- package/dist/queues/types.d.ts +5 -0
- package/dist/queues/types.d.ts.map +1 -1
- package/dist/runtime/create.d.ts +4 -3
- package/dist/runtime/create.d.ts.map +1 -1
- package/dist/runtime/host.d.ts +9 -6
- package/dist/runtime/host.d.ts.map +1 -1
- package/dist/runtime/internal.d.ts +3 -0
- package/dist/runtime/internal.d.ts.map +1 -1
- package/dist/runtime/internal.js +47 -1
- package/dist/runtime/internal.js.map +1 -1
- package/dist/runtime/resolve-definitions.d.ts.map +1 -1
- package/dist/runtime/sixb.d.ts +9 -4
- package/dist/runtime/sixb.d.ts.map +1 -1
- package/dist/runtime/types.d.ts +15 -3
- package/dist/runtime/types.d.ts.map +1 -1
- package/dist/sandboxes/auth.d.ts +16 -0
- package/dist/sandboxes/auth.d.ts.map +1 -0
- package/dist/sandboxes/config.d.ts +5 -0
- package/dist/sandboxes/config.d.ts.map +1 -0
- package/dist/sandboxes/configuration.d.ts +41 -0
- package/dist/sandboxes/configuration.d.ts.map +1 -0
- package/dist/sandboxes/environment.d.ts +13 -0
- package/dist/sandboxes/environment.d.ts.map +1 -0
- package/dist/sandboxes/errors.d.ts +1 -1
- package/dist/sandboxes/errors.d.ts.map +1 -1
- package/dist/sandboxes/index.d.ts +6 -1
- package/dist/sandboxes/index.d.ts.map +1 -1
- package/dist/sandboxes/index.js +16 -3
- package/dist/sandboxes/index.js.map +1 -1
- package/dist/sandboxes/sandbox.d.ts +35 -3
- package/dist/sandboxes/sandbox.d.ts.map +1 -1
- package/dist/shared/params/builders.d.ts +25 -0
- package/dist/shared/params/builders.d.ts.map +1 -0
- package/dist/shared/params/types.d.ts +47 -0
- package/dist/shared/params/types.d.ts.map +1 -0
- package/dist/shared/params/validation.d.ts +15 -0
- package/dist/shared/params/validation.d.ts.map +1 -0
- package/dist/shares/internal.js +23 -22
- package/dist/shares/internal.js.map +2 -2
- package/dist/storage/action-runs/failure.js +4 -3
- package/dist/storage/action-runs/failure.js.map +1 -1
- package/dist/storage/action-runs/provider.js +1 -1
- package/dist/storage/agents/in-memory.d.ts +2 -1
- package/dist/storage/agents/in-memory.d.ts.map +1 -1
- package/dist/storage/agents/index.d.ts +1 -1
- package/dist/storage/agents/index.d.ts.map +1 -1
- package/dist/storage/agents/provider.d.ts +5 -1
- package/dist/storage/agents/provider.d.ts.map +1 -1
- package/dist/storage/agents/provider.js +8 -4
- package/dist/storage/agents/provider.js.map +1 -1
- package/dist/storage/agents/types.d.ts +49 -0
- package/dist/storage/agents/types.d.ts.map +1 -1
- package/dist/storage/ai-cost/analytics.d.ts +1 -0
- package/dist/storage/ai-cost/analytics.d.ts.map +1 -1
- package/dist/storage/ai-cost/index.d.ts +1 -1
- package/dist/storage/ai-cost/index.d.ts.map +1 -1
- package/dist/storage/ai-cost/provider.js +2 -2
- package/dist/storage/ai-cost/types.d.ts +14 -2
- package/dist/storage/ai-cost/types.d.ts.map +1 -1
- package/dist/storage/ai-limits/enforcement.js +4 -3
- package/dist/storage/ai-limits/enforcement.js.map +1 -1
- package/dist/storage/connector-connections/in-memory.d.ts +1 -0
- package/dist/storage/connector-connections/in-memory.d.ts.map +1 -1
- package/dist/storage/connector-connections/provider/connections.d.ts.map +1 -1
- package/dist/storage/connector-connections/provider/runs.d.ts +1 -0
- package/dist/storage/connector-connections/provider/runs.d.ts.map +1 -1
- package/dist/storage/connector-connections/provider/shared.d.ts +1 -0
- package/dist/storage/connector-connections/provider/shared.d.ts.map +1 -1
- package/dist/storage/connector-connections/provider.d.ts +1 -0
- package/dist/storage/connector-connections/provider.d.ts.map +1 -1
- package/dist/storage/connector-connections/provider.js +12 -17
- package/dist/storage/connector-connections/provider.js.map +6 -6
- package/dist/storage/connector-connections/types.d.ts +3 -1
- package/dist/storage/connector-connections/types.d.ts.map +1 -1
- package/dist/storage/executions/provider.d.ts +3 -3
- package/dist/storage/executions/provider.d.ts.map +1 -1
- package/dist/storage/executions/provider.js +13 -11
- package/dist/storage/executions/provider.js.map +3 -3
- package/dist/storage/executions/types.d.ts +3 -0
- package/dist/storage/executions/types.d.ts.map +1 -1
- package/dist/storage/executions/validation.d.ts.map +1 -1
- package/dist/storage/index.d.ts +5 -3
- package/dist/storage/index.d.ts.map +1 -1
- package/dist/storage/index.js +25 -22
- package/dist/storage/index.js.map +1 -1
- package/dist/storage/internal.js +2 -2
- package/dist/storage/objects/in-memory/query.d.ts.map +1 -1
- package/dist/storage/objects/in-memory/read-source.d.ts +5 -0
- package/dist/storage/objects/in-memory/read-source.d.ts.map +1 -1
- package/dist/storage/objects/in-memory/selected-reader.d.ts.map +1 -1
- package/dist/storage/objects/in-memory/storage.d.ts +7 -0
- package/dist/storage/objects/in-memory/storage.d.ts.map +1 -1
- package/dist/storage/objects/types.d.ts +2 -0
- package/dist/storage/objects/types.d.ts.map +1 -1
- package/dist/storage/ontology/commits.d.ts +1 -0
- package/dist/storage/ontology/commits.d.ts.map +1 -1
- package/dist/storage/ontology/in-memory/index.d.ts +4 -0
- package/dist/storage/ontology/in-memory/index.d.ts.map +1 -1
- package/dist/storage/ontology/in-memory/materializations.d.ts +2 -0
- package/dist/storage/ontology/in-memory/materializations.d.ts.map +1 -1
- package/dist/storage/ontology/in-memory/shared-state.d.ts +7 -0
- package/dist/storage/ontology/in-memory/shared-state.d.ts.map +1 -1
- package/dist/storage/ontology/in-memory/vector-indexing.d.ts +44 -0
- package/dist/storage/ontology/in-memory/vector-indexing.d.ts.map +1 -0
- package/dist/storage/ontology/in-memory/vectors.d.ts +31 -0
- package/dist/storage/ontology/in-memory/vectors.d.ts.map +1 -0
- package/dist/storage/ontology/index.d.ts +6 -0
- package/dist/storage/ontology/index.d.ts.map +1 -1
- package/dist/storage/ontology/outbox.d.ts +1 -0
- package/dist/storage/ontology/outbox.d.ts.map +1 -1
- package/dist/storage/ontology/provider.js +2 -2
- package/dist/storage/ontology/vector-indexing.d.ts +94 -0
- package/dist/storage/ontology/vector-indexing.d.ts.map +1 -0
- package/dist/storage/ontology/vectors.d.ts +56 -0
- package/dist/storage/ontology/vectors.d.ts.map +1 -0
- package/dist/storage/operation-scope.d.ts.map +1 -1
- package/dist/storage/operation-scope.js +1 -1
- package/dist/storage/projection-runs/provider.js +4 -3
- package/dist/storage/projection-runs/provider.js.map +1 -1
- package/dist/storage/types.d.ts +1 -1
- package/dist/storage/types.d.ts.map +1 -1
- package/dist/storage/workflow-runs/provider.js +9 -7
- package/dist/storage/workflow-runs/provider.js.map +1 -1
- package/dist/syncs/index.js +29 -28
- package/dist/syncs/index.js.map +1 -1
- package/dist/testing/agent-storage-contract.d.ts.map +1 -1
- package/dist/testing/ai-cost-storage-contract.d.ts.map +1 -1
- package/dist/testing/index.js +488 -81
- package/dist/testing/index.js.map +10 -10
- package/dist/testing/lake-storage-contract.d.ts.map +1 -1
- package/dist/testing/object-query-contract.d.ts.map +1 -1
- package/dist/testing/object-read-scope-contract.d.ts.map +1 -1
- package/dist/testing/ontology-storage-contract.d.ts.map +1 -1
- package/dist/testing/queues-contract.d.ts.map +1 -1
- package/dist/webhooks/internal.js +24 -23
- package/dist/webhooks/internal.js.map +2 -2
- package/dist/workers/index.js +3 -2
- package/dist/workers/index.js.map +2 -2
- package/dist/workflows/failure.d.ts.map +1 -1
- package/dist/workflows/index.js +47 -43
- package/dist/workflows/index.js.map +1 -1
- package/package.json +1 -1
- package/src/actions/builders/params.ts +1 -48
- package/src/actions/types/params.ts +14 -74
- package/src/actions/validation.ts +7 -84
- package/src/agents/errors.ts +3 -0
- package/src/agents/execution.ts +67 -15
- package/src/agents/ids.ts +8 -0
- package/src/agents/index.ts +1 -0
- package/src/agents/model-loop.ts +7 -0
- package/src/agents/request.ts +11 -0
- package/src/agents/sandbox.ts +44 -0
- package/src/agents/validation.ts +2 -108
- package/src/blob-storage/types.ts +4 -1
- package/src/connectors/connections/command-context.ts +21 -4
- package/src/connectors/connections/contracts.ts +4 -1
- package/src/connectors/connections/execution.ts +3 -0
- package/src/connectors/connections/runs.ts +38 -1
- package/src/connectors/connections/service.ts +6 -0
- package/src/datasets/validation.ts +40 -11
- package/src/datasets/write.ts +8 -11
- package/src/error-reporting/capability.ts +11 -0
- package/src/error-reporting/reports.ts +23 -0
- package/src/error-reporting/types.ts +12 -1
- package/src/errors/catalog.ts +12 -0
- package/src/errors/failure-message.ts +15 -0
- package/src/errors/internal.ts +57 -25
- package/src/events/outbox-dispatcher.ts +20 -26
- package/src/execution/authorization.ts +12 -5
- package/src/execution/authorized-object-reader.ts +37 -2
- package/src/execution/kernel-operation.ts +27 -0
- package/src/execution/scopes.ts +2 -0
- package/src/execution/types.ts +4 -4
- package/src/index.ts +60 -1
- package/src/lake-storage/in-memory.ts +7 -3
- package/src/lake-storage/types.ts +2 -0
- package/src/maintenance/ontology-maintenance.ts +6 -2
- package/src/maintenance/types.ts +1 -1
- package/src/materialization/errors.ts +2 -2
- package/src/materialization/index.ts +1 -0
- package/src/materialization/model.ts +2 -0
- package/src/materialization/vectors.ts +18 -0
- package/src/materializer/README.md +15 -1
- package/src/materializer/context.ts +10 -0
- package/src/materializer/edits/commit.ts +8 -1
- package/src/materializer/edits/vector-authority.ts +108 -0
- package/src/materializer/edits/vectors.ts +100 -0
- package/src/materializer/effective/validate.ts +10 -3
- package/src/materializer/effective/vector-indexing.ts +84 -0
- package/src/materializer/effective/vectors.ts +47 -0
- package/src/materializer/execution/work-executor.ts +11 -3
- package/src/materializer/projections/replace.ts +1 -1
- package/src/materializer/shared/normalize.ts +11 -0
- package/src/materializer/telemetry/append.ts +1 -1
- package/src/models/catalog-index.ts +38 -0
- package/src/models/catalog.ts +66 -38
- package/src/models/decision/catalog.ts +32 -0
- package/src/models/decision/errors.ts +18 -0
- package/src/models/decision/output.ts +101 -0
- package/src/models/decision/questions.ts +29 -0
- package/src/models/decision/runtime.ts +188 -0
- package/src/models/decision/types.ts +109 -0
- package/src/models/decision/validation.ts +335 -0
- package/src/models/definitions.ts +20 -1
- package/src/models/embedding-model.ts +129 -0
- package/src/models/execution/README.md +63 -0
- package/src/models/execution/binding.ts +2 -0
- package/src/models/execution/embedding.ts +133 -0
- package/src/models/execution/model-call-recorder.ts +42 -30
- package/src/models/execution/session.ts +81 -0
- package/src/models/execution.ts +10 -52
- package/src/models/generation-types.ts +2 -0
- package/src/models/index.ts +37 -0
- package/src/models/pricing.ts +7 -4
- package/src/objects/authorized-ontology-view.ts +12 -8
- package/src/objects/execution.ts +2 -0
- package/src/objects/query/executor.ts +13 -4
- package/src/objects/query/explain.ts +7 -2
- package/src/objects/query/index.ts +2 -0
- package/src/objects/query/ir.ts +6 -2
- package/src/objects/query/normalize.ts +5 -1
- package/src/objects/query/validate.ts +74 -73
- package/src/objects/sdk/object-handle.ts +3 -0
- package/src/objects/sdk/object-set.ts +1 -0
- package/src/objects/sdk/query-builder.ts +9 -3
- package/src/objects/sdk/query-executor.ts +2 -1
- package/src/objects/sdk/runtime-query-executor.ts +6 -2
- package/src/objects/vectors/README.md +59 -0
- package/src/objects/vectors/handle.ts +91 -0
- package/src/objects/vectors/indexing-batch.ts +163 -0
- package/src/objects/vectors/indexing-generate.ts +184 -0
- package/src/objects/vectors/indexing-runtime.ts +17 -0
- package/src/objects/vectors/indexing-shared.ts +188 -0
- package/src/objects/vectors/indexing-single.ts +51 -0
- package/src/objects/vectors/indexing-store-batch.ts +62 -0
- package/src/objects/vectors/indexing.ts +23 -0
- package/src/objects/vectors/profile.ts +64 -0
- package/src/objects/vectors/query.ts +16 -0
- package/src/objects/vectors/resolve-query.ts +89 -0
- package/src/objects/vectors/types.ts +10 -0
- package/src/ontology/index.ts +2 -0
- package/src/ontology/registry.ts +8 -0
- package/src/ontology/types.ts +9 -9
- package/src/ontology/validation/definition.ts +104 -0
- package/src/ontology/validation/properties.ts +14 -4
- package/src/ontology/validation/query.ts +34 -51
- package/src/ontology/validation/schema.ts +85 -23
- package/src/ontology/vector-profiles.ts +35 -0
- package/src/queues/in-memory.ts +5 -0
- package/src/queues/index.ts +1 -0
- package/src/queues/types.ts +10 -0
- package/src/runtime/create.ts +7 -6
- package/src/runtime/host.ts +42 -6
- package/src/runtime/internal.ts +3 -0
- package/src/runtime/resolve-definitions.ts +19 -1
- package/src/runtime/sixb.ts +27 -9
- package/src/runtime/types.ts +16 -4
- package/src/sandboxes/README.md +41 -0
- package/src/sandboxes/auth.ts +17 -0
- package/src/sandboxes/config.ts +37 -0
- package/src/sandboxes/configuration.ts +268 -0
- package/src/sandboxes/environment.ts +107 -0
- package/src/sandboxes/errors.ts +1 -1
- package/src/sandboxes/index.ts +15 -0
- package/src/sandboxes/sandbox.ts +38 -3
- package/src/shared/params/builders.ts +50 -0
- package/src/shared/params/types.ts +84 -0
- package/src/shared/params/validation.ts +114 -0
- package/src/storage/agents/in-memory.ts +25 -1
- package/src/storage/agents/index.ts +3 -0
- package/src/storage/agents/provider.ts +105 -0
- package/src/storage/agents/types.ts +54 -0
- package/src/storage/ai-cost/analytics.ts +59 -21
- package/src/storage/ai-cost/index.ts +1 -0
- package/src/storage/ai-cost/types.ts +19 -2
- package/src/storage/connector-connections/in-memory.ts +16 -18
- package/src/storage/connector-connections/provider/connections.ts +1 -15
- package/src/storage/connector-connections/provider/runs.ts +6 -0
- package/src/storage/connector-connections/provider/shared.ts +2 -3
- package/src/storage/connector-connections/provider.ts +6 -0
- package/src/storage/connector-connections/types.ts +5 -1
- package/src/storage/executions/provider.ts +24 -12
- package/src/storage/executions/types.ts +1 -0
- package/src/storage/executions/validation.ts +7 -3
- package/src/storage/index.ts +15 -1
- package/src/storage/objects/in-memory/query.ts +25 -11
- package/src/storage/objects/in-memory/read-scope.ts +9 -2
- package/src/storage/objects/in-memory/read-source.ts +5 -0
- package/src/storage/objects/in-memory/selected-reader.ts +5 -1
- package/src/storage/objects/in-memory/storage.ts +19 -1
- package/src/storage/objects/types.ts +2 -0
- package/src/storage/ontology/commits.ts +1 -0
- package/src/storage/ontology/in-memory/index.ts +20 -0
- package/src/storage/ontology/in-memory/materializations.ts +13 -0
- package/src/storage/ontology/in-memory/shared-state.ts +19 -3
- package/src/storage/ontology/in-memory/vector-indexing.ts +179 -0
- package/src/storage/ontology/in-memory/vectors.ts +73 -0
- package/src/storage/ontology/index.ts +14 -0
- package/src/storage/ontology/outbox.ts +1 -0
- package/src/storage/ontology/vector-indexing.ts +98 -0
- package/src/storage/ontology/vectors.ts +48 -0
- package/src/storage/operation-scope.ts +1 -0
- package/src/storage/types.ts +3 -0
- package/src/testing/agent-storage-contract.ts +246 -0
- package/src/testing/ai-cost-storage-contract.ts +134 -0
- package/src/testing/connector-connection-storage-contract.ts +11 -11
- package/src/testing/lake-storage-contract.ts +29 -0
- package/src/testing/object-query-contract.ts +41 -25
- package/src/testing/object-read-scope-contract.ts +1 -5
- package/src/testing/ontology-storage-contract.ts +8 -3
- package/src/testing/queues-contract.ts +31 -0
- package/src/workflows/failure.ts +10 -4
- package/src/workflows/validation.ts +2 -2
- package/dist/chunk-5hz0fnca.js.map +0 -12
- package/dist/chunk-5p1v802y.js.map +0 -44
- package/dist/chunk-7apz6hg4.js.map +0 -10
- package/dist/chunk-7bs40fe1.js.map +0 -12
- package/dist/chunk-860dwwy0.js.map +0 -14
- package/dist/chunk-93csa55g.js.map +0 -11
- package/dist/chunk-aa6z4a19.js.map +0 -12
- package/dist/chunk-ap0g1g74.js.map +0 -11
- package/dist/chunk-e0d1rzef.js.map +0 -15
- package/dist/chunk-f0rwz2vh.js.map +0 -11
- package/dist/chunk-f4w3yp4f.js.map +0 -12
- package/dist/chunk-g7knyczr.js.map +0 -14
- package/dist/chunk-mrp7k0pw.js.map +0 -10
- package/dist/chunk-ms2tmn1k.js.map +0 -17
- package/dist/chunk-nmbxcaqx.js.map +0 -19
- package/dist/chunk-nt99sxd6.js.map +0 -14
- package/dist/chunk-p6a4npdx.js.map +0 -58
- package/dist/chunk-qyeptdyv.js.map +0 -15
- package/dist/chunk-r7fj830t.js.map +0 -36
- package/dist/chunk-rb1xx120.js.map +0 -11
- package/dist/chunk-yv79ncbv.js.map +0 -10
- package/dist/chunk-z3y411fq.js +0 -99
- package/dist/chunk-z3y411fq.js.map +0 -11
- /package/dist/{chunk-17kfctj6.js.map → chunk-0mza4xb2.js.map} +0 -0
- /package/dist/{chunk-rtk71jzp.js.map → chunk-3bnt2wna.js.map} +0 -0
- /package/dist/{chunk-awbhdqyc.js.map → chunk-3ghw2t5q.js.map} +0 -0
- /package/dist/{chunk-b19g04jk.js.map → chunk-3h7ctayx.js.map} +0 -0
- /package/dist/{chunk-wjasrj67.js.map → chunk-3qpcrcj8.js.map} +0 -0
- /package/dist/{chunk-0y39rgsb.js.map → chunk-5tetw4hn.js.map} +0 -0
- /package/dist/{chunk-c5rkjrgp.js.map → chunk-7ytf06d3.js.map} +0 -0
- /package/dist/{chunk-358caqf5.js.map → chunk-bfjv1adk.js.map} +0 -0
- /package/dist/{chunk-b0ec55a1.js.map → chunk-bg2bs62d.js.map} +0 -0
- /package/dist/{chunk-g6cke204.js.map → chunk-f85hpqnm.js.map} +0 -0
- /package/dist/{chunk-vsj3mdfj.js.map → chunk-fc5zfxy1.js.map} +0 -0
- /package/dist/{chunk-1824gssz.js.map → chunk-gswwr35f.js.map} +0 -0
- /package/dist/{chunk-92vk7gta.js.map → chunk-gzt6v1ja.js.map} +0 -0
- /package/dist/{chunk-gqh45d2n.js.map → chunk-hkw8rykk.js.map} +0 -0
- /package/dist/{chunk-5c7ga8zz.js.map → chunk-jjwhy3rs.js.map} +0 -0
- /package/dist/{chunk-9qsh3p5y.js.map → chunk-rb143ggb.js.map} +0 -0
- /package/dist/{chunk-653vwrzr.js.map → chunk-rdghfsss.js.map} +0 -0
- /package/dist/{chunk-bn138h9w.js.map → chunk-t7dzd1tm.js.map} +0 -0
- /package/dist/{chunk-pr2h4bv4.js.map → chunk-tg4g4zh0.js.map} +0 -0
- /package/dist/{chunk-8vj0rjgs.js.map → chunk-wjffn5m4.js.map} +0 -0
- /package/dist/{chunk-agbbygvh.js.map → chunk-xn686q2e.js.map} +0 -0
- /package/dist/{chunk-v2vcg0w6.js.map → chunk-xtfryrfb.js.map} +0 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/storage/action-runs/in-memory.ts", "../src/agents/message.ts", "../src/storage/agents/in-memory.ts", "../src/storage/ai-cost/errors.ts", "../src/storage/ai-cost/in-memory.ts", "../src/storage/ai-limits/in-memory.ts", "../src/storage/connector-connections/in-memory.ts", "../src/storage/file-upload-sessions/errors.ts", "../src/storage/file-upload-sessions/in-memory.ts", "../src/storage/in-memory/index.ts", "../src/storage/executions/in-memory.ts", "../src/objects/vectors/query.ts", "../src/storage/objects/keys.ts", "../src/storage/objects/in-memory/keys.ts", "../src/objects/query/scalar-values.ts", "../src/objects/vectors/profile.ts", "../src/storage/objects/in-memory/query.ts", "../src/storage/objects/in-memory/read-scope.ts", "../src/storage/objects/in-memory/selected-reader.ts", "../src/storage/objects/in-memory/storage.ts", "../src/storage/ontology/in-memory/shared-state.ts", "../src/storage/ontology/in-memory/commits.ts", "../src/storage/timeseries/store.ts", "../src/storage/ontology/in-memory/materializations-state.ts", "../src/storage/ontology/in-memory/materializations-work.ts", "../src/storage/ontology/in-memory/materializations-finalization.ts", "../src/storage/ontology/in-memory/source-roots.ts", "../src/storage/ontology/in-memory/materializations.ts", "../src/storage/ontology/in-memory/outbox.ts", "../src/storage/ontology/in-memory/sources.ts", "../src/storage/ontology/in-memory/testing.ts", "../src/storage/ontology/in-memory/vector-indexing.ts", "../src/storage/ontology/in-memory/vectors.ts", "../src/storage/ontology/in-memory/index.ts", "../src/storage/run-listing.ts", "../src/storage/pipeline-runs/types.ts", "../src/storage/pipeline-runs/in-memory.ts", "../src/storage/projection-runs/in-memory.ts", "../src/storage/rules/in-memory.ts", "../src/storage/share-grants/in-memory.ts", "../src/storage/share-sessions/in-memory.ts", "../src/storage/sync-runs/types.ts", "../src/storage/sync-runs/in-memory.ts", "../src/storage/webhook-runs/types.ts", "../src/storage/webhook-runs/in-memory.ts", "../src/storage/workflow-interventions/errors.ts", "../src/storage/workflow-interventions/in-memory.ts", "../src/storage/workflow-runs/types.ts", "../src/storage/workflow-runs/in-memory.ts", "../src/storage/in-memory/testing.ts", "../src/storage/migrations/migrate-storage.ts", "../src/storage/migrations/check-schema.ts", "../src/storage/migrations/migration-set.ts", "../src/storage/ontology/vector-indexing.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import type { ExecutionStorage } from \"../executions\"\nimport { ActionRunError } from \"./errors\"\nimport { parseActionRunFailure } from \"./failure\"\nimport {\n actionRunPhaseRecordsEqual,\n actionSubjectsEqual,\n canRequeueActionRunAfterEnqueueFailure,\n isTerminalActionRun,\n} from \"./idempotency\"\nimport { assertActionRunExecution } from \"./provider\"\nimport type {\n ActionRunEffectsRecord,\n ActionRunFailure,\n ActionRunParams,\n ActionRunPhase,\n ActionRunRecord,\n ActionRunStorage,\n ActionRunWritebackRecord,\n EnterActionRunPhaseInput,\n FinishActionRunInput,\n ListActionRunsInput,\n ListActionRunsResult,\n LockActionMaterializationRunInput,\n QueueActionRunInput,\n RecordActionEffectsInput,\n RecordActionWritebackInput,\n StartActionRunInput,\n} from \"./types\"\n\ntype RunRootOperation = <T>(run: () => Promise<T> | T) => Promise<T>\n\nconst runDirectly: RunRootOperation = async <T>(run: () => Promise<T> | T): Promise<T> => run()\n\nfunction actionRunKey(projectId: string, id: string): string {\n return JSON.stringify([projectId, id])\n}\n\nfunction assertNonBlank(value: string, fieldName: string): void {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new ActionRunError(`[Sixb] Action materialization ${fieldName} must be nonblank.`)\n }\n}\n\nfunction cloneActionRunRecord(record: ActionRunRecord): ActionRunRecord {\n return structuredClone(record)\n}\n\nfunction normalizeParams(params: ActionRunParams): ActionRunParams {\n return structuredClone(params)\n}\n\nfunction normalizeSubject(subject: QueueActionRunInput[\"subject\"]): QueueActionRunInput[\"subject\"] {\n return structuredClone(subject)\n}\n\nfunction normalizeError<TPhase extends ActionRunPhase>(\n error: ActionRunFailure<TPhase>,\n expectedPhase?: TPhase\n): ActionRunFailure<TPhase> {\n return expectedPhase === undefined\n ? (parseActionRunFailure(error) as ActionRunFailure<TPhase>)\n : parseActionRunFailure(error, expectedPhase)\n}\n\nfunction normalizeWriteback(\n input: RecordActionWritebackInput,\n completedAt: Date\n): ActionRunWritebackRecord {\n if (input.status === \"succeeded\") {\n return {\n status: \"succeeded\",\n completedAt,\n result: structuredClone(input.result),\n }\n }\n\n return {\n status: \"failed\",\n completedAt,\n error: normalizeError(input.error, \"writeback\"),\n }\n}\n\nfunction normalizeEffects(\n input: RecordActionEffectsInput,\n completedAt: Date\n): ActionRunEffectsRecord {\n if (input.status === \"succeeded\") {\n return {\n status: \"succeeded\",\n completedAt,\n }\n }\n\n return {\n status: \"failed\",\n completedAt,\n error: normalizeError(input.error, \"effects\"),\n }\n}\n\nfunction compareRuns(a: ActionRunRecord, b: ActionRunRecord, order: \"asc\" | \"desc\"): number {\n const leftAt = a.startedAt ?? a.queuedAt\n const rightAt = b.startedAt ?? b.queuedAt\n const delta = leftAt.getTime() - rightAt.getTime()\n if (delta !== 0) {\n return order === \"asc\" ? delta : -delta\n }\n\n if (a.id === b.id) {\n return 0\n }\n\n return order === \"asc\" ? a.id.localeCompare(b.id) : b.id.localeCompare(a.id)\n}\n\nexport class InMemoryActionRunStorage implements ActionRunStorage {\n private readonly rows = new Map<string, ActionRunRecord>()\n private readonly runRootOperation: RunRootOperation\n\n constructor(\n private readonly executions: ExecutionStorage,\n input: { readonly runRootOperation?: RunRootOperation } = {}\n ) {\n this.runRootOperation = input.runRootOperation ?? runDirectly\n }\n\n snapshot(): InMemoryActionRunStorageSnapshot {\n return structuredClone(this.rows)\n }\n\n restore(snapshot: InMemoryActionRunStorageSnapshot): void {\n this.rows.clear()\n for (const [key, record] of structuredClone(snapshot)) {\n this.rows.set(key, record)\n }\n }\n\n async lockForMaterialization(input: LockActionMaterializationRunInput): Promise<ActionRunRecord> {\n return this.runRootOperation(() => cloneActionRunRecord(this.requireMaterializationRun(input)))\n }\n\n async queue(input: QueueActionRunInput): Promise<ActionRunRecord> {\n return this.runRootOperation(async () => {\n const key = actionRunKey(input.projectId, input.id)\n const existing = this.rows.get(key)\n if (existing && !canRequeueActionRunAfterEnqueueFailure(existing, input)) {\n throw new ActionRunError(\n `[Sixb] Action run '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n if (\n [...this.rows.values()].some(\n (run) =>\n run.projectId === input.projectId &&\n run.id !== input.id &&\n run.executionId === input.executionId\n )\n ) {\n throw new ActionRunError(\n `[Sixb] Execution '${input.executionId}' already belongs to another Action run.`\n )\n }\n await assertActionRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n actionId: input.actionId,\n })\n\n const record: ActionRunRecord = {\n id: input.id,\n projectId: input.projectId,\n executionId: input.executionId,\n actionId: input.actionId,\n subject: normalizeSubject(input.subject),\n status: \"queued\",\n phase: \"request\",\n queuedAt: new Date(input.queuedAt ?? new Date()),\n params: normalizeParams(input.params),\n idempotencyKey: input.idempotencyKey,\n }\n\n if (existing) {\n const next: ActionRunRecord = {\n ...existing,\n status: \"queued\",\n phase: \"request\",\n queuedAt: record.queuedAt,\n startedAt: undefined,\n finishedAt: undefined,\n error: undefined,\n writeback: undefined,\n effects: undefined,\n }\n this.rows.set(key, structuredClone(next))\n return cloneActionRunRecord(next)\n }\n\n this.rows.set(key, structuredClone(record))\n return cloneActionRunRecord(record)\n })\n }\n\n async start(input: StartActionRunInput): Promise<ActionRunRecord> {\n return this.runRootOperation(() => {\n const key = actionRunKey(input.projectId, input.id)\n const existing = this.rows.get(key)\n\n if (!existing) {\n throw new ActionRunError(\n `[Sixb] Action run '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n\n if (existing.status !== \"queued\") {\n throw new ActionRunError(\n `[Sixb] Action run '${input.id}' cannot start from status '${existing.status}'.`\n )\n }\n\n const next: ActionRunRecord = {\n ...existing,\n status: \"running\",\n phase: input.phase ?? \"validation\",\n startedAt: new Date(input.startedAt ?? new Date()),\n error: undefined,\n }\n\n this.rows.set(key, structuredClone(next))\n return cloneActionRunRecord(next)\n })\n }\n\n async enterPhase(input: EnterActionRunPhaseInput): Promise<ActionRunRecord> {\n return this.runRootOperation(() => {\n const key = actionRunKey(input.projectId, input.id)\n const existing = this.requireRunningRun(key, input.projectId, input.id, \"enter phase\")\n const next: ActionRunRecord = {\n ...existing,\n phase: input.phase,\n }\n\n this.rows.set(key, structuredClone(next))\n return cloneActionRunRecord(next)\n })\n }\n\n async recordWriteback(input: RecordActionWritebackInput): Promise<ActionRunRecord> {\n return this.runRootOperation(() => {\n const key = actionRunKey(input.projectId, input.id)\n const existing = this.requireRunningRun(key, input.projectId, input.id, \"record writeback\")\n const writeback = normalizeWriteback(input, new Date(input.completedAt ?? new Date()))\n\n if (existing.writeback) {\n if (actionRunPhaseRecordsEqual(existing.writeback, writeback)) {\n return cloneActionRunRecord(existing)\n }\n\n throw new ActionRunError(\n `[Sixb] Action run '${input.id}' already has a different writeback record.`\n )\n }\n\n const next: ActionRunRecord = {\n ...existing,\n phase: \"writeback\",\n writeback,\n }\n\n this.rows.set(key, structuredClone(next))\n return cloneActionRunRecord(next)\n })\n }\n\n async recordEffects(input: RecordActionEffectsInput): Promise<ActionRunRecord> {\n return this.runRootOperation(() => {\n const key = actionRunKey(input.projectId, input.id)\n const existing = this.requireRunningRun(key, input.projectId, input.id, \"record effects\")\n const effects = normalizeEffects(input, new Date(input.completedAt ?? new Date()))\n\n if (existing.effects) {\n if (actionRunPhaseRecordsEqual(existing.effects, effects)) {\n return cloneActionRunRecord(existing)\n }\n\n throw new ActionRunError(\n `[Sixb] Action run '${input.id}' already has a different effects record.`\n )\n }\n\n const next: ActionRunRecord = {\n ...existing,\n phase: \"effects\",\n effects,\n }\n\n this.rows.set(key, structuredClone(next))\n return cloneActionRunRecord(next)\n })\n }\n\n async finish(input: FinishActionRunInput): Promise<ActionRunRecord> {\n return this.runRootOperation(() => {\n const key = actionRunKey(input.projectId, input.id)\n const existing = this.rows.get(key)\n\n if (!existing) {\n throw new ActionRunError(\n `[Sixb] Action run '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n\n if (isTerminalActionRun(existing)) {\n throw new ActionRunError(\n `[Sixb] Action run '${input.id}' cannot finish from terminal status '${existing.status}'.`\n )\n }\n\n const phase =\n input.status === \"succeeded\" ? (input.phase ?? existing.phase) : input.error.details.phase\n\n const base: ActionRunRecord = {\n ...existing,\n status: input.status,\n phase,\n finishedAt: new Date(input.finishedAt ?? new Date()),\n }\n\n const next: ActionRunRecord =\n input.status === \"succeeded\"\n ? {\n ...base,\n error: undefined,\n }\n : {\n ...base,\n error: normalizeError(input.error),\n }\n\n this.rows.set(key, structuredClone(next))\n return cloneActionRunRecord(next)\n })\n }\n\n private requireRunningRun(\n key: string,\n projectId: string,\n id: string,\n operation: string\n ): ActionRunRecord {\n const existing = this.rows.get(key)\n\n if (!existing) {\n throw new ActionRunError(`[Sixb] Action run '${id}' not found for project '${projectId}'.`)\n }\n\n if (existing.status !== \"running\") {\n throw new ActionRunError(\n `[Sixb] Action run '${id}' cannot ${operation} from status '${existing.status}'.`\n )\n }\n\n return existing\n }\n\n async getById(params: { projectId: string; id: string }): Promise<ActionRunRecord | null> {\n return this.runRootOperation(() => {\n const record = this.rows.get(actionRunKey(params.projectId, params.id))\n return record ? cloneActionRunRecord(record) : null\n })\n }\n\n async list(input: ListActionRunsInput): Promise<ListActionRunsResult> {\n return this.runRootOperation(() => {\n if (input.actionIds?.length === 0) {\n return { runs: [], hasMore: false, total: 0 }\n }\n\n const order = input.order ?? \"desc\"\n const offset = input.offset ?? 0\n const limit = input.limit ?? this.rows.size\n const actionIds = input.actionIds ? new Set(input.actionIds) : null\n const objectTypeIds = input.objectTypeIds ? new Set(input.objectTypeIds) : null\n const statuses = input.statuses ? new Set(input.statuses) : null\n\n const filtered = [...this.rows.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) => (input.actionId ? record.actionId === input.actionId : true))\n .filter((record) => (actionIds ? actionIds.has(record.actionId) : true))\n .filter((record) =>\n objectTypeIds\n ? record.subject.kind !== \"object\" || objectTypeIds.has(record.subject.objectTypeId)\n : true\n )\n .filter((record) =>\n input.subject ? actionSubjectsEqual(record.subject, input.subject) : true\n )\n .filter((record) =>\n input.objectTypeId\n ? record.subject.kind === \"object\" && record.subject.objectTypeId === input.objectTypeId\n : true\n )\n .filter((record) =>\n input.primaryId\n ? record.subject.kind === \"object\" && record.subject.primaryId === input.primaryId\n : true\n )\n .filter((record) => (statuses ? statuses.has(record.status) : true))\n .filter((record) =>\n input.startedAfter ? (record.startedAt ?? record.queuedAt) >= input.startedAfter : true\n )\n .filter((record) =>\n input.startedBefore ? (record.startedAt ?? record.queuedAt) <= input.startedBefore : true\n )\n .sort((a, b) => compareRuns(a, b, order))\n\n const total = filtered.length\n const runs = filtered.slice(offset, offset + limit).map(cloneActionRunRecord)\n return { runs, hasMore: offset + runs.length < total, total }\n })\n }\n\n private requireMaterializationRun(input: LockActionMaterializationRunInput): ActionRunRecord {\n assertNonBlank(input.projectId, \"projectId\")\n assertNonBlank(input.runId, \"runId\")\n assertNonBlank(input.actionId, \"actionId\")\n\n const existing = this.rows.get(actionRunKey(input.projectId, input.runId))\n if (!existing) {\n throw new ActionRunError(\n `[Sixb] Action run '${input.runId}' not found for project '${input.projectId}'.`\n )\n }\n if (existing.actionId !== input.actionId) {\n throw new ActionRunError(\n `[Sixb] Action run '${input.runId}' does not belong to action '${input.actionId}'.`\n )\n }\n if (existing.status !== \"running\") {\n throw new ActionRunError(\n `[Sixb] Action run '${input.runId}' cannot materialize from status '${existing.status}'.`\n )\n }\n return existing\n }\n}\n\nexport type InMemoryActionRunStorageSnapshot = Map<string, ActionRunRecord>\n",
|
|
6
|
+
"import type { FileRef } from \"../blob-storage\"\nimport type { JsonValue } from \"../json\"\nimport type { ProviderData } from \"../models\"\nimport type { AgentContextPart } from \"./context/entries\"\n\n/**\n * The agent's own, SDK-independent message. We store messages and threads — not an SDK transport —\n * so a message is just a `role` plus structured `parts` (and optional `metadata`). There is no\n * self-describing wrapper: the storage row owns the message's identity, and `contentVersion` (a\n * column) versions the parts shape so it can be migrated.\n *\n * The part union is intentionally focused on what agent runs actually produce (text, reasoning, step\n * boundaries, tool calls). The model loop validates and normalizes output before its steps are\n * projected into this union; storage validates the durable write contract independently.\n */\nexport const AGENT_MESSAGE_CONTENT_VERSION = 2 as const\n\nexport type AgentMessageRole = \"system\" | \"user\" | \"assistant\"\n\n/** A plain text part (assistant output, user input, or system text). */\nexport interface AgentTextPart {\n readonly type: \"text\"\n readonly text: string\n /** Provider passthrough (kept because some providers require it on the next turn). */\n readonly providerMetadata?: ProviderData\n}\n\n/**\n * A reasoning (\"thinking\") part. `providerMetadata` is load-bearing here: some providers require\n * the reasoning signature back on the following turn, so dropping it would break multi-step loops.\n */\nexport interface AgentReasoningPart {\n readonly type: \"reasoning\"\n readonly text: string\n readonly providerMetadata?: ProviderData\n}\n\n/** A step boundary between assistant loop iterations. */\nexport interface AgentStepStartPart {\n readonly type: \"step-start\"\n}\n\n/** A blob-backed file attached to a user message or produced by an agent/tool. */\nexport interface AgentFilePart {\n readonly type: \"file\"\n readonly fileRef: FileRef\n /** Provider passthrough for future model-specific file handling. */\n readonly providerMetadata?: ProviderData\n}\n\ninterface AgentToolCallBase {\n readonly type: \"tool-call\"\n readonly toolCallId: string\n readonly toolName: string\n /** `true` when the model identifies the call as a dynamic tool. */\n readonly dynamic?: boolean\n /** `true` when the provider executed the tool inline (steers model projection). */\n readonly providerExecuted?: boolean\n readonly input: JsonValue\n readonly providerMetadata?: ProviderData\n}\n\n/** Ordered, hidden provider state required to replay a model response losslessly. */\nexport interface AgentProviderStatePart {\n readonly type: \"provider-state\"\n readonly providerId: string\n readonly data: JsonValue\n}\n\n/**\n * A completed tool call. Only terminal states are modelled — transient states\n * (`input-streaming`, `input-available`, `approval-*`) are never persisted because messages are\n * written only once a run finishes.\n */\nexport type AgentToolCallPart = AgentToolCallBase &\n (\n | { readonly state: \"output-available\"; readonly output: JsonValue }\n | { readonly state: \"output-error\"; readonly errorText: string }\n )\n\nexport type AgentMessagePart =\n | AgentTextPart\n | AgentReasoningPart\n | AgentStepStartPart\n | AgentFilePart\n | AgentContextPart\n | AgentToolCallPart\n | AgentProviderStatePart\n\nexport type AgentMessagePartType = AgentMessagePart[\"type\"]\nexport type AgentToolCallState = AgentToolCallPart[\"state\"]\n\n/** The logical agent message the adapters speak and the store persists (as columns). */\nexport interface AgentMessage {\n readonly role: AgentMessageRole\n readonly parts: readonly AgentMessagePart[]\n /** Optional JSON metadata associated with the message. */\n readonly metadata?: JsonValue\n}\n",
|
|
7
|
+
"import { AGENT_MESSAGE_CONTENT_VERSION } from \"../../agents/message\"\nimport { principalsEqual } from \"../../auth\"\nimport { parseSixbFailure } from \"../../errors/internal\"\nimport type { SixbFailure } from \"../../errors/types\"\nimport type { ExecutionStorage } from \"../executions\"\nimport { AgentStorageError } from \"./errors\"\nimport {\n agentContextCheckpointMatchesCreateInput,\n assertAgentContextCheckpointAnchors,\n assertAgentContextCheckpointAuthority,\n assertAgentContextCheckpointReplayState,\n assertAgentRunExecution,\n assertConversationAgentRunSpec,\n assertCreateAgentContextCheckpointInput,\n assertCreateSubagentRunInput,\n assertSubagentRunResult,\n snapshotAgentThreadSandboxParams,\n subagentRunMatchesCreateInput,\n transitionAgentThreadSandbox,\n} from \"./provider\"\nimport type {\n AgentContextCheckpointRecord,\n AgentContextCheckpointStore,\n AgentMessageRecord,\n AgentMessageStore,\n AgentRunFailureCode,\n AgentRunRecord,\n AgentRunStore,\n AgentStorage,\n AgentThreadRecord,\n AgentThreadSandboxState,\n AgentThreadStore,\n AppendAgentMessageInput,\n ConfirmAgentRunExecutionOwnershipInput,\n ConversationAgentRunRecord,\n CreateAgentContextCheckpointInput,\n CreateAgentRunInput,\n CreateAgentThreadInput,\n CreateSubagentRunInput,\n DeleteAgentMessagesByRunInput,\n FinishAgentRunInput,\n FinishQueuedAgentRunInput,\n ListAgentMessagesInput,\n ListAgentMessagesResult,\n ListAgentRunsInput,\n ListAgentRunsResult,\n ListAgentThreadsInput,\n ListAgentThreadsResult,\n ReclaimAgentRunInput,\n StartAgentRunInput,\n SubagentRunRecord,\n TransitionAgentThreadSandboxInput,\n} from \"./types\"\nimport { AGENT_RUN_FAILURE_CODES } from \"./types\"\n\nfunction normalizeFailure(\n failure: SixbFailure<AgentRunFailureCode> | undefined\n): SixbFailure<AgentRunFailureCode> | undefined {\n return failure ? parseSixbFailure(failure, AGENT_RUN_FAILURE_CODES) : undefined\n}\n\nfunction key(projectId: string, id: string): string {\n return JSON.stringify([projectId, id])\n}\n\nfunction clone<T>(value: T): T {\n return structuredClone(value)\n}\n\nfunction compareByDate(\n left: Date | undefined,\n right: Date | undefined,\n leftId: string,\n rightId: string,\n order: \"asc\" | \"desc\"\n): number {\n const delta = (left?.getTime() ?? 0) - (right?.getTime() ?? 0)\n if (delta !== 0) {\n return order === \"asc\" ? delta : -delta\n }\n if (leftId === rightId) {\n return 0\n }\n return order === \"asc\" ? leftId.localeCompare(rightId) : rightId.localeCompare(leftId)\n}\n\ninterface Window<T> {\n readonly page: T[]\n readonly hasMore: boolean\n readonly total: number\n}\n\nfunction applyWindow<T>(rows: T[], offset = 0, limit?: number): Window<T> {\n const total = rows.length\n const end = limit === undefined ? total : offset + limit\n const page = rows.slice(offset, end)\n return { page, hasMore: offset + page.length < total, total }\n}\n\n/**\n * Shared in-memory state behind the four sub-stores. They are tiered for ergonomics\n * (`storage.runs.create(...)`), but several operations span tables — creating/finishing a run\n * updates the thread anchor, appending a message bumps thread stats, and checkpoint creation reads\n * run/thread/message anchors — so they all read and write the same maps through this object.\n */\ninterface AgentStoreState {\n readonly threads: Map<string, AgentThreadRecord>\n readonly runs: Map<string, AgentRunRecord>\n readonly messages: Map<string, AgentMessageRecord>\n readonly checkpoints: Map<string, AgentContextCheckpointRecord>\n}\n\nexport interface InMemoryAgentStorageSnapshot {\n readonly threads: Map<string, AgentThreadRecord>\n readonly runs: Map<string, AgentRunRecord>\n readonly messages: Map<string, AgentMessageRecord>\n readonly checkpoints: Map<string, AgentContextCheckpointRecord>\n}\n\n// ── threads ───────────────────────────────────────────────────────────────────────────────────\n\nclass InMemoryAgentThreadStore implements AgentThreadStore {\n constructor(private readonly state: AgentStoreState) {}\n\n async transitionSandbox(\n input: TransitionAgentThreadSandboxInput\n ): Promise<AgentThreadSandboxState> {\n const threadKey = key(input.projectId, input.id)\n const thread = this.state.threads.get(threadKey) ?? null\n const run =\n input.action === \"recreate\"\n ? null\n : (this.state.runs.get(key(input.projectId, input.runId)) ?? null)\n const sandboxState = transitionAgentThreadSandbox(thread, run, input)\n if (!thread) throw new AgentStorageError(\"thread_not_found\", \"[Sixb] Thread not found.\")\n this.state.threads.set(threadKey, { ...thread, sandboxState: clone(sandboxState) })\n return clone(sandboxState)\n }\n\n async create(input: CreateAgentThreadInput): Promise<AgentThreadRecord> {\n const sandboxParams =\n input.sandboxParams === undefined\n ? undefined\n : snapshotAgentThreadSandboxParams(input.sandboxParams)\n const threadKey = key(input.projectId, input.id)\n if (this.state.threads.has(threadKey)) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[Sixb] Agent thread '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n const createdAt = new Date(input.createdAt ?? new Date())\n const record: AgentThreadRecord = {\n id: input.id,\n projectId: input.projectId,\n ownerPrincipal: clone(input.ownerPrincipal),\n ...(sandboxParams === undefined ? {} : { sandboxParams }),\n ...(input.title === undefined ? {} : { title: input.title }),\n status: input.status ?? \"active\",\n activeRunId: null,\n messageCount: 0,\n createdAt,\n updatedAt: new Date(input.updatedAt ?? createdAt),\n }\n\n this.state.threads.set(threadKey, clone(record))\n return clone(record)\n }\n\n async getById(params: { projectId: string; id: string }): Promise<AgentThreadRecord | null> {\n const record = this.state.threads.get(key(params.projectId, params.id))\n return record ? clone(record) : null\n }\n\n async list(input: ListAgentThreadsInput): Promise<ListAgentThreadsResult> {\n const order = input.order ?? \"desc\"\n const statuses = input.statuses ? new Set(input.statuses) : null\n const filtered = [...this.state.threads.values()]\n .filter((thread) => thread.projectId === input.projectId)\n .filter((thread) => (statuses ? statuses.has(thread.status) : true))\n .filter((thread) =>\n input.ownerPrincipal ? principalsEqual(thread.ownerPrincipal, input.ownerPrincipal) : true\n )\n .sort((a, b) =>\n compareByDate(\n a.lastMessageAt ?? a.createdAt,\n b.lastMessageAt ?? b.createdAt,\n a.id,\n b.id,\n order\n )\n )\n\n const { page, hasMore, total } = applyWindow(filtered, input.offset, input.limit)\n return { threads: page.map(clone), hasMore, total }\n }\n}\n\n// ── runs ──────────────────────────────────────────────────────────────────────────────────────\n\nclass InMemoryAgentRunStore implements AgentRunStore {\n constructor(\n private readonly state: AgentStoreState,\n private readonly executions: ExecutionStorage\n ) {}\n\n async create(input: CreateAgentRunInput): Promise<ConversationAgentRunRecord> {\n assertConversationAgentRunSpec(input.spec)\n await assertAgentRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n })\n // No `await` between read and write: the in-memory critical section is atomic, so two concurrent\n // queued runs on the same thread cannot both win — the second observes `activeRunId` set.\n const threadKey = key(input.projectId, input.threadId)\n const thread = this.state.threads.get(threadKey)\n if (!thread) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[Sixb] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`\n )\n }\n if (thread.activeRunId !== null) {\n throw new AgentStorageError(\n \"active_run_exists\",\n `[Sixb] Agent thread '${input.threadId}' already has an active run '${thread.activeRunId}'.`\n )\n }\n\n const runKey = key(input.projectId, input.id)\n if (this.state.runs.has(runKey)) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[Sixb] Agent run '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n if (\n [...this.state.runs.values()].some(\n (run) => run.projectId === input.projectId && run.executionId === input.executionId\n )\n ) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[Sixb] Execution '${input.executionId}' already belongs to another Agent run.`\n )\n }\n\n const createdAt = new Date(input.createdAt ?? new Date())\n const run: ConversationAgentRunRecord = {\n kind: \"conversation\",\n id: input.id,\n projectId: input.projectId,\n executionId: input.executionId,\n threadId: input.threadId,\n triggerMessageId: input.triggerMessageId,\n spec: clone(input.spec),\n status: \"queued\",\n attempt: 0,\n createdAt,\n }\n this.state.runs.set(runKey, clone(run))\n\n const updatedThread: AgentThreadRecord = {\n ...thread,\n activeRunId: run.id,\n updatedAt: createdAt,\n }\n this.state.threads.set(threadKey, clone(updatedThread))\n\n return clone(run)\n }\n\n async createSubagent(input: CreateSubagentRunInput): Promise<SubagentRunRecord> {\n assertCreateSubagentRunInput(input)\n const execution = await assertAgentRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n })\n\n const runKey = key(input.projectId, input.id)\n const existing = this.state.runs.get(runKey)\n if (existing) {\n if (subagentRunMatchesCreateInput(existing, input)) return clone(existing)\n throw new AgentStorageError(\n \"duplicate_id\",\n `[Sixb] Subagent run '${input.id}' already exists with different immutable inputs.`\n )\n }\n\n const parent = this.state.runs.get(key(input.projectId, input.parentRunId))\n if (!parent || parent.kind !== \"conversation\") {\n throw new AgentStorageError(\n \"run_not_found\",\n `[Sixb] Parent Agent run '${input.parentRunId}' was not found.`\n )\n }\n if (parent.status !== \"running\") {\n throw new AgentStorageError(\n \"invalid_state\",\n `[Sixb] Parent Agent run '${parent.id}' is not running (status '${parent.status}').`\n )\n }\n if (\n execution.source.type !== \"execution\" ||\n execution.source.executionId !== parent.executionId\n ) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[Sixb] Subagent execution '${execution.id}' is not a child of parent execution '${parent.executionId}'.`\n )\n }\n if (parent.execution?.token !== input.parentExecutionToken) {\n throw new AgentStorageError(\n \"execution_lost\",\n `[Sixb] Parent Agent run '${parent.id}' is no longer owned by this execution.`\n )\n }\n const activeChildren = [...this.state.runs.values()].filter(\n (run) =>\n run.kind === \"subagent\" &&\n run.projectId === input.projectId &&\n run.parentRunId === parent.id &&\n (run.status === \"queued\" || run.status === \"running\")\n ).length\n if (activeChildren >= input.maxActiveChildren) {\n throw new AgentStorageError(\n \"active_child_limit\",\n `[Sixb] Agent run '${parent.id}' already has ${activeChildren} active subagents.`\n )\n }\n if (\n [...this.state.runs.values()].some(\n (run) => run.projectId === input.projectId && run.executionId === input.executionId\n )\n ) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[Sixb] Execution '${input.executionId}' already belongs to another Agent run.`\n )\n }\n\n const run: SubagentRunRecord = {\n kind: \"subagent\",\n id: input.id,\n projectId: input.projectId,\n executionId: input.executionId,\n parentRunId: input.parentRunId,\n spawnKey: input.spawnKey,\n spec: clone(input.spec),\n status: \"queued\",\n attempt: 0,\n createdAt: new Date(input.createdAt ?? new Date()),\n }\n this.state.runs.set(runKey, clone(run))\n return clone(run)\n }\n\n async start(input: StartAgentRunInput): Promise<AgentRunRecord> {\n const run = this.requireStatus(input.projectId, input.id, \"queued\")\n const startedAt = new Date(input.startedAt ?? new Date())\n const next: AgentRunRecord = {\n ...run,\n status: \"running\",\n ...(input.modelId === undefined ? {} : { modelId: input.modelId }),\n attempt: 1,\n execution: clone(input.execution),\n startedAt,\n }\n this.state.runs.set(key(input.projectId, input.id), clone(next))\n return clone(next)\n }\n\n async finishQueued(input: FinishQueuedAgentRunInput): Promise<AgentRunRecord> {\n const run = this.requireStatus(input.projectId, input.id, \"queued\")\n const completedAt = new Date(input.completedAt ?? new Date())\n const next: AgentRunRecord = {\n ...run,\n status: input.status,\n ...(input.error === undefined ? {} : { error: normalizeFailure(input.error) }),\n completedAt,\n }\n this.state.runs.set(key(input.projectId, input.id), clone(next))\n this.releaseThread(run, completedAt)\n return clone(next)\n }\n\n async reclaim(input: ReclaimAgentRunInput): Promise<AgentRunRecord> {\n const run = this.requireRunning(input.projectId, input.id)\n const next: AgentRunRecord = {\n ...run,\n attempt: run.attempt + 1,\n execution: clone(input.execution),\n }\n this.state.runs.set(key(input.projectId, input.id), clone(next))\n return clone(next)\n }\n\n async confirmExecutionOwnership(\n input: ConfirmAgentRunExecutionOwnershipInput\n ): Promise<AgentRunRecord> {\n const run = this.requireRunning(input.projectId, input.id)\n if (!run.execution || run.execution.token !== input.executionToken) {\n throw new AgentStorageError(\n \"execution_lost\",\n `[Sixb] Execution token is no longer current on agent run '${input.id}'.`\n )\n }\n\n const next: AgentRunRecord = {\n ...run,\n execution: {\n ...run.execution,\n queueLeaseExpiresAt: new Date(\n Math.max(run.execution.queueLeaseExpiresAt.getTime(), input.queueLeaseExpiresAt.getTime())\n ),\n },\n }\n this.state.runs.set(key(input.projectId, input.id), clone(next))\n return clone(next)\n }\n\n async finish(input: FinishAgentRunInput): Promise<AgentRunRecord> {\n const run = this.requireRunning(input.projectId, input.id)\n if (!run.execution || run.execution.token !== input.executionToken) {\n throw new AgentStorageError(\n \"execution_lost\",\n `[Sixb] Execution token is no longer current on agent run '${input.id}'.`\n )\n }\n if (input.status === \"succeeded\" && run.kind === \"subagent\") {\n assertSubagentRunResult(input.result, run.id)\n }\n if (input.status === \"succeeded\" && run.kind === \"conversation\" && input.result !== undefined) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[Sixb] Conversational Agent run '${run.id}' cannot persist a subagent result.`\n )\n }\n\n const completedAt = new Date(input.completedAt ?? new Date())\n const next: AgentRunRecord = {\n ...run,\n status: input.status,\n ...(input.modelId === undefined ? {} : { modelId: input.modelId }),\n ...(input.finishReason === undefined ? {} : { finishReason: input.finishReason }),\n ...(input.diagnostics === undefined ? {} : { diagnostics: clone(input.diagnostics) }),\n ...(input.status === \"succeeded\" && input.result !== undefined\n ? { result: clone(input.result) }\n : {}),\n ...(input.status === \"succeeded\" || input.error === undefined\n ? {}\n : { error: normalizeFailure(input.error) }),\n execution: undefined,\n completedAt,\n }\n this.state.runs.set(key(input.projectId, input.id), clone(next))\n\n this.releaseThread(run, completedAt)\n\n return clone(next)\n }\n\n async getById(params: { projectId: string; id: string }): Promise<AgentRunRecord | null> {\n const record = this.state.runs.get(key(params.projectId, params.id))\n return record ? clone(record) : null\n }\n\n async getByIds(params: {\n projectId: string\n ids: readonly string[]\n }): Promise<readonly AgentRunRecord[]> {\n return [...new Set(params.ids)]\n .map((id) => this.state.runs.get(key(params.projectId, id)))\n .filter((record): record is AgentRunRecord => record !== undefined)\n .map(clone)\n }\n\n async list(input: ListAgentRunsInput): Promise<ListAgentRunsResult> {\n const order = input.order ?? \"desc\"\n const statuses = input.statuses ? new Set(input.statuses) : null\n const kinds = input.kinds ? new Set(input.kinds) : null\n\n const filtered = [...this.state.runs.values()]\n .filter((run) => run.projectId === input.projectId)\n .filter((run) => (kinds ? kinds.has(run.kind) : true))\n .filter((run) =>\n input.threadId ? run.kind === \"conversation\" && run.threadId === input.threadId : true\n )\n .filter((run) =>\n input.parentRunId ? run.kind === \"subagent\" && run.parentRunId === input.parentRunId : true\n )\n .filter((run) => (statuses ? statuses.has(run.status) : true))\n .filter((run) =>\n input.startedAfter ? (run.startedAt ?? run.createdAt) >= input.startedAfter : true\n )\n .filter((run) =>\n input.startedBefore ? (run.startedAt ?? run.createdAt) <= input.startedBefore : true\n )\n .sort((a, b) =>\n compareByDate(a.startedAt ?? a.createdAt, b.startedAt ?? b.createdAt, a.id, b.id, order)\n )\n\n const { page, hasMore, total } = applyWindow(filtered, input.offset, input.limit)\n return { runs: page.map(clone), hasMore, total }\n }\n\n private requireRunning(projectId: string, id: string): AgentRunRecord {\n return this.requireStatus(projectId, id, \"running\")\n }\n\n private requireStatus(\n projectId: string,\n id: string,\n status: AgentRunRecord[\"status\"]\n ): AgentRunRecord {\n const run = this.state.runs.get(key(projectId, id))\n if (!run) {\n throw new AgentStorageError(\n \"run_not_found\",\n `[Sixb] Agent run '${id}' not found for project '${projectId}'.`\n )\n }\n if (run.status !== status) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[Sixb] Agent run '${id}' is not ${status} (status '${run.status}').`\n )\n }\n return run\n }\n\n private releaseThread(run: AgentRunRecord, completedAt: Date): void {\n if (run.kind !== \"conversation\") return\n const threadKey = key(run.projectId, run.threadId)\n const thread = this.state.threads.get(threadKey)\n if (thread && thread.activeRunId === run.id) {\n this.state.threads.set(\n threadKey,\n clone({ ...thread, activeRunId: null, updatedAt: completedAt })\n )\n }\n }\n}\n\n// ── messages ──────────────────────────────────────────────────────────────────────────────────\n\nclass InMemoryAgentMessageStore implements AgentMessageStore {\n constructor(private readonly state: AgentStoreState) {}\n\n async append(input: AppendAgentMessageInput): Promise<AgentMessageRecord> {\n const threadKey = key(input.projectId, input.threadId)\n const thread = this.state.threads.get(threadKey)\n if (!thread) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[Sixb] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`\n )\n }\n\n const messageKey = key(input.projectId, input.id)\n if (this.state.messages.has(messageKey)) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[Sixb] Agent message '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n if (input.runId !== null && !this.state.runs.has(key(input.projectId, input.runId))) {\n throw new AgentStorageError(\n \"run_not_found\",\n `[Sixb] Agent run '${input.runId}' not found for project '${input.projectId}'.`\n )\n }\n\n const createdAt = new Date(input.createdAt ?? new Date())\n const seq = this.nextSeq(input.projectId, input.threadId)\n const message: AgentMessageRecord = {\n id: input.id,\n projectId: input.projectId,\n threadId: input.threadId,\n runId: input.runId,\n role: input.role,\n ...(input.authorPrincipal === undefined\n ? {}\n : { authorPrincipal: clone(input.authorPrincipal) }),\n seq,\n parts: clone(input.parts),\n ...(input.metadata === undefined ? {} : { metadata: clone(input.metadata) }),\n contentVersion: AGENT_MESSAGE_CONTENT_VERSION,\n createdAt,\n ...(input.completedAt === undefined ? {} : { completedAt: new Date(input.completedAt) }),\n }\n this.state.messages.set(messageKey, clone(message))\n\n this.state.threads.set(\n threadKey,\n clone({\n ...thread,\n messageCount: thread.messageCount + 1,\n lastMessageAt: createdAt,\n updatedAt: createdAt,\n })\n )\n\n return clone(message)\n }\n\n async deleteByRunId(input: DeleteAgentMessagesByRunInput): Promise<number> {\n const threadKey = key(input.projectId, input.threadId)\n const thread = this.state.threads.get(threadKey)\n if (!thread) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[Sixb] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`\n )\n }\n\n const messages = [...this.state.messages.entries()].filter(\n ([, message]) =>\n message.projectId === input.projectId &&\n message.threadId === input.threadId &&\n message.runId === input.runId\n )\n if (messages.length === 0) {\n return 0\n }\n\n for (const [messageKey] of messages) {\n this.state.messages.delete(messageKey)\n }\n\n const remainingMessages = [...this.state.messages.values()]\n .filter(\n (message) => message.projectId === input.projectId && message.threadId === input.threadId\n )\n .sort((left, right) => right.seq - left.seq)\n const latestMessage = remainingMessages[0]\n const updatedAt = new Date()\n this.state.threads.set(\n threadKey,\n clone({\n ...thread,\n messageCount: remainingMessages.length,\n lastMessageAt: latestMessage?.createdAt,\n updatedAt,\n })\n )\n\n return messages.length\n }\n\n async getById(params: { projectId: string; id: string }): Promise<AgentMessageRecord | null> {\n const record = this.state.messages.get(key(params.projectId, params.id))\n return record ? clone(record) : null\n }\n\n async list(input: ListAgentMessagesInput): Promise<ListAgentMessagesResult> {\n const order = input.order ?? \"asc\"\n const roles = input.roles ? new Set(input.roles) : null\n\n const filtered = [...this.state.messages.values()]\n .filter((message) => message.projectId === input.projectId)\n .filter((message) => message.threadId === input.threadId)\n .filter((message) => (input.afterSeq === undefined ? true : message.seq > input.afterSeq))\n .filter((message) => (roles ? roles.has(message.role) : true))\n .sort((a, b) => (order === \"asc\" ? a.seq - b.seq : b.seq - a.seq))\n\n const { page, hasMore, total } = applyWindow(filtered, input.offset, input.limit)\n return { messages: page.map(clone), hasMore, total }\n }\n\n private nextSeq(projectId: string, threadId: string): number {\n let max = 0\n for (const message of this.state.messages.values()) {\n if (message.projectId === projectId && message.threadId === threadId && message.seq > max) {\n max = message.seq\n }\n }\n return max + 1\n }\n}\n\n// ── context checkpoints ──────────────────────────────────────────────────────────────────────\n\nclass InMemoryAgentContextCheckpointStore implements AgentContextCheckpointStore {\n constructor(private readonly state: AgentStoreState) {}\n\n async create(input: CreateAgentContextCheckpointInput): Promise<AgentContextCheckpointRecord> {\n assertCreateAgentContextCheckpointInput(input)\n\n // No `await` between authority checks and append: this is one in-memory critical section.\n const run = this.state.runs.get(key(input.projectId, input.createdByRunId)) ?? null\n const thread = this.state.threads.get(key(input.projectId, input.threadId)) ?? null\n assertAgentContextCheckpointAuthority({ create: input, run, thread })\n\n const messages = [...this.state.messages.values()].filter(\n (message) => message.projectId === input.projectId && message.threadId === input.threadId\n )\n const headSeq = messages.reduce((head, message) => Math.max(head, message.seq), 0)\n const latest = this.findLatest(input.projectId, input.threadId)\n\n const existingForRun = [...this.state.checkpoints.values()].find(\n (checkpoint) =>\n checkpoint.projectId === input.projectId &&\n checkpoint.createdByRunId === input.createdByRunId\n )\n if (existingForRun) {\n if (agentContextCheckpointMatchesCreateInput(existingForRun, input)) {\n assertAgentContextCheckpointReplayState({\n create: input,\n existing: existingForRun,\n latest,\n headSeq,\n })\n return clone(existingForRun)\n }\n throw new AgentStorageError(\n \"invalid_state\",\n `[Sixb] Agent run '${input.createdByRunId}' already created a different context checkpoint.`\n )\n }\n\n if (this.state.checkpoints.has(key(input.projectId, input.id))) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[Sixb] Agent context checkpoint '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n const firstRetained =\n messages\n .filter((message) => message.seq > input.summarizedThroughSeq)\n .sort((left, right) => left.seq - right.seq)[0] ?? null\n assertAgentContextCheckpointAnchors({\n create: input,\n latest,\n headSeq,\n firstRetained,\n })\n\n const record: AgentContextCheckpointRecord = {\n id: input.id,\n projectId: input.projectId,\n threadId: input.threadId,\n createdByRunId: input.createdByRunId,\n ...(input.expectedPreviousCheckpointId === null\n ? {}\n : { previousCheckpointId: input.expectedPreviousCheckpointId }),\n reason: input.reason,\n summary: input.summary,\n summaryFormatVersion: input.summaryFormatVersion,\n summarizedThroughSeq: input.summarizedThroughSeq,\n observedHeadSeq: input.observedHeadSeq,\n estimatedInputTokensBefore: input.estimatedInputTokensBefore,\n estimatedInputTokensAfter: input.estimatedInputTokensAfter,\n summaryModelId: input.summaryModelId,\n createdAt: new Date(input.createdAt ?? new Date()),\n }\n this.state.checkpoints.set(key(input.projectId, input.id), clone(record))\n return clone(record)\n }\n\n async getLatest(input: {\n readonly projectId: string\n readonly threadId: string\n }): Promise<AgentContextCheckpointRecord | null> {\n const record = this.findLatest(input.projectId, input.threadId)\n return record ? clone(record) : null\n }\n\n async getByRunIds(input: {\n readonly projectId: string\n readonly runIds: readonly string[]\n }): Promise<readonly AgentContextCheckpointRecord[]> {\n const byRunId = new Map(\n [...this.state.checkpoints.values()]\n .filter((checkpoint) => checkpoint.projectId === input.projectId)\n .map((checkpoint) => [checkpoint.createdByRunId, checkpoint] as const)\n )\n return [...new Set(input.runIds)].flatMap((runId) => {\n const checkpoint = byRunId.get(runId)\n return checkpoint ? [clone(checkpoint)] : []\n })\n }\n\n private findLatest(projectId: string, threadId: string): AgentContextCheckpointRecord | null {\n return (\n [...this.state.checkpoints.values()]\n .filter(\n (checkpoint) => checkpoint.projectId === projectId && checkpoint.threadId === threadId\n )\n .sort(\n (left, right) =>\n right.summarizedThroughSeq - left.summarizedThroughSeq ||\n right.createdAt.getTime() - left.createdAt.getTime() ||\n right.id.localeCompare(left.id)\n )[0] ?? null\n )\n }\n}\n\nexport class InMemoryAgentStorage implements AgentStorage {\n private readonly state: AgentStoreState = {\n threads: new Map(),\n runs: new Map(),\n messages: new Map(),\n checkpoints: new Map(),\n }\n\n readonly threads: InMemoryAgentThreadStore\n readonly runs: InMemoryAgentRunStore\n readonly messages: InMemoryAgentMessageStore\n readonly checkpoints: InMemoryAgentContextCheckpointStore\n\n constructor(executions: ExecutionStorage) {\n this.threads = new InMemoryAgentThreadStore(this.state)\n this.runs = new InMemoryAgentRunStore(this.state, executions)\n this.messages = new InMemoryAgentMessageStore(this.state)\n this.checkpoints = new InMemoryAgentContextCheckpointStore(this.state)\n }\n\n snapshot(): InMemoryAgentStorageSnapshot {\n return {\n threads: structuredClone(this.state.threads),\n runs: structuredClone(this.state.runs),\n messages: structuredClone(this.state.messages),\n checkpoints: structuredClone(this.state.checkpoints),\n }\n }\n\n restore(snapshot: InMemoryAgentStorageSnapshot): void {\n replace(this.state.threads, snapshot.threads)\n replace(this.state.runs, snapshot.runs)\n replace(this.state.messages, snapshot.messages)\n replace(this.state.checkpoints, snapshot.checkpoints)\n }\n}\n\nfunction replace<T>(target: Map<string, T>, source: Map<string, T>): void {\n target.clear()\n for (const [k, value] of structuredClone(source)) {\n target.set(k, value)\n }\n}\n",
|
|
8
|
+
"export type AiCostStorageErrorCode = \"missing_usage\" | \"cost_mismatch\"\n\nexport class AiCostStorageError extends Error {\n readonly name = \"AiCostStorageError\"\n\n constructor(\n readonly code: AiCostStorageErrorCode,\n message: string\n ) {\n super(message)\n }\n}\n",
|
|
9
|
+
"import type { AiModelCallUsageRecord, InMemoryAiUsageStorageSnapshot } from \"../ai-usage\"\nimport type { AiAccountingRecordSetItem } from \"./analytics\"\nimport { buildAiAccountingOverview, buildAiModelCallAccountingList } from \"./analytics\"\nimport { AiCostStorageError } from \"./errors\"\nimport { type AiAccountingGroupIdentity, buildAiModelCallGroups } from \"./groups\"\nimport type {\n AiAccountingAttribution,\n AiAccountingOverview,\n AiCostStorage,\n AiCostSummary,\n AiModelCallCostRecord,\n AiMoney,\n ListAiModelCallAccountingInput,\n ListAiModelCallAccountingResult,\n ListAiModelCallGroupsInput,\n ListAiModelCallGroupsResult,\n QueryAiAccountingOverviewInput,\n SummarizeAiCostExecutionsInput,\n} from \"./types\"\nimport { aiModelCallCostMatchesUsage, normalizeAiModelCallCostRecord } from \"./validation\"\n\nexport interface InMemoryAiCostStorageSnapshot {\n readonly recordsByUsage: Map<string, AiModelCallCostRecord>\n}\n\ninterface InMemoryAiCostUsageSource {\n snapshot(): InMemoryAiUsageStorageSnapshot\n}\n\nexport interface InMemoryAiAccountingAttributionSource {\n resolveGroup?(input: {\n readonly projectId: string\n readonly executionId: string\n }): Promise<{ readonly executionId: string; readonly attribution?: AiAccountingAttribution }>\n resolve(input: {\n readonly projectId: string\n readonly executionId: string\n }): Promise<AiAccountingAttribution | undefined>\n}\n\n/** In-memory immutable model-call costs and accounting reads. */\nexport class InMemoryAiCostStorage implements AiCostStorage {\n private readonly recordsByUsage = new Map<string, AiModelCallCostRecord>()\n\n constructor(\n private readonly usage: InMemoryAiCostUsageSource,\n private readonly attribution?: InMemoryAiAccountingAttributionSource\n ) {}\n\n async recordModelCallCost(input: AiModelCallCostRecord): Promise<void> {\n const record = normalizeAiModelCallCostRecord(input)\n const usage = this.usageRecord(record.projectId, record.usageRecordId)\n if (!usage) throw missingUsage(record)\n if (!aiModelCallCostMatchesUsage(record, usage)) {\n throw new AiCostStorageError(\n \"cost_mismatch\",\n `[Sixb] AI valuation for usage '${record.usageRecordId}' does not match its usage record.`\n )\n }\n const key = usageRecordKey(record.projectId, record.usageRecordId)\n if (!this.recordsByUsage.has(key)) this.recordsByUsage.set(key, structuredClone(record))\n }\n\n async summarizeExecutions(\n input: SummarizeAiCostExecutionsInput\n ): Promise<readonly AiCostSummary[]> {\n assertNonBlank(input.projectId, \"cost summary projectId\")\n for (const id of input.executionIds) assertNonBlank(id, \"cost summary executionId\")\n const requested = new Set(input.executionIds)\n const usageByExecution = new Map(input.executionIds.map((id) => [id, [] as string[]]))\n for (const usage of this.usage.snapshot().records.values()) {\n if (usage.projectId === input.projectId && requested.has(usage.executionId)) {\n usageByExecution.get(usage.executionId)!.push(usage.id)\n }\n }\n return input.executionIds.map((id) =>\n this.summarizeUsageIds(input.projectId, usageByExecution.get(id) ?? [])\n )\n }\n\n async queryProjectOverview(input: QueryAiAccountingOverviewInput): Promise<AiAccountingOverview> {\n return buildAiAccountingOverview(input, await this.accountingItems())\n }\n\n async listModelCalls(\n input: ListAiModelCallAccountingInput\n ): Promise<ListAiModelCallAccountingResult> {\n return buildAiModelCallAccountingList(input, await this.accountingItems())\n }\n\n snapshot(): InMemoryAiCostStorageSnapshot {\n return structuredClone({ recordsByUsage: this.recordsByUsage })\n }\n\n async listModelCallGroups(\n input: ListAiModelCallGroupsInput\n ): Promise<ListAiModelCallGroupsResult> {\n const items = await this.accountingItems()\n const roots = new Map<string, Promise<AiAccountingGroupIdentity>>()\n return buildAiModelCallGroups(\n input,\n await Promise.all(\n items.map(async (item) => {\n const key = usageRecordKey(item.usage.projectId, item.usage.executionId)\n let root = roots.get(key)\n if (!root) {\n root =\n this.attribution?.resolveGroup?.({\n projectId: item.usage.projectId,\n executionId: item.usage.executionId,\n }) ??\n Promise.resolve({\n executionId: item.usage.executionId,\n attribution: item.attribution,\n })\n roots.set(key, root)\n }\n return { ...item, root: await root }\n })\n )\n )\n }\n\n restore(snapshot: InMemoryAiCostStorageSnapshot): void {\n replaceMap(this.recordsByUsage, snapshot.recordsByUsage)\n }\n\n /** @internal Immutable accounting source used by in-memory AI limit enforcement. */\n getRecord(projectId: string, usageRecordId: string): AiModelCallCostRecord | null {\n const record = this.recordsByUsage.get(usageRecordKey(projectId, usageRecordId))\n return record ? structuredClone(record) : null\n }\n\n private usageRecord(projectId: string, id: string): AiModelCallUsageRecord | undefined {\n return [...this.usage.snapshot().records.values()].find(\n (record) => record.projectId === projectId && record.id === id\n )\n }\n\n private async accountingItems(): Promise<readonly AiAccountingRecordSetItem[]> {\n return Promise.all(\n [...this.usage.snapshot().records.values()].map(async (usage) => {\n const cost = this.recordsByUsage.get(usageRecordKey(usage.projectId, usage.id))\n const attribution = await this.attribution?.resolve({\n projectId: usage.projectId,\n executionId: usage.executionId,\n })\n return {\n usage,\n ...(attribution ? { attribution } : {}),\n ...(cost ? { cost } : {}),\n }\n })\n )\n }\n\n private summarizeUsageIds(projectId: string, ids: readonly string[]): AiCostSummary {\n const amounts = new Map<string, bigint>()\n let ratedCallCount = 0\n let unpriceableCallCount = 0\n let unvaluedCallCount = 0\n for (const id of ids) {\n const cost = this.recordsByUsage.get(usageRecordKey(projectId, id))\n if (!cost) unvaluedCallCount += 1\n else if (cost.status === \"unpriceable\") unpriceableCallCount += 1\n else {\n ratedCallCount += 1\n addMoney(amounts, cost.money)\n }\n }\n return {\n amounts: [...amounts]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([currency, amount]) => ({ currency, amountNanos: amount.toString() })),\n ratedCallCount,\n unpriceableCallCount,\n unvaluedCallCount,\n }\n }\n}\n\nfunction missingUsage(record: { readonly projectId: string; readonly usageRecordId: string }) {\n return new AiCostStorageError(\n \"missing_usage\",\n `[Sixb] AI usage '${record.usageRecordId}' does not exist in project '${record.projectId}'.`\n )\n}\n\nfunction addMoney(amounts: Map<string, bigint>, money: AiMoney): void {\n amounts.set(money.currency, (amounts.get(money.currency) ?? 0n) + BigInt(money.amountNanos))\n}\n\nfunction usageRecordKey(projectId: string, id: string): string {\n return JSON.stringify([projectId, id])\n}\n\nfunction assertNonBlank(value: string, field: string): void {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new TypeError(`[Sixb] AI ${field} must be nonblank.`)\n }\n}\n\nfunction replaceMap<TKey, TValue>(target: Map<TKey, TValue>, source: Map<TKey, TValue>): void {\n target.clear()\n for (const [key, value] of structuredClone(source)) target.set(key, value)\n}\n",
|
|
10
|
+
"import type { AiModelCallCostRecord } from \"../ai-cost\"\nimport type { AiModelCallUsageRecord } from \"../ai-usage\"\nimport type { ExecutionRecord } from \"../executions\"\nimport { AiLimitStorageError } from \"./errors\"\nimport { aiLimitCalendarMonth } from \"./period\"\nimport type { AiLimitAccountingEntry } from \"./provider\"\nimport {\n AiLimitOperationLock,\n aiLimitAccountingEntryAppliesToSubject,\n aiLimitAmountKey,\n aiLimitPolicyDimensionKey,\n aiLimitQuantityFromAmount,\n aiLimitReservationBuckets,\n aiLimitReservationRequestKey,\n aiLimitReservationRequestMatches,\n aiLimitSubjectKey,\n aiLimitSubjectsFromAccountingEntry,\n aiModelCallReservationKey,\n assertAiLimitAccountingMatchesReservation,\n assertNonBlank,\n cloneAiLimitPolicy,\n cloneValidDate,\n type NormalizedAiLimitAmount,\n normalizeAiLimitAmount,\n normalizeAiModelCallReservationIdentity,\n normalizeCreateAiLimitPolicy,\n normalizeReserveAiModelCall,\n normalizeUpdateAiLimitPolicy,\n resolveAiLimitActual,\n} from \"./provider\"\nimport type {\n AiLimitPeriod,\n AiLimitPolicy,\n AiLimitPolicyStatus,\n AiLimitQuantity,\n AiLimitStorage,\n AiLimitSubject,\n AiModelCallReservation,\n CreateAiLimitPolicyInput,\n DeleteAiLimitPolicyInput,\n GetAiLimitPolicyInput,\n ListAiLimitPoliciesInput,\n ListAiLimitPolicyStatusesInput,\n MarkAiModelCallReservationUnknownInput,\n ReconcileAiModelCallInput,\n RecordAiModelCallLimitActualsInput,\n ReserveAiModelCallInput,\n ReserveAiModelCallResult,\n UpdateAiLimitPolicyInput,\n} from \"./types\"\n\ninterface AiLimitPeriodState {\n readonly projectId: string\n readonly subject: AiLimitSubject\n readonly meter: AiLimitQuantity[\"meter\"]\n readonly currency: string\n readonly period: AiLimitPeriod\n actual: bigint\n reserved: bigint\n unknown: bigint\n accountingStatus: \"complete\" | \"unavailable\"\n updatedAt: Date\n}\n\nexport interface InMemoryAiLimitStorageOptions {\n readonly executionExists?: (input: {\n readonly projectId: string\n readonly executionId: string\n }) => boolean | Promise<boolean>\n readonly resolveExecution?: (input: {\n readonly projectId: string\n readonly executionId: string\n }) => ExecutionRecord | null | Promise<ExecutionRecord | null>\n readonly resolveUsageRecord?: (input: {\n readonly projectId: string\n readonly usageRecordId: string\n }) => AiModelCallUsageRecord | null | Promise<AiModelCallUsageRecord | null>\n readonly resolveCostRecord?: (input: {\n readonly projectId: string\n readonly usageRecordId: string\n }) => AiModelCallCostRecord | null | Promise<AiModelCallCostRecord | null>\n readonly listUsageRecords?: (input: {\n readonly projectId: string\n }) => readonly AiModelCallUsageRecord[] | Promise<readonly AiModelCallUsageRecord[]>\n}\n\nexport interface InMemoryAiLimitStorageSnapshot {\n readonly policies: Map<string, AiLimitPolicy>\n readonly policyIdsByDimension: Map<string, string>\n readonly periodStates: Map<string, AiLimitPeriodState>\n readonly reservations: Map<string, AiModelCallReservation>\n}\n\n/** In-memory AI limit provider used by development runtimes and contract tests. */\nexport class InMemoryAiLimitStorage implements AiLimitStorage {\n private readonly policies = new Map<string, AiLimitPolicy>()\n private readonly policyIdsByDimension = new Map<string, string>()\n private readonly periodStates = new Map<string, AiLimitPeriodState>()\n private readonly reservations = new Map<string, AiModelCallReservation>()\n private readonly operations = new AiLimitOperationLock()\n\n constructor(private readonly options: InMemoryAiLimitStorageOptions = {}) {}\n\n /** @internal The root transaction must settle queued work before restoring its snapshot. */\n settleOperations(): Promise<void> {\n return this.operations.settle()\n }\n\n async createPolicy(input: CreateAiLimitPolicyInput): Promise<AiLimitPolicy> {\n return this.operations.run(async () => {\n const policy = normalizeCreateAiLimitPolicy(input)\n const key = policyKey(policy.projectId, policy.id)\n const dimensionKey = aiLimitPolicyDimensionKey(policy)\n if (this.policies.has(key) || this.policyIdsByDimension.has(dimensionKey)) {\n throw new AiLimitStorageError(\n \"duplicate_policy\",\n `[Sixb] An AI limit policy already exists for '${aiLimitSubjectKey(policy.subject)}' and '${aiLimitAmountKey(normalizeAiLimitAmount(policy.limit))}'.`\n )\n }\n this.policies.set(key, structuredClone(policy))\n this.policyIdsByDimension.set(dimensionKey, key)\n return cloneAiLimitPolicy(policy)\n })\n }\n\n async updatePolicy(input: UpdateAiLimitPolicyInput): Promise<AiLimitPolicy> {\n return this.operations.run(async () => {\n const update = normalizeUpdateAiLimitPolicy(input)\n const key = policyKey(update.projectId, update.id)\n const existing = this.policies.get(key)\n if (!existing) throw missingPolicy(update.projectId, update.id)\n if (update.limit !== undefined) {\n const previous = normalizeAiLimitAmount(existing.limit)\n const next = normalizeAiLimitAmount(update.limit)\n if (aiLimitAmountKey(previous) !== aiLimitAmountKey(next)) {\n throw new TypeError(\"[Sixb] AI limit policy meter and cost currency are immutable.\")\n }\n }\n const policy: AiLimitPolicy = {\n ...existing,\n ...(update.limit === undefined ? {} : { limit: update.limit }),\n ...(update.enabled === undefined ? {} : { enabled: update.enabled }),\n updatedAt: update.updatedAt,\n }\n this.policies.set(key, structuredClone(policy))\n return cloneAiLimitPolicy(policy)\n })\n }\n\n async deletePolicy(input: DeleteAiLimitPolicyInput): Promise<boolean> {\n return this.operations.run(async () => {\n validatePolicyIdentity(input)\n const key = policyKey(input.projectId, input.id)\n const existing = this.policies.get(key)\n if (!existing) return false\n this.policies.delete(key)\n this.policyIdsByDimension.delete(aiLimitPolicyDimensionKey(existing))\n return true\n })\n }\n\n async getPolicy(input: GetAiLimitPolicyInput): Promise<AiLimitPolicy | null> {\n validatePolicyIdentity(input)\n const policy = this.policies.get(policyKey(input.projectId, input.id))\n return policy ? cloneAiLimitPolicy(policy) : null\n }\n\n async listPolicies(input: ListAiLimitPoliciesInput): Promise<readonly AiLimitPolicy[]> {\n assertNonBlank(input.projectId, \"projectId\")\n return [...this.policies.values()]\n .filter(\n (policy) =>\n policy.projectId === input.projectId && (input.includeDisabled || policy.enabled)\n )\n .sort((left, right) => left.id.localeCompare(right.id))\n .map(cloneAiLimitPolicy)\n }\n\n async listPolicyStatuses(\n input: ListAiLimitPolicyStatusesInput\n ): Promise<readonly AiLimitPolicyStatus[]> {\n return this.operations.run(async () => {\n assertNonBlank(input.projectId, \"projectId\")\n const period = aiLimitCalendarMonth(input.at ?? new Date())\n const existingGroups =\n input.existingGroupIds === undefined ? undefined : new Set(input.existingGroupIds)\n const policies = await this.listPolicies({\n projectId: input.projectId,\n includeDisabled: input.includeDisabled,\n })\n return Promise.all(\n policies.map((policy) => this.policyStatus(policy, period, existingGroups))\n )\n })\n }\n\n async reserveModelCall(input: ReserveAiModelCallInput): Promise<ReserveAiModelCallResult> {\n return this.operations.run(async () => {\n const request = normalizeReserveAiModelCall(input)\n const reservationKey = aiModelCallReservationKey(request.identity)\n const existing = this.reservations.get(reservationKey)\n if (existing) {\n if (!aiLimitReservationRequestMatches(existing, request)) {\n throw new AiLimitStorageError(\n \"reservation_conflict\",\n `[Sixb] AI model-call reservation '${input.callId}' was replayed with different subjects, estimates, or period.`\n )\n }\n if (existing.state !== \"active\") {\n return { status: \"terminal\", reservation: structuredClone(existing), created: false }\n }\n return { status: \"reserved\", reservation: structuredClone(existing), created: false }\n }\n await this.assertExecutionExists(request.identity.projectId, request.identity.executionId)\n\n const enabledPolicies = [...this.policies.values()].filter(\n (policy) => policy.projectId === request.identity.projectId && policy.enabled\n )\n const subjectKeys = new Set(request.subjects.map(aiLimitSubjectKey))\n const estimates = new Map(\n request.estimates.map((quantity) => {\n const amount = normalizeAiLimitAmount(quantity)\n return [aiLimitAmountKey(amount), amount] as const\n })\n )\n const exhaustedPolicies: AiLimitPolicyStatus[] = []\n const unavailablePolicies: AiLimitPolicyStatus[] = []\n const unavailableReasons = new Set<\"missingEstimate\" | \"incompleteAccounting\">()\n for (const policy of enabledPolicies) {\n if (!subjectKeys.has(aiLimitSubjectKey(policy.subject))) continue\n const limit = normalizeAiLimitAmount(policy.limit)\n const estimate = estimates.get(aiLimitAmountKey(limit))\n const status = await this.policyStatus(policy, request.period)\n if (!estimate || status.accountingStatus === \"unavailable\") {\n unavailablePolicies.push(status)\n if (!estimate) unavailableReasons.add(\"missingEstimate\")\n if (status.accountingStatus === \"unavailable\") {\n unavailableReasons.add(\"incompleteAccounting\")\n }\n continue\n }\n const actual = normalizeAiLimitAmount(status.consumption.actual).amount\n const reserved = normalizeAiLimitAmount(status.consumption.reserved).amount\n const unknown = normalizeAiLimitAmount(status.consumption.unknown).amount\n if (actual + reserved + unknown + estimate.amount > limit.amount) {\n exhaustedPolicies.push(status)\n }\n }\n if (unavailablePolicies.length > 0) {\n unavailablePolicies.sort((left, right) => left.policy.id.localeCompare(right.policy.id))\n return {\n status: \"unavailable\",\n unavailablePolicies,\n reasons: [...unavailableReasons].sort(),\n }\n }\n if (exhaustedPolicies.length > 0) {\n exhaustedPolicies.sort((left, right) => left.policy.id.localeCompare(right.policy.id))\n return {\n status: \"denied\",\n exhaustedPolicies,\n resetAt: new Date(\n Math.min(...exhaustedPolicies.map((status) => status.period.resetAt.getTime()))\n ),\n }\n }\n\n const buckets = aiLimitReservationBuckets(\n enabledPolicies,\n request.subjects,\n request.estimates\n )\n if (buckets.length === 0) return { status: \"notRequired\" }\n for (const bucket of buckets) {\n const amount = normalizeAiLimitAmount(bucket.estimate)\n const state = this.requirePeriodState(\n request.identity.projectId,\n bucket.subject,\n amount,\n request.period\n )\n state.reserved += amount.amount\n state.updatedAt = new Date(request.reservedAt)\n }\n const reservation: AiModelCallReservation = {\n ...request.identity,\n buckets,\n requestKey: aiLimitReservationRequestKey(request),\n period: request.period,\n state: \"active\",\n reservedAt: request.reservedAt,\n updatedAt: new Date(request.reservedAt),\n }\n this.reservations.set(reservationKey, structuredClone(reservation))\n return { status: \"reserved\", reservation: structuredClone(reservation), created: true }\n })\n }\n\n async recordModelCallActuals(input: RecordAiModelCallLimitActualsInput): Promise<void> {\n return this.operations.run(async () => {\n assertNonBlank(input.projectId, \"projectId\")\n assertNonBlank(input.usageRecordId, \"usageRecordId\")\n const recordedAt = cloneValidDate(input.recordedAt ?? new Date(), \"recordedAt\")\n const entry = await this.requireAccountingEntry(input.projectId, input.usageRecordId)\n const period = aiLimitCalendarMonth(entry.occurredAt)\n const subjectKeys = new Set(aiLimitSubjectsFromAccountingEntry(entry).map(aiLimitSubjectKey))\n for (const state of this.periodStates.values()) {\n if (\n state.projectId !== input.projectId ||\n state.period.start.getTime() !== period.start.getTime() ||\n !subjectKeys.has(aiLimitSubjectKey(state.subject))\n ) {\n continue\n }\n const actual = resolveAiLimitActual([entry], state)\n state.actual += actual.amount\n if (actual.accountingStatus === \"unavailable\") state.accountingStatus = \"unavailable\"\n state.updatedAt = new Date(recordedAt)\n }\n })\n }\n\n async reconcileModelCall(input: ReconcileAiModelCallInput): Promise<AiModelCallReservation> {\n return this.operations.run(async () => {\n const identity = normalizeAiModelCallReservationIdentity(input)\n assertNonBlank(input.usageRecordId, \"usageRecordId\")\n const reconciledAt = cloneValidDate(input.reconciledAt ?? new Date(), \"reconciledAt\")\n const key = aiModelCallReservationKey(identity)\n const reservation = this.reservations.get(key)\n if (!reservation) throw missingReservation(identity)\n if (reservation.state === \"reconciled\") {\n if (reservation.usageRecordId === input.usageRecordId) {\n return structuredClone(reservation)\n }\n throw new AiLimitStorageError(\n \"reconciliation_conflict\",\n `[Sixb] AI model-call reservation '${identity.callId}' was reconciled with a different usage record.`\n )\n }\n const accounting = await this.requireAccountingEntry(identity.projectId, input.usageRecordId)\n assertAiLimitAccountingMatchesReservation(reservation, accounting)\n this.reconcileEstimateCounters(reservation, accounting, reconciledAt)\n const reconciled: AiModelCallReservation = {\n ...reservation,\n state: \"reconciled\",\n usageRecordId: input.usageRecordId,\n updatedAt: reconciledAt,\n }\n this.reservations.set(key, structuredClone(reconciled))\n return structuredClone(reconciled)\n })\n }\n\n async markReservationUnknown(\n input: MarkAiModelCallReservationUnknownInput\n ): Promise<AiModelCallReservation> {\n return this.operations.run(async () => {\n const identity = normalizeAiModelCallReservationIdentity(input)\n const markedAt = cloneValidDate(input.markedAt ?? new Date(), \"markedAt\")\n const key = aiModelCallReservationKey(identity)\n const reservation = this.reservations.get(key)\n if (!reservation) throw missingReservation(identity)\n if (reservation.state === \"unknown\") return structuredClone(reservation)\n if (reservation.state !== \"active\") throw invalidState(reservation, \"mark unknown\")\n this.moveEstimateCounter(reservation, \"reserved\", -1n, markedAt)\n this.moveEstimateCounter(reservation, \"unknown\", 1n, markedAt)\n const unknown: AiModelCallReservation = {\n ...reservation,\n state: \"unknown\",\n updatedAt: markedAt,\n }\n this.reservations.set(key, structuredClone(unknown))\n return structuredClone(unknown)\n })\n }\n\n snapshot(): InMemoryAiLimitStorageSnapshot {\n return structuredClone({\n policies: this.policies,\n policyIdsByDimension: this.policyIdsByDimension,\n periodStates: this.periodStates,\n reservations: this.reservations,\n })\n }\n\n restore(snapshot: InMemoryAiLimitStorageSnapshot): void {\n replaceMap(this.policies, snapshot.policies)\n replaceMap(this.policyIdsByDimension, snapshot.policyIdsByDimension)\n replaceMap(this.periodStates, snapshot.periodStates)\n replaceMap(this.reservations, snapshot.reservations)\n }\n\n private async policyStatus(\n policy: AiLimitPolicy,\n period: AiLimitPeriod,\n existingGroups?: ReadonlySet<string>\n ): Promise<AiLimitPolicyStatus> {\n const limit = normalizeAiLimitAmount(policy.limit)\n const state = await this.ensurePeriodState(policy, period)\n const reserved = state.reserved\n const unknown = state.unknown\n const consumed = state.actual + reserved + unknown\n const remaining = limit.amount > consumed ? limit.amount - consumed : 0n\n const quantity = (amount: bigint): AiLimitQuantity =>\n aiLimitQuantityFromAmount({ ...limit, amount })\n return {\n policy: cloneAiLimitPolicy(policy),\n period: structuredClone(period),\n consumption: {\n actual: quantity(state.actual),\n reserved: quantity(reserved),\n unknown: quantity(unknown),\n remaining: quantity(remaining),\n },\n accountingStatus: state.accountingStatus,\n exhausted: consumed >= limit.amount,\n orphaned:\n policy.subject.type === \"group\" &&\n existingGroups !== undefined &&\n !existingGroups.has(policy.subject.id),\n }\n }\n\n private async ensurePeriodState(\n policy: AiLimitPolicy,\n period: AiLimitPeriod\n ): Promise<AiLimitPeriodState> {\n const amount = normalizeAiLimitAmount(policy.limit)\n const key = periodStateKey(policy.projectId, policy.subject, amount, period)\n const existing = this.periodStates.get(key)\n if (existing?.accountingStatus === \"complete\") return existing\n // A late valuation can repair the ledger after this period was cached as unavailable.\n const actual = await this.resolvePolicyActual(policy, period, amount)\n if (existing) {\n existing.actual = actual.amount\n existing.accountingStatus = actual.accountingStatus\n existing.updatedAt = new Date()\n return existing\n }\n const state: AiLimitPeriodState = {\n projectId: policy.projectId,\n subject: structuredClone(policy.subject),\n meter: amount.meter,\n currency: amount.currency,\n period: structuredClone(period),\n actual: actual.amount,\n reserved: 0n,\n unknown: 0n,\n accountingStatus: actual.accountingStatus,\n updatedAt: new Date(),\n }\n this.periodStates.set(key, state)\n return state\n }\n\n private moveEstimateCounter(\n reservation: AiModelCallReservation,\n counter: \"reserved\" | \"unknown\",\n direction: 1n | -1n,\n updatedAt: Date\n ): void {\n for (const bucket of reservation.buckets) {\n const amount = normalizeAiLimitAmount(bucket.estimate)\n const state = this.requirePeriodState(\n reservation.projectId,\n bucket.subject,\n amount,\n reservation.period\n )\n state[counter] += direction * amount.amount\n if (state[counter] < 0n) {\n throw new Error(`[Sixb] In-memory AI limit ${counter} counter became negative.`)\n }\n state.updatedAt = new Date(updatedAt)\n }\n }\n\n private reconcileEstimateCounters(\n reservation: AiModelCallReservation,\n entry: AiLimitAccountingEntry,\n updatedAt: Date\n ): void {\n for (const bucket of reservation.buckets) {\n const amount = normalizeAiLimitAmount(bucket.estimate)\n const state = this.requirePeriodState(\n reservation.projectId,\n bucket.subject,\n amount,\n reservation.period\n )\n const counter = reservation.state === \"active\" ? \"reserved\" : \"unknown\"\n const actual = resolveAiLimitActual([entry], amount)\n if (actual.accountingStatus === \"complete\") {\n state[counter] -= amount.amount\n } else if (reservation.state === \"active\") {\n state.reserved -= amount.amount\n state.unknown += amount.amount\n }\n if (state.reserved < 0n || state.unknown < 0n) {\n throw new Error(\"[Sixb] In-memory AI limit reservation counter became negative.\")\n }\n state.updatedAt = new Date(updatedAt)\n }\n }\n\n private requirePeriodState(\n projectId: string,\n subject: AiLimitSubject,\n amount: NormalizedAiLimitAmount,\n period: AiLimitPeriod\n ): AiLimitPeriodState {\n const state = this.periodStates.get(periodStateKey(projectId, subject, amount, period))\n if (!state) throw new Error(\"[Sixb] In-memory AI limit period state is inconsistent.\")\n return state\n }\n\n private async assertExecutionExists(projectId: string, executionId: string): Promise<void> {\n if (this.options.resolveExecution) {\n if (await this.options.resolveExecution({ projectId, executionId })) return\n throw new AiLimitStorageError(\n \"missing_execution\",\n `[Sixb] AI limit execution '${executionId}' does not exist in project '${projectId}'.`\n )\n }\n if (\n this.options.executionExists &&\n (await this.options.executionExists({ projectId, executionId }))\n ) {\n return\n }\n throw new AiLimitStorageError(\n \"missing_execution\",\n `[Sixb] AI limit execution '${executionId}' does not exist in project '${projectId}'.`\n )\n }\n\n private async resolvePolicyActual(\n policy: AiLimitPolicy,\n period: AiLimitPeriod,\n dimension: NormalizedAiLimitAmount\n ): Promise<ReturnType<typeof resolveAiLimitActual>> {\n if (\n !this.options.listUsageRecords ||\n ((policy.subject.type === \"user\" || policy.subject.type === \"serviceAccount\") &&\n !this.options.resolveExecution)\n ) {\n return { amount: 0n, accountingStatus: \"unavailable\" }\n }\n const records = await this.options.listUsageRecords({ projectId: policy.projectId })\n const entries = await Promise.all(\n records\n .filter(\n (record) =>\n record.occurredAt.getTime() >= period.start.getTime() &&\n record.occurredAt.getTime() < period.end.getTime()\n )\n .map((record) => this.accountingEntry(record))\n )\n return resolveAiLimitActual(\n entries.filter((entry) => aiLimitAccountingEntryAppliesToSubject(entry, policy.subject)),\n dimension\n )\n }\n\n private async requireAccountingEntry(\n projectId: string,\n usageRecordId: string\n ): Promise<AiLimitAccountingEntry> {\n if (!this.options.resolveUsageRecord) {\n throw new AiLimitStorageError(\n \"unavailable_actuals\",\n \"[Sixb] In-memory AI limit storage has no immutable accounting source.\"\n )\n }\n const record = await this.options.resolveUsageRecord({ projectId, usageRecordId })\n if (!record) {\n throw new AiLimitStorageError(\n \"missing_usage_record\",\n `[Sixb] AI usage record '${usageRecordId}' does not exist in project '${projectId}'.`\n )\n }\n return this.accountingEntry(record)\n }\n\n private async accountingEntry(record: AiModelCallUsageRecord): Promise<AiLimitAccountingEntry> {\n const [execution, cost] = await Promise.all([\n this.options.resolveExecution?.({\n projectId: record.projectId,\n executionId: record.executionId,\n }),\n this.options.resolveCostRecord?.({\n projectId: record.projectId,\n usageRecordId: record.id,\n }),\n ])\n const requester = execution?.requestedBy\n return {\n projectId: record.projectId,\n usageRecordId: record.id,\n executionId: record.executionId,\n attempt: record.attempt,\n callId: record.callId,\n occurredAt: new Date(record.occurredAt),\n ...(record.usage.totalTokens === undefined ? {} : { totalTokens: record.usage.totalTokens }),\n requesterGroupIds: [...record.requesterGroupIds],\n ...(requester?.type === \"user\" || requester?.type === \"serviceAccount\"\n ? { requester: { type: requester.type, id: requester.id } }\n : {}),\n ...(cost?.status === \"rated\"\n ? { valuation: { status: \"rated\" as const, money: structuredClone(cost.money) } }\n : cost\n ? { valuation: { status: \"unavailable\" as const } }\n : {}),\n }\n }\n}\n\nfunction policyKey(projectId: string, id: string): string {\n return JSON.stringify([projectId, id])\n}\n\nfunction periodStateKey(\n projectId: string,\n subject: AiLimitSubject,\n amount: Pick<NormalizedAiLimitAmount, \"meter\" | \"currency\">,\n period: AiLimitPeriod\n): string {\n return JSON.stringify([\n projectId,\n aiLimitSubjectKey(subject),\n amount.meter,\n amount.currency,\n period.start.toISOString(),\n ])\n}\n\nfunction validatePolicyIdentity(input: GetAiLimitPolicyInput): void {\n assertNonBlank(input.projectId, \"projectId\")\n assertNonBlank(input.id, \"policy id\")\n}\n\nfunction missingPolicy(projectId: string, id: string): AiLimitStorageError {\n return new AiLimitStorageError(\n \"missing_policy\",\n `[Sixb] AI limit policy '${id}' does not exist in project '${projectId}'.`\n )\n}\n\nfunction missingReservation(identity: {\n readonly projectId: string\n readonly executionId: string\n readonly attempt: number\n readonly callId: string\n}): AiLimitStorageError {\n return new AiLimitStorageError(\n \"missing_reservation\",\n `[Sixb] AI model-call reservation '${identity.callId}' does not exist for execution '${identity.executionId}' attempt ${identity.attempt}.`\n )\n}\n\nfunction invalidState(reservation: AiModelCallReservation, operation: string): AiLimitStorageError {\n return new AiLimitStorageError(\n \"invalid_reservation_state\",\n `[Sixb] Cannot ${operation} AI model-call reservation '${reservation.callId}' in state '${reservation.state}'.`\n )\n}\n\nfunction replaceMap<TKey, TValue>(target: Map<TKey, TValue>, source: Map<TKey, TValue>): void {\n target.clear()\n for (const [key, value] of structuredClone(source)) target.set(key, value)\n}\n",
|
|
11
|
+
"import { timingSafeEqual } from \"node:crypto\"\nimport { createSixbError, parseSixbFailure, toSixbFailure } from \"../../errors/internal\"\nimport { ConnectorConnectionStorageError } from \"./errors\"\nimport type {\n AttachConnectorConnectionRunAuthorizationInput,\n ClaimConnectorConnectionRunCallbackInput,\n ClaimConnectorConnectionRunCallbackResult,\n ClaimConnectorCredentialMutationInput,\n ClaimConnectorCredentialMutationResult,\n ConnectorAuthorizationAttemptRecord,\n ConnectorAuthorizationKey,\n ConnectorAuthorizationRecord,\n ConnectorConnectionKey,\n ConnectorConnectionRecord,\n ConnectorConnectionRunAwaitingProviderRecord,\n ConnectorConnectionRunAwaitingSelectionRecord,\n ConnectorConnectionRunProcessingRecord,\n ConnectorConnectionRunRecord,\n ConnectorConnectionRunSucceededRecord,\n ConnectorConnectionStorage,\n ConnectorCredentialMutationFence,\n CreateConnectorAuthorizationAttemptInput,\n CreateConnectorAuthorizationInput,\n CreateConnectorConnectionRunInput,\n CreateConnectorConnectionSelectionRunInput,\n FinalizeConnectorReauthorizationInput,\n FinishConnectorConnectionRunInput,\n GetConnectorConnectionInput,\n GetConnectorConnectionRunInput,\n InitializeConnectorAuthorizationAccountsInput,\n ListConnectorConnectionsInput,\n MarkConnectorAuthorizationNeedsReauthorizationInput,\n MarkConnectorCredentialMutationExecutingInput,\n PutConnectorConnectionFromRunInput,\n PutConnectorConnectionFromRunResult,\n PutConnectorConnectionInput,\n PutConnectorConnectionResult,\n RecoverExpiredConnectorCredentialMutationInput,\n ReleaseConnectorCredentialMutationInput,\n RenewConnectorCredentialMutationInput,\n StageConnectorCredentialMutationCredentialsInput,\n StageConnectorCredentialMutationRevocationInput,\n WaitForConnectorConnectionRunSelectionInput,\n} from \"./types\"\nimport { CONNECTOR_CONNECTION_RUN_FAILURE_CODES } from \"./types\"\n\nexport interface InMemoryConnectorConnectionStorageSnapshot {\n readonly attempts: Map<string, ConnectorAuthorizationAttemptRecord>\n readonly connectionRuns: Map<string, ConnectorConnectionRunRecord>\n readonly authorizations: Map<string, ConnectorAuthorizationRecord>\n readonly connections: Map<string, ConnectorConnectionRecord>\n}\n\nfunction connectionRunBase(record: ConnectorConnectionRunRecord, updatedAt: Date) {\n return {\n id: record.id,\n projectId: record.projectId,\n connectorId: record.connectorId,\n kind: record.kind,\n owner: structuredClone(record.owner),\n slot: record.slot,\n initiatedByExecutionId: record.initiatedByExecutionId,\n createdAt: new Date(record.createdAt),\n updatedAt: new Date(updatedAt),\n }\n}\n\nfunction expireConnectionRun(\n record: Extract<ConnectorConnectionRunRecord, { readonly status: \"waiting\" }>,\n now: Date\n) {\n return {\n ...connectionRunBase(record, now),\n status: \"expired\" as const,\n ...(record.waitingFor === \"account_selection\"\n ? { authorizationId: record.authorizationId }\n : {}),\n finishedAt: new Date(now),\n }\n}\n\nfunction failExpiredProcessingRun(record: ConnectorConnectionRunProcessingRecord, now: Date) {\n return {\n ...connectionRunBase(record, now),\n status: \"failed\" as const,\n ...(record.authorizationId === undefined ? {} : { authorizationId: record.authorizationId }),\n error: toSixbFailure(\n createSixbError(\n \"internal.unexpected\",\n \"[Sixb] Connector callback processing did not complete before its deadline.\"\n ),\n { allowedCodes: CONNECTOR_CONNECTION_RUN_FAILURE_CODES, at: now }\n ),\n finishedAt: new Date(now),\n }\n}\n\nexport interface InMemoryConnectorConnectionStorageOptions {\n /** Storage-authoritative clock. Durable implementations should use their database clock. */\n readonly now?: () => Date\n}\n\nexport class InMemoryConnectorConnectionStorage implements ConnectorConnectionStorage {\n readonly durability = \"ephemeral\" as const\n private readonly attempts = new Map<string, ConnectorAuthorizationAttemptRecord>()\n private readonly connectionRuns = new Map<string, ConnectorConnectionRunRecord>()\n private readonly authorizations = new Map<string, ConnectorAuthorizationRecord>()\n private readonly connections = new Map<string, ConnectorConnectionRecord>()\n\n constructor(private readonly options: InMemoryConnectorConnectionStorageOptions = {}) {}\n\n async createAuthorizationAttempt(\n input: CreateConnectorAuthorizationAttemptInput\n ): Promise<ConnectorAuthorizationAttemptRecord> {\n assertPositiveDuration(input.ttlMs, \"authorization attempt TTL\")\n if (this.attempts.has(input.id)) {\n throw new ConnectorConnectionStorageError(\n \"attempt_conflict\",\n \"[Sixb] Connector authorization attempt already exists.\"\n )\n }\n if (input.connectionRunId !== undefined) {\n const run = this.connectionRuns.get(input.connectionRunId)\n const existingAttempt = this.findAuthorizationAttemptByConnectionRunId(input.connectionRunId)\n if (\n !run ||\n existingAttempt ||\n run.projectId !== input.projectId ||\n run.connectorId !== input.connectorId ||\n run.status !== \"waiting\" ||\n run.waitingFor !== \"provider_authorization\" ||\n run.slot !== input.slot ||\n run.initiatedByExecutionId !== input.initiatedByExecutionId\n ) {\n throw new ConnectorConnectionStorageError(\n \"attempt_conflict\",\n \"[Sixb] Connector authorization attempt does not match its connection run.\"\n )\n }\n }\n const now = this.now()\n const record: ConnectorAuthorizationAttemptRecord = {\n id: input.id,\n projectId: input.projectId,\n connectorId: input.connectorId,\n owner: structuredClone(input.owner),\n slot: input.slot,\n initiatedByExecutionId: input.initiatedByExecutionId,\n stateHash: input.stateHash,\n ...(input.codeVerifier === undefined\n ? {}\n : { codeVerifier: structuredClone(input.codeVerifier) }),\n redirectUri: input.redirectUri,\n ...(input.connectionRunId === undefined ? {} : { connectionRunId: input.connectionRunId }),\n ...(input.returnTo === undefined ? {} : { returnTo: input.returnTo }),\n ...(input.callbackBindingHash === undefined\n ? {}\n : { callbackBindingHash: input.callbackBindingHash }),\n ...(input.reauthorizationId === undefined\n ? {}\n : { reauthorizationId: input.reauthorizationId }),\n ...(input.reauthorizationRevision === undefined\n ? {}\n : { reauthorizationRevision: input.reauthorizationRevision }),\n ...(input.reauthorizationConnectionIds === undefined\n ? {}\n : { reauthorizationConnectionIds: [...input.reauthorizationConnectionIds] }),\n createdAt: now,\n expiresAt: new Date(now.getTime() + input.ttlMs),\n }\n this.attempts.set(record.id, record)\n return structuredClone(record)\n }\n\n async consumeAuthorizationAttempt(\n input: Parameters<ConnectorConnectionStorage[\"consumeAuthorizationAttempt\"]>[0]\n ): Promise<ConnectorAuthorizationAttemptRecord> {\n const record = this.attempts.get(input.id)\n if (record && record.expiresAt.getTime() <= this.now().getTime()) {\n this.attempts.delete(record.id)\n throw invalidAttempt()\n }\n if (\n !record ||\n record.projectId !== input.projectId ||\n record.connectorId !== input.connectorId ||\n record.redirectUri !== input.redirectUri ||\n !safeEqual(record.stateHash, input.stateHash)\n ) {\n throw invalidAttempt()\n }\n\n this.attempts.delete(input.id)\n return structuredClone(record)\n }\n\n async createConnectionRun(\n input: CreateConnectorConnectionRunInput\n ): Promise<ConnectorConnectionRunRecord> {\n assertPositiveDuration(input.ttlMs, \"connection run TTL\")\n if (this.connectionRuns.has(input.id)) {\n throw new ConnectorConnectionStorageError(\n \"run_conflict\",\n \"[Sixb] Connector connection run already exists.\"\n )\n }\n const now = this.now()\n const record: ConnectorConnectionRunAwaitingProviderRecord = {\n id: input.id,\n projectId: input.projectId,\n connectorId: input.connectorId,\n kind: input.kind,\n owner: structuredClone(input.owner),\n slot: input.slot,\n initiatedByExecutionId: input.initiatedByExecutionId,\n status: \"waiting\",\n waitingFor: \"provider_authorization\",\n createdAt: now,\n updatedAt: now,\n expiresAt: new Date(now.getTime() + input.ttlMs),\n }\n this.connectionRuns.set(record.id, record)\n return structuredClone(record)\n }\n\n async createConnectionSelectionRun(\n input: CreateConnectorConnectionSelectionRunInput\n ): Promise<ConnectorConnectionRunAwaitingSelectionRecord> {\n assertPositiveDuration(input.ttlMs, \"connection run TTL\")\n if (this.connectionRuns.has(input.id)) {\n throw new ConnectorConnectionStorageError(\n \"run_conflict\",\n \"[Sixb] Connector connection run already exists.\"\n )\n }\n const authorization = this.authorizations.get(input.authorizationId)\n if (\n !sameAuthorizationScope(authorization, input) ||\n authorization.status !== \"active\" ||\n authorization.credentialMutation\n ) {\n throw authorizationConflict()\n }\n const now = this.now()\n const record: ConnectorConnectionRunAwaitingSelectionRecord = {\n id: input.id,\n projectId: input.projectId,\n connectorId: input.connectorId,\n kind: \"connect\",\n owner: structuredClone(input.owner),\n slot: input.slot,\n initiatedByExecutionId: input.initiatedByExecutionId,\n status: \"waiting\",\n waitingFor: \"account_selection\",\n authorizationId: input.authorizationId,\n createdAt: now,\n updatedAt: now,\n expiresAt: new Date(now.getTime() + input.ttlMs),\n }\n this.connectionRuns.set(record.id, record)\n return structuredClone(record)\n }\n\n async claimConnectionRunCallback(\n input: ClaimConnectorConnectionRunCallbackInput\n ): Promise<ClaimConnectorConnectionRunCallbackResult | null> {\n assertPositiveDuration(input.processingTtlMs, \"connection run processing TTL\")\n const attempt = this.attempts.get(input.attemptId)\n if (\n !attempt ||\n attempt.projectId !== input.projectId ||\n attempt.connectionRunId === undefined ||\n attempt.returnTo === undefined ||\n attempt.callbackBindingHash === undefined ||\n attempt.redirectUri !== input.redirectUri ||\n !safeEqual(attempt.stateHash, input.stateHash) ||\n !safeEqual(attempt.callbackBindingHash, input.callbackBindingHash)\n ) {\n return null\n }\n\n const run = this.connectionRuns.get(attempt.connectionRunId)\n if (\n !run ||\n run.projectId !== input.projectId ||\n run.connectorId !== attempt.connectorId ||\n run.status !== \"waiting\" ||\n run.waitingFor !== \"provider_authorization\" ||\n run.slot !== attempt.slot ||\n run.initiatedByExecutionId !== attempt.initiatedByExecutionId\n ) {\n return null\n }\n\n const now = this.now()\n this.attempts.delete(attempt.id)\n if (attempt.expiresAt.getTime() <= now.getTime() || run.expiresAt.getTime() <= now.getTime()) {\n const expired = expireConnectionRun(run, now)\n this.connectionRuns.set(run.id, expired)\n return { type: \"expired\", run: structuredClone(expired), returnTo: attempt.returnTo }\n }\n\n const processing: ConnectorConnectionRunProcessingRecord = {\n ...connectionRunBase(run, now),\n status: \"running\" as const,\n processingId: input.processingId,\n callbackStartedAt: now,\n expiresAt: new Date(now.getTime() + input.processingTtlMs),\n ...(attempt.reauthorizationId === undefined\n ? {}\n : { authorizationId: attempt.reauthorizationId }),\n }\n this.connectionRuns.set(run.id, processing)\n return {\n type: \"claimed\",\n run: structuredClone(processing),\n attempt: structuredClone(attempt),\n returnTo: attempt.returnTo,\n }\n }\n\n async attachConnectionRunAuthorization(\n input: AttachConnectorConnectionRunAuthorizationInput\n ): Promise<ConnectorConnectionRunProcessingRecord | null> {\n const run = this.currentConnectionRun(input.runId)\n const authorization = this.authorizations.get(input.authorizationId)\n if (\n !sameConnectionRunScope(run, input) ||\n run.status !== \"running\" ||\n run.processingId !== input.processingId ||\n (run.authorizationId !== undefined && run.authorizationId !== input.authorizationId) ||\n !sameAuthorizationScope(authorization, input) ||\n authorization.status !== \"pending_selection\"\n ) {\n return null\n }\n const updated: ConnectorConnectionRunProcessingRecord = {\n ...run,\n authorizationId: input.authorizationId,\n updatedAt: this.now(),\n }\n this.connectionRuns.set(run.id, updated)\n return structuredClone(updated)\n }\n\n async waitForConnectionRunSelection(input: WaitForConnectorConnectionRunSelectionInput) {\n const run = this.currentConnectionRun(input.runId)\n if (\n !sameConnectionRunScope(run, input) ||\n run.status !== \"running\" ||\n run.kind !== \"connect\" ||\n run.processingId !== input.processingId ||\n run.authorizationId !== input.authorizationId\n ) {\n return null\n }\n const now = this.now()\n const waiting = {\n ...connectionRunBase(run, now),\n status: \"waiting\" as const,\n waitingFor: \"account_selection\" as const,\n authorizationId: input.authorizationId,\n expiresAt: new Date(input.expiresAt),\n }\n this.connectionRuns.set(run.id, waiting)\n return structuredClone(waiting)\n }\n\n async finishConnectionRun(\n input: FinishConnectorConnectionRunInput\n ): Promise<ConnectorConnectionRunRecord | null> {\n const run = this.currentConnectionRun(input.runId)\n if (!sameConnectionRunScope(run, input) || run.status !== \"running\") return null\n if (input.processingId !== run.processingId) return null\n const now = this.now()\n const authorizationId =\n input.status === \"succeeded\"\n ? input.authorizationId\n : input.status === \"failed\"\n ? (input.authorizationId ?? run.authorizationId)\n : run.authorizationId\n if (input.status !== \"succeeded\" && run.kind === \"connect\" && authorizationId) {\n this.markPendingAuthorizationForCleanup(run.connectorId, authorizationId, now)\n }\n const base = connectionRunBase(run, now)\n const finished: ConnectorConnectionRunRecord =\n input.status === \"succeeded\"\n ? {\n ...base,\n status: \"succeeded\",\n authorizationId: input.authorizationId,\n ...(input.cleanupAuthorizationId === undefined\n ? {}\n : { cleanupAuthorizationId: input.cleanupAuthorizationId }),\n connections: structuredClone(input.connections),\n finishedAt: now,\n }\n : input.status === \"failed\"\n ? {\n ...base,\n status: \"failed\",\n ...(authorizationId === undefined ? {} : { authorizationId }),\n error: parseSixbFailure(input.error, CONNECTOR_CONNECTION_RUN_FAILURE_CODES),\n finishedAt: now,\n }\n : {\n ...base,\n status: \"cancelled\",\n ...(authorizationId === undefined ? {} : { authorizationId }),\n finishedAt: now,\n }\n this.connectionRuns.set(run.id, finished)\n return structuredClone(finished)\n }\n\n async listPendingConnectionRuns(\n input: Parameters<ConnectorConnectionStorage[\"listPendingConnectionRuns\"]>[0]\n ): Promise<readonly ConnectorConnectionRunRecord[]> {\n return [...this.connectionRuns.values()]\n .filter(\n (run) =>\n run.projectId === input.projectId &&\n run.connectorId === input.connectorId &&\n (run.status === \"running\" ||\n (run.status === \"waiting\" && run.waitingFor === \"account_selection\"))\n )\n .map((run) => structuredClone(run))\n }\n\n async getConnectionRun(\n input: GetConnectorConnectionRunInput\n ): Promise<ConnectorConnectionRunRecord | null> {\n const run = this.currentConnectionRun(input.runId)\n return sameConnectionRunScope(run, input) ? structuredClone(run) : null\n }\n\n async createAuthorization(\n input: CreateConnectorAuthorizationInput\n ): Promise<ConnectorAuthorizationRecord> {\n assertPositiveDuration(input.selectionTtlMs, \"account selection TTL\")\n if (this.authorizations.has(input.id)) {\n throw new ConnectorConnectionStorageError(\n \"authorization_conflict\",\n \"[Sixb] Connector authorization already exists.\"\n )\n }\n const now = this.now()\n const record: ConnectorAuthorizationRecord = {\n id: input.id,\n projectId: input.projectId,\n connectorId: input.connectorId,\n authorizedBy: structuredClone(input.authorizedBy),\n credentials: structuredClone(input.credentials),\n ...(input.credentialExpiresAt === undefined\n ? {}\n : { credentialExpiresAt: new Date(input.credentialExpiresAt) }),\n scopes: [...input.scopes],\n accounts: structuredClone(input.accounts),\n status: \"pending_selection\",\n selectionExpiresAt: new Date(now.getTime() + input.selectionTtlMs),\n revision: 0,\n createdAt: now,\n updatedAt: now,\n }\n this.authorizations.set(record.id, record)\n return structuredClone(record)\n }\n\n async initializeAuthorizationAccounts(\n input: InitializeConnectorAuthorizationAccountsInput\n ): Promise<ConnectorAuthorizationRecord | null> {\n const record = this.authorizations.get(input.authorizationId)\n if (\n !sameAuthorizationScope(record, input) ||\n record.revision !== input.expectedRevision ||\n record.status !== \"pending_selection\" ||\n record.credentialMutation\n ) {\n return null\n }\n const updated: ConnectorAuthorizationRecord = {\n ...record,\n accounts: structuredClone(input.accounts),\n revision: record.revision + 1,\n updatedAt: this.now(),\n }\n this.authorizations.set(record.id, updated)\n return structuredClone(updated)\n }\n\n async getAuthorization(\n input: ConnectorAuthorizationKey\n ): Promise<ConnectorAuthorizationRecord | null> {\n const authorization = this.authorizations.get(input.authorizationId)\n return sameAuthorizationScope(authorization, input) ? structuredClone(authorization) : null\n }\n\n async getAuthorizationByConnectionId(\n input: ConnectorConnectionKey\n ): Promise<ConnectorAuthorizationRecord | null> {\n const connection = this.connections.get(input.connectionId)\n if (!sameConnectionScope(connection, input)) return null\n const authorization = this.authorizations.get(connection.authorizationId)\n return sameAuthorizationScope(authorization, input) ? structuredClone(authorization) : null\n }\n\n async claimCredentialMutation(\n input: ClaimConnectorCredentialMutationInput\n ): Promise<ClaimConnectorCredentialMutationResult | null> {\n assertPositiveDuration(input.leaseDurationMs, \"credential mutation lease duration\")\n assertPositiveDuration(input.operationTimeoutMs, \"credential mutation timeout\")\n const now = this.now()\n const record = this.authorizations.get(input.authorizationId)\n if (\n !sameAuthorizationScope(record, input) ||\n record.revision !== input.expectedRevision ||\n !canClaimMutation(record.status, input.mutation.kind)\n ) {\n return null\n }\n\n if (record.credentialMutation) {\n const canReplacePrepared =\n record.credentialMutation.phase === \"prepared\" &&\n record.credentialMutation.expiresAt.getTime() <= now.getTime()\n if (!canReplacePrepared) return null\n }\n\n const attached = this.connectedConnectionsForAuthorization(record.id)\n if (\n input.mutation.kind === \"reauthorization\" &&\n !sameIds(\n attached.map((connection) => connection.id),\n input.expectedConnectionIds ?? []\n )\n ) {\n return null\n }\n\n const deadlineAt = new Date(now.getTime() + input.operationTimeoutMs)\n const mutation = {\n ...structuredClone(input.mutation),\n phase: \"prepared\" as const,\n expiresAt: leaseExpiry(now, input.leaseDurationMs, deadlineAt),\n deadlineAt,\n ...(input.mutation.kind === \"reauthorization\"\n ? { expectedConnectionIds: [...(input.expectedConnectionIds ?? [])] }\n : {}),\n }\n const startsRevocation =\n input.mutation.kind === \"revocation\" && record.status !== \"revocation_pending\"\n const updated: ConnectorAuthorizationRecord = {\n ...record,\n status: input.mutation.kind === \"revocation\" ? \"revocation_pending\" : record.status,\n selectionExpiresAt:\n input.mutation.kind === \"revocation\" ? undefined : record.selectionExpiresAt,\n revision: startsRevocation ? record.revision + 1 : record.revision,\n credentialMutation: mutation,\n updatedAt: now,\n }\n this.authorizations.set(record.id, updated)\n\n const disconnected: ConnectorConnectionRecord[] = []\n if (input.mutation.kind === \"revocation\") {\n for (const connection of attached) {\n const updatedConnection = disconnectConnectionRecord(connection, now)\n this.connections.set(connection.id, updatedConnection)\n disconnected.push(structuredClone(updatedConnection))\n }\n }\n return { authorization: structuredClone(updated), disconnected }\n }\n\n async markCredentialMutationExecuting(\n input: MarkConnectorCredentialMutationExecutingInput\n ): Promise<ConnectorAuthorizationRecord | null> {\n const now = this.now()\n const record = this.authorizations.get(input.authorizationId)\n if (\n !matchesMutation(record, input, input.holderId) ||\n record.credentialMutation.phase !== \"prepared\" ||\n mutationExpired(record, now)\n ) {\n return null\n }\n const updated: ConnectorAuthorizationRecord = {\n ...record,\n credentialMutation: { ...record.credentialMutation, phase: \"executing\" },\n updatedAt: now,\n }\n this.authorizations.set(record.id, updated)\n return structuredClone(updated)\n }\n\n async renewCredentialMutation(\n input: RenewConnectorCredentialMutationInput\n ): Promise<ConnectorAuthorizationRecord | null> {\n assertPositiveDuration(input.leaseDurationMs, \"credential mutation lease duration\")\n const now = this.now()\n const record = this.authorizations.get(input.authorizationId)\n if (\n !matchesMutation(record, input, input.holderId) ||\n record.credentialMutation.phase === \"result_staged\" ||\n mutationExpired(record, now)\n ) {\n return null\n }\n const updated: ConnectorAuthorizationRecord = {\n ...record,\n credentialMutation: {\n ...record.credentialMutation,\n expiresAt: leaseExpiry(now, input.leaseDurationMs, record.credentialMutation.deadlineAt),\n },\n }\n this.authorizations.set(record.id, updated)\n return structuredClone(updated)\n }\n\n async stageCredentialMutationCredentials(\n input: StageConnectorCredentialMutationCredentialsInput\n ): Promise<ConnectorAuthorizationRecord | null> {\n const now = this.now()\n const record = this.authorizations.get(input.authorizationId)\n if (\n !matchesMutation(record, input, input.holderId) ||\n record.credentialMutation.phase !== \"executing\" ||\n mutationExpired(record, now) ||\n record.credentialMutation.kind === \"revocation\"\n ) {\n return null\n }\n const updated: ConnectorAuthorizationRecord = {\n ...record,\n credentialMutation: {\n ...record.credentialMutation,\n phase: \"result_staged\",\n stagedCredentials: {\n credentials: structuredClone(input.credentials),\n ...(input.credentialExpiresAt === undefined\n ? {}\n : { credentialExpiresAt: new Date(input.credentialExpiresAt) }),\n scopes: [...input.scopes],\n },\n },\n updatedAt: now,\n }\n this.authorizations.set(record.id, updated)\n return structuredClone(updated)\n }\n\n async stageCredentialMutationRevocation(\n input: StageConnectorCredentialMutationRevocationInput\n ): Promise<ConnectorAuthorizationRecord | null> {\n const now = this.now()\n const record = this.authorizations.get(input.authorizationId)\n if (\n !matchesMutation(record, input, input.holderId) ||\n record.credentialMutation.phase !== \"executing\" ||\n record.credentialMutation.kind !== \"revocation\" ||\n mutationExpired(record, now)\n ) {\n return null\n }\n const updated: ConnectorAuthorizationRecord = {\n ...record,\n credentialMutation: { ...record.credentialMutation, phase: \"result_staged\" },\n updatedAt: now,\n }\n this.authorizations.set(record.id, updated)\n return structuredClone(updated)\n }\n\n async releaseCredentialMutation(\n input: ReleaseConnectorCredentialMutationInput\n ): Promise<boolean> {\n const record = this.authorizations.get(input.authorizationId)\n if (\n !matchesMutation(record, input, input.holderId) ||\n record.credentialMutation.phase === \"result_staged\"\n ) {\n return false\n }\n this.authorizations.set(record.id, {\n ...record,\n credentialMutation: undefined,\n updatedAt: this.now(),\n })\n return true\n }\n\n async recoverExpiredCredentialMutation(\n input: RecoverExpiredConnectorCredentialMutationInput\n ): Promise<ConnectorAuthorizationRecord | null> {\n const record = this.authorizations.get(input.authorizationId)\n if (!sameAuthorizationScope(record, input) || !record.credentialMutation) return null\n if (record.credentialMutation.phase === \"result_staged\") return structuredClone(record)\n\n const now = this.now()\n if (!mutationExpired(record, now)) return null\n const ambiguous = record.credentialMutation.phase === \"executing\"\n const failClosed = ambiguous && record.credentialMutation.kind !== \"revocation\"\n const updated: ConnectorAuthorizationRecord = {\n ...record,\n status: failClosed ? \"needs_reauthorization\" : record.status,\n selectionExpiresAt: failClosed ? undefined : record.selectionExpiresAt,\n revision: failClosed ? record.revision + 1 : record.revision,\n credentialMutation: undefined,\n updatedAt: now,\n }\n this.authorizations.set(record.id, updated)\n return structuredClone(updated)\n }\n\n async markNeedsReauthorization(\n input: MarkConnectorAuthorizationNeedsReauthorizationInput\n ): Promise<ConnectorAuthorizationRecord | null> {\n const record = this.authorizations.get(input.authorizationId)\n if (!matchesMutation(record, input)) return null\n const staged = record.credentialMutation.stagedCredentials\n const updated: ConnectorAuthorizationRecord = {\n ...record,\n ...(staged\n ? {\n credentials: structuredClone(staged.credentials),\n credentialExpiresAt:\n staged.credentialExpiresAt === undefined\n ? undefined\n : new Date(staged.credentialExpiresAt),\n scopes: [...staged.scopes],\n }\n : {}),\n status: \"needs_reauthorization\",\n selectionExpiresAt: undefined,\n revision: record.revision + 1,\n credentialMutation: undefined,\n updatedAt: this.now(),\n }\n this.authorizations.set(record.id, updated)\n return structuredClone(updated)\n }\n\n async finalizeRefresh(\n input: ConnectorCredentialMutationFence\n ): Promise<ConnectorAuthorizationRecord | null> {\n const record = this.authorizations.get(input.authorizationId)\n const staged = stagedCredentials(record, input, \"refresh\")\n if (!record || !staged) return null\n const updated = applyStagedCredentials(record, staged, this.now(), {\n status: \"active\",\n accounts: record.accounts,\n })\n this.authorizations.set(record.id, updated)\n return structuredClone(updated)\n }\n\n async finalizeReauthorization(\n input: FinalizeConnectorReauthorizationInput\n ): Promise<ConnectorAuthorizationRecord | null> {\n const record = this.authorizations.get(input.authorizationId)\n const staged = stagedCredentials(record, input, \"reauthorization\")\n if (!record || !staged || !record.credentialMutation) return null\n const attached = this.connectedConnectionsForAuthorization(record.id)\n if (\n !sameIds(\n attached.map((connection) => connection.id),\n record.credentialMutation.expectedConnectionIds ?? []\n )\n ) {\n throw new ConnectorConnectionStorageError(\n \"authorization_conflict\",\n \"[Sixb] Connections attached to the connector authorization changed during reauthorization.\"\n )\n }\n const accountsById = new Map(input.accounts.map((account) => [account.id, account]))\n if (attached.some((connection) => !accountsById.has(connection.account.id))) {\n throw new ConnectorConnectionStorageError(\n \"authorization_conflict\",\n \"[Sixb] Reauthorized connector grant no longer exposes every attached account.\"\n )\n }\n\n const now = this.now()\n const updated = applyStagedCredentials(record, staged, now, {\n status: \"active\",\n accounts: input.accounts,\n })\n this.authorizations.set(record.id, updated)\n for (const connection of attached) {\n this.connections.set(connection.id, {\n ...connection,\n account: structuredClone(accountsById.get(connection.account.id)!),\n updatedAt: now,\n })\n }\n return structuredClone(updated)\n }\n\n async finalizeRevocation(\n input: ConnectorCredentialMutationFence\n ): Promise<ConnectorAuthorizationRecord | null> {\n const record = this.authorizations.get(input.authorizationId)\n if (\n !matchesMutation(record, input) ||\n record.credentialMutation.kind !== \"revocation\" ||\n record.credentialMutation.phase !== \"result_staged\"\n ) {\n return null\n }\n const updated: ConnectorAuthorizationRecord = {\n ...record,\n status: \"revoked\",\n credentials: undefined,\n credentialExpiresAt: undefined,\n scopes: [],\n accounts: [],\n selectionExpiresAt: undefined,\n revision: record.revision + 1,\n credentialMutation: undefined,\n updatedAt: this.now(),\n }\n this.authorizations.set(record.id, updated)\n return structuredClone(updated)\n }\n\n async putConnection(input: PutConnectorConnectionInput): Promise<PutConnectorConnectionResult> {\n return this.putConnectionNow(input, this.now())\n }\n\n async putConnectionFromRun(\n input: PutConnectorConnectionFromRunInput\n ): Promise<PutConnectorConnectionFromRunResult> {\n const run = this.currentConnectionRun(input.runId)\n if (\n !sameConnectionRunScope(run, input) ||\n run.status !== \"waiting\" ||\n run.waitingFor !== \"account_selection\"\n ) {\n throw invalidRun()\n }\n const now = this.now()\n const result = this.putConnectionNow(\n {\n id: input.id,\n projectId: input.projectId,\n connectorId: input.connectorId,\n owner: run.owner,\n slot: run.slot,\n authorizationId: run.authorizationId,\n account: input.account,\n replace: input.replace,\n },\n now\n )\n const succeeded: ConnectorConnectionRunSucceededRecord = {\n ...connectionRunBase(run, now),\n status: \"succeeded\",\n authorizationId: run.authorizationId,\n ...(result.revocationPendingAuthorizationId === undefined\n ? {}\n : { cleanupAuthorizationId: result.revocationPendingAuthorizationId }),\n connections: [structuredClone(result.connection)],\n finishedAt: now,\n }\n this.connectionRuns.set(run.id, succeeded)\n return { ...result, run: structuredClone(succeeded) }\n }\n\n private putConnectionNow(\n input: PutConnectorConnectionInput,\n now: Date\n ): PutConnectorConnectionResult {\n const authorization = this.authorizations.get(input.authorizationId)\n if (\n !sameAuthorizationScope(authorization, input) ||\n !isSelectable(authorization.status) ||\n authorization.credentialMutation?.kind === \"reauthorization\"\n ) {\n throw authorizationConflict()\n }\n const account = authorization.accounts.find((candidate) => candidate.id === input.account.id)\n if (!account) {\n throw new ConnectorConnectionStorageError(\n \"authorization_conflict\",\n \"[Sixb] Connector connection account is not exposed by its authorization.\"\n )\n }\n const existing = this.findConnectionRecord(input)\n const sameAccount = existing?.account.id === account.id\n if (existing && !sameAccount && !input.replace) {\n throw new ConnectorConnectionStorageError(\n \"connection_conflict\",\n `[Sixb] Connector slot '${input.slot}' is already connected to another account; explicit replacement is required.`\n )\n }\n if (!existing && this.connections.has(input.id)) {\n throw new ConnectorConnectionStorageError(\n \"connection_conflict\",\n \"[Sixb] Connector connection id already exists.\"\n )\n }\n\n let revocationPendingAuthorizationId: string | undefined\n if (existing?.status === \"connected\" && existing.authorizationId !== authorization.id) {\n const previous = this.authorizations.get(existing.authorizationId)\n if (!previous) {\n throw new ConnectorConnectionStorageError(\n \"authorization_conflict\",\n \"[Sixb] Existing connector connection references an unavailable authorization.\"\n )\n }\n const remaining = this.connectedConnectionsForAuthorization(previous.id).filter(\n (connection) => connection.id !== existing.id\n )\n this.assertConnectionCanMove(existing, previous, remaining.length === 0)\n if (remaining.length === 0) {\n const pending = markAuthorizationRevocationPending(previous, now)\n this.authorizations.set(previous.id, pending)\n revocationPendingAuthorizationId = previous.id\n }\n } else if (existing?.status === \"connected\") {\n const previous = this.authorizations.get(existing.authorizationId)\n if (previous) this.assertConnectionCanMove(existing, previous, false)\n }\n\n const updatedAuthorization: ConnectorAuthorizationRecord =\n authorization.status === \"pending_selection\"\n ? {\n ...authorization,\n status: \"active\",\n selectionExpiresAt: undefined,\n revision: authorization.revision + 1,\n updatedAt: now,\n }\n : authorization\n const connection: ConnectorConnectionRecord = existing\n ? {\n ...existing,\n authorizationId: input.authorizationId,\n account: structuredClone(account),\n status: \"connected\",\n disconnectedAt: undefined,\n updatedAt: now,\n }\n : {\n id: input.id,\n projectId: input.projectId,\n connectorId: input.connectorId,\n owner: structuredClone(input.owner),\n slot: input.slot,\n authorizationId: input.authorizationId,\n account: structuredClone(account),\n status: \"connected\",\n createdAt: now,\n updatedAt: now,\n }\n\n if (updatedAuthorization !== authorization) {\n this.authorizations.set(updatedAuthorization.id, updatedAuthorization)\n }\n this.connections.set(connection.id, connection)\n return {\n connection: structuredClone(connection),\n authorization: structuredClone(updatedAuthorization),\n ...(revocationPendingAuthorizationId === undefined\n ? {}\n : { revocationPendingAuthorizationId }),\n created: existing === undefined,\n replaced: existing !== undefined && !sameAccount,\n }\n }\n\n async getConnection(\n input: GetConnectorConnectionInput\n ): Promise<ConnectorConnectionRecord | null> {\n const connection = this.findConnectionRecord(input)\n return connection?.status === \"connected\" ? structuredClone(connection) : null\n }\n\n async getConnectionById(\n input: ConnectorConnectionKey\n ): Promise<ConnectorConnectionRecord | null> {\n const connection = this.connections.get(input.connectionId)\n return sameConnectionScope(connection, input) ? structuredClone(connection) : null\n }\n\n async listConnections(\n input: ListConnectorConnectionsInput\n ): Promise<readonly ConnectorConnectionRecord[]> {\n return [...this.connections.values()]\n .filter((connection) => sameConnectionScope(connection, input))\n .map((connection) => structuredClone(connection))\n }\n\n async listConnectionsByAuthorization(\n input: ConnectorAuthorizationKey\n ): Promise<readonly ConnectorConnectionRecord[]> {\n const authorization = this.authorizations.get(input.authorizationId)\n if (!sameAuthorizationScope(authorization, input)) return []\n return this.connectedConnectionsForAuthorization(input.authorizationId)\n .filter((connection) => sameConnectionScope(connection, input))\n .map((connection) => structuredClone(connection))\n }\n\n async disconnectConnection(input: ConnectorConnectionKey): Promise<{\n readonly connection: ConnectorConnectionRecord\n readonly authorization: ConnectorAuthorizationRecord\n readonly revocationPendingAuthorizationId?: string\n } | null> {\n const connection = this.connections.get(input.connectionId)\n if (\n !connection ||\n connection.projectId !== input.projectId ||\n connection.connectorId !== input.connectorId\n ) {\n return null\n }\n const authorization = this.authorizations.get(connection.authorizationId)\n if (!sameAuthorizationScope(authorization, input)) {\n throw new ConnectorConnectionStorageError(\n \"authorization_conflict\",\n \"[Sixb] Connector connection references an unavailable authorization.\"\n )\n }\n if (connection.status === \"disconnected\") {\n return {\n connection: structuredClone(connection),\n authorization: structuredClone(authorization),\n ...(authorization.status === \"revocation_pending\"\n ? { revocationPendingAuthorizationId: authorization.id }\n : {}),\n }\n }\n\n const now = this.now()\n const remaining = this.connectedConnectionsForAuthorization(authorization.id).filter(\n (candidate) => candidate.id !== connection.id\n )\n this.assertConnectionCanMove(connection, authorization, remaining.length === 0)\n const disconnected = disconnectConnectionRecord(connection, now)\n this.connections.set(connection.id, disconnected)\n const updatedAuthorization =\n remaining.length === 0\n ? markAuthorizationRevocationPending(authorization, now)\n : authorization\n if (updatedAuthorization !== authorization) {\n this.authorizations.set(authorization.id, updatedAuthorization)\n }\n return {\n connection: structuredClone(disconnected),\n authorization: structuredClone(updatedAuthorization),\n ...(updatedAuthorization.status === \"revocation_pending\" && remaining.length === 0\n ? { revocationPendingAuthorizationId: updatedAuthorization.id }\n : {}),\n }\n }\n\n snapshot(): InMemoryConnectorConnectionStorageSnapshot {\n return {\n attempts: structuredClone(this.attempts),\n connectionRuns: structuredClone(this.connectionRuns),\n authorizations: structuredClone(this.authorizations),\n connections: structuredClone(this.connections),\n }\n }\n\n restore(snapshot: InMemoryConnectorConnectionStorageSnapshot): void {\n replaceMap(this.attempts, snapshot.attempts)\n replaceMap(this.connectionRuns, snapshot.connectionRuns)\n replaceMap(this.authorizations, snapshot.authorizations)\n replaceMap(this.connections, snapshot.connections)\n }\n\n private now(): Date {\n return new Date(this.options.now?.() ?? new Date())\n }\n\n private currentConnectionRun(runId: string): ConnectorConnectionRunRecord | undefined {\n const run = this.connectionRuns.get(runId)\n if (!run || (run.status !== \"waiting\" && run.status !== \"running\")) return run\n\n if (run.status === \"waiting\" && run.waitingFor === \"account_selection\") return run\n const now = this.now()\n if (run.expiresAt.getTime() > now.getTime()) return run\n\n if (run.status === \"waiting\" && run.waitingFor === \"provider_authorization\") {\n const attempt = this.findAuthorizationAttemptByConnectionRunId(run.id)\n if (attempt) this.attempts.delete(attempt.id)\n }\n if (run.status === \"waiting\") {\n const expired = expireConnectionRun(run, now)\n this.connectionRuns.set(run.id, expired)\n return expired\n }\n\n if (run.kind === \"connect\" && run.authorizationId) {\n this.markPendingAuthorizationForCleanup(run.connectorId, run.authorizationId, now)\n }\n const failed = failExpiredProcessingRun(run, now)\n this.connectionRuns.set(run.id, failed)\n return failed\n }\n\n private findConnectionRecord(\n input: GetConnectorConnectionInput\n ): ConnectorConnectionRecord | undefined {\n for (const connection of this.connections.values()) {\n if (\n connection.projectId === input.projectId &&\n connection.connectorId === input.connectorId &&\n connection.owner.type === input.owner.type &&\n connection.slot === input.slot\n ) {\n return connection\n }\n }\n return undefined\n }\n\n private findAuthorizationAttemptByConnectionRunId(\n connectionRunId: string\n ): ConnectorAuthorizationAttemptRecord | undefined {\n for (const attempt of this.attempts.values()) {\n if (attempt.connectionRunId === connectionRunId) return attempt\n }\n return undefined\n }\n\n private connectionRecordsForAuthorization(authorizationId: string): ConnectorConnectionRecord[] {\n return [...this.connections.values()].filter(\n (connection) => connection.authorizationId === authorizationId\n )\n }\n\n private connectedConnectionsForAuthorization(\n authorizationId: string\n ): ConnectorConnectionRecord[] {\n return this.connectionRecordsForAuthorization(authorizationId).filter(\n (connection) => connection.status === \"connected\"\n )\n }\n\n private assertConnectionCanMove(\n _connection: ConnectorConnectionRecord,\n authorization: ConnectorAuthorizationRecord,\n removingLastConnection = true\n ): void {\n const mutation = authorization.credentialMutation\n if (mutation?.kind === \"reauthorization\") {\n throw new ConnectorConnectionStorageError(\n \"authorization_conflict\",\n \"[Sixb] Connections cannot change while their connector authorization is being reauthorized.\"\n )\n }\n if (removingLastConnection && mutation) {\n throw new ConnectorConnectionStorageError(\n \"authorization_conflict\",\n \"[Sixb] The last connector connection cannot be removed while credentials are being mutated.\"\n )\n }\n }\n\n private markPendingAuthorizationForCleanup(\n connectorId: string,\n authorizationId: string,\n now: Date\n ): void {\n const authorization = this.authorizations.get(authorizationId)\n if (\n !authorization ||\n authorization.connectorId !== connectorId ||\n authorization.status !== \"pending_selection\"\n ) {\n return\n }\n this.authorizations.set(\n authorization.id,\n markAuthorizationRevocationPending(authorization, now)\n )\n }\n}\n\nfunction disconnectConnectionRecord(\n connection: ConnectorConnectionRecord,\n now: Date\n): ConnectorConnectionRecord {\n return {\n ...connection,\n status: \"disconnected\",\n disconnectedAt: new Date(now),\n updatedAt: new Date(now),\n }\n}\n\nfunction markAuthorizationRevocationPending(\n authorization: ConnectorAuthorizationRecord,\n now: Date\n): ConnectorAuthorizationRecord {\n if (authorization.status === \"revocation_pending\" || authorization.status === \"revoked\") {\n return authorization\n }\n if (authorization.credentialMutation) {\n throw new ConnectorConnectionStorageError(\n \"authorization_conflict\",\n \"[Sixb] Connector authorization cannot begin revocation while credentials are being mutated.\"\n )\n }\n return {\n ...authorization,\n status: \"revocation_pending\",\n selectionExpiresAt: undefined,\n revision: authorization.revision + 1,\n updatedAt: new Date(now),\n }\n}\n\nfunction safeEqual(left: string, right: string): boolean {\n const leftBytes = Buffer.from(left)\n const rightBytes = Buffer.from(right)\n return leftBytes.length === rightBytes.length && timingSafeEqual(leftBytes, rightBytes)\n}\n\nfunction invalidRun(): ConnectorConnectionStorageError {\n return new ConnectorConnectionStorageError(\n \"run_invalid\",\n \"[Sixb] Connector connection run is invalid, expired, or already used.\"\n )\n}\n\nfunction replaceMap<TKey, TValue>(target: Map<TKey, TValue>, source: Map<TKey, TValue>): void {\n target.clear()\n for (const [key, value] of structuredClone(source)) target.set(key, value)\n}\n\nfunction sameIds(left: readonly string[], right: readonly string[]): boolean {\n const leftSorted = [...left].sort()\n const rightSorted = [...right].sort()\n return (\n leftSorted.length === rightSorted.length &&\n leftSorted.every((value, index) => value === rightSorted[index])\n )\n}\n\nfunction invalidAttempt(): ConnectorConnectionStorageError {\n return new ConnectorConnectionStorageError(\n \"attempt_invalid\",\n \"[Sixb] Connector authorization attempt is invalid, expired, or already used.\"\n )\n}\n\nfunction authorizationConflict(): ConnectorConnectionStorageError {\n return new ConnectorConnectionStorageError(\n \"authorization_conflict\",\n \"[Sixb] Connector connection requires a selectable authorization from the same project and connector.\"\n )\n}\n\nfunction assertPositiveDuration(value: number, name: string): void {\n if (!Number.isFinite(value) || value <= 0) {\n throw new ConnectorConnectionStorageError(\n \"invalid_input\",\n `[Sixb] Connector ${name} must be positive.`\n )\n }\n}\n\nfunction sameAuthorizationScope(\n record: ConnectorAuthorizationRecord | undefined,\n input: { readonly projectId: string; readonly connectorId: string }\n): record is ConnectorAuthorizationRecord {\n return (\n record !== undefined &&\n record.projectId === input.projectId &&\n record.connectorId === input.connectorId\n )\n}\n\nfunction sameConnectionScope(\n record: ConnectorConnectionRecord | undefined,\n input: { readonly projectId: string; readonly connectorId: string }\n): record is ConnectorConnectionRecord {\n return (\n record !== undefined &&\n record.projectId === input.projectId &&\n record.connectorId === input.connectorId\n )\n}\n\nfunction sameConnectionRunScope(\n record: ConnectorConnectionRunRecord | undefined,\n input: { readonly projectId: string; readonly connectorId: string }\n): record is ConnectorConnectionRunRecord {\n return (\n record !== undefined &&\n record.projectId === input.projectId &&\n record.connectorId === input.connectorId\n )\n}\n\nfunction canClaimMutation(\n status: ConnectorAuthorizationRecord[\"status\"],\n kind: ClaimConnectorCredentialMutationInput[\"mutation\"][\"kind\"]\n): boolean {\n if (kind === \"refresh\") return status === \"active\"\n if (kind === \"reauthorization\") {\n return status === \"active\" || status === \"needs_reauthorization\"\n }\n return status !== \"revoked\"\n}\n\nfunction isSelectable(status: ConnectorAuthorizationRecord[\"status\"]): boolean {\n return status === \"pending_selection\" || status === \"active\"\n}\n\nfunction leaseExpiry(now: Date, durationMs: number, deadlineAt: Date): Date {\n return new Date(Math.min(now.getTime() + durationMs, deadlineAt.getTime()))\n}\n\nfunction mutationExpired(record: ConnectorAuthorizationRecord, now: Date): boolean {\n return (\n record.credentialMutation!.expiresAt.getTime() <= now.getTime() ||\n record.credentialMutation!.deadlineAt.getTime() <= now.getTime()\n )\n}\n\nfunction matchesMutation(\n record: ConnectorAuthorizationRecord | undefined,\n input: ConnectorCredentialMutationFence,\n holderId?: string\n): record is ConnectorAuthorizationRecord & {\n readonly credentialMutation: NonNullable<ConnectorAuthorizationRecord[\"credentialMutation\"]>\n} {\n return (\n sameAuthorizationScope(record, input) &&\n record.revision === input.expectedRevision &&\n record.credentialMutation?.id === input.mutationId &&\n (holderId === undefined || record.credentialMutation.holderId === holderId)\n )\n}\n\nfunction stagedCredentials(\n record: ConnectorAuthorizationRecord | undefined,\n input: ConnectorCredentialMutationFence,\n kind: \"refresh\" | \"reauthorization\"\n) {\n if (\n !matchesMutation(record, input) ||\n record.credentialMutation.kind !== kind ||\n record.credentialMutation.phase !== \"result_staged\"\n ) {\n return null\n }\n return record.credentialMutation.stagedCredentials ?? null\n}\n\nfunction applyStagedCredentials(\n record: ConnectorAuthorizationRecord,\n staged: NonNullable<ReturnType<typeof stagedCredentials>>,\n now: Date,\n input: {\n readonly status: \"active\"\n readonly accounts: readonly ConnectorAuthorizationRecord[\"accounts\"][number][]\n }\n): ConnectorAuthorizationRecord {\n return {\n ...record,\n credentials: structuredClone(staged.credentials),\n credentialExpiresAt:\n staged.credentialExpiresAt === undefined ? undefined : new Date(staged.credentialExpiresAt),\n scopes: [...staged.scopes],\n accounts: structuredClone(input.accounts),\n status: input.status,\n selectionExpiresAt: undefined,\n revision: record.revision + 1,\n credentialMutation: undefined,\n updatedAt: now,\n }\n}\n",
|
|
12
|
+
"/**\n * Transport-agnostic reasons a file upload session operation can fail. Mapping a\n * reason to an HTTP status (or any other transport) is the responsibility of the\n * boundary that surfaces it, not of core.\n */\nexport type FileUploadSessionErrorReason =\n | \"not_found\"\n | \"expired\"\n | \"already_completed\"\n | \"already_aborted\"\n\n/**\n * Error for file upload session invariants and invalid state transitions.\n */\nexport class FileUploadSessionError extends Error {\n readonly name = \"FileUploadSessionError\"\n\n constructor(\n readonly reason: FileUploadSessionErrorReason,\n message: string\n ) {\n super(message)\n }\n}\n",
|
|
13
|
+
"import type { Principal } from \"../../auth\"\nimport type { FileRef, SignedBlobUploadPart } from \"../../blob-storage\"\nimport { FileUploadSessionError } from \"./errors\"\nimport type {\n CreateFileUploadSessionInput,\n FileUploadSession,\n FileUploadSessionStore,\n} from \"./types\"\nimport {\n createFileUploadId,\n isFileUploadSessionExpired,\n isTerminalFileUploadSessionExpired,\n principalKey,\n shouldDeleteFileUploadSession,\n} from \"./utils\"\n\nexport type InMemoryFileUploadSessionsSnapshot = Map<string, FileUploadSession>\n\n/**\n * In-memory {@link FileUploadSessionStore}.\n *\n * Sessions live only in this process's memory: they do not survive a restart and\n * are not shared across instances. Staged/direct-put uploads therefore require a\n * single-instance deployment for now; a durable (Pg/Sqlite) store is a follow-up.\n * Expired sessions are reaped opportunistically on `create` and on demand via\n * `cleanupExpired` (there is no background sweeper).\n */\nexport class InMemoryFileUploadSessions implements FileUploadSessionStore {\n private readonly sessionsById = new Map<string, FileUploadSession>()\n\n snapshot(): InMemoryFileUploadSessionsSnapshot {\n return structuredClone(this.sessionsById)\n }\n\n restore(snapshot: InMemoryFileUploadSessionsSnapshot): void {\n this.sessionsById.clear()\n for (const [id, session] of snapshot) {\n this.sessionsById.set(id, structuredClone(session))\n }\n }\n\n async create(input: CreateFileUploadSessionInput): Promise<FileUploadSession> {\n await this.cleanupExpired()\n\n const session: FileUploadSession = {\n id: input.id ?? createFileUploadId(),\n projectId: input.projectId,\n principalKey: principalKey(input.principal),\n strategy: input.strategy,\n status: \"pending\",\n ...(input.fileName === undefined ? {} : { fileName: input.fileName }),\n ...(input.mediaType === undefined ? {} : { mediaType: input.mediaType }),\n ...(input.logicalPath === undefined ? {} : { logicalPath: input.logicalPath }),\n ...(input.expectedSizeBytes === undefined\n ? {}\n : { expectedSizeBytes: input.expectedSizeBytes }),\n ...(input.expectedDigest === undefined ? {} : { expectedDigest: input.expectedDigest }),\n ...(input.providerUpload === undefined ? {} : { providerUpload: input.providerUpload }),\n signedParts: [],\n createdAt: new Date(),\n expiresAt: input.expiresAt,\n }\n\n this.sessionsById.set(session.id, session)\n return session\n }\n\n async getForPrincipal(uploadId: string, principal: Principal): Promise<FileUploadSession> {\n const session = this.sessionsById.get(uploadId)\n if (!session || session.principalKey !== principalKey(principal)) {\n throw new FileUploadSessionError(\"not_found\", \"File upload session not found.\")\n }\n\n const nowMs = Date.now()\n if (isFileUploadSessionExpired(session, nowMs)) {\n this.sessionsById.delete(uploadId)\n throw new FileUploadSessionError(\"expired\", \"File upload session has expired.\")\n }\n\n if (isTerminalFileUploadSessionExpired(session, nowMs)) {\n this.sessionsById.delete(uploadId)\n throw new FileUploadSessionError(\"not_found\", \"File upload session not found.\")\n }\n\n return session\n }\n\n async markUploaded(uploadId: string, fileRef: FileRef): Promise<FileUploadSession> {\n const session = this.requirePending(uploadId)\n const updated = {\n ...session,\n fileRef,\n }\n this.sessionsById.set(uploadId, updated)\n return updated\n }\n\n async addSignedPart(uploadId: string, part: SignedBlobUploadPart): Promise<FileUploadSession> {\n const session = this.requirePending(uploadId)\n const updated = {\n ...session,\n signedParts: [\n ...session.signedParts.filter((candidate) => candidate.partNumber !== part.partNumber),\n part,\n ].sort((left, right) => left.partNumber - right.partNumber),\n }\n this.sessionsById.set(uploadId, updated)\n return updated\n }\n\n async complete(uploadId: string, fileRef: FileRef): Promise<FileUploadSession> {\n const session = this.requirePending(uploadId)\n const updated = {\n ...session,\n status: \"completed\" as const,\n fileRef,\n completedAt: new Date(),\n }\n this.sessionsById.set(uploadId, updated)\n return updated\n }\n\n async abort(uploadId: string): Promise<FileUploadSession> {\n const session = this.requirePending(uploadId)\n const updated = {\n ...session,\n status: \"aborted\" as const,\n abortedAt: new Date(),\n }\n this.sessionsById.set(uploadId, updated)\n return updated\n }\n\n async cleanupExpired(now = new Date()): Promise<number> {\n let deleted = 0\n for (const [id, session] of this.sessionsById) {\n if (shouldDeleteFileUploadSession(session, now.getTime())) {\n this.sessionsById.delete(id)\n deleted += 1\n }\n }\n\n return deleted\n }\n\n private requirePending(uploadId: string): FileUploadSession {\n const session = this.sessionsById.get(uploadId)\n if (!session) {\n throw new FileUploadSessionError(\"not_found\", \"File upload session not found.\")\n }\n\n if (session.status !== \"pending\") {\n throw new FileUploadSessionError(\n session.status === \"completed\" ? \"already_completed\" : \"already_aborted\",\n `File upload session is already ${session.status}.`\n )\n }\n\n return session\n }\n}\n",
|
|
14
|
+
"import { AsyncLocalStorage } from \"node:async_hooks\"\nimport { InMemoryActionRunStorage } from \"../action-runs\"\nimport { type AgentStorage, InMemoryAgentStorage } from \"../agents\"\nimport { type AiAccountingAttribution, type AiCostStorage, InMemoryAiCostStorage } from \"../ai-cost\"\nimport { directModelCallAttribution } from \"../ai-cost/attribution\"\nimport { type AiLimitStorage, InMemoryAiLimitStorage } from \"../ai-limits\"\nimport { type AiUsageStorage, InMemoryAiUsageStorage } from \"../ai-usage\"\nimport { type AuthStorage, InMemoryAuthStorage } from \"../auth\"\nimport {\n type ConnectorConnectionStorage,\n InMemoryConnectorConnectionStorage,\n} from \"../connector-connections\"\nimport { StorageTransactionError } from \"../errors\"\nimport { InMemoryExecutionStorage } from \"../executions/in-memory\"\nimport type { ExecutionStorage } from \"../executions/types\"\nimport { type FileUploadSessionStore, InMemoryFileUploadSessions } from \"../file-upload-sessions\"\nimport type { ObjectStorage } from \"../objects\"\nimport { InMemoryObjectStorage } from \"../objects/in-memory\"\nimport type { OntologyStorage } from \"../ontology\"\nimport { InMemoryOntologyStorage } from \"../ontology/in-memory\"\nimport { ProviderMaterializationTransactionLifecycle } from \"../ontology/provider\"\nimport {\n createAgentOperationScope,\n createAuthOperationScope,\n createObjectOperationScope,\n createOntologyOperationScope,\n createOperationScopedFacade,\n createStorageOperationScope,\n createWorkflowRunOperationScope,\n} from \"../operation-scope\"\nimport { InMemoryPipelineRunStorage, type PipelineRunStorage } from \"../pipeline-runs\"\nimport { InMemoryProjectionRunStorage } from \"../projection-runs\"\nimport { InMemoryRulesStorage, type RulesStorage } from \"../rules\"\nimport { InMemoryShareGrantStorage, type ShareGrantStorage } from \"../share-grants\"\nimport { InMemoryShareSessionStorage, type ShareSessionStorage } from \"../share-sessions\"\nimport { InMemorySyncRunStorage, type SyncRunStorage } from \"../sync-runs\"\nimport type { TimeseriesStorage } from \"../timeseries\"\nimport { InMemoryTimeseriesStorage } from \"../timeseries/store\"\nimport { createTransactionStorageProxy, throwNestedStorageTransaction } from \"../transaction\"\nimport type { Storage, StorageTransactionOptions } from \"../types\"\nimport { InMemoryWebhookRunStorage, type WebhookRunStorage } from \"../webhook-runs\"\nimport {\n InMemoryWorkflowInterventionStorage,\n type WorkflowInterventionStorage,\n} from \"../workflow-interventions\"\nimport { InMemoryWorkflowRunStorage, type WorkflowRunStorage } from \"../workflow-runs\"\nimport { registerInMemoryStorageTestingAdapter } from \"./testing\"\n\n/**\n * In-memory {@link Storage} used for dev and tests.\n *\n * Every top-level storage call (\"root operation\") serializes against a single promise-chain lock\n * unless a transaction is already active, which is what gives {@link InMemoryStorage.transaction}\n * snapshot/rollback atomicity. The provider owns one operation scope and applies it to every async\n * root capability. Transaction calls reuse the already-active scope and therefore never reacquire\n * its non-reentrant lock.\n */\nexport interface InMemoryStorageOptions {\n readonly connectorConnections?: {\n /** Storage-authoritative clock override for deterministic development and tests. */\n readonly now?: () => Date\n }\n}\n\nexport class InMemoryStorage implements Storage {\n readonly objects: ObjectStorage\n readonly timeseries: TimeseriesStorage\n readonly ontology: OntologyStorage\n private readonly objectStorage = new InMemoryObjectStorage()\n private readonly timeseriesStorage = new InMemoryTimeseriesStorage()\n private readonly ontologyStorage: InMemoryOntologyStorage\n private readonly authStorage = new InMemoryAuthStorage()\n private readonly shareGrantStorage = new InMemoryShareGrantStorage()\n private readonly shareSessionStorage = new InMemoryShareSessionStorage(this.shareGrantStorage)\n private readonly executionStorage = new InMemoryExecutionStorage(this.authStorage, {\n shareSessions: this.shareSessionStorage,\n })\n private readonly agentStorage = new InMemoryAgentStorage(this.executionStorage)\n private readonly aiUsageStorage = new InMemoryAiUsageStorage(this.executionStorage)\n private readonly aiCostStorage = new InMemoryAiCostStorage(this.aiUsageStorage, {\n resolve: (input) => this.resolveAiAccountingAttribution(input),\n resolveGroup: async (input) => {\n const attribution = await this.resolveAiAccountingAttribution(input)\n if (attribution?.kind !== \"subagent\") return { executionId: input.executionId, attribution }\n const parent = await this.agentStorage.runs.getById({\n projectId: input.projectId,\n id: attribution.parentRunId,\n })\n if (!parent) throw new Error(\"[Sixb] Subagent accounting parent is missing.\")\n return {\n executionId: parent.executionId,\n attribution: await this.resolveAiAccountingAttribution({\n ...input,\n executionId: parent.executionId,\n }),\n }\n },\n })\n private readonly aiLimitStorage = new InMemoryAiLimitStorage({\n resolveExecution: ({ projectId, executionId }) =>\n this.executionStorage.getById({ projectId, id: executionId }),\n resolveUsageRecord: ({ projectId, usageRecordId }) =>\n this.aiUsageStorage.getRecord(projectId, usageRecordId),\n resolveCostRecord: ({ projectId, usageRecordId }) =>\n this.aiCostStorage.getRecord(projectId, usageRecordId),\n listUsageRecords: ({ projectId }) => this.aiUsageStorage.listRecords(projectId),\n })\n private readonly actionRunStorage = new InMemoryActionRunStorage(this.executionStorage)\n private readonly syncRunStorage = new InMemorySyncRunStorage(this.executionStorage)\n private readonly pipelineRunStorage = new InMemoryPipelineRunStorage(this.executionStorage)\n private readonly projectionRunStorage = new InMemoryProjectionRunStorage({\n executions: this.executionStorage,\n })\n private readonly workflowRunStorage = new InMemoryWorkflowRunStorage(this.executionStorage)\n private readonly workflowInterventionStorage = new InMemoryWorkflowInterventionStorage()\n private readonly webhookRunStorage = new InMemoryWebhookRunStorage(this.executionStorage)\n private readonly rulesStorage = new InMemoryRulesStorage()\n private readonly fileUploadSessionStorage = new InMemoryFileUploadSessions()\n private readonly connectorConnectionStorage: InMemoryConnectorConnectionStorage\n readonly auth: AuthStorage\n readonly executions: ExecutionStorage\n readonly agents: AgentStorage\n readonly aiUsage: AiUsageStorage\n readonly aiCosts: AiCostStorage\n readonly aiLimits: AiLimitStorage\n readonly actionRuns: InMemoryActionRunStorage\n readonly syncRuns: SyncRunStorage\n readonly pipelineRuns: PipelineRunStorage\n readonly projectionRuns: InMemoryProjectionRunStorage\n readonly workflowRuns: WorkflowRunStorage\n readonly workflowInterventions: WorkflowInterventionStorage\n readonly webhookRuns: WebhookRunStorage\n readonly rules: RulesStorage\n readonly shareGrants: ShareGrantStorage\n readonly shareSessions: ShareSessionStorage\n readonly fileUploadSessions: FileUploadSessionStore\n readonly connectorConnections: ConnectorConnectionStorage\n\n constructor(options: InMemoryStorageOptions = {}) {\n this.connectorConnectionStorage = new InMemoryConnectorConnectionStorage(\n options.connectorConnections\n )\n const scope = createStorageOperationScope(\n (run) => this.withStorageOperation(run),\n () => this.assertRootOperationAvailable()\n )\n this.objects = createObjectOperationScope(this.objectStorage, scope)\n this.timeseries = createOperationScopedFacade(this.timeseriesStorage, scope)\n this.auth = createAuthOperationScope(this.authStorage, scope)\n this.executions = createOperationScopedFacade(this.executionStorage, scope)\n this.agents = createAgentOperationScope(this.agentStorage, scope)\n this.aiUsage = createOperationScopedFacade(this.aiUsageStorage, scope)\n this.aiCosts = createOperationScopedFacade(this.aiCostStorage, scope)\n this.aiLimits = createOperationScopedFacade(this.aiLimitStorage, scope)\n this.actionRuns = createOperationScopedFacade(this.actionRunStorage, scope)\n this.syncRuns = createOperationScopedFacade(this.syncRunStorage, scope)\n this.pipelineRuns = createOperationScopedFacade(this.pipelineRunStorage, scope)\n this.projectionRuns = createOperationScopedFacade(this.projectionRunStorage, scope)\n this.workflowRuns = createWorkflowRunOperationScope(this.workflowRunStorage, scope)\n this.workflowInterventions = createOperationScopedFacade(\n this.workflowInterventionStorage,\n scope\n )\n this.webhookRuns = createOperationScopedFacade(this.webhookRunStorage, scope)\n this.rules = createOperationScopedFacade(this.rulesStorage, scope)\n this.shareGrants = createOperationScopedFacade(this.shareGrantStorage, scope)\n this.shareSessions = createOperationScopedFacade(this.shareSessionStorage, scope)\n this.fileUploadSessions = createOperationScopedFacade(this.fileUploadSessionStorage, scope)\n this.connectorConnections = createOperationScopedFacade(this.connectorConnectionStorage, scope)\n this.ontologyStorage = new InMemoryOntologyStorage(this.objectStorage, this.timeseriesStorage, {\n runRootOperation: async (run) => run(),\n getTransactionToken: () => this.getActiveTransactionToken(),\n getMaterializationLifecycle: () => this.getActiveMaterializationLifecycle(),\n assertSourceMaterializationExecution: (input) =>\n this.projectionRunStorage.assertSourceMaterializationExecutionUnlocked(input),\n executionExists: async (projectId, executionId) =>\n (await this.executionStorage.getById({ projectId, id: executionId })) !== null,\n })\n this.ontology = createOntologyOperationScope(this.ontologyStorage, scope)\n this.ontologyStorage.registerTestingAlias(this.ontology)\n registerInMemoryStorageTestingAdapter(this, { snapshot: () => this.snapshot() })\n }\n\n private async resolveAiAccountingAttribution(input: {\n readonly projectId: string\n readonly executionId: string\n }): Promise<AiAccountingAttribution | undefined> {\n const execution = await this.executionStorage.getById({\n projectId: input.projectId,\n id: input.executionId,\n })\n if (!execution) return undefined\n if (execution.executor.type !== \"agent\") {\n const executor = execution.executor\n return directModelCallAttribution(\n executor.type === \"primitive\" ? executor.kind : executor.type,\n executor.type === \"request\"\n ? executor.requestId\n : executor.type === \"primitive\"\n ? executor.runId\n : null,\n execution.authorizationRef.type === \"trustedPrimitive\"\n ? execution.authorizationRef.primitive.id\n : null\n )\n }\n const directRun = await this.agentStorage.runs.getById({\n projectId: input.projectId,\n id: execution.executor.runId,\n })\n if (directRun?.kind === \"conversation\") {\n return {\n kind: \"agent\",\n agentRunId: directRun.id,\n threadId: directRun.threadId,\n }\n }\n if (directRun?.kind === \"subagent\") {\n return {\n kind: \"subagent\",\n subagentRunId: directRun.id,\n parentRunId: directRun.parentRunId,\n }\n }\n const agentRun = await this.workflowRunStorage.agentNodes.getByNodeRunId({\n projectId: input.projectId,\n nodeRunId: execution.executor.runId,\n })\n if (!agentRun) return undefined\n const node = await this.workflowRunStorage.nodes.getById({\n projectId: input.projectId,\n id: agentRun.nodeRunId,\n })\n if (!node) return undefined\n return {\n kind: \"workflowAgent\",\n agentStepId: node.nodeId,\n nodeRunId: agentRun.nodeRunId,\n workflowId: node.workflowId,\n workflowRunId: node.workflowRunId,\n }\n }\n\n private readonly transactionScope = new AsyncLocalStorage<object>()\n private readonly activeTransactionTokens = new WeakSet<object>()\n private readonly materializationLifecycles = new WeakMap<\n object,\n ProviderMaterializationTransactionLifecycle\n >()\n private transactionTail: Promise<void> = Promise.resolve()\n\n async ping(): Promise<void> {\n await this.withStorageOperation(() => undefined)\n }\n\n /**\n * Run `run` against a transactional view of this storage.\n *\n * Atomicity is achieved by snapshotting every store before the callback and restoring that\n * snapshot if it throws. The snapshot is a full structural clone of the in-memory dataset, so\n * its cost scales with total dataset size rather than changeset size. That is acceptable for the\n * dev/test role of {@link InMemoryStorage} but is the reason it is not intended for large\n * datasets under heavy transactional load — the SQL providers use real database transactions.\n *\n * The `isolation` option is intentionally ignored: the promise-chain lock serializes\n * transactions one at a time, which is at least as strong as `serializable`.\n */\n async transaction<T>(\n run: (tx: Storage) => Promise<T> | T,\n _options: StorageTransactionOptions = {}\n ): Promise<T> {\n const inheritedTransactionToken = this.transactionScope.getStore()\n if (inheritedTransactionToken && this.activeTransactionTokens.has(inheritedTransactionToken)) {\n throwNestedStorageTransaction()\n }\n\n return this.withTransactionLock(async () => {\n const snapshot = this.snapshot()\n let active = true\n const tx = createTransactionStorageProxy(this.createTransactionStorage(), () => active)\n const transactionToken = {}\n const materializationLifecycle = new ProviderMaterializationTransactionLifecycle()\n this.activeTransactionTokens.add(transactionToken)\n this.materializationLifecycles.set(transactionToken, materializationLifecycle)\n\n try {\n const result = await this.transactionScope.run(transactionToken, async () => {\n try {\n return await run(tx)\n } finally {\n await this.aiLimitStorage.settleOperations()\n }\n })\n materializationLifecycle.assertCommittable()\n return result\n } catch (error) {\n // A failed rollback leaves the store in an unknown state. Surface that explicitly instead\n // of letting the restore error silently replace (mask) the original transaction error.\n try {\n this.restore(snapshot)\n } catch (restoreError) {\n throw new StorageTransactionError(\n `[Sixb] In-memory storage failed to roll back after a transaction error; state may be inconsistent. Original transaction error: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { cause: restoreError }\n )\n }\n throw error\n } finally {\n this.ontologyStorage.completeTransaction(transactionToken)\n materializationLifecycle.deactivate()\n this.activeTransactionTokens.delete(transactionToken)\n active = false\n }\n })\n }\n\n private async withStorageOperation<T>(run: () => Promise<T> | T): Promise<T> {\n this.assertRootOperationAvailable()\n return this.withTransactionLock(async () => run())\n }\n\n private assertRootOperationAvailable(): void {\n if (!this.getActiveTransactionToken()) return\n throw new StorageTransactionError(\n \"[Sixb] Root storage cannot be used inside a transaction callback; use the provided tx storage.\"\n )\n }\n\n private getActiveTransactionToken(): object | null {\n const token = this.transactionScope.getStore()\n return token && this.activeTransactionTokens.has(token) ? token : null\n }\n\n private getActiveMaterializationLifecycle(): ProviderMaterializationTransactionLifecycle | null {\n const token = this.getActiveTransactionToken()\n return token ? (this.materializationLifecycles.get(token) ?? null) : null\n }\n\n private async withTransactionLock<T>(run: () => Promise<T>): Promise<T> {\n const previous = this.transactionTail\n let release!: () => void\n this.transactionTail = new Promise<void>((resolve) => {\n release = resolve\n })\n\n await previous\n try {\n return await run()\n } finally {\n release()\n }\n }\n\n private createTransactionStorage(): Storage {\n return {\n objects: this.objectStorage,\n timeseries: this.timeseriesStorage,\n ontology: this.ontologyStorage,\n auth: this.authStorage,\n executions: this.executionStorage,\n agents: this.agentStorage,\n aiUsage: this.aiUsageStorage,\n aiCosts: this.aiCostStorage,\n aiLimits: this.aiLimitStorage,\n actionRuns: this.actionRunStorage,\n syncRuns: this.syncRunStorage,\n pipelineRuns: this.pipelineRunStorage,\n projectionRuns: this.projectionRunStorage,\n workflowRuns: this.workflowRunStorage,\n workflowInterventions: this.workflowInterventionStorage,\n webhookRuns: this.webhookRunStorage,\n rules: this.rulesStorage,\n shareGrants: this.shareGrantStorage,\n shareSessions: this.shareSessionStorage,\n fileUploadSessions: this.fileUploadSessionStorage,\n connectorConnections: this.connectorConnectionStorage,\n ping: async () => undefined,\n transaction: async <T>(): Promise<T> => {\n throwNestedStorageTransaction()\n },\n }\n }\n\n private snapshot(): InMemoryStorageSnapshot {\n return {\n objects: this.objectStorage.snapshot(),\n timeseries: this.timeseriesStorage.snapshot(),\n ontology: this.ontologyStorage.snapshot(),\n auth: this.authStorage.snapshot(),\n executions: this.executionStorage.snapshot(),\n agents: this.agentStorage.snapshot(),\n aiUsage: this.aiUsageStorage.snapshot(),\n aiCosts: this.aiCostStorage.snapshot(),\n aiLimits: this.aiLimitStorage.snapshot(),\n actionRuns: this.actionRunStorage.snapshot(),\n syncRuns: this.syncRunStorage.snapshot(),\n pipelineRuns: this.pipelineRunStorage.snapshot(),\n projectionRuns: this.projectionRunStorage.snapshot(),\n workflowRuns: this.workflowRunStorage.snapshot(),\n workflowInterventions: this.workflowInterventionStorage.snapshot(),\n webhookRuns: this.webhookRunStorage.snapshot(),\n rules: this.rulesStorage.snapshot(),\n shareGrants: this.shareGrantStorage.snapshot(),\n shareSessions: this.shareSessionStorage.snapshot(),\n fileUploadSessions: this.fileUploadSessionStorage.snapshot(),\n connectorConnections: this.connectorConnectionStorage.snapshot(),\n }\n }\n\n private restore(snapshot: InMemoryStorageSnapshot): void {\n this.objectStorage.restore(snapshot.objects)\n this.timeseriesStorage.restore(snapshot.timeseries)\n this.ontologyStorage.restore(snapshot.ontology)\n this.authStorage.restore(snapshot.auth)\n this.executionStorage.restore(snapshot.executions)\n this.agentStorage.restore(snapshot.agents)\n this.aiUsageStorage.restore(snapshot.aiUsage)\n this.aiCostStorage.restore(snapshot.aiCosts)\n this.aiLimitStorage.restore(snapshot.aiLimits)\n this.actionRunStorage.restore(snapshot.actionRuns)\n this.syncRunStorage.restore(snapshot.syncRuns)\n this.pipelineRunStorage.restore(snapshot.pipelineRuns)\n this.projectionRunStorage.restore(snapshot.projectionRuns)\n this.workflowRunStorage.restore(snapshot.workflowRuns)\n this.workflowInterventionStorage.restore(snapshot.workflowInterventions)\n this.webhookRunStorage.restore(snapshot.webhookRuns)\n this.rulesStorage.restore(snapshot.rules)\n this.shareGrantStorage.restore(snapshot.shareGrants)\n this.shareSessionStorage.restore(snapshot.shareSessions)\n this.fileUploadSessionStorage.restore(snapshot.fileUploadSessions)\n this.connectorConnectionStorage.restore(snapshot.connectorConnections)\n }\n}\n\nexport interface InMemoryStorageSnapshot {\n readonly objects: ReturnType<InMemoryObjectStorage[\"snapshot\"]>\n readonly timeseries: ReturnType<InMemoryTimeseriesStorage[\"snapshot\"]>\n readonly ontology: ReturnType<InMemoryOntologyStorage[\"snapshot\"]>\n readonly auth: ReturnType<InMemoryAuthStorage[\"snapshot\"]>\n readonly executions: ReturnType<InMemoryExecutionStorage[\"snapshot\"]>\n readonly agents: ReturnType<InMemoryAgentStorage[\"snapshot\"]>\n readonly aiUsage: ReturnType<InMemoryAiUsageStorage[\"snapshot\"]>\n readonly aiCosts: ReturnType<InMemoryAiCostStorage[\"snapshot\"]>\n readonly aiLimits: ReturnType<InMemoryAiLimitStorage[\"snapshot\"]>\n readonly actionRuns: ReturnType<InMemoryActionRunStorage[\"snapshot\"]>\n readonly syncRuns: ReturnType<InMemorySyncRunStorage[\"snapshot\"]>\n readonly pipelineRuns: ReturnType<InMemoryPipelineRunStorage[\"snapshot\"]>\n readonly projectionRuns: ReturnType<InMemoryProjectionRunStorage[\"snapshot\"]>\n readonly workflowRuns: ReturnType<InMemoryWorkflowRunStorage[\"snapshot\"]>\n readonly workflowInterventions: ReturnType<InMemoryWorkflowInterventionStorage[\"snapshot\"]>\n readonly webhookRuns: ReturnType<InMemoryWebhookRunStorage[\"snapshot\"]>\n readonly rules: ReturnType<InMemoryRulesStorage[\"snapshot\"]>\n readonly shareGrants: ReturnType<InMemoryShareGrantStorage[\"snapshot\"]>\n readonly shareSessions: ReturnType<InMemoryShareSessionStorage[\"snapshot\"]>\n readonly fileUploadSessions: ReturnType<InMemoryFileUploadSessions[\"snapshot\"]>\n readonly connectorConnections: ReturnType<InMemoryConnectorConnectionStorage[\"snapshot\"]>\n}\n",
|
|
15
|
+
"import type { AuthStorage } from \"../auth\"\nimport type { ShareSessionStorage } from \"../share-sessions\"\nimport { ExecutionStorageError } from \"./errors\"\nimport type { CreateExecutionInput, ExecutionRecord, ExecutionStorage } from \"./types\"\nimport { cloneExecutionRecord, prepareExecutionRecord } from \"./validation\"\n\ntype RunRootOperation = <T>(run: () => Promise<T> | T) => Promise<T>\n\nconst runDirectly: RunRootOperation = async <T>(run: () => Promise<T> | T): Promise<T> => run()\n\nfunction executionKey(projectId: string, id: string): string {\n return JSON.stringify([projectId, id])\n}\n\nexport class InMemoryExecutionStorage implements ExecutionStorage {\n private readonly rows = new Map<string, ExecutionRecord>()\n private readonly runRootOperation: RunRootOperation\n private readonly shareSessions?: Pick<ShareSessionStorage, \"getById\">\n\n constructor(\n private readonly auth: AuthStorage,\n input: {\n readonly runRootOperation?: RunRootOperation\n readonly shareSessions?: Pick<ShareSessionStorage, \"getById\">\n } = {}\n ) {\n this.runRootOperation = input.runRootOperation ?? runDirectly\n this.shareSessions = input.shareSessions\n }\n\n snapshot(): InMemoryExecutionStorageSnapshot {\n return structuredClone(this.rows)\n }\n\n restore(snapshot: InMemoryExecutionStorageSnapshot): void {\n this.rows.clear()\n for (const [key, record] of structuredClone(snapshot)) {\n this.rows.set(key, record)\n }\n }\n\n async create(input: CreateExecutionInput): Promise<ExecutionRecord> {\n return this.runRootOperation(async () => {\n const key = executionKey(input.projectId, input.id)\n if (this.rows.has(key)) {\n throw new ExecutionStorageError(\n \"duplicate_execution\",\n `[Sixb] Execution '${input.id}' already exists in project '${input.projectId}'.`\n )\n }\n\n const record = await prepareExecutionRecord(input, {\n auth: this.auth,\n getExecution: async ({ projectId, id }) => {\n const existing = this.rows.get(executionKey(projectId, id))\n return existing ? cloneExecutionRecord(existing) : null\n },\n getShareSession: async ({ projectId, id }) =>\n (await this.shareSessions?.getById({ projectId, id })) ?? null,\n })\n\n this.rows.set(key, cloneExecutionRecord(record))\n return cloneExecutionRecord(record)\n })\n }\n\n async getById(params: {\n readonly projectId: string\n readonly id: string\n }): Promise<ExecutionRecord | null> {\n return this.runRootOperation(() => {\n const record = this.rows.get(executionKey(params.projectId, params.id))\n return record ? cloneExecutionRecord(record) : null\n })\n }\n}\n\nexport type InMemoryExecutionStorageSnapshot = Map<string, ExecutionRecord>\n",
|
|
16
|
+
"import type { ObjectQuery } from \"../query/ir\"\n\nexport function hasVectorProfile(query: ObjectQuery): boolean {\n if (query.kind === \"vector\") return true\n if (query.kind === \"set\") return query.inputs.some(hasVectorProfile)\n return \"input\" in query && hasVectorProfile(query.input)\n}\n\n/** V1 supports one exact top-k, with filters applied before ranking. */\nexport function isVectorProfileQuery(query: ObjectQuery): boolean {\n if (query.kind === \"limit\" || query.kind === \"project\") return isVectorProfileQuery(query.input)\n if (query.kind !== \"vector\" || !query.profile) return false\n let input = query.input\n while (input.kind === \"filter\") input = input.input\n return input.kind === \"start\" && !input.includeSubtypes\n}\n",
|
|
17
|
+
"import type { ObjectLinkCursor, ObjectLinkRow } from \"./types\"\n\nexport type ObjectBatchKey = string & {\n readonly __sixbObjectBatchKey: true\n}\n\nexport type LinkBatchKey = string & {\n readonly __sixbLinkBatchKey: true\n}\n\n/** Collision-safe key for object batch-read results. */\nexport function objectBatchKey(objectTypeId: string, primaryId: string): ObjectBatchKey {\n return JSON.stringify([objectTypeId, primaryId]) as ObjectBatchKey\n}\n\n/** Collision-safe key for directional link batch-read results, keyed by the requested object. */\nexport function linkBatchKey(objectTypeId: string, objectId: string, linkId: string): LinkBatchKey {\n return JSON.stringify([objectTypeId, objectId, linkId]) as LinkBatchKey\n}\n\n/** Canonical storage ordering and cursor for physical links. */\nexport function objectLinkCursor(link: ObjectLinkRow): ObjectLinkCursor {\n return [link.sourceTypeId, link.sourceId, link.linkId, link.targetTypeId, link.targetId]\n}\n\nexport function compareObjectLinkCursors(left: ObjectLinkCursor, right: ObjectLinkCursor): number {\n for (let index = 0; index < left.length; index += 1) {\n if (left[index] < right[index]) return -1\n if (left[index] > right[index]) return 1\n }\n return 0\n}\n\nexport function compareObjectLinks(left: ObjectLinkRow, right: ObjectLinkRow): number {\n return compareObjectLinkCursors(objectLinkCursor(left), objectLinkCursor(right))\n}\n",
|
|
18
|
+
"import { objectBatchKey } from \"../keys\"\nimport type { ObjectLinkRow, ObjectRow } from \"../types\"\n\nexport function objectRowKey(projectId: string, objectTypeId: string): string {\n return JSON.stringify([projectId, objectTypeId])\n}\n\nexport function objectRowProjectPrefix(projectId: string): string {\n return `[${JSON.stringify(projectId)},`\n}\n\nexport function compareStrings(left: string, right: string): number {\n if (left < right) return -1\n if (left > right) return 1\n return 0\n}\n\nexport function sourceLinkBucketKey(\n projectId: string,\n sourceTypeId: string,\n sourceId: string\n): string {\n return JSON.stringify([projectId, sourceTypeId, sourceId])\n}\n\nexport function linkRowKey(linkId: string, targetTypeId: string, targetId: string): string {\n return JSON.stringify([linkId, targetTypeId, targetId])\n}\n\nexport function fullLinkRowKey(row: ObjectLinkRow): string {\n return JSON.stringify([\n row.sourceTypeId,\n row.sourceId,\n row.linkId,\n row.targetTypeId,\n row.targetId,\n ])\n}\n\nexport function rowIdentityKey(row: ObjectRow): string {\n return rowIdentityKeyParts(row.objectTypeId, row.primaryId)\n}\n\nexport function rowIdentityKeyParts(objectTypeId: string, primaryId: string): string {\n return objectBatchKey(objectTypeId, primaryId)\n}\n",
|
|
19
|
+
"import { compareDecimalValues } from \"../../ontology\"\nimport type { QueryScalarKind } from \"./ir\"\n\n/** Compare two values according to the scalar schema resolved by query validation. */\nexport function compareQueryScalarValues(\n left: unknown,\n right: unknown,\n scalarKind?: QueryScalarKind\n): number {\n if (left === undefined || right === undefined || left === null || right === null) {\n return Number.NaN\n }\n\n if (scalarKind === undefined) return compareRuntimeValues(left, right)\n\n switch (scalarKind) {\n case \"string\":\n case \"uuid\":\n return typeof left === \"string\" && typeof right === \"string\"\n ? compareStrings(left, right)\n : Number.NaN\n case \"boolean\":\n return typeof left === \"boolean\" && typeof right === \"boolean\"\n ? Number(left) - Number(right)\n : Number.NaN\n case \"integer\":\n case \"double\":\n return typeof left === \"number\" && typeof right === \"number\" ? left - right : Number.NaN\n case \"decimal\":\n return typeof left === \"string\" && typeof right === \"string\"\n ? compareDecimalValues(left, right)\n : Number.NaN\n case \"date\":\n case \"timestamp\":\n return compareTemporalValues(left, right)\n }\n}\n\n/** Test equality with the same schema semantics used for ordered comparisons. */\nexport function queryScalarValuesEqual(\n left: unknown,\n right: unknown,\n scalarKind?: QueryScalarKind\n): boolean {\n if (scalarKind === \"decimal\") {\n const comparison = compareQueryScalarValues(left, right, scalarKind)\n return !Number.isNaN(comparison) && comparison === 0\n }\n\n if (scalarKind === \"date\" || scalarKind === \"timestamp\") {\n const comparison = compareTemporalValues(left, right)\n return !Number.isNaN(comparison) && comparison === 0\n }\n\n if (scalarKind !== undefined) return Object.is(left, right)\n return runtimeValuesEqual(left, right)\n}\n\nfunction compareRuntimeValues(left: unknown, right: unknown): number {\n if (typeof left === \"number\" && typeof right === \"number\") return left - right\n if (typeof left === \"string\" && typeof right === \"string\") return compareStrings(left, right)\n if (typeof left === \"boolean\" && typeof right === \"boolean\") {\n return Number(left) - Number(right)\n }\n if (left instanceof Date || right instanceof Date) return compareTemporalValues(left, right)\n return Number.NaN\n}\n\nfunction runtimeValuesEqual(left: unknown, right: unknown): boolean {\n if (left instanceof Date || right instanceof Date) {\n const comparison = compareTemporalValues(left, right)\n return !Number.isNaN(comparison) && comparison === 0\n }\n return Object.is(left, right)\n}\n\nfunction compareTemporalValues(left: unknown, right: unknown): number {\n const leftTime = dateTime(left)\n const rightTime = dateTime(right)\n if (leftTime === null || rightTime === null) return Number.NaN\n return leftTime - rightTime\n}\n\nfunction dateTime(value: unknown): number | null {\n if (value instanceof Date) {\n const time = value.getTime()\n return Number.isNaN(time) ? null : time\n }\n if (typeof value === \"string\" || typeof value === \"number\") {\n const time = new Date(value).getTime()\n return Number.isNaN(time) ? null : time\n }\n return null\n}\n\nfunction compareStrings(left: string, right: string): number {\n if (left < right) return -1\n if (left > right) return 1\n return 0\n}\n",
|
|
20
|
+
"import { MaterializationValidationError } from \"../../materialization/errors\"\nimport { sha256Canonical } from \"../../materialization/identity\"\nimport type { ObjectVectorSearchProfile } from \"../../ontology/types\"\n\nexport const MAX_VECTOR_K = 1000\nexport const VECTOR_INPUT_VERSION = 1\n\nexport function vectorConfiguration(profile: ObjectVectorSearchProfile): string {\n return sha256Canonical({\n format: VECTOR_INPUT_VERSION,\n sources: [...profile.source],\n provider: profile.model.providerId,\n model: profile.model.modelId,\n representation: profile.model.definition.representation ?? { name: profile.model.modelId },\n dimensions: profile.model.definition.dimensions,\n metric: \"cosine\",\n precision: \"float32\",\n normalization: \"l2-v1\",\n })\n}\n\nexport function vectorSources(\n source: readonly string[],\n properties: Readonly<Record<string, unknown>>\n) {\n const values: Record<string, string | null> = Object.create(null)\n for (const key of source) {\n const value = properties[key]\n if (value !== undefined && value !== null && typeof value !== \"string\") {\n throw new MaterializationValidationError(`Vector source must be text: ${key}`)\n }\n values[key] = typeof value === \"string\" ? value : null\n }\n // Ordered JSON pairs preserve field boundaries, escaping and absent/empty distinction.\n const text = JSON.stringify(source.map((key) => [key, values[key]]))\n return { text, sourceFingerprint: sha256Canonical(text) }\n}\n\n/** Unit-length float32 representation keeps native cosine arithmetic within range. */\nexport function normalizeVector(values: readonly number[], dimensions: number): readonly number[] {\n if (!Array.isArray(values) || values.length !== dimensions) {\n throw new MaterializationValidationError(`Vector dimension mismatch; expected ${dimensions}`)\n }\n const normalized = Array.from(values, (value) => {\n if (\n typeof value !== \"number\" ||\n !Number.isFinite(value) ||\n !Number.isFinite(Math.fround(value))\n ) {\n throw new MaterializationValidationError(\"Vector values must be finite float32 numbers.\")\n }\n return Math.fround(value)\n })\n if (!normalized.some((value) => value !== 0)) {\n throw new MaterializationValidationError(\"Cosine search requires a nonzero vector.\")\n }\n const norm = Math.hypot(...normalized)\n return Object.freeze(normalized.map((value) => Math.fround(value / norm)))\n}\n\n/** V1 envelope for exact SQL scoring; exceeding it must fail rather than truncate candidates. */\nexport function vectorSearchCandidateLimit(dimensions: number): number {\n return Math.min(10000, Math.floor(16000000 / dimensions))\n}\n",
|
|
21
|
+
"import type {\n ObjectQuery,\n ObjectQueryPredicate,\n ObjectQuerySortField,\n} from \"../../../objects/query\"\nimport {\n compareQueryScalarValues,\n queryScalarValuesEqual,\n} from \"../../../objects/query/scalar-values\"\nimport { vectorSources } from \"../../../objects/vectors/profile\"\nimport type { LinkBatchKey } from \"../keys\"\nimport {\n compareObjectLinkCursors,\n compareObjectLinks,\n linkBatchKey,\n objectLinkCursor,\n} from \"../keys\"\nimport type {\n ObjectFacetRequest,\n ObjectFacetResult,\n ObjectLinkRow,\n ObjectQueryCapabilities,\n ObjectReadStorage,\n ObjectRow,\n QueryObjectLinksInput,\n QueryObjectLinksResult,\n} from \"../types\"\nimport { compareStrings, fullLinkRowKey, rowIdentityKey, rowIdentityKeyParts } from \"./keys\"\nimport type { InMemoryReadSource } from \"./read-source\"\n\nexport const IN_MEMORY_OBJECT_QUERY_CAPABILITIES: ObjectQueryCapabilities = {\n queryObjects: true,\n countObjects: true,\n existsObjects: true,\n facetObjects: true,\n nodes: {\n start: true,\n refs: true,\n filter: true,\n text: true,\n vector: true,\n traverse: true,\n set: true,\n sort: true,\n limit: true,\n page: true,\n project: true,\n },\n predicateOps: {\n and: true,\n or: true,\n not: true,\n eq: true,\n neq: true,\n lt: true,\n lte: true,\n gt: true,\n gte: true,\n in: true,\n exists: true,\n contains: true,\n },\n sortKinds: {\n property: true,\n relevance: true,\n },\n traversalDirections: {\n outgoing: true,\n incoming: true,\n },\n setOps: {\n union: true,\n intersect: true,\n subtract: true,\n },\n scalarOperations: {\n string: { equality: true, ordering: true },\n uuid: { equality: true, ordering: true },\n boolean: { equality: true },\n integer: { equality: true, ordering: true },\n double: { equality: true, ordering: true },\n decimal: { equality: true, ordering: true },\n date: { equality: true, ordering: true },\n timestamp: { equality: true, ordering: true },\n },\n limits: {\n totalCount: true,\n stablePageTokens: true,\n },\n}\n\ntype QueryEntry = {\n row: ObjectRow\n score: number\n order: number\n}\n\ntype QueryEvaluation = {\n entries: QueryEntry[]\n total: number\n hasMore: boolean\n nextPageToken?: string\n}\n\nconst PAGE_TOKEN_PREFIX = \"offset:\"\n\nfunction assertLinkQueryLimit(limit: number): void {\n if (!Number.isSafeInteger(limit) || limit <= 0) {\n throw new Error(\"Object link query limit must be a positive safe integer.\")\n }\n}\n\nexport function evaluateObjectQuery(\n query: ObjectQuery,\n source: InMemoryReadSource\n): QueryEvaluation {\n switch (query.kind) {\n case \"start\":\n return evaluateStart(query.objectTypeId, source)\n case \"refs\":\n return evaluateRefs(query.refs, source)\n case \"filter\": {\n const input = evaluateObjectQuery(query.input, source)\n const entries = input.entries.filter((entry) => matchesPredicate(entry.row, query.predicate))\n return completeEvaluation(entries)\n }\n case \"text\": {\n const input = evaluateObjectQuery(query.input, source)\n const scoredEntries = input.entries.flatMap((entry) => {\n const score = textScore(entry.row, query.query, query.fields, query.fieldsByObjectType)\n return score > 0 ? [{ ...entry, score: entry.score + score }] : []\n })\n return completeEvaluation(scoredEntries)\n }\n case \"vector\": {\n if (typeof query.vector === \"string\")\n throw new Error(\"[Sixb] Vector search text must be embedded before storage execution.\")\n const vector = query.vector\n const input = evaluateObjectQuery(query.input, source)\n const scoredEntries = input.entries.flatMap((entry) => {\n const stored = source.getVector?.(entry.row, query.profile)\n if (\n !stored ||\n !query.configuration ||\n stored.configuration !== query.configuration ||\n vectorSources(stored.source, entry.row.properties).sourceFingerprint !==\n stored.sourceFingerprint\n )\n return []\n const score = vectorSimilarity(stored.values, vector)\n return score === null\n ? []\n : [{ ...entry, score: entry.score + Math.max(-1, Math.min(1, score)) }]\n })\n scoredEntries.sort(\n (a, b) =>\n b.score - a.score ||\n Buffer.compare(Buffer.from(a.row.objectTypeId), Buffer.from(b.row.objectTypeId)) ||\n Buffer.compare(Buffer.from(a.row.primaryId), Buffer.from(b.row.primaryId))\n )\n const limit = Math.max(0, query.k)\n return {\n entries: scoredEntries.slice(0, limit),\n total: Math.min(limit, scoredEntries.length),\n hasMore: false,\n }\n }\n case \"traverse\": {\n const input = evaluateObjectQuery(query.input, source)\n const entries =\n query.direction === \"outgoing\"\n ? traverseOutgoing(input.entries, query.linkId, source)\n : traverseIncoming(input.entries, query.linkId, query.sourceObjectTypeId, source)\n return completeEvaluation(entries)\n }\n case \"set\":\n return evaluateSet(query.op, query.inputs, source)\n case \"sort\": {\n const input = evaluateObjectQuery(query.input, source)\n return {\n ...input,\n entries: sortEntries(input.entries, query.fields),\n }\n }\n case \"limit\": {\n const input = evaluateObjectQuery(query.input, source)\n const limit = Math.max(0, query.limit)\n return {\n entries: input.entries.slice(0, limit),\n total: input.entries.length,\n hasMore: limit < input.entries.length,\n }\n }\n case \"page\": {\n const input = evaluateObjectQuery(query.input, source)\n const offset = decodePageOffset(query.pageToken)\n const pageSize = Math.max(0, query.pageSize)\n const nextOffset = offset + pageSize\n const hasMore = pageSize > 0 && nextOffset < input.entries.length\n return {\n entries: input.entries.slice(offset, nextOffset),\n total: input.entries.length,\n hasMore,\n nextPageToken: hasMore ? encodePageOffset(nextOffset) : undefined,\n }\n }\n case \"project\": {\n const input = evaluateObjectQuery(query.input, source)\n if (!query.properties) return input\n const properties = query.properties\n return {\n ...input,\n entries: input.entries.map((entry) => ({\n ...entry,\n row: projectRow(entry.row, properties),\n })),\n }\n }\n case \"expand\":\n // `expand` is output-shaping and is gated off by the planner in this\n // slice (and stripped before aggregates run), so the in-memory engine\n // should never receive one. Link hydration lands in a later slice.\n throw new Error(\"[Sixb] In-memory object storage does not support 'expand' execution yet\")\n }\n}\n\nfunction evaluateStart(objectTypeId: string, source: InMemoryReadSource): QueryEvaluation {\n const rows = source.objectsOfType(objectTypeId)\n const entries = rows.map((row, index) => ({\n row,\n score: 0,\n order: index,\n }))\n return completeEvaluation(entries)\n}\n\nfunction evaluateRefs(\n refs: readonly { objectTypeId: string; primaryId: string }[],\n source: InMemoryReadSource\n): QueryEvaluation {\n const seen = new Set<string>()\n const entries = refs\n .flatMap((ref) => {\n const key = JSON.stringify([ref.objectTypeId, ref.primaryId])\n if (seen.has(key)) return []\n seen.add(key)\n const row = source.getObject(ref.objectTypeId, ref.primaryId)\n return row ? [row] : []\n })\n .sort(\n (left, right) =>\n compareStrings(left.objectTypeId, right.objectTypeId) ||\n compareStrings(left.primaryId, right.primaryId)\n )\n .map((row, order) => ({ row, score: 0, order }))\n\n return completeEvaluation(entries)\n}\n\nfunction evaluateSet(\n op: \"union\" | \"intersect\" | \"subtract\",\n inputs: readonly ObjectQuery[],\n source: InMemoryReadSource\n): QueryEvaluation {\n const evaluations = inputs.map((input) => evaluateObjectQuery(input, source))\n const first = evaluations[0]\n if (!first) return completeEvaluation([])\n\n if (op === \"union\") {\n const entriesByKey = new Map<string, QueryEntry>()\n for (const evaluation of evaluations) {\n for (const entry of evaluation.entries) {\n upsertEntry(entriesByKey, entry)\n }\n }\n return completeEvaluation([...entriesByKey.values()])\n }\n\n if (op === \"intersect\") {\n const otherKeySets = evaluations\n .slice(1)\n .map((evaluation) => new Set(evaluation.entries.map((entry) => rowIdentityKey(entry.row))))\n const entries = first.entries.filter((entry) => {\n const key = rowIdentityKey(entry.row)\n return otherKeySets.every((keys) => keys.has(key))\n })\n return completeEvaluation(entries)\n }\n\n const subtractKeys = new Set(\n evaluations\n .slice(1)\n .flatMap((evaluation) => evaluation.entries.map((entry) => rowIdentityKey(entry.row)))\n )\n return completeEvaluation(\n first.entries.filter((entry) => !subtractKeys.has(rowIdentityKey(entry.row)))\n )\n}\n\nfunction traverseOutgoing(\n entries: readonly QueryEntry[],\n linkId: string,\n source: InMemoryReadSource\n): QueryEntry[] {\n const resultsByKey = new Map<string, QueryEntry>()\n\n entries.forEach((entry, index) => {\n const links = [...source.outgoingLinks(entry.row.objectTypeId, entry.row.primaryId)]\n\n for (const link of links) {\n if (link.linkId !== linkId) continue\n const target = source.getObject(link.targetTypeId, link.targetId)\n if (!target) continue\n upsertEntry(resultsByKey, {\n row: target,\n score: entry.score,\n order: entry.order + index / 1_000_000,\n })\n }\n })\n\n return [...resultsByKey.values()]\n}\n\nfunction traverseIncoming(\n entries: readonly QueryEntry[],\n linkId: string,\n sourceObjectTypeId: string | undefined,\n source: InMemoryReadSource\n): QueryEntry[] {\n const inputEntriesByTarget = new Map(entries.map((entry) => [rowIdentityKey(entry.row), entry]))\n const resultsByKey = new Map<string, QueryEntry>()\n\n const links = [...source.allLinks()]\n for (const link of links) {\n if (link.projectId !== source.projectId || link.linkId !== linkId) continue\n if (sourceObjectTypeId !== undefined && link.sourceTypeId !== sourceObjectTypeId) continue\n const targetEntry = inputEntriesByTarget.get(\n rowIdentityKeyParts(link.targetTypeId, link.targetId)\n )\n if (!targetEntry) continue\n\n const row = source.getObject(link.sourceTypeId, link.sourceId)\n if (!row) continue\n upsertEntry(resultsByKey, {\n row,\n score: targetEntry.score,\n order: targetEntry.order,\n })\n }\n\n return [...resultsByKey.values()]\n}\n\nfunction completeEvaluation(entries: QueryEntry[]): QueryEvaluation {\n return {\n entries,\n total: entries.length,\n hasMore: false,\n }\n}\n\nfunction matchesPredicate(row: ObjectRow, predicate: ObjectQueryPredicate): boolean {\n switch (predicate.op) {\n case \"and\":\n return predicate.items.every((item) => matchesPredicate(row, item))\n case \"or\":\n return predicate.items.some((item) => matchesPredicate(row, item))\n case \"not\":\n return !matchesPredicate(row, predicate.item)\n case \"eq\":\n return queryScalarValuesEqual(\n row.properties[predicate.propertyId],\n predicate.value,\n predicate.scalarKind\n )\n case \"neq\":\n return !queryScalarValuesEqual(\n row.properties[predicate.propertyId],\n predicate.value,\n predicate.scalarKind\n )\n case \"lt\":\n return (\n compareQueryScalarValues(\n row.properties[predicate.propertyId],\n predicate.value,\n predicate.scalarKind\n ) < 0\n )\n case \"lte\":\n return (\n compareQueryScalarValues(\n row.properties[predicate.propertyId],\n predicate.value,\n predicate.scalarKind\n ) <= 0\n )\n case \"gt\":\n return (\n compareQueryScalarValues(\n row.properties[predicate.propertyId],\n predicate.value,\n predicate.scalarKind\n ) > 0\n )\n case \"gte\":\n return (\n compareQueryScalarValues(\n row.properties[predicate.propertyId],\n predicate.value,\n predicate.scalarKind\n ) >= 0\n )\n case \"in\":\n return predicate.values.some((value) =>\n queryScalarValuesEqual(row.properties[predicate.propertyId], value, predicate.scalarKind)\n )\n case \"exists\": {\n const exists =\n Object.hasOwn(row.properties, predicate.propertyId) &&\n row.properties[predicate.propertyId] !== undefined\n return predicate.value ? exists : !exists\n }\n case \"contains\":\n return containsValue(row.properties[predicate.propertyId], predicate.value)\n }\n}\n\nfunction containsValue(actual: unknown, expected: unknown): boolean {\n if (typeof actual === \"string\" && typeof expected === \"string\") {\n return actual.includes(expected)\n }\n\n if (Array.isArray(actual)) {\n return actual.some((item) => queryScalarValuesEqual(item, expected))\n }\n\n if (isPlainObject(actual) && typeof expected === \"string\") {\n return Object.hasOwn(actual, expected)\n }\n\n return false\n}\n\nfunction textScore(\n row: ObjectRow,\n query: string,\n fields: readonly string[] | undefined,\n fieldsByObjectType: Readonly<Record<string, readonly string[]>> | undefined\n): number {\n const terms = tokenize(query)\n if (terms.length === 0) return 0\n\n const scopedFields = fields ?? fieldsByObjectType?.[row.objectTypeId]\n const values = fields\n ? fields.flatMap((field) => collectTextValues(row.properties[field]))\n : scopedFields\n ? scopedFields.flatMap((field) => collectTextValues(row.properties[field]))\n : [row.primaryId, ...Object.values(row.properties).flatMap(collectTextValues)]\n const haystack = values.join(\" \").toLowerCase()\n if (!terms.every((term) => haystack.includes(term))) return 0\n\n const phrase = query.trim().toLowerCase()\n const phraseBoost = phrase.length > 0 && haystack.includes(phrase) ? terms.length : 0\n return terms.reduce((score, term) => score + countOccurrences(haystack, term), phraseBoost)\n}\n\nfunction tokenize(query: string): string[] {\n return query\n .trim()\n .toLowerCase()\n .split(/\\s+/)\n .filter((term) => term.length > 0)\n}\n\nfunction collectTextValues(value: unknown): string[] {\n if (typeof value === \"string\") return [value]\n if (Array.isArray(value)) return value.flatMap(collectTextValues)\n return []\n}\n\nfunction countOccurrences(value: string, needle: string): number {\n if (!needle) return 0\n let count = 0\n let index = value.indexOf(needle)\n while (index !== -1) {\n count += 1\n index = value.indexOf(needle, index + needle.length)\n }\n return count\n}\n\nfunction vectorSimilarity(actual: unknown, expected: readonly number[]): number | null {\n if (!Array.isArray(actual) || actual.length !== expected.length || actual.length === 0) {\n return null\n }\n\n let dot = 0\n let actualNorm = 0\n let expectedNorm = 0\n for (let index = 0; index < expected.length; index += 1) {\n const actualValue = actual[index]\n const expectedValue = expected[index]\n if (\n typeof actualValue !== \"number\" ||\n typeof expectedValue !== \"number\" ||\n !Number.isFinite(actualValue) ||\n !Number.isFinite(expectedValue)\n ) {\n return null\n }\n\n dot += actualValue * expectedValue\n actualNorm += actualValue * actualValue\n expectedNorm += expectedValue * expectedValue\n }\n\n if (actualNorm === 0 || expectedNorm === 0) return null\n return dot / (Math.sqrt(actualNorm) * Math.sqrt(expectedNorm))\n}\n\nfunction sortEntries(\n entries: readonly QueryEntry[],\n fields: readonly ObjectQuerySortField[]\n): QueryEntry[] {\n return [...entries].sort((left, right) => {\n for (const field of fields) {\n const comparison = compareSortField(left, right, field)\n if (comparison !== 0) return comparison\n }\n return (\n left.order - right.order || rowIdentityKey(left.row).localeCompare(rowIdentityKey(right.row))\n )\n })\n}\n\nfunction compareSortField(\n left: QueryEntry,\n right: QueryEntry,\n field: ObjectQuerySortField\n): number {\n if (field.kind === \"relevance\") {\n const direction = field.direction ?? \"desc\"\n const comparison = right.score - left.score\n return direction === \"desc\" ? comparison : -comparison\n }\n\n const leftValue = left.row.properties[field.propertyId]\n const rightValue = right.row.properties[field.propertyId]\n const leftMissing = leftValue === undefined || leftValue === null\n const rightMissing = rightValue === undefined || rightValue === null\n if (leftMissing && rightMissing) return 0\n if (leftMissing) return 1\n if (rightMissing) return -1\n\n const comparison = compareQueryScalarValues(leftValue, rightValue, field.scalarKind)\n if (Number.isNaN(comparison)) return 0\n return field.direction === \"desc\" ? -comparison : comparison\n}\n\nfunction projectRow(row: ObjectRow, properties: readonly string[]): ObjectRow {\n const projected: Record<string, unknown> = {}\n for (const propertyId of properties) {\n if (Object.hasOwn(row.properties, propertyId)) {\n projected[propertyId] = row.properties[propertyId]\n }\n }\n return {\n ...row,\n properties: projected,\n }\n}\n\nexport function stripOuterRowShape(query: ObjectQuery): ObjectQuery {\n switch (query.kind) {\n case \"limit\":\n case \"page\":\n case \"project\":\n case \"sort\":\n // `expand` is output-shaping: aggregates ignore it (it never changes which\n // objects match).\n case \"expand\":\n return stripOuterRowShape(query.input)\n default:\n return query\n }\n}\n\nexport function buildFacetResults(\n rows: readonly ObjectRow[],\n facets: readonly ObjectFacetRequest[]\n): ObjectFacetResult[] {\n return facets.map((facet) => ({\n propertyId: facet.propertyId,\n buckets: buildFacetBuckets(rows, facet),\n }))\n}\n\nfunction buildFacetBuckets(\n rows: readonly ObjectRow[],\n facet: ObjectFacetRequest\n): ObjectFacetResult[\"buckets\"] {\n const buckets = new Map<string, { value: unknown; count: number }>()\n\n for (const row of rows) {\n if (!Object.hasOwn(row.properties, facet.propertyId)) continue\n const value = row.properties[facet.propertyId]\n if (value === undefined) continue\n const key = facetValueKey(value)\n const existing = buckets.get(key)\n if (existing) {\n existing.count += 1\n } else {\n buckets.set(key, { value, count: 1 })\n }\n }\n\n return [...buckets.values()]\n .sort(\n (left, right) =>\n right.count - left.count ||\n facetValueSortKey(left.value).localeCompare(facetValueSortKey(right.value))\n )\n .slice(0, facet.limit)\n}\n\nfunction facetValueKey(value: unknown): string {\n return JSON.stringify(value) ?? String(value)\n}\n\nfunction facetValueSortKey(value: unknown): string {\n return JSON.stringify(value) ?? String(value)\n}\n\nexport async function queryLinksFrom(\n params: QueryObjectLinksInput,\n listLinks: (\n input: Parameters<ObjectReadStorage[\"listLinks\"]>[0]\n ) => Promise<readonly ObjectLinkRow[]> | readonly ObjectLinkRow[]\n): Promise<QueryObjectLinksResult> {\n assertLinkQueryLimit(params.limit)\n if (params.objectRefs.length === 0 || params.endpointObjectTypeIds?.length === 0) {\n return { links: [], hasMore: false }\n }\n\n const allowedTypes = params.endpointObjectTypeIds\n ? new Set(params.endpointObjectTypeIds)\n : undefined\n const deduped = new Map<string, ObjectLinkRow>()\n for (const object of params.objectRefs) {\n const rows = await listLinks({\n projectId: params.projectId,\n objectTypeId: object.objectTypeId,\n objectId: object.primaryId,\n direction: params.direction,\n ...(params.linkId === undefined ? {} : { linkId: params.linkId }),\n })\n for (const row of rows) {\n if (\n allowedTypes &&\n (!allowedTypes.has(row.sourceTypeId) || !allowedTypes.has(row.targetTypeId))\n ) {\n continue\n }\n if (params.after && compareObjectLinkCursors(objectLinkCursor(row), params.after) <= 0) {\n continue\n }\n deduped.set(fullLinkRowKey(row), row)\n }\n }\n\n const rows = [...deduped.values()].sort(compareObjectLinks).slice(0, params.limit + 1)\n return { links: rows.slice(0, params.limit), hasMore: rows.length > params.limit }\n}\n\ninterface LinkBatchSource {\n all(): Iterable<ObjectLinkRow>\n outgoing(item: {\n readonly objectTypeId: string\n readonly objectId: string\n readonly linkId: string\n }): Iterable<ObjectLinkRow>\n}\n\nexport function collectLinksBatch(\n source: LinkBatchSource,\n params: Parameters<ObjectReadStorage[\"listLinksBatch\"]>[0],\n cloneRows: boolean\n): Map<LinkBatchKey, ObjectLinkRow[]> {\n const direction = params.direction ?? \"outgoing\"\n const orderedKeys = [\n ...new Set(\n params.items.map((item) => linkBatchKey(item.objectTypeId, item.objectId, item.linkId))\n ),\n ]\n const requestedKeys = new Set(orderedKeys)\n const grouped = new Map<LinkBatchKey, Map<string, ObjectLinkRow>>()\n const append = (key: LinkBatchKey, row: ObjectLinkRow): void => {\n const bucket = grouped.get(key) ?? new Map<string, ObjectLinkRow>()\n bucket.set(fullLinkRowKey(row), row)\n grouped.set(key, bucket)\n }\n\n if (direction === \"outgoing\" || direction === \"both\") {\n for (const item of params.items) {\n const key = linkBatchKey(item.objectTypeId, item.objectId, item.linkId)\n for (const row of source.outgoing(item)) {\n if (row.projectId === params.projectId && row.linkId === item.linkId) append(key, row)\n }\n }\n }\n\n if (direction === \"incoming\" || direction === \"both\") {\n for (const row of source.all()) {\n if (row.projectId !== params.projectId) continue\n const key = linkBatchKey(row.targetTypeId, row.targetId, row.linkId)\n if (requestedKeys.has(key)) append(key, row)\n }\n }\n\n return new Map(\n orderedKeys.flatMap((key) => {\n const bucket = grouped.get(key)\n if (!bucket) return []\n return [\n [key, [...bucket.values()].map((row) => (cloneRows ? structuredClone(row) : row))] as const,\n ]\n })\n )\n}\n\nfunction upsertEntry(entriesByKey: Map<string, QueryEntry>, entry: QueryEntry): void {\n const key = rowIdentityKey(entry.row)\n const existing = entriesByKey.get(key)\n if (!existing) {\n entriesByKey.set(key, entry)\n return\n }\n\n if (entry.score > existing.score) {\n entriesByKey.set(key, {\n ...existing,\n score: entry.score,\n })\n }\n}\n\nfunction encodePageOffset(offset: number): string {\n return `${PAGE_TOKEN_PREFIX}${offset}`\n}\n\nfunction decodePageOffset(token: string | undefined): number {\n if (!token) return 0\n if (!token.startsWith(PAGE_TOKEN_PREFIX)) {\n throw new Error(\"[Sixb] Invalid object query page token\")\n }\n\n const offset = Number(token.slice(PAGE_TOKEN_PREFIX.length))\n if (!Number.isInteger(offset) || offset < 0) {\n throw new Error(\"[Sixb] Invalid object query page token\")\n }\n return offset\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n",
|
|
22
|
+
"import { type ObjectReadExecutionLimits, ObjectReadLimitExceededError } from \"../execution-limits\"\nimport type {\n CompiledObjectReadRoot,\n CompiledObjectReadStep,\n CompiledSelectedObjectReadScope,\n ObjectLinkRow,\n ObjectRow,\n} from \"../types\"\nimport { fullLinkRowKey, rowIdentityKey, rowIdentityKeyParts, sourceLinkBucketKey } from \"./keys\"\nimport type { InMemoryReadSource } from \"./read-source\"\n\nexport interface InMemoryReadUniverse extends InMemoryReadSource {\n readonly objects: ReadonlyMap<string, ObjectRow>\n readonly links: ReadonlyMap<string, ObjectLinkRow>\n readonly linksBySource: ReadonlyMap<string, readonly ObjectLinkRow[]>\n readonly objectProperties: ReadonlyMap<string, ReadonlySet<string>>\n}\n\ninterface InMemoryReadPlan {\n readonly roots: readonly CompiledObjectReadRoot[]\n readonly selectionsByNode: ReadonlyMap<number, ReadonlyMap<string, ReadonlySet<string>>>\n readonly steps: readonly CompiledObjectReadStep[]\n}\n\nexport function prepareReadPlan(scope: CompiledSelectedObjectReadScope): InMemoryReadPlan {\n const selectionsByNode = new Map<number, Map<string, ReadonlySet<string>>>()\n for (const selection of scope.objects) {\n const byType = selectionsByNode.get(selection.nodeId) ?? new Map()\n byType.set(selection.objectTypeId, new Set(selection.propertyIds))\n selectionsByNode.set(selection.nodeId, byType)\n }\n\n // The compiler allocates node ids parent-first. Resolve every step from lower parent ids to\n // higher child ids so a node reached through several concrete definitions is complete before\n // its nested selections run.\n const steps = [...scope.steps].sort(\n (left, right) =>\n left.parentNodeId - right.parentNodeId ||\n left.nodeId - right.nodeId ||\n left.sourceObjectTypeId.localeCompare(right.sourceObjectTypeId) ||\n left.linkId.localeCompare(right.linkId) ||\n left.targetObjectTypeId.localeCompare(right.targetObjectTypeId)\n )\n return {\n roots: scope.roots,\n selectionsByNode,\n steps,\n }\n}\n\nexport function resolveSelectedReadUniverse(\n source: InMemoryReadSource,\n plan: InMemoryReadPlan,\n limits: ObjectReadExecutionLimits\n): InMemoryReadUniverse {\n // Reachability stays path-sensitive until every finite selection step has run. The final\n // object/link universes union exact identities only after that traversal, so the same type\n // reached through another branch cannot inherit nested link authority.\n const reachableByNode = new Map<number, Map<string, ObjectRow>>()\n const rawObjects = new Map<string, ObjectRow>()\n const objectProperties = new Map<string, Set<string>>()\n const authorizedLinks = new Map<\n string,\n { readonly row: ObjectLinkRow; readonly propertyIds: Set<string> }\n >()\n let traversalFacts = 0\n const consumeTraversalFact = (): void => {\n traversalFacts += 1\n if (traversalFacts > limits.maxTraversalFacts) {\n throw new ObjectReadLimitExceededError(\"traversalFacts\", limits.maxTraversalFacts)\n }\n }\n\n const addReachable = (nodeId: number, row: ObjectRow): void => {\n const selectedProperties = plan.selectionsByNode.get(nodeId)?.get(row.objectTypeId)\n if (!selectedProperties) return\n const key = rowIdentityKey(row)\n const reachable = reachableByNode.get(nodeId) ?? new Map<string, ObjectRow>()\n reachable.set(key, row)\n reachableByNode.set(nodeId, reachable)\n rawObjects.set(key, row)\n unionInto(objectProperties, key, selectedProperties)\n }\n\n for (const root of plan.roots) {\n const row = source.getObject(root.objectTypeId, root.primaryId)\n if (row) {\n consumeTraversalFact()\n addReachable(root.nodeId, row)\n }\n }\n\n for (const step of plan.steps) {\n const parents = reachableByNode.get(step.parentNodeId)\n if (!parents) continue\n for (const parent of parents.values()) {\n if (parent.objectTypeId !== step.sourceObjectTypeId) continue\n for (const link of source.outgoingLinks(parent.objectTypeId, parent.primaryId)) {\n if (link.linkId !== step.linkId || link.targetTypeId !== step.targetObjectTypeId) {\n continue\n }\n const target = source.getObject(link.targetTypeId, link.targetId)\n if (!target) continue\n consumeTraversalFact()\n addReachable(step.nodeId, target)\n\n const linkKey = fullLinkRowKey(link)\n const selected = authorizedLinks.get(linkKey)\n if (selected) {\n for (const propertyId of step.propertyIds) selected.propertyIds.add(propertyId)\n } else {\n authorizedLinks.set(linkKey, {\n row: link,\n propertyIds: new Set(step.propertyIds),\n })\n }\n }\n }\n }\n\n const objects = new Map<string, ObjectRow>()\n for (const [key, propertyIds] of objectProperties) {\n const row = rawObjects.get(key)\n if (row) objects.set(key, redactObjectRow(row, propertyIds))\n }\n\n const links = new Map<string, ObjectLinkRow>()\n for (const [key, selected] of authorizedLinks) {\n // Both endpoint identities must remain live and selected. This also prevents a stale link\n // from exposing metadata after its target object disappears.\n if (\n !objects.has(rowIdentityKeyParts(selected.row.sourceTypeId, selected.row.sourceId)) ||\n !objects.has(rowIdentityKeyParts(selected.row.targetTypeId, selected.row.targetId))\n ) {\n continue\n }\n links.set(key, redactLinkRow(selected.row, selected.propertyIds))\n }\n\n return createReadUniverse(source, objects, links, objectProperties)\n}\n\nfunction createReadUniverse(\n source: InMemoryReadSource,\n objects: ReadonlyMap<string, ObjectRow>,\n links: ReadonlyMap<string, ObjectLinkRow>,\n objectProperties: ReadonlyMap<string, ReadonlySet<string>>\n): InMemoryReadUniverse {\n const projectId = source.projectId\n const linksBySource = new Map<string, ObjectLinkRow[]>()\n for (const link of links.values()) {\n const key = sourceLinkBucketKey(link.projectId, link.sourceTypeId, link.sourceId)\n const bucket = linksBySource.get(key) ?? []\n bucket.push(link)\n linksBySource.set(key, bucket)\n }\n return {\n projectId,\n objects,\n links,\n linksBySource,\n objectProperties,\n getVector: (ref, profile) => {\n const key = rowIdentityKeyParts(ref.objectTypeId, ref.primaryId)\n if (!objects.has(key)) return undefined\n const value = source.getVector?.(ref, profile)\n return value?.source.every((id) => objectProperties.get(key)?.has(id)) ? value : undefined\n },\n objectsOfType: (objectTypeId) =>\n [...objects.values()].filter((row) => row.objectTypeId === objectTypeId),\n getObject: (objectTypeId, primaryId) =>\n objects.get(rowIdentityKeyParts(objectTypeId, primaryId)),\n outgoingLinks: (objectTypeId, primaryId) =>\n linksBySource.get(sourceLinkBucketKey(projectId, objectTypeId, primaryId)) ?? [],\n allLinks: () => links.values(),\n }\n}\n\nfunction unionInto(\n target: Map<string, Set<string>>,\n key: string,\n values: ReadonlySet<string>\n): void {\n const union = target.get(key) ?? new Set<string>()\n for (const value of values) union.add(value)\n target.set(key, union)\n}\n\nfunction redactObjectRow(row: ObjectRow, propertyIds: ReadonlySet<string>): ObjectRow {\n const clone = structuredClone(row)\n delete clone.links\n clone.properties = redactProperties(clone.properties, propertyIds)\n return clone\n}\n\nfunction redactLinkRow(row: ObjectLinkRow, propertyIds: ReadonlySet<string>): ObjectLinkRow {\n const clone = structuredClone(row)\n const properties = redactProperties(clone.properties ?? {}, propertyIds)\n if (Object.keys(properties).length === 0) {\n delete clone.properties\n } else {\n clone.properties = properties\n }\n return clone\n}\n\nfunction redactProperties(\n properties: Readonly<Record<string, unknown>>,\n propertyIds: ReadonlySet<string>\n): Record<string, unknown> {\n // Object.fromEntries uses CreateDataProperty, so valid ontology ids such as `__proto__` remain\n // ordinary own properties without changing the returned object's prototype.\n return Object.fromEntries(\n [...propertyIds]\n .filter((propertyId) => Object.hasOwn(properties, propertyId))\n .map((propertyId) => [propertyId, properties[propertyId]])\n )\n}\n",
|
|
23
|
+
"import { hasVectorProfile } from \"../../../objects/vectors/query\"\nimport {\n assertObjectReadFacetCount,\n assertObjectReadOutputWithinLimit,\n type ObjectReadExecutionLimits,\n snapshotObjectReadExecutionLimits,\n} from \"../execution-limits\"\nimport { type ObjectBatchKey, objectBatchKey } from \"../keys\"\nimport { assertObjectReaderProject } from \"../read-scope\"\nimport type {\n CompiledSelectedObjectReadScope,\n CountObjectsInput,\n ExistsObjectsInput,\n FacetObjectsInput,\n LinkDirection,\n ObjectLinkRow,\n ObjectQueryCapabilities,\n ObjectReadStorage,\n ObjectRow,\n QueryObjectsInput,\n} from \"../types\"\nimport { fullLinkRowKey, rowIdentityKeyParts, sourceLinkBucketKey } from \"./keys\"\nimport {\n buildFacetResults,\n collectLinksBatch,\n evaluateObjectQuery,\n queryLinksFrom,\n stripOuterRowShape,\n} from \"./query\"\nimport {\n type InMemoryReadUniverse,\n prepareReadPlan,\n resolveSelectedReadUniverse,\n} from \"./read-scope\"\nimport type { InMemoryReadSource } from \"./read-source\"\n\n/** Capture a selection once, then resolve its live data and enforce budgets per operation. */\nexport function createInMemorySelectedReader(\n source: InMemoryReadSource,\n params: {\n scope: CompiledSelectedObjectReadScope\n limits: ObjectReadExecutionLimits\n },\n queryCapabilities: () => ObjectQueryCapabilities\n): ObjectReadStorage {\n const projectId = source.projectId\n const plan = prepareReadPlan(params.scope)\n const limits = snapshotObjectReadExecutionLimits(params.limits)\n const assertProject = (actualProjectId: string) =>\n assertObjectReaderProject(projectId, actualProjectId)\n const visible = <T>(value: T): T => {\n assertObjectReadOutputWithinLimit(value, limits)\n return value\n }\n const visibleMap = <TKey, TValue>(value: Map<TKey, TValue>): Map<TKey, TValue> => {\n assertObjectReadOutputWithinLimit([...value.entries()], limits)\n return value\n }\n const selectsObjectProperties: ObjectReadStorage[\"selectsObjectProperties\"] = async (input) => {\n assertProject(input.projectId)\n const universe = resolveSelectedReadUniverse(source, plan, limits)\n return visible(\n input.items.map((item) => {\n const key = rowIdentityKeyParts(item.objectTypeId, item.primaryId)\n if (!universe.objects.has(key)) return false\n return universe.objectProperties.get(key)?.has(item.propertyId) ?? false\n })\n )\n }\n\n return Object.freeze({\n queryCapabilities,\n queryObjects: async (input: QueryObjectsInput) => {\n assertProject(input.projectId)\n const universe = resolveSelectedReadUniverse(source, plan, limits)\n const result = evaluateObjectQuery(input.query, universe)\n return visible({\n objects: result.entries.map((entry) => ({\n ...structuredClone(entry.row),\n ...(hasVectorProfile(input.query) ? { score: entry.score } : {}),\n })),\n hasMore: result.hasMore,\n nextPageToken: result.nextPageToken,\n ...(input.includeTotal === false ? {} : { total: result.total }),\n })\n },\n countObjects: async (input: CountObjectsInput) => {\n assertProject(input.projectId)\n const universe = resolveSelectedReadUniverse(source, plan, limits)\n return visible({\n count: evaluateObjectQuery(stripOuterRowShape(input.query), universe).total,\n })\n },\n existsObjects: async (input: ExistsObjectsInput) => {\n assertProject(input.projectId)\n const universe = resolveSelectedReadUniverse(source, plan, limits)\n return visible({\n exists: evaluateObjectQuery(stripOuterRowShape(input.query), universe).total > 0,\n })\n },\n facetObjects: async (input: FacetObjectsInput) => {\n assertProject(input.projectId)\n assertObjectReadFacetCount(input.facets.length)\n const universe = resolveSelectedReadUniverse(source, plan, limits)\n const result = evaluateObjectQuery(stripOuterRowShape(input.query), universe)\n return visible(\n structuredClone({\n facets: buildFacetResults(\n result.entries.map((entry) => entry.row),\n input.facets\n ),\n })\n )\n },\n getByPrimaryId: async (input) => {\n assertProject(input.projectId)\n const universe = resolveSelectedReadUniverse(source, plan, limits)\n const row = universe.objects.get(rowIdentityKeyParts(input.objectTypeId, input.primaryId))\n return visible(row ? structuredClone(row) : null)\n },\n selectsObjectProperties,\n listLinks: async (input) => {\n assertProject(input.projectId)\n const universe = resolveSelectedReadUniverse(source, plan, limits)\n return visible(listUniverseLinks(universe, input).map((row) => structuredClone(row)))\n },\n getByPrimaryIdBatch: async (input) => {\n assertProject(input.projectId)\n const universe = resolveSelectedReadUniverse(source, plan, limits)\n const rows = new Map<ObjectBatchKey, ObjectRow>()\n for (const item of input.items) {\n const row = universe.objects.get(rowIdentityKeyParts(item.objectTypeId, item.primaryId))\n if (row) {\n rows.set(objectBatchKey(item.objectTypeId, item.primaryId), structuredClone(row))\n }\n }\n return visibleMap(rows)\n },\n listLinksBatch: async (input) => {\n assertProject(input.projectId)\n const universe = resolveSelectedReadUniverse(source, plan, limits)\n return visibleMap(\n collectLinksBatch(\n {\n all: () => universe.links.values(),\n outgoing: (item) =>\n universe.linksBySource.get(\n sourceLinkBucketKey(projectId, item.objectTypeId, item.objectId)\n ) ?? [],\n },\n input,\n true\n )\n )\n },\n queryLinks: async (input) => {\n assertProject(input.projectId)\n const universe = resolveSelectedReadUniverse(source, plan, limits)\n return visible(\n structuredClone(await queryLinksFrom(input, (item) => listUniverseLinks(universe, item)))\n )\n },\n list: async (input) => {\n assertProject(input.projectId)\n const universe = resolveSelectedReadUniverse(source, plan, limits)\n return visible(listRows(input, [...universe.objects.values()]))\n },\n } satisfies ObjectReadStorage)\n}\n\nfunction listUniverseLinks(\n universe: InMemoryReadUniverse,\n params: {\n readonly projectId: string\n readonly objectTypeId: string\n readonly objectId: string\n readonly linkId?: string\n readonly direction?: LinkDirection\n }\n): ObjectLinkRow[] {\n const direction = params.direction ?? \"outgoing\"\n const matches = (row: ObjectLinkRow) => !params.linkId || row.linkId === params.linkId\n const rows: ObjectLinkRow[] = []\n\n if (direction === \"outgoing\" || direction === \"both\") {\n const outgoing = universe.linksBySource.get(\n sourceLinkBucketKey(params.projectId, params.objectTypeId, params.objectId)\n )\n if (outgoing) rows.push(...outgoing.filter(matches))\n }\n if (direction === \"incoming\" || direction === \"both\") {\n for (const row of universe.links.values()) {\n if (\n row.targetTypeId === params.objectTypeId &&\n row.targetId === params.objectId &&\n matches(row)\n ) {\n rows.push(row)\n }\n }\n }\n\n if (direction !== \"both\") return rows\n return [...new Map(rows.map((row) => [fullLinkRowKey(row), row])).values()]\n}\n\nfunction listRows(\n params: Parameters<ObjectReadStorage[\"list\"]>[0],\n candidates: readonly ObjectRow[]\n): { objects: readonly ObjectRow[]; hasMore: boolean; total: number } {\n const requestedTypes =\n params.objectTypeId === undefined\n ? undefined\n : new Set(\n typeof params.objectTypeId === \"string\" ? [params.objectTypeId] : params.objectTypeId\n )\n let rows = candidates.filter(\n (row) =>\n row.projectId === params.projectId &&\n (!requestedTypes || requestedTypes.has(row.objectTypeId))\n )\n\n rows = rows.filter(\n (row) =>\n (!params.primaryIdPrefix || row.primaryId.startsWith(params.primaryIdPrefix)) &&\n (!params.primaryIdSuffix || row.primaryId.endsWith(params.primaryIdSuffix)) &&\n (!params.updatedAfter || row.updatedAt >= params.updatedAfter) &&\n (!params.updatedBefore || row.updatedAt <= params.updatedBefore) &&\n (!params.createdAfter || row.createdAt >= params.createdAfter) &&\n (!params.createdBefore || row.createdAt <= params.createdBefore)\n )\n\n const total = rows.length\n const offset = params.offset ?? 0\n const limit = params.limit ?? 50\n if (limit === 0) return { objects: [], hasMore: offset < total, total }\n\n const orderBy = params.orderBy ?? \"updatedAt\"\n const order = params.order ?? \"desc\"\n rows.sort((left, right) => {\n const comparison =\n orderBy === \"primaryId\"\n ? left.primaryId.localeCompare(right.primaryId)\n : orderBy === \"createdAt\"\n ? left.createdAt.getTime() - right.createdAt.getTime()\n : left.updatedAt.getTime() - right.updatedAt.getTime()\n return order === \"desc\" ? -comparison : comparison\n })\n\n const objects = rows.slice(offset, offset + limit).map((row) => structuredClone(row))\n return {\n objects,\n hasMore: offset + limit < total,\n total,\n }\n}\n",
|
|
24
|
+
"import type { EffectiveLinkSnapshot, EffectiveObjectSnapshot } from \"../../../materialization/model\"\nimport { hasVectorProfile } from \"../../../objects/vectors/query\"\nimport type { StoredObjectVector } from \"../../ontology/vectors\"\nimport type { ObjectReadExecutionLimits } from \"../execution-limits\"\nimport { type LinkBatchKey, type ObjectBatchKey, objectBatchKey } from \"../keys\"\nimport type {\n CompiledSelectedObjectReadScope,\n CountObjectsInput,\n CountObjectsResult,\n ExistsObjectsInput,\n ExistsObjectsResult,\n FacetObjectsInput,\n FacetObjectsResult,\n LinkDirection,\n ObjectLinkRow,\n ObjectQueryCapabilities,\n ObjectReadStorage,\n ObjectRow,\n ObjectStorage,\n QueryObjectLinksInput,\n QueryObjectLinksResult,\n QueryObjectsInput,\n QueryObjectsResult,\n} from \"../types\"\nimport {\n compareStrings,\n fullLinkRowKey,\n linkRowKey,\n objectRowKey,\n objectRowProjectPrefix,\n sourceLinkBucketKey,\n} from \"./keys\"\nimport {\n buildFacetResults,\n collectLinksBatch,\n evaluateObjectQuery,\n IN_MEMORY_OBJECT_QUERY_CAPABILITIES,\n queryLinksFrom,\n stripOuterRowShape,\n} from \"./query\"\nimport type { InMemoryReadSource } from \"./read-source\"\nimport { createInMemorySelectedReader } from \"./selected-reader\"\n\nexport interface InMemoryObjectStorageSnapshot {\n readonly rows: Map<string, Map<string, ObjectRow>>\n readonly links: Map<string, Map<string, ObjectLinkRow>>\n}\n\ntype VectorReader = (\n projectId: string,\n ref: { objectTypeId: string; primaryId: string },\n profile: string\n) => StoredObjectVector | undefined\n\ninterface InMemoryObjectMaterializerAdapter {\n setVectorReader(reader: VectorReader): void\n getExactObjectRow(projectId: string, objectTypeId: string, primaryId: string): ObjectRow | null\n getExactLinkRow(\n projectId: string,\n ref: {\n readonly sourceTypeId: string\n readonly sourceId: string\n readonly linkId: string\n readonly targetTypeId: string\n readonly targetId: string\n }\n ): ObjectLinkRow | null\n applyExactObject(row: EffectiveObjectSnapshot, projectId: string): void\n deleteExactObject(projectId: string, objectTypeId: string, primaryId: string): void\n applyExactLink(row: EffectiveLinkSnapshot, projectId: string): void\n deleteExactLink(row: {\n projectId: string\n sourceTypeId: string\n sourceId: string\n linkId: string\n targetTypeId: string\n targetId: string\n }): void\n visitExactLinks(projectId: string, visit: (row: ObjectLinkRow) => void): void\n visitExactScopeLinks(\n projectId: string,\n sourceTypeId: string,\n sourceId: string,\n linkId: string,\n visit: (row: ObjectLinkRow) => void\n ): void\n}\n\nconst materializerAdapters = new WeakMap<InMemoryObjectStorage, InMemoryObjectMaterializerAdapter>()\n\n/** @internal Exact access for the in-memory ontology provider; not exported from package barrels. */\nexport function getInMemoryObjectMaterializerAdapter(\n storage: InMemoryObjectStorage\n): InMemoryObjectMaterializerAdapter {\n const adapter = materializerAdapters.get(storage)\n if (!adapter) throw new Error(\"[Sixb] In-memory object materializer adapter is unavailable.\")\n return adapter\n}\n\nexport class InMemoryObjectStorage implements ObjectStorage {\n private readonly rows = new Map<string, Map<string, ObjectRow>>()\n private readonly links = new Map<string, Map<string, ObjectLinkRow>>()\n\n private vectorReader?: VectorReader\n\n constructor() {\n materializerAdapters.set(this, {\n setVectorReader: (reader) => {\n this.vectorReader = reader\n },\n getExactObjectRow: (projectId, objectTypeId, primaryId) =>\n this.getExactObjectRow(projectId, objectTypeId, primaryId),\n getExactLinkRow: (projectId, ref) => this.getExactLinkRow(projectId, ref),\n applyExactObject: (row, projectId) => this.applyExactObject(row, projectId),\n deleteExactObject: (projectId, objectTypeId, primaryId) =>\n this.deleteExactObject(projectId, objectTypeId, primaryId),\n applyExactLink: (row, projectId) => this.applyExactLink(row, projectId),\n deleteExactLink: (row) => this.deleteExactLink(row),\n visitExactLinks: (projectId, visit) => {\n for (const bucket of this.links.values()) {\n for (const row of bucket.values()) {\n if (row.projectId === projectId) visit(structuredClone(row))\n }\n }\n },\n visitExactScopeLinks: (projectId, sourceTypeId, sourceId, linkId, visit) => {\n const bucket = this.links.get(sourceLinkBucketKey(projectId, sourceTypeId, sourceId))\n if (!bucket) return\n for (const row of bucket.values()) {\n if (row.linkId === linkId) visit(structuredClone(row))\n }\n },\n })\n }\n\n snapshot(): InMemoryObjectStorageSnapshot {\n return {\n rows: cloneObjectBuckets(this.rows),\n links: cloneLinkBuckets(this.links),\n }\n }\n\n restore(snapshot: InMemoryObjectStorageSnapshot): void {\n this.rows.clear()\n for (const [key, bucket] of cloneObjectBuckets(snapshot.rows)) {\n this.rows.set(key, bucket)\n }\n\n this.links.clear()\n for (const [key, bucket] of cloneLinkBuckets(snapshot.links)) {\n this.links.set(key, bucket)\n }\n }\n\n private getExactObjectRow(\n projectId: string,\n objectTypeId: string,\n primaryId: string\n ): ObjectRow | null {\n const row = this.rows.get(objectRowKey(projectId, objectTypeId))?.get(primaryId)\n return row ? structuredClone(row) : null\n }\n\n private getExactLinkRow(\n projectId: string,\n ref: {\n readonly sourceTypeId: string\n readonly sourceId: string\n readonly linkId: string\n readonly targetTypeId: string\n readonly targetId: string\n }\n ): ObjectLinkRow | null {\n const row = this.links\n .get(sourceLinkBucketKey(projectId, ref.sourceTypeId, ref.sourceId))\n ?.get(linkRowKey(ref.linkId, ref.targetTypeId, ref.targetId))\n return row ? structuredClone(row) : null\n }\n\n private applyExactObject(row: EffectiveObjectSnapshot, projectId: string): void {\n const bucketId = objectRowKey(projectId, row.ref.objectTypeId)\n const bucket = this.rows.get(bucketId) ?? new Map<string, ObjectRow>()\n this.rows.set(bucketId, bucket)\n bucket.set(row.ref.primaryId, {\n projectId,\n objectTypeId: row.ref.objectTypeId,\n primaryId: row.ref.primaryId,\n properties: structuredClone(row.properties) as Record<string, unknown>,\n createdAt: new Date(row.createdAt),\n updatedAt: new Date(row.updatedAt),\n version: row.version,\n lastCommitId: row.lastCommitId,\n })\n }\n\n private deleteExactObject(projectId: string, objectTypeId: string, primaryId: string): void {\n this.deleteObjectRow(projectId, objectTypeId, primaryId)\n }\n\n private applyExactLink(row: EffectiveLinkSnapshot, projectId: string): void {\n const bucketKey = sourceLinkBucketKey(\n projectId,\n row.ref.source.objectTypeId,\n row.ref.source.primaryId\n )\n const bucket = this.links.get(bucketKey) ?? new Map<string, ObjectLinkRow>()\n this.links.set(bucketKey, bucket)\n bucket.set(linkRowKey(row.ref.linkId, row.ref.target.objectTypeId, row.ref.target.primaryId), {\n projectId,\n sourceTypeId: row.ref.source.objectTypeId,\n sourceId: row.ref.source.primaryId,\n linkId: row.ref.linkId,\n targetTypeId: row.ref.target.objectTypeId,\n targetId: row.ref.target.primaryId,\n properties: row.properties\n ? (structuredClone(row.properties) as Record<string, unknown>)\n : undefined,\n createdAt: new Date(row.createdAt),\n updatedAt: new Date(row.updatedAt),\n lastCommitId: row.lastCommitId,\n })\n }\n\n private deleteExactLink(row: {\n projectId: string\n sourceTypeId: string\n sourceId: string\n linkId: string\n targetTypeId: string\n targetId: string\n }): void {\n this.deleteLinkRow(\n row.projectId,\n row.sourceTypeId,\n row.sourceId,\n row.linkId,\n row.targetTypeId,\n row.targetId\n )\n }\n\n queryCapabilities(): ObjectQueryCapabilities {\n return IN_MEMORY_OBJECT_QUERY_CAPABILITIES\n }\n\n createSelectedReadScope(params: {\n projectId: string\n scope: CompiledSelectedObjectReadScope\n limits: ObjectReadExecutionLimits\n }): ObjectReadStorage {\n return createInMemorySelectedReader(this.readSource(params.projectId), params, () =>\n this.queryCapabilities()\n )\n }\n\n private readSource(projectId: string): InMemoryReadSource {\n // Keep indexed access live across writes and snapshot restores; do not capture individual buckets.\n return {\n projectId,\n getVector: (ref, profile) => this.vectorReader?.(projectId, ref, profile),\n objectsOfType: (objectTypeId) => [\n ...(this.rows.get(objectRowKey(projectId, objectTypeId))?.values() ?? []),\n ],\n getObject: (objectTypeId, primaryId) =>\n this.rows.get(objectRowKey(projectId, objectTypeId))?.get(primaryId),\n outgoingLinks: (objectTypeId, primaryId) =>\n this.links.get(sourceLinkBucketKey(projectId, objectTypeId, primaryId))?.values() ?? [],\n allLinks: () => allLinkRows(this.links),\n }\n }\n\n async queryObjects(params: QueryObjectsInput): Promise<QueryObjectsResult> {\n const result = evaluateObjectQuery(params.query, this.readSource(params.projectId))\n return {\n objects: result.entries.map((entry) => ({\n ...entry.row,\n ...(hasVectorProfile(params.query) ? { score: entry.score } : {}),\n })),\n hasMore: result.hasMore,\n nextPageToken: result.nextPageToken,\n ...(params.includeTotal === false ? {} : { total: result.total }),\n }\n }\n\n async countObjects(params: CountObjectsInput): Promise<CountObjectsResult> {\n return {\n count: evaluateObjectQuery(\n stripOuterRowShape(params.query),\n this.readSource(params.projectId)\n ).total,\n }\n }\n\n async existsObjects(params: ExistsObjectsInput): Promise<ExistsObjectsResult> {\n return {\n exists:\n evaluateObjectQuery(stripOuterRowShape(params.query), this.readSource(params.projectId))\n .total > 0,\n }\n }\n\n async facetObjects(params: FacetObjectsInput): Promise<FacetObjectsResult> {\n const result = evaluateObjectQuery(\n stripOuterRowShape(params.query),\n this.readSource(params.projectId)\n )\n return {\n facets: buildFacetResults(\n result.entries.map((entry) => entry.row),\n params.facets\n ),\n }\n }\n\n /**\n * Reads return the *live* stored row by reference (the SQL providers detach a copy via JSON\n * round-trip). Callers must treat read results as immutable: mutating a returned row mutates the\n * store in place — including after the transaction that read it has completed, which escapes the\n * transaction guard. Internal call sites (e.g. the EditBatch planner) already copy before\n * mutating; external callers must do the same.\n */\n async getByPrimaryId(params: {\n projectId: string\n objectTypeId: string\n primaryId: string\n }): Promise<ObjectRow | null> {\n const bucket = this.rows.get(objectRowKey(params.projectId, params.objectTypeId))\n if (!bucket) return null\n return bucket.get(params.primaryId) ?? null\n }\n\n async selectsObjectProperties(\n params: Parameters<ObjectReadStorage[\"selectsObjectProperties\"]>[0]\n ): Promise<readonly boolean[]> {\n return params.items.map(\n (item) =>\n this.rows.get(objectRowKey(params.projectId, item.objectTypeId))?.has(item.primaryId) ??\n false\n )\n }\n\n async listLinks(params: {\n projectId: string\n objectTypeId: string\n objectId: string\n linkId?: string\n direction?: LinkDirection\n }): Promise<readonly ObjectLinkRow[]> {\n const direction = params.direction ?? \"outgoing\"\n const matches = (row: ObjectLinkRow) => !params.linkId || row.linkId === params.linkId\n const rows: ObjectLinkRow[] = []\n\n if (direction === \"outgoing\" || direction === \"both\") {\n const bucket = this.links.get(\n sourceLinkBucketKey(params.projectId, params.objectTypeId, params.objectId)\n )\n if (bucket) rows.push(...[...bucket.values()].filter(matches))\n }\n\n if (direction === \"incoming\" || direction === \"both\") {\n for (const bucket of this.links.values()) {\n for (const row of bucket.values()) {\n if (\n row.projectId === params.projectId &&\n row.targetTypeId === params.objectTypeId &&\n row.targetId === params.objectId &&\n matches(row)\n ) {\n rows.push(row)\n }\n }\n }\n }\n\n if (direction !== \"both\") return rows\n return [...new Map(rows.map((row) => [fullLinkRowKey(row), row])).values()]\n }\n\n async getByPrimaryIdBatch(params: {\n projectId: string\n items: readonly { objectTypeId: string; primaryId: string }[]\n }): Promise<Map<ObjectBatchKey, ObjectRow>> {\n const result = new Map<ObjectBatchKey, ObjectRow>()\n for (const item of params.items) {\n const row = await this.getByPrimaryId({\n projectId: params.projectId,\n objectTypeId: item.objectTypeId,\n primaryId: item.primaryId,\n })\n if (row) {\n result.set(objectBatchKey(item.objectTypeId, item.primaryId), row)\n }\n }\n return result\n }\n\n async listLinksBatch(params: {\n projectId: string\n direction?: LinkDirection\n items: readonly { objectTypeId: string; objectId: string; linkId: string }[]\n }): Promise<Map<LinkBatchKey, ObjectLinkRow[]>> {\n return collectLinksBatch(\n {\n all: () => allLinkRows(this.links),\n outgoing: (item) =>\n this.links\n .get(sourceLinkBucketKey(params.projectId, item.objectTypeId, item.objectId))\n ?.values() ?? [],\n },\n params,\n false\n )\n }\n\n async queryLinks(params: QueryObjectLinksInput): Promise<QueryObjectLinksResult> {\n return queryLinksFrom(params, (input) => this.listLinks(input))\n }\n\n async listIncidentLinksBatch(params: {\n projectId: string\n items: readonly { objectTypeId: string; objectId: string }[]\n }): Promise<readonly ObjectLinkRow[]> {\n const deduped = new Map<string, ObjectLinkRow>()\n for (const item of params.items) {\n const rows = await this.listLinks({\n projectId: params.projectId,\n objectTypeId: item.objectTypeId,\n objectId: item.objectId,\n direction: \"both\",\n })\n for (const row of rows) {\n deduped.set(fullLinkRowKey(row), row)\n }\n }\n return [...deduped.values()]\n }\n\n async listByPrimaryIdPage(params: {\n projectId: string\n objectTypeId: string\n afterPrimaryId?: string\n limit: number\n }): Promise<{ objects: readonly ObjectRow[]; nextPrimaryId?: string }> {\n assertReconciliationPageLimit(params.limit)\n const bucket = this.rows.get(objectRowKey(params.projectId, params.objectTypeId))\n const rows = [...(bucket?.values() ?? [])]\n .filter(\n (row) => !params.afterPrimaryId || compareStrings(row.primaryId, params.afterPrimaryId) > 0\n )\n .sort((left, right) => compareStrings(left.primaryId, right.primaryId))\n .slice(0, params.limit + 1)\n const hasMore = rows.length > params.limit\n const objects = rows.slice(0, params.limit).map((row) => structuredClone(row))\n const last = objects.at(-1)\n return {\n objects,\n ...(hasMore && last ? { nextPrimaryId: last.primaryId } : {}),\n }\n }\n\n async list(params: {\n projectId: string\n objectTypeId?: string | readonly string[]\n primaryIdPrefix?: string\n primaryIdSuffix?: string\n updatedAfter?: Date\n updatedBefore?: Date\n createdAfter?: Date\n createdBefore?: Date\n limit?: number\n offset?: number\n orderBy?: \"createdAt\" | \"updatedAt\" | \"primaryId\"\n order?: \"asc\" | \"desc\"\n }): Promise<{ objects: readonly ObjectRow[]; hasMore: boolean; total: number }> {\n let allRows: ObjectRow[] = []\n\n if (params.objectTypeId) {\n const typeIds = Array.isArray(params.objectTypeId)\n ? params.objectTypeId\n : [params.objectTypeId]\n for (const typeId of typeIds) {\n const bucket = this.rows.get(objectRowKey(params.projectId, typeId))\n if (bucket) {\n allRows.push(...bucket.values())\n }\n }\n } else {\n for (const [key, bucket] of this.rows) {\n if (key.startsWith(objectRowProjectPrefix(params.projectId))) {\n allRows.push(...bucket.values())\n }\n }\n }\n\n const {\n primaryIdPrefix,\n primaryIdSuffix,\n updatedAfter,\n updatedBefore,\n createdAfter,\n createdBefore,\n } = params\n if (\n primaryIdPrefix ||\n primaryIdSuffix ||\n updatedAfter ||\n updatedBefore ||\n createdAfter ||\n createdBefore\n ) {\n allRows = allRows.filter(\n (row) =>\n (!primaryIdPrefix || row.primaryId.startsWith(primaryIdPrefix)) &&\n (!primaryIdSuffix || row.primaryId.endsWith(primaryIdSuffix)) &&\n (!updatedAfter || row.updatedAt >= updatedAfter) &&\n (!updatedBefore || row.updatedAt <= updatedBefore) &&\n (!createdAfter || row.createdAt >= createdAfter) &&\n (!createdBefore || row.createdAt <= createdBefore)\n )\n }\n\n const total = allRows.length\n\n const offset = params.offset ?? 0\n const limit = params.limit ?? 50\n if (limit === 0) return { objects: [], hasMore: offset < total, total }\n\n const orderBy = params.orderBy ?? \"updatedAt\"\n const order = params.order ?? \"desc\"\n\n allRows.sort((a, b) => {\n let comparison = 0\n switch (orderBy) {\n case \"primaryId\":\n comparison = a.primaryId.localeCompare(b.primaryId)\n break\n case \"createdAt\":\n comparison = a.createdAt.getTime() - b.createdAt.getTime()\n break\n default:\n comparison = a.updatedAt.getTime() - b.updatedAt.getTime()\n break\n }\n return order === \"desc\" ? -comparison : comparison\n })\n\n const objects = allRows.slice(offset, offset + limit)\n const hasMore = offset + limit < total\n\n return { objects, hasMore, total }\n }\n\n private deleteObjectRow(projectId: string, objectTypeId: string, primaryId: string): void {\n const bucket = this.rows.get(objectRowKey(projectId, objectTypeId))\n bucket?.delete(primaryId)\n }\n\n private deleteLinkRow(\n projectId: string,\n sourceTypeId: string,\n sourceId: string,\n linkId: string,\n targetTypeId: string,\n targetId: string\n ): void {\n const bucket = this.links.get(sourceLinkBucketKey(projectId, sourceTypeId, sourceId))\n bucket?.delete(linkRowKey(linkId, targetTypeId, targetId))\n }\n}\n\nfunction assertReconciliationPageLimit(limit: number): void {\n if (!Number.isSafeInteger(limit) || limit <= 0) {\n throw new Error(\"Object reconciliation page limit must be a positive safe integer.\")\n }\n}\n\nfunction cloneObjectBuckets(\n rows: Map<string, Map<string, ObjectRow>>\n): Map<string, Map<string, ObjectRow>> {\n const clone = new Map<string, Map<string, ObjectRow>>()\n for (const [key, bucket] of rows) {\n clone.set(\n key,\n new Map([...bucket.entries()].map(([primaryId, row]) => [primaryId, structuredClone(row)]))\n )\n }\n return clone\n}\n\nfunction cloneLinkBuckets(\n links: Map<string, Map<string, ObjectLinkRow>>\n): Map<string, Map<string, ObjectLinkRow>> {\n const clone = new Map<string, Map<string, ObjectLinkRow>>()\n for (const [key, bucket] of links) {\n clone.set(\n key,\n new Map([...bucket.entries()].map(([linkId, row]) => [linkId, structuredClone(row)]))\n )\n }\n return clone\n}\n\nfunction* allLinkRows(\n buckets: ReadonlyMap<string, ReadonlyMap<string, ObjectLinkRow>>\n): Iterable<ObjectLinkRow> {\n for (const bucket of buckets.values()) yield* bucket.values()\n}\n",
|
|
25
|
+
"import { MaterializationValidationError } from \"../../../materialization/errors\"\nimport type {\n LinkSlotOverride,\n OntologyMaterializationOrigin,\n ProjectionEntityRef,\n} from \"../../../materialization/model\"\nimport type { OntologyCommitOriginSelector, OntologyCommitRecord } from \"../commits\"\nimport type {\n MaterializationWorkRecord,\n StoredLinkOverride,\n StoredLinkSlotOverride,\n StoredObjectOverride,\n} from \"../materializations\"\nimport type { OntologyOutboxRecord } from \"../outbox\"\nimport type {\n OntologySourceRecord,\n StageSourceAssertion,\n StoredSourceAssertion,\n StoredSourceLinkAssertion,\n} from \"../sources\"\nimport type { VectorIndexingWork } from \"../vector-indexing\"\nimport type { StoredObjectVector } from \"../vectors\"\n\nexport interface InMemorySourceRoot {\n readonly root: ProjectionEntityRef\n readonly stagingOrdinal: number\n readonly deleted: boolean\n readonly entityKeys: Set<string>\n active: boolean\n retiredAt: string | null\n}\n\nexport interface InMemorySourceMaterialization extends OntologySourceRecord {\n readonly roots: Map<string, InMemorySourceRoot>\n readonly rowsByEntity: Map<string, StageSourceAssertion>\n readonly rootOrdinals: Map<string, number>\n readonly ordinalRoots: Map<number, string>\n}\n\nexport interface InMemoryStoredObjectOverride extends StoredObjectOverride {\n readonly projectId: string\n}\n\nexport interface InMemoryStoredLinkOverride extends StoredLinkOverride {\n readonly projectId: string\n}\n\nexport interface InMemoryStoredLinkSlotOverride extends Omit<StoredLinkSlotOverride, \"value\"> {\n readonly projectId: string\n readonly value: LinkSlotOverride\n}\n\nexport interface InMemoryOntologyState {\n readonly vectorIndexing: Map<\n string,\n VectorIndexingWork & { projectId: string; dispatchAt: string }\n >\n readonly vectors: Map<string, Map<string, StoredObjectVector>>\n readonly commitsById: Map<string, OntologyCommitRecord>\n readonly commitIdByIdempotency: Map<string, string>\n readonly commitIdByOrigin: Map<string, string>\n readonly sourceMaterializations: Map<string, InMemorySourceMaterialization>\n readonly activeSourceHeads: Map<string, string>\n readonly activeSourceRoots: Map<string, Map<string, string>>\n readonly activeSourceRows: Map<string, Map<string, StoredSourceAssertion>>\n readonly activeSourceLinkScopes: Map<string, Map<string, StoredSourceLinkAssertion>>\n readonly objectOverrides: Map<string, InMemoryStoredObjectOverride>\n readonly linkOverrides: Map<string, InMemoryStoredLinkOverride>\n readonly linkSlotOverrides: Map<string, InMemoryStoredLinkSlotOverride>\n readonly outbox: Map<string, OntologyOutboxRecord>\n}\n\n/** @internal Test-only failure injection for the in-memory ontology provider. */\nexport interface InMemoryOntologyStorageTestHooks {\n readonly beforeRead?: (boundary: string) => void\n readonly beforeWrite?: (boundary: string, ordinal: number) => void\n readonly observeBuffer?: (boundary: string, rows: number) => void\n readonly observeWork?: (records: readonly MaterializationWorkRecord[]) => void\n}\n\nexport function createInMemoryOntologyState(): InMemoryOntologyState {\n return {\n vectors: new Map(),\n vectorIndexing: new Map(),\n commitsById: new Map(),\n commitIdByIdempotency: new Map(),\n commitIdByOrigin: new Map(),\n sourceMaterializations: new Map(),\n activeSourceHeads: new Map(),\n activeSourceRoots: new Map(),\n activeSourceRows: new Map(),\n activeSourceLinkScopes: new Map(),\n objectOverrides: new Map(),\n linkOverrides: new Map(),\n linkSlotOverrides: new Map(),\n outbox: new Map(),\n }\n}\n\nexport function projectEntityKey(projectId: string, entityKey: string): string {\n return JSON.stringify([projectId, entityKey])\n}\n\nexport function sourceMaterializationKey(\n projectId: string,\n sourceId: string,\n materializationId: string\n): string {\n return JSON.stringify([projectId, sourceId, materializationId])\n}\n\nexport function sourceMaterializationRecord(\n materialization: InMemorySourceMaterialization\n): OntologySourceRecord {\n const {\n rowsByEntity: _rows,\n rootOrdinals: _roots,\n ordinalRoots: _ordinals,\n roots: _sourceRoots,\n ...record\n } = materialization\n return structuredClone(record)\n}\n\nexport function commitKey(projectId: string, commitId: string): string {\n return JSON.stringify([projectId, commitId])\n}\n\nexport function idempotencyKey(projectId: string, key: string): string {\n return JSON.stringify([projectId, key])\n}\n\nexport function ontologyCommitOriginSelector(\n origin: OntologyMaterializationOrigin\n): OntologyCommitOriginSelector | null {\n if (origin.kind === \"action\") return { kind: \"action\", actionRunId: origin.runId }\n if (origin.kind === \"projection\") {\n return { kind: \"projection\", projectionRunId: origin.projectionRunId }\n }\n if (origin.kind === \"telemetry\" && origin.source.kind === \"projection\") {\n return {\n kind: \"telemetry\",\n projectionRunId: origin.source.projectionRunId,\n batchOrdinal: origin.source.batchOrdinal,\n }\n }\n return null\n}\n\nexport function commitOriginKey(projectId: string, origin: OntologyCommitOriginSelector): string {\n switch (origin.kind) {\n case \"action\":\n return JSON.stringify([projectId, origin.kind, origin.actionRunId])\n case \"projection\":\n return JSON.stringify([projectId, origin.kind, origin.projectionRunId])\n case \"telemetry\":\n return JSON.stringify([projectId, origin.kind, origin.projectionRunId, origin.batchOrdinal])\n }\n}\n\nexport function outboxKey(projectId: string, eventId: string): string {\n return JSON.stringify([projectId, eventId])\n}\n\nexport function cloneOntologyState(state: InMemoryOntologyState): InMemoryOntologyState {\n return structuredClone(state)\n}\n\nexport function restoreOntologyState(\n target: InMemoryOntologyState,\n snapshot: InMemoryOntologyState\n): void {\n for (const key of Object.keys(target) as (keyof InMemoryOntologyState)[]) {\n const targetMap = target[key] as Map<unknown, unknown>\n const sourceMap = structuredClone(snapshot[key]) as Map<unknown, unknown>\n targetMap.clear()\n for (const [entryKey, value] of sourceMap) targetMap.set(entryKey, value)\n }\n}\n\n/** Insert `value` into a sorted, size-bounded accumulator, dropping the largest entry past `limit`. */\nexport function insertBounded<T>(\n values: T[],\n value: T,\n limit: number,\n compare: (left: T, right: T) => number\n): void {\n if (limit <= 0) return\n if (values.length >= limit && compare(value, values[values.length - 1]!) >= 0) return\n let low = 0\n let high = values.length\n while (low < high) {\n const middle = (low + high) >>> 1\n if (compare(value, values[middle]!) < 0) high = middle\n else low = middle + 1\n }\n values.splice(low, 0, value)\n if (values.length > limit) values.pop()\n}\n\nexport function assertNonblank(value: string, label: string): void {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new MaterializationValidationError(`${label} must be nonblank.`)\n }\n}\n\nexport function assertTimestamp(value: string, label: string): number {\n const milliseconds = Date.parse(value)\n if (!Number.isFinite(milliseconds) || new Date(milliseconds).toISOString() !== value) {\n throw new MaterializationValidationError(`${label} must be a canonical UTC timestamp.`)\n }\n return milliseconds\n}\n",
|
|
26
|
+
"import type {\n GetOntologyCommitByIdempotencyKeyInput,\n GetOntologyCommitByIdInput,\n GetOntologyCommitByOriginInput,\n ListOntologyCommitsInput,\n ListOntologyCommitsResult,\n OntologyCommitRecord,\n OntologyCommitRunSelector,\n OntologyCommitStorage,\n} from \"../commits\"\nimport {\n commitKey,\n commitOriginKey,\n type InMemoryOntologyState,\n idempotencyKey,\n} from \"./shared-state\"\n\nexport class InMemoryOntologyCommitStorage implements OntologyCommitStorage {\n constructor(\n private readonly state: InMemoryOntologyState,\n private readonly runRootOperation: <T>(run: () => Promise<T> | T) => Promise<T>\n ) {}\n\n async getByIdempotencyKey(\n input: GetOntologyCommitByIdempotencyKeyInput\n ): Promise<OntologyCommitRecord | null> {\n return this.runRootOperation(() => {\n const id = this.state.commitIdByIdempotency.get(\n idempotencyKey(input.projectId, input.idempotencyKey)\n )\n if (!id) return null\n return structuredClone(this.state.commitsById.get(commitKey(input.projectId, id)) ?? null)\n })\n }\n\n async getById(input: GetOntologyCommitByIdInput): Promise<OntologyCommitRecord | null> {\n return this.runRootOperation(() =>\n structuredClone(this.state.commitsById.get(commitKey(input.projectId, input.id)) ?? null)\n )\n }\n\n async getByOrigin(input: GetOntologyCommitByOriginInput): Promise<OntologyCommitRecord | null> {\n return this.runRootOperation(() => {\n assertOriginLookup(input)\n const id = this.state.commitIdByOrigin.get(commitOriginKey(input.projectId, input.origin))\n if (!id) return null\n return structuredClone(this.state.commitsById.get(commitKey(input.projectId, id)) ?? null)\n })\n }\n\n async list(input: ListOntologyCommitsInput): Promise<ListOntologyCommitsResult> {\n return this.runRootOperation(() => {\n if (input.projectId.trim().length === 0 || input.run?.id.trim().length === 0) {\n throw new Error(\"[Sixb] Ontology commit project and run ids must be nonblank.\")\n }\n const offset = input.offset ?? 0\n const limit = input.limit ?? this.state.commitsById.size\n if (\n !Number.isSafeInteger(offset) ||\n offset < 0 ||\n !Number.isSafeInteger(limit) ||\n limit < 0\n ) {\n throw new Error(\n \"[Sixb] Ontology commit list limit and offset must be nonnegative integers.\"\n )\n }\n const direction = input.order === \"desc\" ? -1 : 1\n const commits = [...this.state.commitsById.values()]\n .filter((commit) => commit.projectId === input.projectId)\n .filter((commit) => (input.run ? commitMatchesRun(commit, input.run) : true))\n .sort((left, right) => {\n if (input.run?.kind === \"projection\") {\n const byOrdinal = projectionRunOrdinal(left) - projectionRunOrdinal(right)\n if (byOrdinal !== 0) return byOrdinal * direction\n }\n const byTime = left.committedAt.localeCompare(right.committedAt)\n if (byTime !== 0) return byTime * direction\n return left.id.localeCompare(right.id) * direction\n })\n const total = commits.length\n const page = commits.slice(offset, offset + limit).map((commit) => structuredClone(commit))\n return { commits: page, total, hasMore: offset + page.length < total }\n })\n }\n}\n\nfunction assertOriginLookup(input: GetOntologyCommitByOriginInput): void {\n if (input.projectId.trim().length === 0) {\n throw new Error(\"[Sixb] Ontology commit project id must be nonblank.\")\n }\n const runId =\n input.origin.kind === \"action\" ? input.origin.actionRunId : input.origin.projectionRunId\n if (runId.trim().length === 0) {\n throw new Error(\"[Sixb] Ontology commit origin run id must be nonblank.\")\n }\n if (\n input.origin.kind === \"telemetry\" &&\n (!Number.isSafeInteger(input.origin.batchOrdinal) || input.origin.batchOrdinal < 0)\n ) {\n throw new Error(\"[Sixb] Ontology telemetry commit batch ordinal must be nonnegative.\")\n }\n}\n\nfunction commitMatchesRun(commit: OntologyCommitRecord, run: OntologyCommitRunSelector): boolean {\n if (run.kind === \"action\") {\n return commit.origin.kind === \"action\" && commit.origin.runId === run.id\n }\n if (commit.origin.kind === \"projection\") return commit.origin.projectionRunId === run.id\n return (\n commit.origin.kind === \"telemetry\" &&\n commit.origin.source.kind === \"projection\" &&\n commit.origin.source.projectionRunId === run.id\n )\n}\n\nfunction projectionRunOrdinal(commit: OntologyCommitRecord): number {\n if (commit.origin.kind === \"telemetry\" && commit.origin.source.kind === \"projection\") {\n return commit.origin.source.batchOrdinal\n }\n return 0\n}\n",
|
|
27
|
+
"import type { TelemetrySeriesRef } from \"../../materialization/model\"\nimport type { StoredTelemetryPoint } from \"../ontology/materializations\"\nimport type { TimeseriesHistoryBatchInput, TimeseriesPoint, TimeseriesStorage } from \"./types\"\n\nfunction pointKey(\n projectId: string,\n objectTypeId: string,\n objectId: string,\n propertyId: string\n): string {\n return JSON.stringify([projectId, objectTypeId, objectId, propertyId])\n}\n\nexport class InMemoryTimeseriesStorage implements TimeseriesStorage {\n // A telemetry point is uniquely identified by (series, at): one value per\n // instant per series. Re-applying the same instant is a last-write-wins\n // upsert, which makes telemetry writes idempotent under replay for free.\n private readonly pointsByKey = new Map<string, Map<number, TimeseriesPoint>>()\n\n constructor() {\n materializerAdapters.set(this, {\n getExactPoint: (projectId, series, at) => this.getExactPoint(projectId, series, at),\n listLatestForObject: (projectId, objectTypeId, objectId) =>\n this.listLatestForObject(projectId, objectTypeId, objectId),\n applyExactPoint: (projectId, point) => this.applyExactPoint(projectId, point),\n })\n }\n\n snapshot(): InMemoryTimeseriesStorageSnapshot {\n return {\n pointsByKey: structuredClone(this.pointsByKey),\n }\n }\n\n restore(snapshot: InMemoryTimeseriesStorageSnapshot): void {\n this.pointsByKey.clear()\n for (const [key, points] of structuredClone(snapshot.pointsByKey)) {\n this.pointsByKey.set(key, points)\n }\n }\n\n private getExactPoint(\n projectId: string,\n series: TelemetrySeriesRef,\n at: string\n ): TimeseriesPoint | null {\n const point =\n this.pointsByKey\n .get(\n pointKey(\n projectId,\n series.object.objectTypeId,\n series.object.primaryId,\n series.propertyId\n )\n )\n ?.get(new Date(at).getTime()) ?? null\n return point ? clonePoint(point) : null\n }\n\n private listLatestForObject(\n projectId: string,\n objectTypeId: string,\n objectId: string\n ): TimeseriesPoint[] {\n const latest: TimeseriesPoint[] = []\n for (const series of this.pointsByKey.values()) {\n let point: TimeseriesPoint | null = null\n for (const candidate of series.values()) {\n if (\n candidate.projectId !== projectId ||\n candidate.objectTypeId !== objectTypeId ||\n candidate.objectId !== objectId\n ) {\n continue\n }\n if (!point || candidate.at > point.at) point = candidate\n }\n if (point) latest.push(clonePoint(point))\n }\n return latest\n }\n\n private applyExactPoint(projectId: string, point: StoredTelemetryPoint): void {\n const key = pointKey(\n projectId,\n point.series.object.objectTypeId,\n point.series.object.primaryId,\n point.series.propertyId\n )\n const series = this.pointsByKey.get(key) ?? new Map<number, TimeseriesPoint>()\n series.set(new Date(point.at).getTime(), {\n projectId,\n objectTypeId: point.series.object.objectTypeId,\n objectId: point.series.object.primaryId,\n propertyId: point.series.propertyId,\n value: structuredClone(point.value),\n ...(point.unit !== undefined ? { unit: point.unit } : {}),\n at: new Date(point.at),\n lastCommitId: point.lastCommitId,\n })\n this.pointsByKey.set(key, series)\n }\n\n async getHistory(params: {\n projectId: string\n objectTypeId: string\n objectId: string\n propertyId: string\n from?: Date\n to?: Date\n limit?: number\n order?: \"asc\" | \"desc\"\n }): Promise<readonly TimeseriesPoint[]> {\n const key = pointKey(params.projectId, params.objectTypeId, params.objectId, params.propertyId)\n const { from, to } = params\n let points = [...(this.pointsByKey.get(key)?.values() ?? [])]\n if (from || to) {\n points = points.filter((point) => (!from || point.at >= from) && (!to || point.at <= to))\n }\n\n points.sort((a, b) => a.at.getTime() - b.at.getTime())\n if (params.order === \"desc\") {\n points.reverse()\n }\n\n if (params.limit !== undefined) {\n points = points.slice(0, Math.max(0, params.limit))\n }\n\n return points.map(clonePoint)\n }\n\n async getHistoryBatch(input: TimeseriesHistoryBatchInput): Promise<\n readonly {\n objectTypeId: string\n objectId: string\n propertyId: string\n points: readonly TimeseriesPoint[]\n }[]\n > {\n // Start every read before yielding so one batch observes one in-memory snapshot. The SQL\n // providers get the same guarantee from their single query.\n return Promise.all(\n input.series.map(async (series) => ({\n ...series,\n points: await this.getHistory({\n projectId: input.projectId,\n objectTypeId: series.objectTypeId,\n objectId: series.objectId,\n propertyId: series.propertyId,\n from: input.from,\n to: input.to,\n limit: input.limitPerSeries,\n order: input.order,\n }),\n }))\n )\n }\n\n async getLatest(params: {\n projectId: string\n objectTypeId: string\n objectId: string\n propertyId: string\n }): Promise<TimeseriesPoint | null> {\n const series = this.pointsByKey.get(\n pointKey(params.projectId, params.objectTypeId, params.objectId, params.propertyId)\n )\n if (!series || series.size === 0) {\n return null\n }\n\n let latest: TimeseriesPoint | null = null\n for (const point of series.values()) {\n if (!latest || point.at.getTime() > latest.at.getTime()) {\n latest = point\n }\n }\n return latest ? clonePoint(latest) : null\n }\n}\n\ninterface InMemoryTimeseriesMaterializerAdapter {\n getExactPoint(projectId: string, series: TelemetrySeriesRef, at: string): TimeseriesPoint | null\n listLatestForObject(projectId: string, objectTypeId: string, objectId: string): TimeseriesPoint[]\n applyExactPoint(projectId: string, point: StoredTelemetryPoint): void\n}\n\nconst materializerAdapters = new WeakMap<\n InMemoryTimeseriesStorage,\n InMemoryTimeseriesMaterializerAdapter\n>()\n\n/** @internal Exact access for the in-memory ontology provider; not exported from package barrels. */\nexport function getInMemoryTimeseriesMaterializerAdapter(\n storage: InMemoryTimeseriesStorage\n): InMemoryTimeseriesMaterializerAdapter {\n const adapter = materializerAdapters.get(storage)\n if (!adapter) throw new Error(\"[Sixb] In-memory timeseries materializer adapter is unavailable.\")\n return adapter\n}\n\nfunction clonePoint(point: TimeseriesPoint): TimeseriesPoint {\n return {\n ...structuredClone(point),\n value: structuredClone(point.value),\n at: new Date(point.at),\n }\n}\n\nexport interface InMemoryTimeseriesStorageSnapshot {\n readonly pointsByKey: Map<string, Map<number, TimeseriesPoint>>\n}\n",
|
|
28
|
+
"import { MaterializationConflictError } from \"../../../materialization/errors\"\nimport type {\n EffectiveLinkSnapshot,\n EffectiveObjectSnapshot,\n OntologyLinkRef,\n} from \"../../../materialization/model\"\nimport { linkRefKey, linkRefSortKey, linkScopeSortKey } from \"../../../materialization/refs\"\nimport type { ObjectLinkRow, ObjectRow } from \"../../objects/types\"\nimport type { TimeseriesPoint } from \"../../timeseries/types\"\nimport type {\n StoredLinkOverride,\n StoredLinkSlotOverride,\n StoredObjectOverride,\n StoredTelemetryPoint,\n} from \"../materializations\"\nimport type {\n StageSourceAssertion,\n StoredSourceAssertion,\n StoredSourceLinkAssertion,\n StoredSourceObjectAssertion,\n} from \"../sources\"\nimport type { ReplacementSessionState } from \"./materializations\"\nimport type {\n InMemoryOntologyState,\n InMemorySourceMaterialization,\n InMemoryStoredLinkOverride,\n InMemoryStoredLinkSlotOverride,\n InMemoryStoredObjectOverride,\n} from \"./shared-state\"\nimport { projectEntityKey, sourceMaterializationKey } from \"./shared-state\"\n\nexport function publicObjectOverride(\n value: InMemoryStoredObjectOverride | undefined\n): StoredObjectOverride | null {\n if (!value) return null\n const { projectId: _, ...stored } = value\n return stored\n}\n\nexport function publicLinkOverride(\n value: InMemoryStoredLinkOverride | undefined\n): StoredLinkOverride | null {\n if (!value) return null\n const { projectId: _, ...stored } = value\n return stored\n}\n\nexport function publicLinkSlotOverride(\n value: InMemoryStoredLinkSlotOverride | undefined\n): StoredLinkSlotOverride | null {\n if (!value) return null\n const { projectId: _, ...stored } = value\n return stored\n}\n\nexport function uniqueBy<T>(values: readonly T[], keyOf: (value: T) => string): T[] {\n return [...new Map(values.map((value) => [keyOf(value), structuredClone(value)])).values()]\n}\n\nexport function objectSnapshot(row: ObjectRow): EffectiveObjectSnapshot {\n if (!row.lastCommitId)\n throw new MaterializationConflictError(\n \"effective-state\",\n `Effective object ${row.objectTypeId}:${row.primaryId} lacks materializer provenance.`\n )\n return {\n ref: { objectTypeId: row.objectTypeId, primaryId: row.primaryId },\n properties: structuredClone(row.properties) as EffectiveObjectSnapshot[\"properties\"],\n version: row.version,\n createdAt: row.createdAt.toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n lastCommitId: row.lastCommitId,\n }\n}\n\nexport function linkSnapshot(row: ObjectLinkRow): EffectiveLinkSnapshot {\n if (!row.lastCommitId)\n throw new MaterializationConflictError(\n \"effective-state\",\n `Effective link lacks materializer provenance.`\n )\n return {\n ref: linkRef(row),\n ...(row.properties\n ? { properties: structuredClone(row.properties) as EffectiveLinkSnapshot[\"properties\"] }\n : {}),\n createdAt: row.createdAt.toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n lastCommitId: row.lastCommitId,\n }\n}\n\nexport function linkRef(row: ObjectLinkRow): OntologyLinkRef {\n return {\n source: { objectTypeId: row.sourceTypeId, primaryId: row.sourceId },\n linkId: row.linkId,\n target: { objectTypeId: row.targetTypeId, primaryId: row.targetId },\n }\n}\n\nexport function storedPoint(point: TimeseriesPoint): StoredTelemetryPoint {\n if (!point.lastCommitId)\n throw new MaterializationConflictError(\n \"timeseries-point\",\n \"Telemetry point lacks materializer provenance.\"\n )\n return {\n series: {\n object: { objectTypeId: point.objectTypeId, primaryId: point.objectId },\n propertyId: point.propertyId,\n },\n value: structuredClone(point.value) as StoredTelemetryPoint[\"value\"],\n ...(point.unit !== undefined ? { unit: point.unit } : {}),\n at: point.at.toISOString(),\n lastCommitId: point.lastCommitId,\n }\n}\n\nexport function findActiveSourceMaterialization(\n state: InMemoryOntologyState,\n projectId: string,\n sourceId: string\n): InMemorySourceMaterialization | undefined {\n const id = state.activeSourceHeads.get(projectEntityKey(projectId, sourceId))\n return id\n ? state.sourceMaterializations.get(sourceMaterializationKey(projectId, sourceId, id))\n : undefined\n}\n\nexport function storedSource(\n sourceId: string,\n materializationId: string,\n row: StageSourceAssertion\n): StoredSourceAssertion {\n return {\n source: { projectionId: sourceId },\n materializationId,\n root: structuredClone(row.root),\n assertion: structuredClone(row.assertion),\n stagingOrdinal: row.stagingOrdinal,\n } as StoredSourceAssertion\n}\n\nexport function storedSourceObject(\n sourceId: string,\n materializationId: string | undefined,\n row: StageSourceAssertion | undefined\n): StoredSourceObjectAssertion | null {\n if (!materializationId || !row || row.assertion.kind !== \"object\") return null\n return storedSource(sourceId, materializationId, row) as StoredSourceObjectAssertion\n}\n\nexport function storedSourceLink(\n sourceId: string,\n materializationId: string | undefined,\n row: StageSourceAssertion | undefined\n): StoredSourceLinkAssertion | null {\n if (!materializationId || !row || row.assertion.kind !== \"link\") return null\n return storedSource(sourceId, materializationId, row) as StoredSourceLinkAssertion\n}\n\nexport function addReplacementLink(\n replacement: ReplacementSessionState,\n ref: OntologyLinkRef,\n diffRequired: boolean\n): void {\n const key = linkRefKey(ref)\n const existing = replacement.links.get(key)\n if (existing) {\n existing.diffRequired ||= diffRequired\n if (diffRequired) replacement.affectedScopes.add(linkScopeSortKey(ref.source, ref.linkId))\n return\n }\n replacement.links.set(key, {\n ref: structuredClone(ref),\n sortKey: linkRefSortKey(ref),\n diffRequired,\n })\n if (diffRequired) replacement.affectedScopes.add(linkScopeSortKey(ref.source, ref.linkId))\n}\n",
|
|
29
|
+
"import { stableJsonStringify } from \"../../../json\"\nimport { MaterializationConflictError } from \"../../../materialization/errors\"\nimport type {\n MaterializationPlanChunk,\n StoredLinkOverride,\n StoredLinkSlotOverride,\n StoredObjectOverride,\n} from \"../materializations\"\nimport { invalidCorrelation, materializationPlanItems } from \"../provider-work\"\nimport type { SessionState } from \"./materializations\"\n\nexport * from \"../provider-work\"\n\nexport function assertChunkSequence(session: SessionState, chunk: MaterializationPlanChunk): void {\n const planItems = materializationPlanItems(chunk)\n const applyStream = session.workStreams.apply\n const appliedStart = session.appliedPlanItems.length\n if (\n planItems.length > 0 &&\n (!applyStream.started || appliedStart + planItems.length > applyStream.emittedCount)\n ) {\n invalidCorrelation(\"Materialization plan items cannot be applied before they are streamed.\")\n }\n for (let offset = 0; offset < planItems.length; offset += 1) {\n const expected = session.applyWork[appliedStart + offset]?.item\n if (!expected || stableJsonStringify(planItems[offset]) !== stableJsonStringify(expected)) {\n invalidCorrelation(\"Materialization plan items must be applied in exact streamed order.\")\n }\n }\n\n const eventStream = session.workStreams.event\n const appliedOutboxCount = session.outboxEnvelopes.size\n if (\n chunk.outbox.length > 0 &&\n (!eventStream.started || appliedOutboxCount + chunk.outbox.length > eventStream.emittedCount)\n ) {\n invalidCorrelation(\"Materialization events cannot be applied before they are streamed.\")\n }\n for (let offset = 0; offset < chunk.outbox.length; offset += 1) {\n const expected = session.eventWork[appliedOutboxCount + offset]\n const actual = chunk.outbox[offset]?.envelope\n if (!expected || !actual) {\n invalidCorrelation(\"Materialization outbox events must follow exact streamed order.\")\n }\n const { id: _id, commitOrdinal, ...actualDraft } = actual\n if (\n commitOrdinal !== appliedOutboxCount + offset ||\n stableJsonStringify(actualDraft) !== stableJsonStringify(expected.draft)\n ) {\n invalidCorrelation(\"Materialization outbox events must follow exact streamed order.\")\n }\n }\n}\n\nexport function assertLastCommit(\n value: StoredObjectOverride | StoredLinkOverride | StoredLinkSlotOverride | undefined,\n expected: string | null,\n label: string\n): void {\n if ((value?.lastCommitId ?? null) !== expected) {\n throw new MaterializationConflictError(\"effective-state\", `Expected ${label} changed.`)\n }\n}\n",
|
|
30
|
+
"import { stableJsonStringify } from \"../../../json\"\nimport { assertPinnedDatasetWatermark } from \"../../../materialization/dataset-watermark\"\nimport { MaterializationConflictError } from \"../../../materialization/errors\"\nimport { createEventId } from \"../../../materialization/identity\"\nimport type {\n EffectiveChangeCounts,\n OntologyObjectRef,\n PinnedDatasetVersion,\n TelemetryCommitResult,\n} from \"../../../materialization/model\"\nimport { linkRefSortKey } from \"../../../materialization/refs\"\nimport {\n getInMemoryObjectMaterializerAdapter,\n type InMemoryObjectStorage,\n} from \"../../objects/in-memory\"\nimport type { MaterializationCardinalityOccupantWorkRecord } from \"../materializations\"\nimport type { SessionState } from \"./materializations\"\nimport { findActiveSourceMaterialization, linkRef } from \"./materializations-state\"\nimport { compareEventWork, invalidCorrelation } from \"./materializations-work\"\nimport { type InMemoryOntologyState, outboxKey, sourceMaterializationKey } from \"./shared-state\"\n\nexport function assertFinalizationCorrelations(\n session: SessionState,\n finalization: import(\"../materializations\").MaterializationPlanFinalization,\n state: InMemoryOntologyState,\n objects: InMemoryObjectStorage\n): void {\n const { commit } = session.header\n const { result, sourceActivations } = finalization\n if (\n result.commitId !== commit.id ||\n result.kind !== commit.intent.kind ||\n result.committedAt !== commit.committedAt ||\n result.created !== true ||\n !Number.isSafeInteger(result.eventCount) ||\n result.eventCount < 0 ||\n result.eventCount !== session.outboxEnvelopes.size\n ) {\n invalidCorrelation(\"Materialization result does not correlate with its commit intent.\")\n }\n for (let ordinal = 0; ordinal < result.eventCount; ordinal += 1) {\n if (!session.outboxEnvelopes.has(ordinal)) {\n invalidCorrelation(\"Outbox event ordinals must be contiguous from zero.\")\n }\n }\n\n if (commit.intent.kind === \"edit\") {\n if (result.kind !== \"edit\" || result.outcomes.length !== commit.intent.operationCount) {\n invalidCorrelation(\"Edit result does not correlate with its operation count.\")\n }\n if (sourceActivations.length !== 0) {\n invalidCorrelation(\"Edit materialization cannot activate a source materialization.\")\n }\n } else if (commit.intent.kind === \"projection\") {\n if (result.kind !== \"projection\" || sourceActivations.length !== 1) {\n invalidCorrelation(\"Projection result requires exactly one correlated source activation.\")\n }\n } else if (result.kind !== \"telemetry\" || sourceActivations.length !== 0) {\n invalidCorrelation(\"Telemetry result does not correlate with its point intent.\")\n }\n\n for (const activation of sourceActivations) {\n assertSourceActivationCorrelation(activation, session, state)\n }\n if (sourceActivations[0]) {\n assertReplacementFullyStreamed(session, sourceActivations[0])\n }\n assertFinalizedWork(session, state, objects)\n if (commit.intent.kind === \"projection\") {\n if (result.kind !== \"projection\" || !projectionCountsCorrelate(session, result.counts)) {\n invalidCorrelation(\"Projection result counts do not correlate with finalized work.\")\n }\n } else if (\n commit.intent.kind === \"telemetry\" &&\n (result.kind !== \"telemetry\" ||\n !telemetryCountsCorrelate(session, commit.intent.pointCount, result))\n ) {\n invalidCorrelation(\"Telemetry result counts do not correlate with finalized work.\")\n }\n}\n\nfunction projectionCountsCorrelate(session: SessionState, actual: EffectiveChangeCounts): boolean {\n const expected = deriveExpectedProjectionCounts(session)\n if (expected === null) return false\n\n return effectiveChangeCountsMatch(actual, expected)\n}\n\ninterface ClassifiedProjectionCounts {\n objects: number\n links: number\n}\n\ninterface AppliedProjectionChangeCounts {\n objectsCreated: number\n objectsUpdated: number\n objectsDeleted: number\n linksCreated: number\n linksUpdated: number\n linksDeleted: number\n}\n\nconst effectiveChangeCountKeys = [\n \"objectsCreated\",\n \"objectsUpdated\",\n \"objectsDeleted\",\n \"objectsUnchanged\",\n \"linksCreated\",\n \"linksUpdated\",\n \"linksDeleted\",\n \"linksUnchanged\",\n] as const satisfies readonly (keyof EffectiveChangeCounts)[]\n\nfunction deriveExpectedProjectionCounts(session: SessionState): EffectiveChangeCounts | null {\n const classified = countClassifiedProjectionEntities(session)\n const applied = countAppliedProjectionChanges(session)\n const objectsUnchanged = remainingClassifiedCount(\n classified.objects,\n applied.objectsCreated,\n applied.objectsUpdated,\n applied.objectsDeleted\n )\n const linksUnchanged = remainingClassifiedCount(\n classified.links,\n applied.linksCreated,\n applied.linksUpdated,\n applied.linksDeleted\n )\n\n if (objectsUnchanged < 0 || linksUnchanged < 0) return null\n\n return { ...applied, objectsUnchanged, linksUnchanged }\n}\n\nfunction countClassifiedProjectionEntities(session: SessionState): ClassifiedProjectionCounts {\n const counts = { objects: 0, links: 0 }\n\n for (const record of session.work.values()) {\n if (record.kind !== \"classification\") continue\n\n if (record.entityKind === \"object\") counts.objects += 1\n if (record.entityKind === \"link\") counts.links += 1\n }\n\n return counts\n}\n\nfunction countAppliedProjectionChanges(session: SessionState): AppliedProjectionChangeCounts {\n const counts: AppliedProjectionChangeCounts = {\n objectsCreated: 0,\n objectsUpdated: 0,\n objectsDeleted: 0,\n linksCreated: 0,\n linksUpdated: 0,\n linksDeleted: 0,\n }\n\n for (const work of session.applyWork) {\n const { item } = work\n\n switch (item.kind) {\n case \"object-upsert\":\n if (item.value.expected.exists) counts.objectsUpdated += 1\n else counts.objectsCreated += 1\n break\n case \"object-delete\":\n counts.objectsDeleted += 1\n break\n case \"link-upsert\":\n if (item.value.expected.exists) counts.linksUpdated += 1\n else counts.linksCreated += 1\n break\n case \"link-delete\":\n counts.linksDeleted += 1\n break\n }\n }\n\n return counts\n}\n\nfunction remainingClassifiedCount(\n classified: number,\n created: number,\n updated: number,\n deleted: number\n): number {\n return classified - created - updated - deleted\n}\n\nfunction effectiveChangeCountsMatch(\n actual: EffectiveChangeCounts,\n expected: EffectiveChangeCounts\n): boolean {\n return effectiveChangeCountKeys.every((key) => {\n const count = actual[key]\n return Number.isSafeInteger(count) && count >= 0 && count === expected[key]\n })\n}\n\nfunction telemetryCountsCorrelate(\n session: SessionState,\n pointCount: number,\n actual: TelemetryCommitResult\n): boolean {\n let pointsCreated = 0\n let pointsUpdated = 0\n let latestObjectsChanged = 0\n for (const work of session.applyWork) {\n if (work.item.kind === \"point-upsert\") {\n if (work.item.value.expected.lastCommitId === null) pointsCreated += 1\n else pointsUpdated += 1\n } else if (work.item.kind === \"object-upsert\") {\n latestObjectsChanged += 1\n }\n }\n const expected = {\n pointsCreated,\n pointsUpdated,\n pointsUnchanged: pointCount - pointsCreated - pointsUpdated,\n latestObjectsChanged,\n }\n return (\n expected.pointsUnchanged >= 0 &&\n (Object.keys(expected) as (keyof typeof expected)[]).every(\n (key) =>\n Number.isSafeInteger(actual[key]) && actual[key] >= 0 && actual[key] === expected[key]\n )\n )\n}\n\nfunction assertSourceActivationCorrelation(\n activation: import(\"../materializations\").SourceActivationWrite,\n session: SessionState,\n state: InMemoryOntologyState\n): void {\n const { header } = session\n const { commit } = header\n if (\n commit.intent.kind !== \"projection\" ||\n commit.origin.kind !== \"projection\" ||\n activation.source.projectionId !== commit.intent.source.projectionId ||\n activation.source.projectionId !== commit.origin.projectionId ||\n activation.execution.projectionRunId !== commit.origin.projectionRunId ||\n activation.protocol !== \"replacement\" ||\n stableJsonStringify(activation.datasetVersion) !==\n stableJsonStringify(commit.intent.datasetVersion) ||\n activation.projectionRevision !== commit.projectionRevision ||\n activation.ownershipHash !== commit.ownershipHash ||\n activation.ontologyRevision !== commit.ontologyRevision ||\n activation.lastCommitId !== commit.id ||\n activation.updatedAt !== commit.committedAt ||\n !header.expected.sources.some(\n (expected) => stableJsonStringify(expected) === stableJsonStringify(activation.expected)\n )\n ) {\n invalidCorrelation(\"Source activation does not correlate with its projection commit.\")\n }\n const candidate = state.sourceMaterializations.get(\n sourceMaterializationKey(\n commit.projectId,\n activation.source.projectionId,\n activation.materializationId\n )\n )\n if (!candidate || candidate.status !== \"ready\") {\n throw new MaterializationConflictError(\n \"source-materialization\",\n \"Source activation candidate is missing or is not ready.\"\n )\n }\n if (\n candidate.projectionRunId !== activation.execution.projectionRunId ||\n candidate.executionToken !== activation.execution.executionToken ||\n candidate.projectionKind !== activation.projectionKind ||\n candidate.protocol !== activation.protocol ||\n stableJsonStringify(candidate.datasetVersion) !==\n stableJsonStringify(activation.datasetVersion) ||\n candidate.projectionRevision !== activation.projectionRevision ||\n candidate.ownershipHash !== activation.ownershipHash ||\n candidate.ontologyRevision !== activation.ontologyRevision\n ) {\n invalidCorrelation(\"Source activation does not match its ready candidate identity.\")\n }\n if (candidate.readyAt === null) {\n invalidCorrelation(\"Source activation candidate has no ready timestamp.\")\n }\n assertTimestampNotBefore(\n activation.updatedAt,\n candidate.readyAt,\n \"Source activation cannot precede candidate readiness.\"\n )\n const previous = findActiveSourceMaterialization(\n state,\n commit.projectId,\n activation.source.projectionId\n )\n if (previous) {\n assertSourceDatasetWatermark(previous.datasetVersion, activation.datasetVersion)\n assertTimestampNotBefore(\n activation.updatedAt,\n previous.updatedAt,\n \"Source activation cannot precede the active materialization update.\"\n )\n }\n}\n\nfunction assertSourceDatasetWatermark(\n active: PinnedDatasetVersion,\n next: PinnedDatasetVersion\n): void {\n assertPinnedDatasetWatermark(active, next, \"Source activation\")\n}\n\nfunction assertFinalizedWork(\n session: SessionState,\n state: InMemoryOntologyState,\n objects: InMemoryObjectStorage\n): void {\n const expectedPlanItems = session.applyWork.map((record) => stableJsonStringify(record.item))\n const appliedPlanItems = session.appliedPlanItems\n if (expectedPlanItems.length > 0 && !session.workStreams.apply.completed) {\n invalidCorrelation(\"Materialization plan work was not fully streamed.\")\n }\n if (stableJsonStringify(appliedPlanItems) !== stableJsonStringify(expectedPlanItems)) {\n invalidCorrelation(\"Materialization plan work was not applied exactly once.\")\n }\n if (session.cardinalityWork.length > 0 && !session.workStreams.cardinality.completed) {\n invalidCorrelation(\"Materialization cardinality work was not fully validated.\")\n }\n assertFinalCardinality(session.cardinalityWork, session.header.commit.projectId, objects)\n if (session.header.commit.intent.kind === \"telemetry\") {\n const pointKeys = classificationKeys(session, \"point\")\n if (pointKeys.length !== session.header.commit.intent.pointCount) {\n invalidCorrelation(\n \"Telemetry point classification coverage does not match the commit intent.\"\n )\n }\n }\n\n const expectedEvents = [...session.eventWork].sort(compareEventWork)\n if (expectedEvents.length > 0 && !session.workStreams.event.completed) {\n invalidCorrelation(\"Materialization event work was not fully drained.\")\n }\n if (session.outboxEnvelopes.size !== expectedEvents.length) {\n invalidCorrelation(\"Materialization event work was not fully written to the outbox.\")\n }\n for (let ordinal = 0; ordinal < expectedEvents.length; ordinal += 1) {\n const expected = expectedEvents[ordinal]\n const actual = session.outboxEnvelopes.get(ordinal)\n if (!expected || !actual) {\n invalidCorrelation(\"Materialization event work was not fully written to the outbox.\")\n }\n const { id, commitOrdinal, ...actualDraft } = actual\n if (\n commitOrdinal !== ordinal ||\n id !== createEventId(session.header.commit.projectId, session.header.commit.id, ordinal) ||\n stableJsonStringify(actualDraft) !== stableJsonStringify(expected.draft)\n ) {\n invalidCorrelation(\"Materialization outbox event does not match its staged event work.\")\n }\n const persisted = state.outbox.get(outboxKey(session.header.commit.projectId, actual.id))\n if (!persisted || stableJsonStringify(persisted.envelope) !== stableJsonStringify(actual)) {\n invalidCorrelation(\"Materialization outbox event was not persisted.\")\n }\n }\n}\n\nfunction assertFinalCardinality(\n records: readonly MaterializationCardinalityOccupantWorkRecord[],\n projectId: string,\n objects: InMemoryObjectStorage\n): void {\n const effectiveOccupants = records.filter((record) => record.view === \"effective\")\n const scopes = new Map<\n string,\n {\n readonly source: OntologyObjectRef\n readonly linkId: string\n readonly occupiedLinkKeys: Set<string>\n }\n >()\n let currentScope: string | null = null\n let occupiedCount = 0\n for (const record of effectiveOccupants) {\n if (record.scopeSortKey !== currentScope) {\n currentScope = record.scopeSortKey\n occupiedCount = 0\n }\n const scope = scopes.get(record.scopeSortKey) ?? {\n source: structuredClone(record.ref.source),\n linkId: record.ref.linkId,\n occupiedLinkKeys: new Set<string>(),\n }\n scopes.set(record.scopeSortKey, scope)\n if (record.occupied) {\n occupiedCount += 1\n scope.occupiedLinkKeys.add(record.linkSortKey)\n if (occupiedCount > 1) {\n invalidCorrelation(\"Materialization cardinality work violates cardinality-one.\")\n }\n }\n }\n\n const adapter = getInMemoryObjectMaterializerAdapter(objects)\n for (const scope of scopes.values()) {\n const effectiveLinkKeys: string[] = []\n adapter.visitExactScopeLinks(\n projectId,\n scope.source.objectTypeId,\n scope.source.primaryId,\n scope.linkId,\n (row) => effectiveLinkKeys.push(linkRefSortKey(linkRef(row)))\n )\n effectiveLinkKeys.sort()\n const occupiedLinkKeys = [...scope.occupiedLinkKeys].sort()\n if (stableJsonStringify(effectiveLinkKeys) !== stableJsonStringify(occupiedLinkKeys)) {\n invalidCorrelation(\n \"Materialization cardinality work does not match the final effective link scope.\"\n )\n }\n }\n}\n\nfunction assertReplacementFullyStreamed(\n session: SessionState,\n activation: import(\"../materializations\").SourceActivationWrite\n): void {\n const replacement = session.replacement\n if (\n !replacement ||\n replacement.sourceId !== activation.source.projectionId ||\n replacement.candidateMaterializationId !== activation.materializationId ||\n replacement.candidate.materializationId !== activation.materializationId ||\n replacement.candidate.projectionKind !== activation.projectionKind ||\n replacement.candidate.protocol !== activation.protocol\n ) {\n invalidCorrelation(\n \"Source activation does not match the replacement candidate opened by the session.\"\n )\n }\n if (\n activation.projectionKind === \"object\" &&\n (!replacement.objectStreamCompleted || !replacement.linkStreamCompleted)\n ) {\n invalidCorrelation(\"Object projection replacement state was not fully streamed.\")\n }\n if (activation.projectionKind === \"link\" && !replacement.linkStreamCompleted) {\n invalidCorrelation(\"Link projection replacement state was not fully streamed.\")\n }\n const expectedObjectKeys =\n activation.projectionKind === \"object\" ? [...replacement.objects.keys()].sort() : []\n const expectedLinkKeys = [...replacement.links.entries()]\n .filter(([, value]) => value.diffRequired)\n .map(([key]) => key)\n .sort()\n if (\n stableJsonStringify(classificationKeys(session, \"object\")) !==\n stableJsonStringify(expectedObjectKeys) ||\n stableJsonStringify(classificationKeys(session, \"link\")) !==\n stableJsonStringify(expectedLinkKeys) ||\n classificationKeys(session, \"point\").length > 0\n ) {\n invalidCorrelation(\n \"Projection replacement classification coverage does not match its streamed state.\"\n )\n }\n}\n\nfunction classificationKeys(\n session: SessionState,\n entityKind: import(\"../materializations\").MaterializationWorkEntityKind\n): string[] {\n return [...session.work.values()]\n .filter(\n (record): record is import(\"../materializations\").MaterializationClassificationWorkRecord =>\n record.kind === \"classification\" && record.entityKind === entityKind\n )\n .map((record) => record.identityKey)\n .sort()\n}\n\nfunction assertTimestampNotBefore(value: string, minimum: string, message: string): void {\n if (Date.parse(value) < Date.parse(minimum)) invalidCorrelation(message)\n}\n",
|
|
31
|
+
"import { MaterializationConflictError } from \"../../../materialization/errors\"\nimport { linkScopeSortKey, projectionEntityKey } from \"../../../materialization/refs\"\nimport type { SourceActivationWrite } from \"../materializations\"\nimport type { StoredSourceAssertion, StoredSourceLinkAssertion } from \"../sources\"\nimport { storedSource } from \"./materializations-state\"\nimport {\n type InMemoryOntologyState,\n type InMemorySourceMaterialization,\n projectEntityKey,\n sourceMaterializationKey,\n} from \"./shared-state\"\n\nexport function* previousSourceRows(\n state: InMemoryOntologyState,\n candidate: InMemorySourceMaterialization\n): Iterable<StoredSourceAssertion> {\n const sourceKey = projectEntityKey(candidate.projectId, candidate.source.projectionId)\n const active = state.activeSourceRoots.get(sourceKey)\n if (!active) return\n for (const rootKey of candidate.base ? candidate.roots.keys() : active.keys()) {\n const materializationId = active.get(rootKey)\n if (!materializationId) continue\n const materialization = state.sourceMaterializations.get(\n sourceMaterializationKey(\n candidate.projectId,\n candidate.source.projectionId,\n materializationId\n )\n )!\n for (const entityKey of materialization.roots.get(rootKey)!.entityKeys) {\n yield storedSource(\n candidate.source.projectionId,\n materializationId,\n materialization.rowsByEntity.get(entityKey)!\n )\n }\n }\n}\n\nexport function activateSourceRoots(\n state: InMemoryOntologyState,\n candidate: InMemorySourceMaterialization,\n activation: SourceActivationWrite\n): void {\n if (\n candidate.base &&\n (candidate.base.materializationId !== activation.expected.activeMaterializationId ||\n candidate.base.lastCommitId !== activation.expected.lastCommitId)\n ) {\n throw new MaterializationConflictError(\n \"projection-fence\",\n \"Source delta base changed before activation.\"\n )\n }\n const sourceKey = projectEntityKey(candidate.projectId, candidate.source.projectionId)\n const active = state.activeSourceRoots.get(sourceKey) ?? new Map<string, string>()\n for (const key of candidate.base ? candidate.roots.keys() : [...active.keys()]) {\n const materializationId = active.get(key)\n if (!materializationId) continue\n const old = state.sourceMaterializations.get(\n sourceMaterializationKey(\n candidate.projectId,\n candidate.source.projectionId,\n materializationId\n )\n )!\n const root = old.roots.get(key)!\n root.active = false\n root.retiredAt = activation.updatedAt\n active.delete(key)\n for (const entityKey of root.entityKeys) {\n const row = old.rowsByEntity.get(entityKey)!\n const indexKey = projectEntityKey(candidate.projectId, entityKey)\n const sources = state.activeSourceRows.get(indexKey)!\n sources.delete(candidate.source.projectionId)\n if (sources.size === 0) state.activeSourceRows.delete(indexKey)\n if (row.assertion.kind === \"link\") {\n const scopeKey = projectEntityKey(\n candidate.projectId,\n linkScopeSortKey(row.assertion.ref.source, row.assertion.ref.linkId)\n )\n const scope = state.activeSourceLinkScopes.get(scopeKey)!\n scope.delete(JSON.stringify([candidate.source.projectionId, entityKey]))\n if (scope.size === 0) state.activeSourceLinkScopes.delete(scopeKey)\n }\n }\n }\n for (const [rootKey, root] of candidate.roots) {\n root.active = !root.deleted\n root.retiredAt = root.deleted ? activation.updatedAt : null\n if (root.deleted) continue\n active.set(rootKey, candidate.materializationId)\n for (const entityKey of root.entityKeys) {\n // These are internal immutable assertions. Share their payload between indexes;\n // read methods clone returned values and transaction snapshots preserve aliases.\n const row = {\n source: candidate.source,\n materializationId: candidate.materializationId,\n ...candidate.rowsByEntity.get(entityKey)!,\n } as StoredSourceAssertion\n const indexKey = projectEntityKey(candidate.projectId, projectionEntityKey(row.assertion))\n const sources =\n state.activeSourceRows.get(indexKey) ?? new Map<string, StoredSourceAssertion>()\n sources.set(candidate.source.projectionId, row)\n state.activeSourceRows.set(indexKey, sources)\n if (row.assertion.kind === \"link\") {\n const scopeKey = projectEntityKey(\n candidate.projectId,\n linkScopeSortKey(row.assertion.ref.source, row.assertion.ref.linkId)\n )\n const scope =\n state.activeSourceLinkScopes.get(scopeKey) ?? new Map<string, StoredSourceLinkAssertion>()\n scope.set(\n JSON.stringify([candidate.source.projectionId, entityKey]),\n row as StoredSourceLinkAssertion\n )\n state.activeSourceLinkScopes.set(scopeKey, scope)\n }\n }\n }\n state.activeSourceRoots.set(sourceKey, active)\n state.activeSourceHeads.set(sourceKey, candidate.materializationId)\n}\n",
|
|
32
|
+
"import { stableJsonStringify } from \"../../../json\"\nimport {\n MaterializationConflictError,\n MaterializationValidationError,\n} from \"../../../materialization/errors\"\nimport type {\n ExpectedLinkRevision,\n ExpectedObjectRevision,\n OntologyLinkRef,\n OntologyObjectRef,\n} from \"../../../materialization/model\"\nimport {\n linkRefKey,\n linkRefSortKey,\n linkScopeKey,\n linkScopeSortKey,\n objectRefKey,\n objectRefSortKey,\n projectionEntityKey,\n telemetryPointKey,\n telemetryPointSortKey,\n} from \"../../../materialization/refs\"\nimport {\n getInMemoryObjectMaterializerAdapter,\n type InMemoryObjectStorage,\n} from \"../../objects/in-memory\"\nimport type { ObjectLinkRow } from \"../../objects/types\"\nimport {\n getInMemoryTimeseriesMaterializerAdapter,\n type InMemoryTimeseriesStorage,\n} from \"../../timeseries/store\"\nimport type { OntologyCommitRecord } from \"../commits\"\nimport type {\n ApplyMaterializationChunkInput,\n ApplyMaterializationResult,\n ExpectedSourceRevision,\n ExpectedTimeseriesPointRevision,\n FinalizeMaterializationInput,\n MaterializationCardinalityOccupantWorkRecord,\n MaterializationEventWorkRecord,\n MaterializationLinkScopeRevision,\n MaterializationLinkScopeState,\n MaterializationLinkState,\n MaterializationObjectExistence,\n MaterializationObjectExistenceWorkRecord,\n MaterializationObjectState,\n MaterializationPlanHeader,\n MaterializationPlanWorkRecord,\n MaterializationSession,\n MaterializationStatePage,\n MaterializationWorkPage,\n MaterializationWorkRecord,\n OntologyMaterializationStorage,\n ReadMaterializationObjectExistenceInput,\n SourceReplacementLinkState,\n SourceReplacementObjectState,\n SourceReplacementStatePage,\n StageMaterializationWorkInput,\n StoredTelemetryPoint,\n StreamMaterializationStateInput,\n StreamMaterializationWorkInput,\n StreamSourceReplacementStateInput,\n} from \"../materializations\"\nimport type { OntologyMaterializationEvent } from \"../outbox\"\nimport {\n appendScopeSnapshot,\n assertMaterializationHeader,\n finishScopeAccumulator,\n type ProviderMaterializationTransactionLifecycle,\n startScopeAccumulator,\n uniqueSorted,\n} from \"../provider\"\nimport type {\n StoredSourceAssertion,\n StoredSourceLinkAssertion,\n StoredSourceObjectAssertion,\n} from \"../sources\"\nimport { assertFinalizationCorrelations } from \"./materializations-finalization\"\nimport {\n addReplacementLink,\n findActiveSourceMaterialization,\n linkRef,\n linkSnapshot,\n objectSnapshot,\n publicLinkOverride,\n publicLinkSlotOverride,\n publicObjectOverride,\n storedPoint,\n storedSourceLink,\n storedSourceObject,\n uniqueBy,\n} from \"./materializations-state\"\nimport {\n assertChunkSequence,\n assertLastCommit,\n assertPageRows,\n assertPlanChunkCorrelations,\n assertWorkRecord,\n compareCardinalityWork,\n compareEventWork,\n comparePlanWork,\n materializationChunkRows,\n materializationPlanItems,\n workUniquenessKey,\n} from \"./materializations-work\"\nimport {\n assertTimestamp,\n commitKey,\n commitOriginKey,\n type InMemoryOntologyState,\n type InMemoryOntologyStorageTestHooks,\n type InMemorySourceMaterialization,\n idempotencyKey,\n ontologyCommitOriginSelector,\n outboxKey,\n projectEntityKey,\n sourceMaterializationKey,\n} from \"./shared-state\"\nimport { activateSourceRoots, previousSourceRows } from \"./source-roots\"\n\nexport interface SessionState {\n readonly providerToken: object\n readonly header: MaterializationPlanHeader\n readonly transactionToken: object\n readonly lifecycle: ProviderMaterializationTransactionLifecycle\n active: boolean\n writeOrdinal: number\n readonly work: Map<string, MaterializationWorkRecord>\n readonly workUniqueKeys: Set<string>\n readonly applyWork: MaterializationPlanWorkRecord[]\n readonly cardinalityWork: MaterializationCardinalityOccupantWorkRecord[]\n readonly eventWork: MaterializationEventWorkRecord[]\n readonly appliedPlanItems: string[]\n readonly outboxEnvelopes: Map<number, OntologyMaterializationEvent>\n readonly workStreams: Record<StreamMaterializationWorkInput[\"order\"], WorkStreamState>\n workSealed: boolean\n incidentLinksByObject: Map<string, readonly OntologyLinkRef[]> | null\n linkSlotStates: Map<string, MaterializationLinkScopeState> | null\n readonly objectExistence: Map<string, MaterializationObjectExistenceWorkRecord>\n replacement: ReplacementSessionState | null\n}\n\nexport interface WorkStreamState {\n started: boolean\n completed: boolean\n emittedCount: number\n}\n\nexport interface ReplacementObjectWork {\n readonly ref: OntologyObjectRef\n readonly sortKey: string\n}\n\nexport interface ReplacementLinkWork {\n readonly ref: OntologyLinkRef\n readonly sortKey: string\n diffRequired: boolean\n}\n\nexport interface ReplacementSessionState {\n readonly sourceId: string\n readonly candidateMaterializationId: string\n readonly owned: Set<string>\n readonly candidate: InMemorySourceMaterialization\n readonly objects: Map<string, ReplacementObjectWork>\n readonly links: Map<string, ReplacementLinkWork>\n orderedObjects: ReplacementObjectWork[]\n orderedLinks: ReplacementLinkWork[] | null\n readonly affectedScopes: Set<string>\n readonly incidentObjects: Map<string, OntologyObjectRef>\n objectStreamStarted: boolean\n objectStreamCompleted: boolean\n linkStreamStarted: boolean\n linkStreamCompleted: boolean\n linksExpanded: boolean\n}\n\nexport class InMemoryOntologyMaterializationStorage implements OntologyMaterializationStorage {\n private readonly sessions = new WeakMap<object, SessionState>()\n private readonly liveSessions = new Set<SessionState>()\n\n constructor(\n private readonly state: InMemoryOntologyState,\n private readonly objects: InMemoryObjectStorage,\n private readonly timeseries: InMemoryTimeseriesStorage,\n private readonly getTransactionToken: () => object | null,\n private readonly getMaterializationLifecycle: () => ProviderMaterializationTransactionLifecycle | null,\n private readonly executionExists: (projectId: string, executionId: string) => Promise<boolean>,\n private readonly hooks: InMemoryOntologyStorageTestHooks = {}\n ) {}\n\n async begin(input: MaterializationPlanHeader): Promise<MaterializationSession> {\n const transactionToken = this.getTransactionToken()\n const lifecycle = this.getMaterializationLifecycle()\n if (!transactionToken || !lifecycle) {\n throw new MaterializationValidationError(\n \"Materialization sessions require an active storage transaction.\"\n )\n }\n assertMaterializationHeader(input)\n if (!(await this.executionExists(input.commit.projectId, input.commit.executionId))) {\n throw new MaterializationValidationError(\n `Ontology commit execution '${input.commit.executionId}' does not exist in project '${input.commit.projectId}'.`\n )\n }\n this.assertCommitAbsent(input)\n for (const expected of input.expected.sources)\n this.assertSource(expected, input.commit.projectId)\n for (const expected of input.expected.objects)\n await this.assertObject(expected, input.commit.projectId)\n for (const expected of input.expected.links)\n await this.assertLink(expected, input.commit.projectId)\n const expectedScopeRevisions = new Map<string, MaterializationLinkScopeRevision>()\n for (const expected of input.expected.linkScopes) {\n const key = linkScopeSortKey(expected.source, expected.linkId)\n const current =\n expectedScopeRevisions.get(key) ??\n this.computeEffectiveLinkScope(input.commit.projectId, expected.source, expected.linkId)\n expectedScopeRevisions.set(key, current)\n if (current.fingerprint !== expected.fingerprint) {\n throw new MaterializationConflictError(\n \"effective-state\",\n `Expected link scope changed for ${expected.source.objectTypeId}:${expected.source.primaryId}.${expected.linkId}.`\n )\n }\n }\n for (const expected of input.expected.points) this.assertPoint(expected, input.commit.projectId)\n\n const providerToken = {}\n const session = {\n providerToken,\n header: structuredClone(input),\n transactionToken,\n lifecycle,\n active: true,\n writeOrdinal: 0,\n work: new Map<string, MaterializationWorkRecord>(),\n workUniqueKeys: new Set<string>(),\n applyWork: [],\n cardinalityWork: [],\n eventWork: [],\n appliedPlanItems: [],\n outboxEnvelopes: new Map<number, OntologyMaterializationEvent>(),\n workStreams: {\n apply: { started: false, completed: false, emittedCount: 0 },\n cardinality: { started: false, completed: false, emittedCount: 0 },\n event: { started: false, completed: false, emittedCount: 0 },\n },\n workSealed: false,\n incidentLinksByObject: null,\n linkSlotStates: new Map(),\n objectExistence: new Map<string, MaterializationObjectExistenceWorkRecord>(),\n replacement: null,\n }\n this.sessions.set(providerToken, session)\n this.liveSessions.add(session)\n lifecycle.register(providerToken)\n return { providerToken }\n }\n\n deactivateTransaction(transactionToken: object): void {\n for (const session of this.liveSessions) {\n if (session.transactionToken !== transactionToken) continue\n this.releaseSession(session)\n }\n }\n\n /** Deactivate a session, drop its transaction-local work, and stop tracking it as live. */\n private releaseSession(session: SessionState): void {\n session.active = false\n session.work.clear()\n session.workUniqueKeys.clear()\n session.applyWork.length = 0\n session.cardinalityWork.length = 0\n session.eventWork.length = 0\n session.appliedPlanItems.length = 0\n session.outboxEnvelopes.clear()\n session.incidentLinksByObject = null\n session.linkSlotStates = null\n session.objectExistence.clear()\n session.replacement = null\n this.liveSessions.delete(session)\n session.lifecycle.complete(session.providerToken)\n }\n\n async *streamState(\n input: StreamMaterializationStateInput\n ): AsyncIterable<MaterializationStatePage> {\n const session = this.requireSession(input.session)\n assertPageRows(input.pageRows)\n for await (const request of input.requests) {\n this.requireSession(input.session)\n this.hooks.beforeRead?.(\"state.read\")\n const objectRefs = uniqueSorted(request.objects, objectRefKey, objectRefSortKey)\n for (let offset = 0; offset < objectRefs.length; offset += input.pageRows) {\n this.requireSession(input.session)\n const objects: MaterializationObjectState[] = []\n for (const ref of objectRefs.slice(offset, offset + input.pageRows)) {\n objects.push(await this.objectState(session, ref))\n }\n this.requireSession(input.session)\n this.hooks.observeBuffer?.(\"state.object.page\", objects.length)\n yield { objects, links: [], linkScopes: [], points: [] }\n }\n\n const linkRefs = uniqueSorted(request.links, linkRefKey, linkRefSortKey)\n for (let offset = 0; offset < linkRefs.length; offset += input.pageRows) {\n this.requireSession(input.session)\n const links: MaterializationLinkState[] = []\n for (const ref of linkRefs.slice(offset, offset + input.pageRows)) {\n links.push(await this.linkState(session, ref))\n }\n this.requireSession(input.session)\n this.hooks.observeBuffer?.(\"state.link.page\", links.length)\n yield { objects: [], links, linkScopes: [], points: [] }\n }\n\n const incidentRefs = this.incidentLinkRefs(session, request.incidentObjects)\n for (let offset = 0; offset < incidentRefs.length; offset += input.pageRows) {\n this.requireSession(input.session)\n const refs = incidentRefs.slice(offset, offset + input.pageRows)\n const links: MaterializationLinkState[] = []\n for (const ref of refs) links.push(await this.linkState(session, ref))\n this.requireSession(input.session)\n this.hooks.observeBuffer?.(\"state.incident-link.page\", links.length)\n yield { objects: [], links, linkScopes: [], points: [] }\n }\n\n for (const scope of uniqueBy(request.linkScopes, (value) =>\n linkScopeSortKey(value.source, value.linkId)\n )) {\n this.requireSession(input.session)\n const value = this.linkSlotState(session, scope.source, scope.linkId)\n // Scope rows are currently only requested for cardinality-one links, so the complete member\n // set is bounded by the ontology invariant. Replacement scope enumeration is flattened in\n // its dedicated stream and never uses this shape.\n yield { objects: [], links: [], linkScopes: [value], points: [] }\n }\n\n const requestedPoints = uniqueSorted(\n request.points,\n (point) => telemetryPointKey(point.series, point.at),\n (point) => telemetryPointSortKey(point.series, point.at)\n )\n for (let offset = 0; offset < requestedPoints.length; offset += input.pageRows) {\n this.requireSession(input.session)\n const points: StoredTelemetryPoint[] = []\n for (const point of requestedPoints.slice(offset, offset + input.pageRows)) {\n const stored = getInMemoryTimeseriesMaterializerAdapter(this.timeseries).getExactPoint(\n session.header.commit.projectId,\n point.series,\n point.at\n )\n if (stored) points.push(storedPoint(stored))\n }\n this.requireSession(input.session)\n this.hooks.observeBuffer?.(\"state.point.page\", points.length)\n if (points.length > 0) yield { objects: [], links: [], linkScopes: [], points }\n }\n }\n }\n\n async *streamSourceReplacementState(\n input: StreamSourceReplacementStateInput\n ): AsyncIterable<SourceReplacementStatePage> {\n const session = this.requireSession(input.session)\n assertPageRows(input.pageRows)\n const replacement = this.requireReplacement(session, input)\n if (input.entityKind === \"object\") {\n if (replacement.candidate.projectionKind !== \"object\") {\n throw new MaterializationConflictError(\n \"source-materialization\",\n \"Link projection replacement cannot stream object state.\"\n )\n }\n if (replacement.objectStreamStarted)\n throw new MaterializationConflictError(\n \"effective-state\",\n \"Replacement object state may only be streamed once per session.\"\n )\n replacement.objectStreamStarted = true\n this.hooks.beforeRead?.(\"source-replacement.object\")\n for (let offset = 0; offset < replacement.orderedObjects.length; offset += input.pageRows) {\n this.requireSession(input.session)\n const selected = replacement.orderedObjects.slice(offset, offset + input.pageRows)\n const objects: SourceReplacementObjectState[] = []\n for (const entry of selected) {\n const key = projectionEntityKey({ kind: \"object\", ref: entry.ref })\n const base = await this.objectState(session, entry.ref)\n objects.push({\n ref: base.ref,\n candidateSource: storedSourceObject(\n input.source.projectionId,\n replacement.candidate.materializationId,\n replacement.candidate.rowsByEntity.get(key)\n ),\n override: base.override,\n effective: base.effective,\n latestTelemetry: base.latestTelemetry,\n })\n }\n this.requireSession(input.session)\n this.hooks.observeBuffer?.(\"replacement.object.page\", objects.length)\n yield { objects, links: [] }\n }\n this.requireSession(input.session)\n replacement.objectStreamCompleted = true\n return\n }\n\n if (replacement.candidate.projectionKind === \"object\" && !replacement.objectStreamCompleted) {\n throw new MaterializationConflictError(\n \"effective-state\",\n \"Object projection replacement must fully stream object state before link state.\"\n )\n }\n if (replacement.linkStreamStarted)\n throw new MaterializationConflictError(\n \"effective-state\",\n \"Replacement link state may only be streamed once per session.\"\n )\n replacement.linkStreamStarted = true\n this.hooks.beforeRead?.(\"source-replacement.link\")\n this.expandReplacementLinks(session, replacement)\n replacement.orderedLinks ??= [...replacement.links.values()].sort((left, right) =>\n left.sortKey.localeCompare(right.sortKey)\n )\n for (let offset = 0; offset < replacement.orderedLinks.length; offset += input.pageRows) {\n this.requireSession(input.session)\n const selected = replacement.orderedLinks.slice(offset, offset + input.pageRows)\n const links: SourceReplacementLinkState[] = []\n for (const entry of selected) {\n const key = projectionEntityKey({ kind: \"link\", ref: entry.ref })\n const base = await this.linkState(session, entry.ref)\n const ownedByReplacement = replacement.owned.has(key)\n links.push({\n ref: base.ref,\n candidateSource: ownedByReplacement\n ? storedSourceLink(\n input.source.projectionId,\n replacement.candidate.materializationId,\n replacement.candidate.rowsByEntity.get(key)\n )\n : base.source,\n override: base.override,\n slotOverride: base.slotOverride,\n effective: base.effective,\n diffRequired: entry.diffRequired,\n })\n }\n this.requireSession(input.session)\n this.hooks.observeBuffer?.(\"replacement.link.page\", links.length)\n yield { objects: [], links }\n }\n this.requireSession(input.session)\n replacement.linkStreamCompleted = true\n }\n\n async stageWork(input: StageMaterializationWorkInput): Promise<void> {\n const session = this.requireSession(input.session)\n if (session.workSealed) {\n throw new MaterializationConflictError(\n \"effective-state\",\n \"Materialization work cannot be staged after draining begins.\"\n )\n }\n const batchKeys = new Set<string>()\n const batchUniqueKeys = new Set<string>()\n for (const record of input.records) {\n assertWorkRecord(record, session.header)\n const uniqueKey = workUniquenessKey(record)\n if (\n batchKeys.has(record.recordKey) ||\n session.work.has(record.recordKey) ||\n batchUniqueKeys.has(uniqueKey) ||\n session.workUniqueKeys.has(uniqueKey)\n ) {\n throw new MaterializationConflictError(\n \"effective-state\",\n `Duplicate materialization work key '${record.recordKey}'.`\n )\n }\n if (\n record.kind === \"incident-object\" &&\n (!session.replacement || session.replacement.linkStreamStarted)\n ) {\n throw new MaterializationConflictError(\n \"effective-state\",\n \"Incident replacement work must be staged before link state is streamed.\"\n )\n }\n batchKeys.add(record.recordKey)\n batchUniqueKeys.add(uniqueKey)\n }\n const cloned = input.records.map((record) => structuredClone(record))\n this.hooks.observeWork?.(cloned)\n for (const record of cloned) {\n session.work.set(record.recordKey, record)\n session.workUniqueKeys.add(workUniquenessKey(record))\n if (record.kind === \"plan\") session.applyWork.push(record)\n if (record.kind === \"cardinality\") session.cardinalityWork.push(record)\n if (record.kind === \"event\") session.eventWork.push(record)\n if (record.kind === \"object-existence\") {\n session.objectExistence.set(objectRefKey(record.ref), record)\n }\n if (record.kind === \"incident-object\") {\n const replacement = session.replacement\n if (replacement) {\n replacement.incidentObjects.set(objectRefKey(record.ref), record.ref)\n replacement.linksExpanded = false\n replacement.orderedLinks = null\n }\n }\n }\n this.hooks.observeBuffer?.(\"work.stage\", cloned.length)\n }\n\n async *streamWork(input: StreamMaterializationWorkInput): AsyncIterable<MaterializationWorkPage> {\n const session = this.requireSession(input.session)\n assertPageRows(input.pageRows)\n const stream = session.workStreams[input.order]\n if (stream.started) {\n throw new MaterializationConflictError(\n \"effective-state\",\n `Materialization ${input.order} work may only be streamed once per session.`\n )\n }\n stream.started = true\n if (!session.workSealed) {\n session.applyWork.sort(comparePlanWork)\n session.cardinalityWork.sort(compareCardinalityWork)\n session.eventWork.sort(compareEventWork)\n session.workSealed = true\n }\n const records =\n input.order === \"apply\"\n ? session.applyWork\n : input.order === \"cardinality\"\n ? session.cardinalityWork\n : session.eventWork\n for (let offset = 0; offset < records.length; offset += input.pageRows) {\n this.requireSession(input.session)\n const selected = records.slice(offset, offset + input.pageRows)\n this.hooks.observeBuffer?.(`work.${input.order}.page`, selected.length)\n stream.emittedCount = offset + selected.length\n yield { records: structuredClone(selected) }\n }\n this.requireSession(input.session)\n stream.completed = true\n }\n\n async readObjectExistence(\n input: ReadMaterializationObjectExistenceInput\n ): Promise<readonly MaterializationObjectExistence[]> {\n const session = this.requireSession(input.session)\n const result: MaterializationObjectExistence[] = []\n for (const ref of input.refs) {\n const record = session.objectExistence.get(objectRefKey(ref))\n if (record) {\n result.push({ ref: structuredClone(record.ref), exists: record.exists })\n }\n }\n return result\n }\n\n async applyChunk(input: ApplyMaterializationChunkInput): Promise<void> {\n const session = this.requireSession(input.session)\n const projectId = session.header.commit.projectId\n assertPlanChunkCorrelations(input.chunk, session.header.commit)\n assertChunkSequence(session, input.chunk)\n this.hooks.observeBuffer?.(\"apply.chunk\", materializationChunkRows(input.chunk))\n const write = (boundary: string, apply: () => void): void => {\n this.hooks.beforeWrite?.(boundary, session.writeOrdinal++)\n apply()\n }\n\n for (const item of input.chunk.overrides.objects.upserts)\n write(\"override.object.upsert\", () => {\n const key = projectEntityKey(projectId, objectRefKey(item.ref))\n assertLastCommit(\n this.state.objectOverrides.get(key),\n item.expectedLastCommitId,\n \"object override\"\n )\n this.state.objectOverrides.set(\n key,\n structuredClone({\n projectId,\n ref: item.ref,\n value: item.value,\n editedAt: { ...item.editedAt },\n lastCommitId: item.lastCommitId,\n updatedAt: item.updatedAt,\n })\n )\n })\n for (const item of input.chunk.overrides.objects.deletes)\n write(\"override.object.delete\", () => {\n const key = projectEntityKey(projectId, objectRefKey(item.ref))\n assertLastCommit(\n this.state.objectOverrides.get(key),\n item.expectedLastCommitId,\n \"object override\"\n )\n this.state.objectOverrides.delete(key)\n })\n for (const item of input.chunk.overrides.links.edges.upserts)\n write(\"override.link.upsert\", () => {\n const key = projectEntityKey(projectId, linkRefKey(item.ref))\n assertLastCommit(\n this.state.linkOverrides.get(key),\n item.expectedLastCommitId,\n \"link edge override\"\n )\n this.state.linkOverrides.set(\n key,\n structuredClone({\n projectId,\n ref: item.ref,\n value: item.value,\n lastCommitId: item.lastCommitId,\n updatedAt: item.updatedAt,\n })\n )\n })\n for (const item of input.chunk.overrides.links.edges.deletes)\n write(\"override.link.delete\", () => {\n const key = projectEntityKey(projectId, linkRefKey(item.ref))\n assertLastCommit(\n this.state.linkOverrides.get(key),\n item.expectedLastCommitId,\n \"link edge override\"\n )\n this.state.linkOverrides.delete(key)\n })\n for (const item of input.chunk.overrides.links.slots.upserts)\n write(\"override.link-slot.upsert\", () => {\n const key = projectEntityKey(projectId, linkScopeKey(item.ref.source, item.ref.linkId))\n assertLastCommit(\n this.state.linkSlotOverrides.get(key),\n item.expectedLastCommitId,\n \"link slot override\"\n )\n this.state.linkSlotOverrides.set(\n key,\n structuredClone({\n projectId,\n ref: item.ref,\n value: item.value,\n lastCommitId: item.lastCommitId,\n updatedAt: item.updatedAt,\n })\n )\n })\n for (const item of input.chunk.overrides.links.slots.deletes)\n write(\"override.link-slot.delete\", () => {\n const key = projectEntityKey(projectId, linkScopeKey(item.ref.source, item.ref.linkId))\n assertLastCommit(\n this.state.linkSlotOverrides.get(key),\n item.expectedLastCommitId,\n \"link slot override\"\n )\n this.state.linkSlotOverrides.delete(key)\n })\n\n for (const item of input.chunk.effective.linkDeletes)\n write(\"effective.link.delete\", () => {\n this.assertLinkSync(item.expected, projectId)\n getInMemoryObjectMaterializerAdapter(this.objects).deleteExactLink({\n projectId,\n sourceTypeId: item.ref.source.objectTypeId,\n sourceId: item.ref.source.primaryId,\n linkId: item.ref.linkId,\n targetTypeId: item.ref.target.objectTypeId,\n targetId: item.ref.target.primaryId,\n })\n })\n for (const item of input.chunk.effective.objectDeletes)\n write(\"effective.object.delete\", () => {\n this.assertObjectSync(item.expected, projectId)\n getInMemoryObjectMaterializerAdapter(this.objects).deleteExactObject(\n projectId,\n item.ref.objectTypeId,\n item.ref.primaryId\n )\n })\n for (const item of input.chunk.effective.objectUpserts)\n write(\"effective.object.upsert\", () => {\n this.assertObjectSync(item.expected, projectId)\n getInMemoryObjectMaterializerAdapter(this.objects).applyExactObject(item.row, projectId)\n })\n for (const item of input.chunk.effective.linkUpserts)\n write(\"effective.link.upsert\", () => {\n this.assertLinkSync(item.expected, projectId)\n getInMemoryObjectMaterializerAdapter(this.objects).applyExactLink(item.row, projectId)\n })\n for (const item of input.chunk.timeseries.pointUpserts)\n write(\"timeseries.point.upsert\", () => {\n this.assertPoint(item.expected, projectId)\n getInMemoryTimeseriesMaterializerAdapter(this.timeseries).applyExactPoint(\n projectId,\n item.point\n )\n })\n for (const item of input.chunk.outbox)\n write(\"outbox.insert\", () => {\n const envelope = item.envelope\n if (envelope.projectId !== projectId || envelope.commitId !== session.header.commit.id) {\n throw new MaterializationValidationError(\n \"Outbox event does not correlate with its materialization commit.\"\n )\n }\n assertTimestamp(item.availableAt, \"Outbox availableAt\")\n assertTimestamp(item.createdAt, \"Outbox createdAt\")\n assertTimestamp(envelope.occurredAt, \"Outbox event occurredAt\")\n const key = outboxKey(projectId, envelope.id)\n if (this.state.outbox.has(key)) {\n throw new MaterializationConflictError(\n \"effective-state\",\n `Duplicate outbox event '${envelope.id}'.`\n )\n }\n if (session.outboxEnvelopes.has(envelope.commitOrdinal))\n throw new MaterializationConflictError(\n \"effective-state\",\n \"Duplicate outbox commit ordinal.\"\n )\n this.state.outbox.set(key, {\n envelope: structuredClone(envelope),\n availableAt: item.availableAt,\n attempts: 0,\n leaseId: null,\n leaseExpiresAt: null,\n publishedAt: null,\n lastFailure: null,\n createdAt: item.createdAt,\n })\n session.outboxEnvelopes.set(envelope.commitOrdinal, structuredClone(envelope))\n })\n for (const item of materializationPlanItems(input.chunk)) {\n session.appliedPlanItems.push(stableJsonStringify(item))\n }\n }\n\n async finalize(input: FinalizeMaterializationInput): Promise<ApplyMaterializationResult> {\n const session = this.requireSession(input.session)\n const { commit } = session.header\n // Recheck reservations at the durable boundary: callers may open more than one session in the\n // same transaction before either one finalizes.\n this.assertCommitAbsent(session.header)\n assertFinalizationCorrelations(session, input.finalization, this.state, this.objects)\n this.hooks.beforeWrite?.(\"finalize\", session.writeOrdinal++)\n for (const activation of input.finalization.sourceActivations) {\n this.hooks.beforeWrite?.(\"source.activate\", session.writeOrdinal++)\n assertTimestamp(activation.datasetVersion.createdAt, \"Source dataset version createdAt\")\n assertTimestamp(activation.updatedAt, \"Source activation updatedAt\")\n this.assertSource(activation.expected, commit.projectId)\n const candidateKey = sourceMaterializationKey(\n commit.projectId,\n activation.source.projectionId,\n activation.materializationId\n )\n const candidate = this.state.sourceMaterializations.get(candidateKey)\n if (!candidate || candidate.status !== \"ready\")\n throw new MaterializationConflictError(\n \"source-materialization\",\n \"Source activation candidate is missing or is not ready.\"\n )\n const previous = findActiveSourceMaterialization(\n this.state,\n commit.projectId,\n activation.source.projectionId\n )\n if (previous) {\n this.state.sourceMaterializations.set(\n sourceMaterializationKey(\n previous.projectId,\n previous.source.projectionId,\n previous.materializationId\n ),\n {\n ...previous,\n status: \"superseded\",\n executionToken: null,\n terminalAt: activation.updatedAt,\n updatedAt: activation.updatedAt,\n }\n )\n }\n activateSourceRoots(this.state, candidate, activation)\n this.state.sourceMaterializations.set(candidateKey, {\n ...candidate,\n status: \"active\",\n executionToken: null,\n activatedAt: activation.updatedAt,\n lastCommitId: activation.lastCommitId,\n updatedAt: activation.updatedAt,\n })\n }\n const record = {\n ...structuredClone(commit),\n result: structuredClone(input.finalization.result),\n } as OntologyCommitRecord\n this.state.commitsById.set(commitKey(commit.projectId, commit.id), record)\n this.state.commitIdByIdempotency.set(\n idempotencyKey(commit.projectId, commit.idempotencyKey),\n commit.id\n )\n const origin = ontologyCommitOriginSelector(commit.origin)\n if (origin) {\n this.state.commitIdByOrigin.set(commitOriginKey(commit.projectId, origin), commit.id)\n }\n this.releaseSession(session)\n return { commit: structuredClone(record) }\n }\n\n /** @internal Share the existing transaction/session fence with derived vector writes. */\n assertVectorSession(session: MaterializationSession, projectId: string, commitId?: string): void {\n const active = this.requireSession(session)\n if (\n active.header.commit.projectId !== projectId ||\n (commitId !== undefined && active.header.commit.id !== commitId)\n ) {\n throw new MaterializationValidationError(\n \"Vector mutation does not belong to this materialization session.\"\n )\n }\n }\n\n private requireSession(session: MaterializationSession): SessionState {\n const value = this.sessions.get(session.providerToken)\n if (\n !value ||\n !value.active ||\n !this.getTransactionToken() ||\n this.getTransactionToken() !== value.transactionToken\n ) {\n throw new MaterializationConflictError(\n \"effective-state\",\n \"Materialization session is inactive.\"\n )\n }\n return value\n }\n\n private requireReplacement(\n session: SessionState,\n input: StreamSourceReplacementStateInput\n ): ReplacementSessionState {\n if (session.replacement) {\n if (\n session.replacement.sourceId !== input.source.projectionId ||\n session.replacement.candidateMaterializationId !== input.candidateMaterializationId\n ) {\n throw new MaterializationConflictError(\n \"source-materialization\",\n \"Materialization session already owns another replacement union.\"\n )\n }\n return session.replacement\n }\n const projectId = session.header.commit.projectId\n const sourceId = input.source.projectionId\n const candidate = this.state.sourceMaterializations.get(\n sourceMaterializationKey(projectId, sourceId, input.candidateMaterializationId)\n )\n if (!candidate || candidate.status !== \"ready\") {\n throw new MaterializationConflictError(\n \"source-materialization\",\n `Candidate source materialization '${input.candidateMaterializationId}' is missing or is not ready.`\n )\n }\n const previous = findActiveSourceMaterialization(this.state, projectId, sourceId)\n if (\n candidate.protocol !== \"replacement\" ||\n (previous &&\n (previous.protocol !== candidate.protocol ||\n previous.projectionKind !== candidate.projectionKind))\n ) {\n throw new MaterializationConflictError(\n \"source-materialization\",\n \"Source replacement kind or protocol does not match its active materialization.\"\n )\n }\n const replacement: ReplacementSessionState = {\n sourceId,\n candidateMaterializationId: input.candidateMaterializationId,\n owned: new Set(),\n candidate,\n objects: new Map(),\n links: new Map(),\n orderedObjects: [],\n orderedLinks: null,\n affectedScopes: new Set(),\n incidentObjects: new Map(),\n objectStreamStarted: false,\n objectStreamCompleted: false,\n linkStreamStarted: false,\n linkStreamCompleted: false,\n linksExpanded: false,\n }\n for (const rows of [\n previousSourceRows(this.state, candidate),\n candidate.rowsByEntity.values(),\n ]) {\n for (const row of rows) {\n replacement.owned.add(projectionEntityKey(row.assertion))\n if (row.assertion.kind === \"object\") {\n const ref = row.assertion.ref\n replacement.objects.set(objectRefKey(ref), { ref, sortKey: objectRefSortKey(ref) })\n } else {\n addReplacementLink(replacement, row.assertion.ref, true)\n }\n }\n }\n replacement.orderedObjects = [...replacement.objects.values()].sort((left, right) =>\n left.sortKey.localeCompare(right.sortKey)\n )\n session.replacement = replacement\n return replacement\n }\n\n private expandReplacementLinks(\n session: SessionState,\n replacement: ReplacementSessionState\n ): void {\n if (replacement.linksExpanded) return\n const projectId = session.header.commit.projectId\n const incident = replacement.incidentObjects\n const touchesIncident = (ref: OntologyLinkRef): boolean =>\n incident.has(objectRefKey(ref.source)) || incident.has(objectRefKey(ref.target))\n\n const adapter = getInMemoryObjectMaterializerAdapter(this.objects)\n if (incident.size > 0) {\n adapter.visitExactLinks(projectId, (row) => {\n const ref = linkRef(row)\n if (touchesIncident(ref)) addReplacementLink(replacement, ref, true)\n })\n for (const override of this.state.linkOverrides.values()) {\n if (override.projectId !== projectId) continue\n if (touchesIncident(override.ref)) addReplacementLink(replacement, override.ref, true)\n }\n for (const override of this.state.linkSlotOverrides.values()) {\n if (override.projectId !== projectId) continue\n const ref = {\n source: override.ref.source,\n linkId: override.ref.linkId,\n target: override.value.target,\n }\n if (touchesIncident(ref)) addReplacementLink(replacement, ref, true)\n }\n for (const [scopeKey, rows] of this.state.activeSourceLinkScopes) {\n if (JSON.parse(scopeKey)[0] !== projectId) continue\n for (const row of rows.values()) {\n if (row.assertion.kind === \"link\" && touchesIncident(row.assertion.ref)) {\n addReplacementLink(replacement, row.assertion.ref, true)\n }\n }\n }\n }\n const scopes = new Map<string, { source: OntologyObjectRef; linkId: string }>()\n for (const { ref } of replacement.links.values()) {\n const key = linkScopeSortKey(ref.source, ref.linkId)\n if (replacement.affectedScopes.has(key)) scopes.set(key, ref)\n }\n for (const scope of scopes.values()) {\n adapter.visitExactScopeLinks(\n projectId,\n scope.source.objectTypeId,\n scope.source.primaryId,\n scope.linkId,\n (row) => {\n addReplacementLink(replacement, linkRef(row), false)\n }\n )\n const override = this.state.linkSlotOverrides.get(\n projectEntityKey(projectId, linkScopeKey(scope.source, scope.linkId))\n )\n if (override)\n addReplacementLink(replacement, { ...scope, target: override.value.target }, false)\n }\n replacement.linksExpanded = true\n replacement.orderedLinks = null\n }\n\n private assertCommitAbsent(header: MaterializationPlanHeader): void {\n if (this.state.commitsById.has(commitKey(header.commit.projectId, header.commit.id))) {\n throw new MaterializationConflictError(\n \"idempotency\",\n `Ontology commit '${header.commit.id}' already exists.`\n )\n }\n if (\n this.state.commitIdByIdempotency.has(\n idempotencyKey(header.commit.projectId, header.commit.idempotencyKey)\n )\n ) {\n throw new MaterializationConflictError(\n \"idempotency\",\n \"Ontology idempotency key already exists.\"\n )\n }\n const origin = ontologyCommitOriginSelector(header.commit.origin)\n if (\n origin &&\n this.state.commitIdByOrigin.has(commitOriginKey(header.commit.projectId, origin))\n ) {\n throw new MaterializationConflictError(\n \"run-correlation\",\n \"Ontology commit origin already has an authoritative commit.\"\n )\n }\n }\n\n private assertSource(expected: ExpectedSourceRevision, projectId: string): void {\n const current = findActiveSourceMaterialization(\n this.state,\n projectId,\n expected.source.projectionId\n )\n if (\n (current?.materializationId ?? null) !== expected.activeMaterializationId ||\n (current?.lastCommitId ?? null) !== expected.lastCommitId\n ) {\n throw new MaterializationConflictError(\n \"projection-fence\",\n `Source '${expected.source.projectionId}' changed.`\n )\n }\n }\n\n private async assertObject(expected: ExpectedObjectRevision, projectId: string): Promise<void> {\n this.assertObjectSync(expected, projectId)\n }\n\n private assertObjectSync(expected: ExpectedObjectRevision, projectId: string): void {\n const row = getInMemoryObjectMaterializerAdapter(this.objects).getExactObjectRow(\n projectId,\n expected.ref.objectTypeId,\n expected.ref.primaryId\n )\n if (!expected.exists) {\n if (row)\n throw new MaterializationConflictError(\n \"effective-state\",\n `Expected object ${objectRefKey(expected.ref)} to be absent.`\n )\n return\n }\n if (!row || row.version !== expected.version || row.lastCommitId !== expected.lastCommitId) {\n throw new MaterializationConflictError(\n \"effective-state\",\n `Expected object ${objectRefKey(expected.ref)} changed.`\n )\n }\n }\n\n private async assertLink(expected: ExpectedLinkRevision, projectId: string): Promise<void> {\n this.assertLinkSync(expected, projectId)\n }\n\n private assertLinkSync(expected: ExpectedLinkRevision, projectId: string): void {\n const row = getInMemoryObjectMaterializerAdapter(this.objects).getExactLinkRow(projectId, {\n sourceTypeId: expected.ref.source.objectTypeId,\n sourceId: expected.ref.source.primaryId,\n linkId: expected.ref.linkId,\n targetTypeId: expected.ref.target.objectTypeId,\n targetId: expected.ref.target.primaryId,\n })\n if (!expected.exists) {\n if (row)\n throw new MaterializationConflictError(\n \"effective-state\",\n `Expected link ${linkRefKey(expected.ref)} to be absent.`\n )\n return\n }\n if (!row || row.lastCommitId !== expected.lastCommitId) {\n throw new MaterializationConflictError(\n \"effective-state\",\n `Expected link ${linkRefKey(expected.ref)} changed.`\n )\n }\n }\n\n private assertPoint(expected: ExpectedTimeseriesPointRevision, projectId: string): void {\n const point = getInMemoryTimeseriesMaterializerAdapter(this.timeseries).getExactPoint(\n projectId,\n expected.series,\n expected.at\n )\n if ((point?.lastCommitId ?? null) !== expected.lastCommitId) {\n throw new MaterializationConflictError(\n \"timeseries-point\",\n `Telemetry point ${telemetryPointKey(expected.series, expected.at)} changed.`\n )\n }\n }\n\n private async objectState(\n session: SessionState,\n ref: OntologyObjectRef\n ): Promise<MaterializationObjectState> {\n const projectId = session.header.commit.projectId\n const row = await this.objects.getByPrimaryId({\n projectId,\n objectTypeId: ref.objectTypeId,\n primaryId: ref.primaryId,\n })\n return {\n ref: structuredClone(ref),\n source: this.findActiveObjectSource(projectId, ref),\n override: structuredClone(\n publicObjectOverride(\n this.state.objectOverrides.get(projectEntityKey(projectId, objectRefKey(ref)))\n )\n ),\n effective: row ? objectSnapshot(row) : null,\n latestTelemetry: getInMemoryTimeseriesMaterializerAdapter(this.timeseries)\n .listLatestForObject(projectId, ref.objectTypeId, ref.primaryId)\n .map(storedPoint),\n }\n }\n\n private async linkState(\n session: SessionState,\n ref: OntologyLinkRef\n ): Promise<MaterializationLinkState> {\n const projectId = session.header.commit.projectId\n const row = getInMemoryObjectMaterializerAdapter(this.objects).getExactLinkRow(projectId, {\n sourceTypeId: ref.source.objectTypeId,\n sourceId: ref.source.primaryId,\n linkId: ref.linkId,\n targetTypeId: ref.target.objectTypeId,\n targetId: ref.target.primaryId,\n })\n return {\n ref: structuredClone(ref),\n source: this.findActiveLinkSource(projectId, ref),\n override: structuredClone(\n publicLinkOverride(\n this.state.linkOverrides.get(projectEntityKey(projectId, linkRefKey(ref)))\n )\n ),\n slotOverride: structuredClone(\n publicLinkSlotOverride(\n this.state.linkSlotOverrides.get(\n projectEntityKey(projectId, linkScopeKey(ref.source, ref.linkId))\n )\n )\n ),\n effective: row ? linkSnapshot(row) : null,\n }\n }\n\n private linkSlotState(\n session: SessionState,\n source: OntologyObjectRef,\n linkId: string\n ): MaterializationLinkScopeState {\n session.linkSlotStates ??= new Map()\n const key = linkScopeSortKey(source, linkId)\n const existing = session.linkSlotStates.get(key)\n if (existing) return structuredClone(existing)\n const computed = this.computeLinkSlotState(session.header.commit.projectId, source, linkId)\n session.linkSlotStates.set(key, computed)\n return structuredClone(computed)\n }\n\n private computeLinkSlotState(\n projectId: string,\n source: OntologyObjectRef,\n linkId: string\n ): MaterializationLinkScopeState {\n const value = this.computeEffectiveLinkScope(projectId, source, linkId)\n return {\n ...value,\n sourceAssertion: this.findActiveLinkScopeSource(projectId, source, linkId),\n override: structuredClone(\n publicLinkSlotOverride(\n this.state.linkSlotOverrides.get(\n projectEntityKey(projectId, linkScopeKey(source, linkId))\n )\n )\n ),\n }\n }\n\n private computeEffectiveLinkScope(\n projectId: string,\n source: OntologyObjectRef,\n linkId: string\n ): MaterializationLinkScopeRevision & Pick<MaterializationLinkScopeState, \"effective\"> {\n const rows: ObjectLinkRow[] = []\n getInMemoryObjectMaterializerAdapter(this.objects).visitExactScopeLinks(\n projectId,\n source.objectTypeId,\n source.primaryId,\n linkId,\n (row) => rows.push(row)\n )\n rows.sort((left, right) =>\n linkRefSortKey(linkRef(left)).localeCompare(linkRefSortKey(linkRef(right)))\n )\n const accumulator = startScopeAccumulator(source, linkId)\n for (let offset = 0; offset < rows.length; offset += 1_000) {\n const page = rows.slice(offset, offset + 1_000)\n this.hooks.observeBuffer?.(\"state.link-scope.page\", page.length)\n for (const row of page) {\n appendScopeSnapshot(accumulator, linkSnapshot(row))\n }\n }\n const effective = rows.length === 1 ? linkSnapshot(rows[0]!) : null\n return {\n ...finishScopeAccumulator(accumulator),\n effective,\n }\n }\n\n private findActiveLinkScopeSource(\n projectId: string,\n source: OntologyObjectRef,\n linkId: string\n ): StoredSourceLinkAssertion | null {\n const rows = this.state.activeSourceLinkScopes.get(\n projectEntityKey(projectId, linkScopeSortKey(source, linkId))\n )\n if (rows && rows.size > 1)\n throw new MaterializationConflictError(\n \"source-materialization\",\n `Multiple active source links assert cardinality-one scope '${source.objectTypeId}.${linkId}'.`\n )\n return structuredClone(rows?.values().next().value ?? null)\n }\n\n private findActiveObjectSource(\n projectId: string,\n ref: OntologyObjectRef\n ): StoredSourceObjectAssertion | null {\n const found = this.findActiveSource(projectId, projectionEntityKey({ kind: \"object\", ref }))\n return found?.assertion.kind === \"object\" ? (found as StoredSourceObjectAssertion) : null\n }\n\n private findActiveLinkSource(\n projectId: string,\n ref: OntologyLinkRef\n ): StoredSourceLinkAssertion | null {\n const found = this.findActiveSource(projectId, projectionEntityKey({ kind: \"link\", ref }))\n return found?.assertion.kind === \"link\" ? (found as StoredSourceLinkAssertion) : null\n }\n\n private findActiveSource(projectId: string, entityKey: string): StoredSourceAssertion | null {\n const rows = this.state.activeSourceRows.get(projectEntityKey(projectId, entityKey))\n if (rows && rows.size > 1)\n throw new MaterializationConflictError(\n \"source-materialization\",\n `Multiple active sources assert ${entityKey}.`\n )\n return structuredClone(rows?.values().next().value ?? null)\n }\n\n private incidentLinkRefs(\n session: SessionState,\n objects: readonly OntologyObjectRef[]\n ): readonly OntologyLinkRef[] {\n if (objects.length === 0) return []\n session.incidentLinksByObject ??= this.buildIncidentLinkIndex(session.header.commit.projectId)\n const selected = new Map<string, OntologyLinkRef>()\n for (const object of objects) {\n for (const ref of session.incidentLinksByObject.get(objectRefKey(object)) ?? []) {\n selected.set(linkRefSortKey(ref), ref)\n }\n }\n return [...selected.entries()]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([, ref]) => ref)\n }\n\n private buildIncidentLinkIndex(projectId: string): Map<string, readonly OntologyLinkRef[]> {\n const mutable = new Map<string, Map<string, OntologyLinkRef>>()\n const consider = (ref: OntologyLinkRef): void => {\n const sortKey = linkRefSortKey(ref)\n for (const endpoint of [ref.source, ref.target]) {\n const key = objectRefKey(endpoint)\n const links = mutable.get(key) ?? new Map<string, OntologyLinkRef>()\n links.set(sortKey, structuredClone(ref))\n mutable.set(key, links)\n }\n }\n getInMemoryObjectMaterializerAdapter(this.objects).visitExactLinks(projectId, (row) =>\n consider(linkRef(row))\n )\n for (const override of this.state.linkOverrides.values()) {\n if (override.projectId === projectId) consider(override.ref)\n }\n for (const override of this.state.linkSlotOverrides.values()) {\n if (override.projectId !== projectId) continue\n consider({\n source: override.ref.source,\n linkId: override.ref.linkId,\n target: override.value.target,\n })\n }\n for (const [scopeKey, rows] of this.state.activeSourceLinkScopes) {\n if (JSON.parse(scopeKey)[0] !== projectId) continue\n for (const row of rows.values()) {\n if (row.assertion.kind === \"link\") consider(row.assertion.ref)\n }\n }\n const index = new Map<string, readonly OntologyLinkRef[]>()\n for (const [objectKey, refs] of mutable) {\n index.set(\n objectKey,\n [...refs.entries()]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([, ref]) => ref)\n )\n }\n return index\n }\n}\n",
|
|
33
|
+
"import {\n MaterializationConflictError,\n MaterializationValidationError,\n} from \"../../../materialization/errors\"\nimport type {\n ClaimedOntologyOutboxRow,\n ClaimOntologyOutboxInput,\n CompleteOntologyOutboxLeaseInput,\n OntologyOutboxRecord,\n OntologyOutboxStorage,\n OntologyOutboxSummary,\n PurgePublishedOntologyOutboxInput,\n RescheduleOntologyOutboxLeaseInput,\n SummarizeOntologyOutboxInput,\n} from \"../outbox\"\nimport {\n assertNonblank,\n assertTimestamp,\n type InMemoryOntologyState,\n insertBounded,\n outboxKey,\n} from \"./shared-state\"\n\nexport class InMemoryOntologyOutboxStorage implements OntologyOutboxStorage {\n constructor(\n private readonly state: InMemoryOntologyState,\n private readonly runRootOperation: <T>(run: () => Promise<T> | T) => Promise<T>\n ) {}\n\n async claim(input: ClaimOntologyOutboxInput): Promise<readonly ClaimedOntologyOutboxRow[]> {\n return this.runRootOperation(() => this.claimUnlocked(input))\n }\n\n private claimUnlocked(input: ClaimOntologyOutboxInput): readonly ClaimedOntologyOutboxRow[] {\n assertNonblank(input.projectId, \"Ontology outbox project id\")\n assertPositiveLimit(input.limit)\n const now = assertTimestamp(input.now, \"Ontology outbox claim time\")\n const leaseExpiresAt = assertTimestamp(input.leaseExpiresAt, \"Ontology outbox lease expiry\")\n assertNonblank(input.leaseId, \"Ontology outbox lease id\")\n if (leaseExpiresAt <= now) {\n throw new MaterializationValidationError(\n \"Ontology outbox lease expiry must be later than the claim time.\"\n )\n }\n const rows: OntologyOutboxRecord[] = []\n for (const row of this.state.outbox.values()) {\n if (row.envelope.projectId !== input.projectId) continue\n assertPairedLease(row)\n if (row.publishedAt !== null || Date.parse(row.availableAt) > now) continue\n if (row.leaseExpiresAt !== null && Date.parse(row.leaseExpiresAt) > now) continue\n insertBounded(rows, row, input.limit, compareClaimRows)\n }\n return rows.map((row) => {\n const claimed: ClaimedOntologyOutboxRow = {\n ...row,\n attempts: row.attempts + 1,\n leaseId: input.leaseId,\n leaseExpiresAt: input.leaseExpiresAt,\n }\n this.state.outbox.set(outboxKey(input.projectId, row.envelope.id), structuredClone(claimed))\n return structuredClone(claimed)\n })\n }\n\n async markPublished(input: CompleteOntologyOutboxLeaseInput): Promise<void> {\n await this.runRootOperation(() => this.markPublishedUnlocked(input))\n }\n\n private markPublishedUnlocked(input: CompleteOntologyOutboxLeaseInput): void {\n assertNonblank(input.projectId, \"Ontology outbox project id\")\n assertNonblank(input.leaseId, \"Ontology outbox lease id\")\n assertTimestamp(input.publishedAt, \"Ontology outbox publishedAt\")\n const rows = this.validateLeaseBatch(input.projectId, input.ids, input.leaseId)\n for (const [key, row] of rows) {\n this.state.outbox.set(key, {\n ...row,\n publishedAt: input.publishedAt,\n leaseId: null,\n leaseExpiresAt: null,\n })\n }\n }\n\n async reschedule(input: RescheduleOntologyOutboxLeaseInput): Promise<void> {\n await this.runRootOperation(() => this.rescheduleUnlocked(input))\n }\n\n private rescheduleUnlocked(input: RescheduleOntologyOutboxLeaseInput): void {\n assertNonblank(input.projectId, \"Ontology outbox project id\")\n assertNonblank(input.leaseId, \"Ontology outbox lease id\")\n assertTimestamp(input.availableAt, \"Ontology outbox availableAt\")\n const rows = this.validateLeaseBatch(input.projectId, input.ids, input.leaseId)\n for (const [key, row] of rows) {\n this.state.outbox.set(key, {\n ...row,\n availableAt: input.availableAt,\n lastFailure: input.failure === undefined ? row.lastFailure : structuredClone(input.failure),\n leaseId: null,\n leaseExpiresAt: null,\n })\n }\n }\n\n async purgePublished(input: PurgePublishedOntologyOutboxInput): Promise<number> {\n return this.runRootOperation(() => this.purgePublishedUnlocked(input))\n }\n\n async summarize(input: SummarizeOntologyOutboxInput): Promise<OntologyOutboxSummary> {\n return this.runRootOperation(() => {\n assertNonblank(input.projectId, \"Ontology outbox project id\")\n let pendingCount = 0\n let oldestPendingAt: string | null = null\n let retryingCount = 0\n let maxAttempts = 0\n\n for (const row of this.state.outbox.values()) {\n if (row.envelope.projectId !== input.projectId || row.publishedAt !== null) continue\n pendingCount += 1\n if (row.attempts > 0) retryingCount += 1\n maxAttempts = Math.max(maxAttempts, row.attempts)\n if (oldestPendingAt === null || row.createdAt < oldestPendingAt) {\n oldestPendingAt = row.createdAt\n }\n }\n\n return { pendingCount, oldestPendingAt, retryingCount, maxAttempts }\n })\n }\n\n private purgePublishedUnlocked(input: PurgePublishedOntologyOutboxInput): number {\n assertNonblank(input.projectId, \"Ontology outbox project id\")\n assertPositiveLimit(input.limit)\n const cutoff = assertTimestamp(input.publishedBefore, \"Ontology outbox purge cutoff\")\n const rows: [string, OntologyOutboxRecord][] = []\n for (const entry of this.state.outbox.entries()) {\n const [, row] = entry\n if (\n row.envelope.projectId !== input.projectId ||\n row.publishedAt === null ||\n Date.parse(row.publishedAt) >= cutoff\n ) {\n continue\n }\n insertBounded(rows, entry, input.limit, ([, left], [, right]) =>\n comparePublishedRows(left, right)\n )\n }\n for (const [key] of rows) this.state.outbox.delete(key)\n return rows.length\n }\n\n private requireLease(key: string, leaseId: string) {\n const row = this.state.outbox.get(key)\n if (!row || row.leaseId !== leaseId || row.leaseExpiresAt === null) {\n throw new MaterializationConflictError(\n \"outbox-lease\",\n \"Ontology outbox lease does not match.\"\n )\n }\n return row\n }\n\n private validateLeaseBatch(\n projectId: string,\n ids: readonly string[],\n leaseId: string\n ): readonly (readonly [string, ReturnType<InMemoryOntologyOutboxStorage[\"requireLease\"]>])[] {\n const seen = new Set<string>()\n return ids.map((id) => {\n assertNonblank(id, \"Ontology outbox event id\")\n if (seen.has(id)) {\n throw new MaterializationValidationError(\n `Ontology outbox lease batch repeats event '${id}'.`\n )\n }\n seen.add(id)\n const key = outboxKey(projectId, id)\n return [key, this.requireLease(key, leaseId)] as const\n })\n }\n}\n\n/**\n * Deterministic claim order.\n *\n * Every row of one commit shares `createdAt`, so `commitOrdinal` gives providers a stable batch\n * order. It correlates facts but does not promise broker delivery order: concurrent leases and\n * retries may publish later rows first.\n */\nfunction compareClaimRows(\n left: import(\"../outbox\").OntologyOutboxRecord,\n right: import(\"../outbox\").OntologyOutboxRecord\n): number {\n return (\n left.createdAt.localeCompare(right.createdAt) ||\n left.envelope.commitId.localeCompare(right.envelope.commitId) ||\n left.envelope.commitOrdinal - right.envelope.commitOrdinal\n )\n}\n\nfunction comparePublishedRows(\n left: import(\"../outbox\").OntologyOutboxRecord,\n right: import(\"../outbox\").OntologyOutboxRecord\n): number {\n return (\n (left.publishedAt ?? \"\").localeCompare(right.publishedAt ?? \"\") ||\n left.envelope.id.localeCompare(right.envelope.id)\n )\n}\n\nfunction assertPositiveLimit(limit: number): void {\n if (!Number.isSafeInteger(limit) || limit <= 0) {\n throw new MaterializationValidationError(\"Ontology outbox limit must be positive.\")\n }\n}\n\nfunction assertPairedLease(row: {\n readonly leaseId: string | null\n readonly leaseExpiresAt: string | null\n}): void {\n if ((row.leaseId === null) !== (row.leaseExpiresAt === null)) {\n throw new MaterializationConflictError(\n \"outbox-lease\",\n \"Ontology outbox row has an unpaired lease lifecycle.\"\n )\n }\n}\n",
|
|
34
|
+
"import { stableJsonStringify } from \"../../../json\"\nimport { MaterializationValidationError } from \"../../../materialization/errors\"\nimport type { ProjectionExecution } from \"../../../materialization/model\"\nimport { projectionEntityKey } from \"../../../materialization/refs\"\nimport {\n assertSourceBeginInput as assertBeginInput,\n assertTimestamp as assertCanonicalTimestamp,\n assertSourceProject as assertProjectAndSource,\n assertSourceCandidateOwner,\n assertSourceExecutionIdentity,\n assertSourceStagedRow,\n assertSourceWriteIdentity as assertWriteIdentity,\n isExactStagingManifest,\n sourceConflict,\n sourceMaterializationIdentity,\n sourceStageRoots,\n} from \"../provider\"\nimport type {\n AbandonSourceMaterializationCandidateInput,\n AbandonSourceMaterializationInput,\n AssertSourceMaterializationExecution,\n BeginSourceMaterializationInput,\n CleanupTerminalSourceMaterializationsInput,\n CleanupTerminalSourceMaterializationsResult,\n GetActiveOntologySourceInput,\n MarkSourceMaterializationReadyInput,\n OntologySourceRecord,\n OntologySourceStorage,\n ReclaimSourceMaterializationInput,\n StageSourceAssertion,\n StageSourceRowsInput,\n StageSourceRowsResult,\n SummarizeTerminalSourceMaterializationsInput,\n TerminalSourceMaterializationSummary,\n} from \"../sources\"\nimport { findActiveSourceMaterialization } from \"./materializations-state\"\nimport {\n assertNonblank,\n type InMemoryOntologyState,\n type InMemorySourceMaterialization,\n insertBounded,\n sourceMaterializationKey,\n sourceMaterializationRecord,\n} from \"./shared-state\"\n\nexport class InMemoryOntologySourceStorage implements OntologySourceStorage {\n constructor(\n private readonly state: InMemoryOntologyState,\n private readonly runRootOperation: <T>(run: () => Promise<T> | T) => Promise<T>,\n private readonly assertExecution: AssertSourceMaterializationExecution\n ) {}\n\n async beginMaterialization(\n input: BeginSourceMaterializationInput\n ): Promise<OntologySourceRecord> {\n return this.runRootOperation(async () => {\n assertBeginInput(input)\n await this.assertCurrentExecution(input)\n const key = sourceMaterializationKey(\n input.projectId,\n input.source.projectionId,\n input.materializationId\n )\n const existing = this.state.sourceMaterializations.get(key)\n if (existing) {\n if (isExactStagingManifest(sourceMaterializationRecord(existing), input)) {\n return sourceMaterializationRecord(existing)\n }\n throw sourceConflict(\n `Source materialization '${input.materializationId}' already exists with different identity or state.`\n )\n }\n\n const nonterminal = this.findRunCandidates(\n input.projectId,\n input.source.projectionId,\n input.execution.projectionRunId\n )\n if (nonterminal.length > 0) {\n throw sourceConflict(\n `Projection run '${input.execution.projectionRunId}' already has a nonterminal source materialization; reclaim it before beginning another.`\n )\n }\n\n const materialization: InMemorySourceMaterialization = {\n projectId: input.projectId,\n source: structuredClone(input.source),\n materializationId: input.materializationId,\n projectionRunId: input.execution.projectionRunId,\n projectionKind: input.projectionKind,\n protocol: input.protocol,\n status: \"staging\",\n executionToken: input.execution.executionToken,\n datasetVersion: structuredClone(input.datasetVersion),\n projectionRevision: input.projectionRevision,\n ownershipHash: input.ownershipHash,\n ontologyRevision: input.ontologyRevision,\n ...(input.base ? { base: structuredClone(input.base) } : {}),\n rootCount: null,\n assertionCount: null,\n createdAt: input.createdAt,\n readyAt: null,\n activatedAt: null,\n terminalAt: null,\n lastCommitId: null,\n updatedAt: input.createdAt,\n rowsByEntity: new Map(),\n roots: new Map(),\n rootOrdinals: new Map(),\n ordinalRoots: new Map(),\n }\n this.state.sourceMaterializations.set(key, materialization)\n return sourceMaterializationRecord(materialization)\n })\n }\n\n async stageRows(input: StageSourceRowsInput): Promise<StageSourceRowsResult> {\n return this.runRootOperation(async () => {\n assertWriteIdentity(input)\n await this.assertCurrentExecution(input)\n const materialization = this.requireMaterialization(input)\n assertSourceCandidateOwner(sourceMaterializationRecord(materialization), input.execution)\n if (materialization.status !== \"staging\") {\n throw sourceConflict(\n `Source materialization '${input.materializationId}' is '${materialization.status}' and cannot accept rows.`\n )\n }\n return stageRowsAtomically(materialization, input)\n })\n }\n\n async markReady(input: MarkSourceMaterializationReadyInput): Promise<OntologySourceRecord> {\n return this.runRootOperation(async () => {\n assertWriteIdentity(input)\n assertCanonicalTimestamp(input.readyAt, \"Source readyAt\")\n assertCount(input.rootCount, \"Source root count\")\n assertCount(input.assertionCount, \"Source assertion count\")\n await this.assertCurrentExecution(input)\n const materialization = this.requireMaterialization(input)\n assertSourceCandidateOwner(sourceMaterializationRecord(materialization), input.execution)\n\n if (materialization.status === \"ready\") {\n if (\n materialization.rootCount === input.rootCount &&\n materialization.assertionCount === input.assertionCount &&\n materialization.readyAt === input.readyAt\n ) {\n return sourceMaterializationRecord(materialization)\n }\n throw sourceConflict(\n `Source materialization '${input.materializationId}' was marked ready with different counts or time.`\n )\n }\n if (materialization.status !== \"staging\") {\n throw sourceConflict(\n `Source materialization '${input.materializationId}' cannot transition from '${materialization.status}' to 'ready'.`\n )\n }\n assertNotBefore(input.readyAt, materialization.createdAt, \"Source readyAt\", \"createdAt\")\n assertReadyCounts(materialization, input.rootCount, input.assertionCount)\n\n const ready: InMemorySourceMaterialization = {\n ...materialization,\n status: \"ready\",\n rootCount: input.rootCount,\n assertionCount: input.assertionCount,\n readyAt: input.readyAt,\n updatedAt: input.readyAt,\n }\n this.state.sourceMaterializations.set(\n sourceMaterializationKey(\n input.projectId,\n input.source.projectionId,\n input.materializationId\n ),\n ready\n )\n return sourceMaterializationRecord(ready)\n })\n }\n\n async getActive(input: GetActiveOntologySourceInput): Promise<OntologySourceRecord | null> {\n return this.runRootOperation(() => {\n assertProjectAndSource(input)\n const active = findActiveSourceMaterialization(\n this.state,\n input.projectId,\n input.source.projectionId\n )\n return active ? sourceMaterializationRecord(active) : null\n })\n }\n\n async abandon(input: AbandonSourceMaterializationCandidateInput): Promise<OntologySourceRecord>\n async abandon(input: ReclaimSourceMaterializationInput): Promise<OntologySourceRecord | null>\n async abandon(input: AbandonSourceMaterializationInput): Promise<OntologySourceRecord | null> {\n return this.runRootOperation(async () => {\n assertProjectAndSource(input)\n assertSourceExecutionIdentity(input.execution.projectionRunId, input.execution.executionToken)\n assertCanonicalTimestamp(input.abandonedAt, \"Source abandonedAt\")\n await this.assertCurrentExecution(input)\n return input.kind === \"candidate\"\n ? this.abandonCandidate(input)\n : this.abandonForReclaim(input)\n })\n }\n\n async cleanupTerminal(\n input: CleanupTerminalSourceMaterializationsInput\n ): Promise<CleanupTerminalSourceMaterializationsResult> {\n return this.runRootOperation(() => {\n assertNonblank(input.projectId, \"Terminal source cleanup project id\")\n assertCanonicalTimestamp(input.terminalBefore, \"Terminal source cleanup cutoff\")\n if (!Number.isSafeInteger(input.limit) || input.limit <= 0) {\n throw new MaterializationValidationError(\n \"Terminal source cleanup limit must be a positive safe integer.\"\n )\n }\n\n const candidates: [string, InMemorySourceMaterialization][] = []\n for (const entry of this.state.sourceMaterializations.entries()) {\n const materialization = entry[1]\n if (\n materialization.projectId !== input.projectId ||\n (materialization.status !== \"superseded\" && materialization.status !== \"abandoned\") ||\n materialization.terminalAt === null ||\n materialization.terminalAt >= input.terminalBefore\n ) {\n continue\n }\n if (\n materialization.roots.size > 0 &&\n ![...materialization.roots.values()].some(\n (root) =>\n !root.active && root.retiredAt !== null && root.retiredAt < input.terminalBefore\n )\n )\n continue\n insertBounded(candidates, entry, input.limit, compareTerminalMaterializations)\n }\n\n let remaining = input.limit\n let rowsDeleted = 0\n let materializationsDeleted = 0\n for (const [key, candidate] of candidates) {\n if (remaining === 0) break\n const current = this.state.sourceMaterializations.get(key)\n if (current !== candidate) continue\n current.rootOrdinals.clear()\n current.ordinalRoots.clear()\n for (const [rootKey, root] of current.roots) {\n if (remaining === 0) break\n if (root.active || root.retiredAt === null || root.retiredAt >= input.terminalBefore)\n continue\n for (const entityKey of root.entityKeys) {\n if (remaining === 0) break\n current.rowsByEntity.delete(entityKey)\n root.entityKeys.delete(entityKey)\n rowsDeleted += 1\n remaining -= 1\n }\n if (root.entityKeys.size === 0 && remaining > 0) {\n current.roots.delete(rootKey)\n current.rootOrdinals.delete(rootKey)\n current.ordinalRoots.delete(root.stagingOrdinal)\n rowsDeleted += 1\n remaining -= 1\n }\n }\n if (current.roots.size === 0 && current.rowsByEntity.size === 0 && remaining > 0) {\n this.state.sourceMaterializations.delete(key)\n materializationsDeleted += 1\n remaining -= 1\n }\n }\n return { rowsDeleted, materializationsDeleted }\n })\n }\n\n async summarizeTerminal(\n input: SummarizeTerminalSourceMaterializationsInput\n ): Promise<TerminalSourceMaterializationSummary> {\n return this.runRootOperation(() => {\n assertNonblank(input.projectId, \"Terminal source summary project id\")\n let count = 0\n let oldestTerminalAt: string | null = null\n for (const materialization of this.state.sourceMaterializations.values()) {\n if (\n materialization.projectId !== input.projectId ||\n (materialization.status !== \"superseded\" && materialization.status !== \"abandoned\") ||\n materialization.terminalAt === null\n ) {\n continue\n }\n count += 1\n if (oldestTerminalAt === null || materialization.terminalAt < oldestTerminalAt) {\n oldestTerminalAt = materialization.terminalAt\n }\n }\n return { count, oldestTerminalAt }\n })\n }\n\n private async assertCurrentExecution(\n input:\n | BeginSourceMaterializationInput\n | {\n readonly projectId: string\n readonly source: BeginSourceMaterializationInput[\"source\"]\n readonly execution: ProjectionExecution\n }\n ): Promise<void> {\n await this.assertExecution({\n projectId: input.projectId,\n source: input.source,\n execution: input.execution,\n ...(\"projectionKind\" in input ? { identity: sourceMaterializationIdentity(input) } : {}),\n })\n }\n\n private requireMaterialization(input: {\n readonly projectId: string\n readonly source: BeginSourceMaterializationInput[\"source\"]\n readonly materializationId: string\n }): InMemorySourceMaterialization {\n const materialization = this.state.sourceMaterializations.get(\n sourceMaterializationKey(input.projectId, input.source.projectionId, input.materializationId)\n )\n if (!materialization) {\n throw sourceConflict(`Source materialization '${input.materializationId}' does not exist.`)\n }\n return materialization\n }\n\n private abandonCandidate(\n input: AbandonSourceMaterializationCandidateInput\n ): OntologySourceRecord {\n const materialization = this.requireMaterialization(input)\n if (materialization.status === \"abandoned\") {\n if (\n materialization.projectionRunId === input.execution.projectionRunId &&\n materialization.terminalAt === input.abandonedAt\n ) {\n return sourceMaterializationRecord(materialization)\n }\n throw sourceConflict(\n `Source materialization '${input.materializationId}' was abandoned by another execution or at another time.`\n )\n }\n assertSourceCandidateOwner(sourceMaterializationRecord(materialization), input.execution)\n if (materialization.status !== \"staging\" && materialization.status !== \"ready\") {\n throw sourceConflict(\n `Source materialization '${input.materializationId}' cannot transition from '${materialization.status}' to 'abandoned'.`\n )\n }\n return this.transitionToAbandoned(materialization, input.abandonedAt)\n }\n\n private abandonForReclaim(input: ReclaimSourceMaterializationInput): OntologySourceRecord | null {\n const candidates = this.findRunCandidates(\n input.projectId,\n input.source.projectionId,\n input.execution.projectionRunId\n )\n if (\n candidates.some(\n ([, materialization]) => materialization.executionToken === input.execution.executionToken\n )\n ) {\n throw sourceConflict(\n `Projection run '${input.execution.projectionRunId}' already has a source materialization owned by the current execution.`\n )\n }\n if (candidates.length > 1) {\n throw sourceConflict(\n `Projection run '${input.execution.projectionRunId}' has multiple nonterminal source materializations.`\n )\n }\n const candidate = candidates[0]?.[1]\n return candidate ? this.transitionToAbandoned(candidate, input.abandonedAt) : null\n }\n\n private transitionToAbandoned(\n materialization: InMemorySourceMaterialization,\n abandonedAt: string\n ): OntologySourceRecord {\n assertNotBefore(abandonedAt, materialization.createdAt, \"Source abandonedAt\", \"createdAt\")\n if (materialization.readyAt !== null) {\n assertNotBefore(abandonedAt, materialization.readyAt, \"Source abandonedAt\", \"readyAt\")\n }\n for (const root of materialization.roots.values()) root.retiredAt = abandonedAt\n const abandoned: InMemorySourceMaterialization = {\n ...materialization,\n status: \"abandoned\",\n executionToken: null,\n terminalAt: abandonedAt,\n updatedAt: abandonedAt,\n }\n this.state.sourceMaterializations.set(\n sourceMaterializationKey(\n materialization.projectId,\n materialization.source.projectionId,\n materialization.materializationId\n ),\n abandoned\n )\n return sourceMaterializationRecord(abandoned)\n }\n\n private findRunCandidates(\n projectId: string,\n sourceId: string,\n projectionRunId: string\n ): [string, InMemorySourceMaterialization][] {\n return [...this.state.sourceMaterializations.entries()].filter(\n ([, materialization]) =>\n materialization.projectId === projectId &&\n materialization.source.projectionId === sourceId &&\n materialization.projectionRunId === projectionRunId &&\n (materialization.status === \"staging\" || materialization.status === \"ready\")\n )\n }\n}\n\nfunction stageRowsAtomically(\n materialization: InMemorySourceMaterialization,\n input: StageSourceRowsInput\n): StageSourceRowsResult {\n let inserted = 0\n let unchanged = 0\n const newRows = new Map<string, StageSourceRowsInput[\"rows\"][number]>()\n const newRootOrdinals = new Map<string, number>()\n const newOrdinalRoots = new Map<number, string>()\n const roots = sourceStageRoots(materialization.projectionKind, input)\n if (!materialization.base && roots.some((root) => root.deleted)) {\n throw new MaterializationValidationError(\"Root deletions require a source delta base.\")\n }\n for (const root of roots) {\n const previous = materialization.roots.get(root.rootKey)\n const otherRoot = materialization.ordinalRoots.get(root.stagingOrdinal)\n if (\n (previous &&\n (previous.deleted !== root.deleted || previous.stagingOrdinal !== root.stagingOrdinal)) ||\n (otherRoot !== undefined && otherRoot !== root.rootKey)\n ) {\n throw new MaterializationValidationError(\n \"Source materialization repeats root or stream ordinal with different content.\"\n )\n }\n newRootOrdinals.set(root.rootKey, root.stagingOrdinal)\n newOrdinalRoots.set(root.stagingOrdinal, root.rootKey)\n }\n for (const row of input.rows) {\n assertSourceStagedRow(materialization.projectionKind, row)\n\n const rootKey = projectionEntityKey(row.root)\n const existingOrdinal =\n materialization.rootOrdinals.get(rootKey) ?? newRootOrdinals.get(rootKey)\n if (existingOrdinal !== undefined && existingOrdinal !== row.stagingOrdinal) {\n throw new MaterializationValidationError(\n `Source materialization repeats root ${rootKey} at a different stream ordinal.`\n )\n }\n const existingRoot =\n materialization.ordinalRoots.get(row.stagingOrdinal) ??\n newOrdinalRoots.get(row.stagingOrdinal)\n if (existingRoot !== undefined && existingRoot !== rootKey) {\n throw new MaterializationValidationError(\n `Source materialization repeats stream ordinal ${row.stagingOrdinal} for another root.`\n )\n }\n\n const entityKey = projectionEntityKey(row.assertion)\n const existing = materialization.rowsByEntity.get(entityKey) ?? newRows.get(entityKey)\n if (existing) {\n if (stableJsonStringify(existing) === stableJsonStringify(row)) {\n unchanged += 1\n continue\n }\n throw new MaterializationValidationError(\n `Source materialization repeats asserted entity ${entityKey}.`\n )\n }\n\n newRootOrdinals.set(rootKey, row.stagingOrdinal)\n newOrdinalRoots.set(row.stagingOrdinal, rootKey)\n newRows.set(entityKey, structuredClone(row))\n inserted += 1\n }\n\n for (const [rootKey, ordinal] of newRootOrdinals) {\n materialization.rootOrdinals.set(rootKey, ordinal)\n }\n for (const [ordinal, rootKey] of newOrdinalRoots) {\n materialization.ordinalRoots.set(ordinal, rootKey)\n }\n for (const root of roots) {\n if (!materialization.roots.has(root.rootKey))\n materialization.roots.set(root.rootKey, {\n root: structuredClone(root.root),\n stagingOrdinal: root.stagingOrdinal,\n deleted: root.deleted,\n entityKeys: new Set(),\n active: false,\n retiredAt: null,\n })\n }\n for (const [entityKey, row] of newRows) {\n materialization.rowsByEntity.set(entityKey, row)\n materialization.roots.get(projectionEntityKey(row.root))!.entityKeys.add(entityKey)\n }\n return { inserted, unchanged }\n}\n\nfunction assertReadyCounts(\n materialization: InMemorySourceMaterialization,\n rootCount: number,\n assertionCount: number\n): void {\n if (\n materialization.rootOrdinals.size !== rootCount ||\n materialization.ordinalRoots.size !== rootCount ||\n materialization.rowsByEntity.size !== assertionCount\n ) {\n throw new MaterializationValidationError(\n \"Source ready counts do not match the staged roots and assertions.\"\n )\n }\n for (let ordinal = 0; ordinal < rootCount; ordinal += 1) {\n if (!materialization.ordinalRoots.has(ordinal)) {\n throw new MaterializationValidationError(\n `Source staging ordinals must be contiguous from zero; missing ${ordinal}.`\n )\n }\n }\n assertReadyTopology(materialization)\n}\n\nfunction assertReadyTopology(materialization: InMemorySourceMaterialization): void {\n const rowsByRoot = new Map<string, StageSourceAssertion[]>()\n for (const row of materialization.rowsByEntity.values()) {\n const rootKey = projectionEntityKey(row.root)\n const rows = rowsByRoot.get(rootKey) ?? []\n rows.push(row)\n rowsByRoot.set(rootKey, rows)\n }\n\n for (const rootKey of materialization.rootOrdinals.keys()) {\n const rows = rowsByRoot.get(rootKey) ?? []\n if (materialization.roots.get(rootKey)?.deleted) {\n if (rows.length > 0)\n throw new MaterializationValidationError(\"Deleted source roots cannot contain assertions.\")\n continue\n }\n const first = rows[0]\n if (!first) {\n throw new MaterializationValidationError(`Source root ${rootKey} has no staged assertions.`)\n }\n const root = first.root\n\n if (materialization.projectionKind === \"link\") {\n if (\n rows.length !== 1 ||\n root.kind !== \"link\" ||\n first.assertion.kind !== \"link\" ||\n projectionEntityKey(first.assertion) !== rootKey\n ) {\n throw new MaterializationValidationError(\n `Link projection root ${rootKey} must contain exactly its matching link assertion.`\n )\n }\n continue\n }\n\n if (root.kind !== \"object\") {\n throw new MaterializationValidationError(\n `Object projection root ${rootKey} must be an object.`\n )\n }\n const matchingObjects = rows.filter(\n (row) => row.assertion.kind === \"object\" && projectionEntityKey(row.assertion) === rootKey\n )\n const hasForeignAssertion = rows.some((row) => {\n if (row.assertion.kind === \"object\") return projectionEntityKey(row.assertion) !== rootKey\n return projectionEntityKey({ kind: \"object\", ref: row.assertion.ref.source }) !== rootKey\n })\n if (matchingObjects.length !== 1 || hasForeignAssertion) {\n throw new MaterializationValidationError(\n `Object projection root ${rootKey} must contain exactly its matching object assertion plus links sourced from that root.`\n )\n }\n }\n}\n\nfunction assertCount(value: number, label: string): void {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new MaterializationValidationError(`${label} must be a nonnegative safe integer.`)\n }\n}\n\nfunction assertNotBefore(\n value: string,\n minimum: string,\n label: string,\n minimumLabel: string\n): void {\n if (value < minimum) {\n throw new MaterializationValidationError(`${label} cannot precede source ${minimumLabel}.`)\n }\n}\n\nfunction compareTerminalMaterializations(\n [, left]: readonly [string, InMemorySourceMaterialization],\n [, right]: readonly [string, InMemorySourceMaterialization]\n): number {\n return (\n (left.terminalAt ?? \"\").localeCompare(right.terminalAt ?? \"\") ||\n left.source.projectionId.localeCompare(right.source.projectionId) ||\n left.materializationId.localeCompare(right.materializationId)\n )\n}\n",
|
|
35
|
+
"import type { OntologyStorage } from \"..\"\nimport type { InMemoryOntologyState, InMemoryOntologyStorageTestHooks } from \"./shared-state\"\n\nexport interface InMemoryOntologyStorageTestingAdapter {\n setTestHooks(hooks: InMemoryOntologyStorageTestHooks): void\n snapshot(): InMemoryOntologyState\n}\n\nconst testingAdapters = new WeakMap<object, InMemoryOntologyStorageTestingAdapter>()\n\nexport function registerInMemoryOntologyStorageTestingAdapter(\n storage: OntologyStorage,\n adapter: InMemoryOntologyStorageTestingAdapter\n): void {\n testingAdapters.set(storage, adapter)\n}\n\n/** @internal Relative test-only access; intentionally absent from every package barrel. */\nexport function getInMemoryOntologyStorageTestingAdapter(\n storage: OntologyStorage\n): InMemoryOntologyStorageTestingAdapter {\n const adapter = testingAdapters.get(storage)\n if (!adapter) {\n throw new Error(\"[Sixb] In-memory ontology storage testing adapter is unavailable.\")\n }\n return adapter\n}\n\nexport type { InMemoryOntologyStorageTestHooks } from \"./shared-state\"\n",
|
|
36
|
+
"import type { MaterializationSession } from \"../materializations\"\nimport type { OntologyVectorIndexingStorage, VectorIndexingWork } from \"../vector-indexing\"\n\nexport class InMemoryVectorIndexingStorage implements OntologyVectorIndexingStorage {\n constructor(\n private readonly state: Map<\n string,\n VectorIndexingWork & { projectId: string; dispatchAt: string }\n >,\n private readonly assertSession: (session: MaterializationSession, projectId: string) => void,\n private readonly run: <T>(fn: () => T) => Promise<T>\n ) {}\n\n async schedule(input: Parameters<OntologyVectorIndexingStorage[\"schedule\"]>[0]) {\n this.assertSession(input.session, input.projectId)\n if (input.deleted.length) {\n const deleted = new Set(\n input.deleted.map((ref) => JSON.stringify([ref.objectTypeId, ref.primaryId]))\n )\n for (const [key, work] of this.state) {\n if (\n work.projectId === input.projectId &&\n deleted.has(JSON.stringify([work.ref.objectTypeId, work.ref.primaryId]))\n )\n this.state.delete(key)\n }\n }\n for (const request of input.requests) {\n const key = JSON.stringify([\n input.projectId,\n request.ref.objectTypeId,\n request.ref.primaryId,\n request.profile,\n ])\n this.state.set(\n key,\n structuredClone({\n ...request,\n projectId: input.projectId,\n status: \"pending\",\n availableAt: input.availableAt,\n dispatchAt: input.availableAt,\n })\n )\n }\n }\n\n async complete(input: Parameters<OntologyVectorIndexingStorage[\"complete\"]>[0]) {\n this.assertSession(input.session, input.projectId)\n for (const entry of input.entries) {\n const key = JSON.stringify([\n input.projectId,\n entry.ref.objectTypeId,\n entry.ref.primaryId,\n entry.profile,\n ])\n const work = this.state.get(key)\n if (\n work?.configuration === entry.configuration &&\n work.sourceFingerprint === entry.sourceFingerprint\n ) {\n this.state.delete(key)\n }\n }\n }\n\n async dispatched(input: Parameters<OntologyVectorIndexingStorage[\"dispatched\"]>[0]) {\n await this.run(() => {\n for (const [key, work] of this.state)\n if (work.projectId === input.projectId && input.ids.includes(work.id))\n this.state.set(key, { ...work, dispatchAt: input.nextDispatchAt })\n })\n }\n async get(input: Parameters<OntologyVectorIndexingStorage[\"get\"]>[0]) {\n return this.run(() =>\n structuredClone(\n [...this.state.values()].find(\n (work) => work.projectId === input.projectId && work.id === input.id\n ) ?? null\n )\n )\n }\n\n async getBatch(input: Parameters<OntologyVectorIndexingStorage[\"getBatch\"]>[0]) {\n return this.run(() =>\n structuredClone(\n [...this.state.values()]\n .filter((work) => work.projectId === input.projectId && work.batchId === input.batchId)\n .sort((a, b) => a.id.localeCompare(b.id))\n )\n )\n }\n\n async getBatchMember(input: Parameters<OntologyVectorIndexingStorage[\"getBatchMember\"]>[0]) {\n return this.run(() => {\n const work = this.state.get(\n JSON.stringify([\n input.projectId,\n input.ref.objectTypeId,\n input.ref.primaryId,\n input.profile,\n ])\n )\n return work?.batchId === input.batchId ? structuredClone(work) : null\n })\n }\n\n async updateBatch(input: Parameters<OntologyVectorIndexingStorage[\"updateBatch\"]>[0]) {\n return this.run(() => {\n const updates = new Map(input.updates.map((update) => [update.id, update]))\n const matches = [...this.state.entries()].filter(\n ([, work]) =>\n work.projectId === input.projectId && updates.get(work.id)?.expectedStatus === work.status\n )\n if (input.requireAll && matches.length !== input.updates.length) return false\n for (const [key, work] of matches) {\n const update = updates.get(work.id)!\n this.state.set(\n key,\n structuredClone({\n ...work,\n status: update.status,\n availableAt: update.availableAt,\n values: update.values ?? work.values,\n error: update.error,\n })\n )\n }\n return true\n })\n }\n\n async listDue(input: Parameters<OntologyVectorIndexingStorage[\"listDue\"]>[0]) {\n return this.run(() =>\n [...this.state.values()]\n .filter(\n (work) =>\n work.projectId === input.projectId &&\n work.status !== \"failed\" &&\n work.dispatchAt <= input.now\n )\n .sort((a, b) => a.dispatchAt.localeCompare(b.dispatchAt) || a.id.localeCompare(b.id))\n .slice(0, input.limit)\n .map(({ values: _values, ...work }) => structuredClone(work))\n )\n }\n\n async update(input: Parameters<OntologyVectorIndexingStorage[\"update\"]>[0]) {\n return this.run(() => {\n for (const [key, work] of this.state) {\n if (\n work.projectId !== input.projectId ||\n work.id !== input.id ||\n work.status !== input.expectedStatus\n )\n continue\n this.state.set(\n key,\n structuredClone({\n ...work,\n status: input.status,\n availableAt: input.availableAt,\n values: input.values ?? work.values,\n error: input.error,\n })\n )\n return true\n }\n return false\n })\n }\n\n async remove(input: Parameters<OntologyVectorIndexingStorage[\"remove\"]>[0]) {\n await this.run(() => {\n for (const [key, work] of this.state)\n if (work.projectId === input.projectId && work.id === input.id) this.state.delete(key)\n })\n }\n}\n",
|
|
37
|
+
"import { MaterializationConflictError } from \"../../../materialization/errors\"\nimport type { MaterializationSession } from \"../materializations\"\nimport type { OntologyVectorStorage, StoredObjectVector } from \"../vectors\"\n\nexport function vectorObjectKey(projectId: string, ref: StoredObjectVector[\"ref\"]): string {\n return JSON.stringify([projectId, ref.objectTypeId, ref.primaryId])\n}\n\nexport class InMemoryOntologyVectorStorage implements OntologyVectorStorage {\n constructor(\n private readonly state: Map<string, Map<string, StoredObjectVector>>,\n private readonly assertSession: (\n session: MaterializationSession,\n projectId: string,\n commitId?: string\n ) => void,\n private readonly runRootOperation: <T>(run: () => T) => Promise<T>\n ) {}\n\n async list(input: Parameters<OntologyVectorStorage[\"list\"]>[0]) {\n return this.listBatch({ projectId: input.projectId, refs: [input.ref] })\n }\n\n async listBatch(input: Parameters<OntologyVectorStorage[\"listBatch\"]>[0]) {\n return this.runRootOperation(() =>\n [...new Set(input.refs.map((ref) => vectorObjectKey(input.projectId, ref)))].flatMap((key) =>\n [...(this.state.get(key)?.values() ?? [])].map(({ values: _values, ...metadata }) =>\n structuredClone(metadata)\n )\n )\n )\n }\n\n async removeBatch(input: Parameters<OntologyVectorStorage[\"removeBatch\"]>[0]) {\n this.assertSession(input.session, input.projectId)\n for (const entry of input.entries) {\n await this.remove({ session: input.session, projectId: input.projectId, ...entry })\n }\n }\n\n async write(input: Parameters<OntologyVectorStorage[\"write\"]>[0]) {\n this.assertSession(input.session, input.projectId, input.value.lastCommitId)\n const key = vectorObjectKey(input.projectId, input.value.ref)\n const profiles = this.state.get(key) ?? new Map<string, StoredObjectVector>()\n this.assertRevision(profiles.get(input.value.profile), input.expectedCommitId)\n profiles.set(input.value.profile, structuredClone(input.value))\n this.state.set(key, profiles)\n }\n\n async writeBatch(input: Parameters<OntologyVectorStorage[\"writeBatch\"]>[0]): Promise<void> {\n for (const entry of input.entries) {\n await this.write({ session: input.session, projectId: input.projectId, ...entry })\n }\n }\n\n async remove(input: Parameters<OntologyVectorStorage[\"remove\"]>[0]) {\n this.assertSession(input.session, input.projectId)\n const key = vectorObjectKey(input.projectId, input.ref)\n const profiles = this.state.get(key)\n this.assertRevision(profiles?.get(input.profile), input.expectedCommitId)\n profiles?.delete(input.profile)\n if (profiles?.size === 0) this.state.delete(key)\n }\n\n private assertRevision(current: StoredObjectVector | undefined, expected: string | null) {\n if ((current?.lastCommitId ?? null) !== expected) {\n throw new MaterializationConflictError(\n \"effective-state\",\n \"Vector changed since it was prepared.\"\n )\n }\n }\n}\n",
|
|
38
|
+
"import type { InMemoryObjectStorage } from \"../../objects/in-memory\"\nimport { getInMemoryObjectMaterializerAdapter } from \"../../objects/in-memory\"\nimport type { InMemoryTimeseriesStorage } from \"../../timeseries/store\"\nimport type { OntologyStorage } from \"..\"\nimport type { ProviderMaterializationTransactionLifecycle } from \"../provider\"\nimport type { AssertSourceMaterializationExecution } from \"../sources\"\nimport { InMemoryOntologyCommitStorage } from \"./commits\"\nimport { InMemoryOntologyMaterializationStorage } from \"./materializations\"\nimport { InMemoryOntologyOutboxStorage } from \"./outbox\"\nimport {\n cloneOntologyState,\n createInMemoryOntologyState,\n type InMemoryOntologyState,\n type InMemoryOntologyStorageTestHooks,\n restoreOntologyState,\n} from \"./shared-state\"\nimport { InMemoryOntologySourceStorage } from \"./sources\"\nimport {\n type InMemoryOntologyStorageTestingAdapter,\n registerInMemoryOntologyStorageTestingAdapter,\n} from \"./testing\"\n\nexport type InMemoryOntologyStorageSnapshot = InMemoryOntologyState\n\ninterface InMemoryOntologyStorageOptions {\n readonly runRootOperation: <T>(run: () => Promise<T> | T) => Promise<T>\n readonly getTransactionToken: () => object | null\n readonly getMaterializationLifecycle: () => ProviderMaterializationTransactionLifecycle | null\n readonly assertSourceMaterializationExecution: AssertSourceMaterializationExecution\n readonly executionExists: (projectId: string, executionId: string) => Promise<boolean>\n}\n\nimport { InMemoryVectorIndexingStorage } from \"./vector-indexing\"\nimport { InMemoryOntologyVectorStorage, vectorObjectKey } from \"./vectors\"\n\nexport class InMemoryOntologyStorage implements OntologyStorage {\n private readonly state = createInMemoryOntologyState()\n readonly vectorIndexing: InMemoryVectorIndexingStorage\n readonly vectors: InMemoryOntologyVectorStorage\n readonly commits: InMemoryOntologyCommitStorage\n readonly sources: InMemoryOntologySourceStorage\n readonly materializations: InMemoryOntologyMaterializationStorage\n readonly outbox: InMemoryOntologyOutboxStorage\n private testHooks: InMemoryOntologyStorageTestHooks = {}\n private readonly testingAdapter: InMemoryOntologyStorageTestingAdapter = {\n setTestHooks: (hooks) => this.setTestHooks(hooks),\n snapshot: () => this.snapshot(),\n }\n\n constructor(\n objects: InMemoryObjectStorage,\n timeseries: InMemoryTimeseriesStorage,\n options: InMemoryOntologyStorageOptions\n ) {\n this.vectorIndexing = new InMemoryVectorIndexingStorage(\n this.state.vectorIndexing,\n (session, projectId) => this.materializations.assertVectorSession(session, projectId),\n options.runRootOperation\n )\n this.vectors = new InMemoryOntologyVectorStorage(\n this.state.vectors,\n (session, projectId, commitId) =>\n this.materializations.assertVectorSession(session, projectId, commitId),\n options.runRootOperation\n )\n getInMemoryObjectMaterializerAdapter(objects).setVectorReader((projectId, ref, profile) =>\n this.state.vectors.get(vectorObjectKey(projectId, ref))?.get(profile)\n )\n this.commits = new InMemoryOntologyCommitStorage(this.state, options.runRootOperation)\n this.sources = new InMemoryOntologySourceStorage(\n this.state,\n options.runRootOperation,\n options.assertSourceMaterializationExecution\n )\n this.outbox = new InMemoryOntologyOutboxStorage(this.state, options.runRootOperation)\n this.materializations = new InMemoryOntologyMaterializationStorage(\n this.state,\n objects,\n timeseries,\n options.getTransactionToken,\n options.getMaterializationLifecycle,\n options.executionExists,\n {\n beforeRead: (boundary) => this.testHooks.beforeRead?.(boundary),\n beforeWrite: (boundary, ordinal) => this.testHooks.beforeWrite?.(boundary, ordinal),\n observeBuffer: (boundary, rows) => this.testHooks.observeBuffer?.(boundary, rows),\n observeWork: (records) => this.testHooks.observeWork?.(records),\n }\n )\n registerInMemoryOntologyStorageTestingAdapter(this, this.testingAdapter)\n }\n\n /** @internal Test-only failure injection; not part of OntologyStorage. */\n setTestHooks(hooks: InMemoryOntologyStorageTestHooks): void {\n this.testHooks = hooks\n }\n\n /** @internal Register a decorated facade as an alias for the same test adapter. */\n registerTestingAlias(storage: OntologyStorage): void {\n registerInMemoryOntologyStorageTestingAdapter(storage, this.testingAdapter)\n }\n\n snapshot(): InMemoryOntologyStorageSnapshot {\n return cloneOntologyState(this.state)\n }\n\n restore(snapshot: InMemoryOntologyStorageSnapshot): void {\n restoreOntologyState(this.state, snapshot)\n }\n\n completeTransaction(transactionToken: object): void {\n this.materializations.deactivateTransaction(transactionToken)\n }\n}\n\nexport type { InMemoryOntologyStorageTestHooks } from \"./shared-state\"\n",
|
|
39
|
+
"export type RunListOrder = \"asc\" | \"desc\"\n\nexport type { ListPage as RunListPage, ListWindow as RunListWindow } from \"./pagination\"\nexport { paginate } from \"./pagination\"\n\nexport interface StartedAtRunRecord<TStatus extends string = string> {\n readonly id: string\n readonly status: TStatus\n readonly startedAt?: Date\n readonly queuedAt?: Date\n}\n\nexport function storageKey(projectId: string, id: string): string {\n return `${projectId}:${id}`\n}\n\nexport function cloneRecord<T>(record: T): T {\n return structuredClone(record)\n}\n\nexport function hasEmptyStatuses(input: { readonly statuses?: readonly unknown[] }): boolean {\n return input.statuses !== undefined && input.statuses.length === 0\n}\n\nexport function toStatusSet<TStatus extends string>(\n statuses: readonly TStatus[] | undefined\n): ReadonlySet<TStatus> | null {\n return statuses ? new Set(statuses) : null\n}\n\nexport function matchesRunListDateFilters<TStatus extends string>(\n record: StartedAtRunRecord<TStatus>,\n filters: {\n readonly statuses: ReadonlySet<TStatus> | null\n readonly startedAfter?: Date\n readonly startedBefore?: Date\n }\n): boolean {\n if (filters.statuses && !filters.statuses.has(record.status)) {\n return false\n }\n\n const startedAt = effectiveStartedAt(record)\n\n if (filters.startedAfter && startedAt < filters.startedAfter) {\n return false\n }\n\n if (filters.startedBefore && startedAt > filters.startedBefore) {\n return false\n }\n\n return true\n}\n\nexport function compareStartedAt(\n left: { readonly id: string; readonly startedAt?: Date; readonly queuedAt?: Date },\n right: { readonly id: string; readonly startedAt?: Date; readonly queuedAt?: Date },\n order: RunListOrder\n): number {\n const delta = effectiveStartedAt(left).getTime() - effectiveStartedAt(right).getTime()\n if (delta !== 0) {\n return order === \"asc\" ? delta : -delta\n }\n\n if (left.id === right.id) {\n return 0\n }\n\n return order === \"asc\" ? left.id.localeCompare(right.id) : right.id.localeCompare(left.id)\n}\n\nexport function latestStartedAtByOwnerId<\n TRecord extends { readonly id: string; readonly startedAt?: Date; readonly queuedAt?: Date },\n>(\n records: readonly TRecord[],\n ownerIds: readonly string[],\n ownerIdFor: (record: TRecord) => string\n): readonly TRecord[] {\n const uniqueOwnerIds = [...new Set(ownerIds)]\n if (uniqueOwnerIds.length === 0) {\n return []\n }\n\n const requested = new Set(uniqueOwnerIds)\n const latestByOwnerId = new Map<string, TRecord>()\n\n for (const record of records) {\n const ownerId = ownerIdFor(record)\n if (!requested.has(ownerId)) {\n continue\n }\n\n const current = latestByOwnerId.get(ownerId)\n if (!current || compareStartedAt(record, current, \"desc\") < 0) {\n latestByOwnerId.set(ownerId, record)\n }\n }\n\n return uniqueOwnerIds.flatMap((ownerId) => {\n const record = latestByOwnerId.get(ownerId)\n return record ? [record] : []\n })\n}\n\nfunction effectiveStartedAt(record: {\n readonly id: string\n readonly startedAt?: Date\n readonly queuedAt?: Date\n}): Date {\n const value = record.startedAt ?? record.queuedAt\n if (!value) {\n throw new Error(`[Sixb] Run '${record.id}' has neither startedAt nor queuedAt.`)\n }\n return value\n}\n",
|
|
40
|
+
"import type { SixbErrorCode, SixbFailure } from \"../../errors/types\"\nimport type { DatasetVersionRef, DatasetWriteMode } from \"../../lake-storage\"\n\nexport type PipelineRunStatus = \"queued\" | \"running\" | \"succeeded\" | \"failed\" | \"cancelled\"\nexport type PipelineStepRunStatus = Exclude<PipelineRunStatus, \"queued\">\n/** Error codes a pipeline or pipeline-step run can persist and expose. */\nexport const PIPELINE_RUN_FAILURE_CODES = [\n \"internal.unexpected\",\n \"runtime.cancelled\",\n \"queue.enqueue_failed\",\n \"pipeline.step_failed\",\n] as const satisfies readonly [SixbErrorCode, ...SixbErrorCode[]]\n\nexport type PipelineRunFailureCode = (typeof PIPELINE_RUN_FAILURE_CODES)[number]\n\nexport interface PipelineRunRecord {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly pipelineId: string\n readonly status: PipelineRunStatus\n readonly queuedAt: Date\n readonly startedAt?: Date\n readonly finishedAt?: Date\n /** Final step output in sequential V1. */\n readonly output?: DatasetVersionRef\n readonly error?: SixbFailure<PipelineRunFailureCode>\n}\n\nexport interface PipelineStepRunRecord {\n readonly id: string\n readonly projectId: string\n readonly pipelineRunId: string\n readonly pipelineId: string\n readonly stepId: string\n readonly datasetId: string\n readonly mode: DatasetWriteMode\n readonly status: PipelineStepRunStatus\n readonly startedAt: Date\n readonly finishedAt?: Date\n readonly inputs: readonly DatasetVersionRef[]\n readonly output?: DatasetVersionRef\n readonly rowsWritten?: number\n readonly error?: SixbFailure<PipelineRunFailureCode>\n}\n\nexport interface QueuePipelineRunInput {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly pipelineId: string\n readonly queuedAt?: Date\n}\n\nexport interface StartPipelineRunInput {\n readonly id: string\n readonly projectId: string\n readonly startedAt?: Date\n}\n\nexport type FinishPipelineRunInput =\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"succeeded\"\n readonly finishedAt?: Date\n readonly output?: DatasetVersionRef\n }\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"failed\"\n readonly finishedAt?: Date\n readonly error: SixbFailure<PipelineRunFailureCode>\n }\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"cancelled\"\n readonly finishedAt?: Date\n readonly error?: SixbFailure<PipelineRunFailureCode>\n }\n\nexport interface StartPipelineStepRunInput {\n readonly id: string\n readonly projectId: string\n readonly pipelineRunId: string\n readonly pipelineId: string\n readonly stepId: string\n readonly datasetId: string\n readonly mode: DatasetWriteMode\n readonly startedAt?: Date\n readonly inputs: readonly DatasetVersionRef[]\n}\n\nexport type FinishPipelineStepRunInput =\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"succeeded\"\n readonly finishedAt?: Date\n readonly output: DatasetVersionRef\n readonly rowsWritten?: number\n }\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"failed\" | \"cancelled\"\n readonly finishedAt?: Date\n readonly rowsWritten?: number\n readonly error?: SixbFailure<PipelineRunFailureCode>\n }\n\nexport interface ListPipelineRunsInput {\n readonly projectId: string\n readonly pipelineId?: string\n readonly pipelineIds?: readonly string[]\n readonly statuses?: readonly PipelineRunStatus[]\n readonly startedAfter?: Date\n readonly startedBefore?: Date\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListPipelineRunsResult {\n readonly runs: readonly PipelineRunRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\nexport interface ListLatestPipelineRunsInput {\n readonly projectId: string\n readonly pipelineIds: readonly string[]\n}\n\nexport interface ListLatestPipelineRunsResult {\n readonly runs: readonly PipelineRunRecord[]\n}\n\nexport interface ListPipelineStepRunsInput {\n readonly projectId: string\n readonly pipelineRunId?: string\n readonly pipelineId?: string\n readonly stepId?: string\n readonly datasetId?: string\n readonly statuses?: readonly PipelineStepRunStatus[]\n readonly startedAfter?: Date\n readonly startedBefore?: Date\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListPipelineStepRunsResult {\n readonly steps: readonly PipelineStepRunRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\nexport interface PipelineRunStorage {\n queue(input: QueuePipelineRunInput): Promise<PipelineRunRecord>\n start(input: StartPipelineRunInput): Promise<PipelineRunRecord>\n finish(input: FinishPipelineRunInput): Promise<PipelineRunRecord>\n startStep(input: StartPipelineStepRunInput): Promise<PipelineStepRunRecord>\n finishStep(input: FinishPipelineStepRunInput): Promise<PipelineStepRunRecord>\n getById(params: { projectId: string; id: string }): Promise<PipelineRunRecord | null>\n list(input: ListPipelineRunsInput): Promise<ListPipelineRunsResult>\n listLatestByPipelineIds(input: ListLatestPipelineRunsInput): Promise<ListLatestPipelineRunsResult>\n listSteps(input: ListPipelineStepRunsInput): Promise<ListPipelineStepRunsResult>\n}\n",
|
|
41
|
+
"import { parseSixbFailure } from \"../../errors/internal\"\nimport type { SixbFailure } from \"../../errors/types\"\nimport type { ExecutionStorage } from \"../executions\"\nimport {\n cloneRecord,\n compareStartedAt,\n hasEmptyStatuses,\n latestStartedAtByOwnerId,\n matchesRunListDateFilters,\n paginate,\n storageKey,\n toStatusSet,\n} from \"../run-listing\"\nimport { PipelineRunError } from \"./errors\"\nimport { canRequeuePipelineRunAfterEnqueueFailure } from \"./idempotency\"\nimport { assertPipelineRunExecution } from \"./provider\"\nimport type {\n FinishPipelineRunInput,\n FinishPipelineStepRunInput,\n ListLatestPipelineRunsInput,\n ListLatestPipelineRunsResult,\n ListPipelineRunsInput,\n ListPipelineRunsResult,\n ListPipelineStepRunsInput,\n ListPipelineStepRunsResult,\n PipelineRunFailureCode,\n PipelineRunRecord,\n PipelineRunStorage,\n PipelineStepRunRecord,\n QueuePipelineRunInput,\n StartPipelineRunInput,\n StartPipelineStepRunInput,\n} from \"./types\"\nimport { PIPELINE_RUN_FAILURE_CODES } from \"./types\"\n\nfunction normalizeError(\n error: SixbFailure<PipelineRunFailureCode> | undefined\n): SixbFailure<PipelineRunFailureCode> | undefined {\n return error ? parseSixbFailure(error, PIPELINE_RUN_FAILURE_CODES) : undefined\n}\n\nfunction assertNonNegativeInteger(value: number | undefined, fieldName: string): void {\n if (value !== undefined && (!Number.isInteger(value) || value < 0)) {\n throw new PipelineRunError(`[Sixb] Pipeline run ${fieldName} must be a non-negative integer.`)\n }\n}\n\nexport class InMemoryPipelineRunStorage implements PipelineRunStorage {\n private readonly runs = new Map<string, PipelineRunRecord>()\n private readonly steps = new Map<string, PipelineStepRunRecord>()\n\n constructor(private readonly executions: ExecutionStorage) {}\n\n snapshot(): InMemoryPipelineRunStorageSnapshot {\n return {\n runs: structuredClone(this.runs),\n steps: structuredClone(this.steps),\n }\n }\n\n restore(snapshot: InMemoryPipelineRunStorageSnapshot): void {\n this.runs.clear()\n for (const [key, record] of structuredClone(snapshot.runs)) {\n this.runs.set(key, record)\n }\n\n this.steps.clear()\n for (const [key, record] of structuredClone(snapshot.steps)) {\n this.steps.set(key, record)\n }\n }\n\n async queue(input: QueuePipelineRunInput): Promise<PipelineRunRecord> {\n const key = storageKey(input.projectId, input.id)\n const existing = this.runs.get(key)\n if (existing && !canRequeuePipelineRunAfterEnqueueFailure(existing, input)) {\n throw new PipelineRunError(\n `[Sixb] Pipeline run '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n if (\n [...this.runs.values()].some(\n (run) =>\n run.projectId === input.projectId &&\n run.id !== input.id &&\n run.executionId === input.executionId\n )\n ) {\n throw new PipelineRunError(\n `[Sixb] Execution '${input.executionId}' already belongs to another Pipeline run.`\n )\n }\n await assertPipelineRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n pipelineId: input.pipelineId,\n })\n\n const queuedAt = new Date(input.queuedAt ?? new Date())\n if (existing) {\n const next: PipelineRunRecord = {\n ...existing,\n status: \"queued\",\n queuedAt,\n startedAt: undefined,\n finishedAt: undefined,\n output: undefined,\n error: undefined,\n }\n this.runs.set(key, cloneRecord(next))\n return cloneRecord(next)\n }\n\n const record: PipelineRunRecord = {\n id: input.id,\n projectId: input.projectId,\n executionId: input.executionId,\n pipelineId: input.pipelineId,\n status: \"queued\",\n queuedAt,\n }\n\n this.runs.set(key, cloneRecord(record))\n return cloneRecord(record)\n }\n\n async start(input: StartPipelineRunInput): Promise<PipelineRunRecord> {\n const key = storageKey(input.projectId, input.id)\n const existing = this.runs.get(key)\n if (!existing) {\n throw new PipelineRunError(\n `[Sixb] Pipeline run '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n if (existing.status !== \"queued\") {\n throw new PipelineRunError(\n `[Sixb] Pipeline run '${input.id}' cannot start from status '${existing.status}'.`\n )\n }\n\n const next: PipelineRunRecord = {\n ...existing,\n status: \"running\",\n startedAt: new Date(input.startedAt ?? new Date()),\n error: undefined,\n }\n this.runs.set(key, cloneRecord(next))\n return cloneRecord(next)\n }\n\n async finish(input: FinishPipelineRunInput): Promise<PipelineRunRecord> {\n const existing = this.requireExistingPipelineRun(input.projectId, input.id)\n const enqueueFailure = input.status === \"failed\" && input.error.code === \"queue.enqueue_failed\"\n if (\n (enqueueFailure && existing.status !== \"queued\") ||\n (!enqueueFailure && existing.status !== \"running\")\n ) {\n throw new PipelineRunError(\n `[Sixb] Pipeline run '${input.id}' cannot finish from status '${existing.status}'.`\n )\n }\n const base: PipelineRunRecord = {\n ...existing,\n status: input.status,\n finishedAt: new Date(input.finishedAt ?? new Date()),\n }\n\n const next: PipelineRunRecord =\n input.status === \"succeeded\"\n ? {\n ...base,\n output: input.output ? cloneRecord(input.output) : undefined,\n error: undefined,\n }\n : {\n ...base,\n output: undefined,\n error: normalizeError(input.error),\n }\n\n this.runs.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async startStep(input: StartPipelineStepRunInput): Promise<PipelineStepRunRecord> {\n const pipelineRun = this.requireRunningPipelineRun(input.projectId, input.pipelineRunId)\n if (pipelineRun.pipelineId !== input.pipelineId) {\n throw new PipelineRunError(\n `[Sixb] Pipeline step run '${input.id}' pipeline '${input.pipelineId}' does not match pipeline run '${input.pipelineRunId}' pipeline '${pipelineRun.pipelineId}'.`\n )\n }\n\n const key = storageKey(input.projectId, input.id)\n if (this.steps.has(key)) {\n throw new PipelineRunError(\n `[Sixb] Pipeline step run '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n const record: PipelineStepRunRecord = {\n id: input.id,\n projectId: input.projectId,\n pipelineRunId: input.pipelineRunId,\n pipelineId: input.pipelineId,\n stepId: input.stepId,\n datasetId: input.datasetId,\n mode: input.mode,\n status: \"running\",\n startedAt: new Date(input.startedAt ?? new Date()),\n inputs: cloneRecord(input.inputs),\n }\n\n this.steps.set(key, cloneRecord(record))\n return cloneRecord(record)\n }\n\n async finishStep(input: FinishPipelineStepRunInput): Promise<PipelineStepRunRecord> {\n assertNonNegativeInteger(input.rowsWritten, \"rowsWritten\")\n\n const existing = this.requireRunningStepRun(input.projectId, input.id)\n\n if (input.status === \"succeeded\" && input.output.datasetId !== existing.datasetId) {\n throw new PipelineRunError(\n `[Sixb] Pipeline step run '${input.id}' output dataset '${input.output.datasetId}' does not match '${existing.datasetId}'.`\n )\n }\n\n const base: PipelineStepRunRecord = {\n ...existing,\n status: input.status,\n finishedAt: new Date(input.finishedAt ?? new Date()),\n rowsWritten: input.rowsWritten ?? existing.rowsWritten,\n }\n\n const next: PipelineStepRunRecord =\n input.status === \"succeeded\"\n ? {\n ...base,\n output: cloneRecord(input.output),\n error: undefined,\n }\n : {\n ...base,\n output: undefined,\n error: normalizeError(input.error),\n }\n\n this.steps.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async getById(params: { projectId: string; id: string }): Promise<PipelineRunRecord | null> {\n const record = this.runs.get(storageKey(params.projectId, params.id))\n return record ? cloneRecord(record) : null\n }\n\n async list(input: ListPipelineRunsInput): Promise<ListPipelineRunsResult> {\n if (hasEmptyStatuses(input) || input.pipelineIds?.length === 0) {\n return {\n runs: [],\n hasMore: false,\n total: 0,\n }\n }\n\n const order = input.order ?? \"desc\"\n const statuses = toStatusSet(input.statuses)\n const pipelineIds = input.pipelineIds ? new Set(input.pipelineIds) : null\n const filtered = [...this.runs.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) => (input.pipelineId ? record.pipelineId === input.pipelineId : true))\n .filter((record) => (pipelineIds ? pipelineIds.has(record.pipelineId) : true))\n .filter((record) =>\n matchesRunListDateFilters(record, {\n statuses,\n startedAfter: input.startedAfter,\n startedBefore: input.startedBefore,\n })\n )\n .sort((left, right) => compareStartedAt(left, right, order))\n\n const { page, total, hasMore } = paginate(filtered, input)\n\n return {\n runs: page.map(cloneRecord),\n hasMore,\n total,\n }\n }\n\n async listLatestByPipelineIds(\n input: ListLatestPipelineRunsInput\n ): Promise<ListLatestPipelineRunsResult> {\n const runs = latestStartedAtByOwnerId(\n [...this.runs.values()].filter((record) => record.projectId === input.projectId),\n input.pipelineIds,\n (record) => record.pipelineId\n )\n\n return {\n runs: runs.map(cloneRecord),\n }\n }\n\n async listSteps(input: ListPipelineStepRunsInput): Promise<ListPipelineStepRunsResult> {\n if (hasEmptyStatuses(input)) {\n return {\n steps: [],\n hasMore: false,\n total: 0,\n }\n }\n\n const order = input.order ?? \"desc\"\n const statuses = toStatusSet(input.statuses)\n const filtered = [...this.steps.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) =>\n input.pipelineRunId ? record.pipelineRunId === input.pipelineRunId : true\n )\n .filter((record) => (input.pipelineId ? record.pipelineId === input.pipelineId : true))\n .filter((record) => (input.stepId ? record.stepId === input.stepId : true))\n .filter((record) => (input.datasetId ? record.datasetId === input.datasetId : true))\n .filter((record) =>\n matchesRunListDateFilters(record, {\n statuses,\n startedAfter: input.startedAfter,\n startedBefore: input.startedBefore,\n })\n )\n .sort((left, right) => compareStartedAt(left, right, order))\n\n const { page, total, hasMore } = paginate(filtered, input)\n\n return {\n steps: page.map(cloneRecord),\n hasMore,\n total,\n }\n }\n\n private requireExistingPipelineRun(projectId: string, id: string): PipelineRunRecord {\n const record = this.runs.get(storageKey(projectId, id))\n if (!record) {\n throw new PipelineRunError(\n `[Sixb] Pipeline run '${id}' not found for project '${projectId}'.`\n )\n }\n\n return record\n }\n\n private requireRunningPipelineRun(projectId: string, id: string): PipelineRunRecord {\n const record = this.requireExistingPipelineRun(projectId, id)\n if (record.status !== \"running\") {\n throw new PipelineRunError(\n `[Sixb] Pipeline run '${id}' for project '${projectId}' is already terminal.`\n )\n }\n\n return record\n }\n\n private requireRunningStepRun(projectId: string, id: string): PipelineStepRunRecord {\n const record = this.steps.get(storageKey(projectId, id))\n if (!record) {\n throw new PipelineRunError(\n `[Sixb] Pipeline step run '${id}' not found for project '${projectId}'.`\n )\n }\n\n if (record.status !== \"running\") {\n throw new PipelineRunError(\n `[Sixb] Pipeline step run '${id}' for project '${projectId}' is already terminal.`\n )\n }\n\n return record\n }\n}\n\nexport interface InMemoryPipelineRunStorageSnapshot {\n readonly runs: Map<string, PipelineRunRecord>\n readonly steps: Map<string, PipelineStepRunRecord>\n}\n",
|
|
42
|
+
"import { randomUUID } from \"node:crypto\"\nimport type { ExecutionStorage } from \"../executions\"\nimport type { AssertSourceMaterializationExecutionInput } from \"../ontology/sources\"\nimport {\n compareStartedAt,\n latestStartedAtByOwnerId,\n matchesRunListDateFilters,\n} from \"../run-listing\"\nimport { ProjectionRunError } from \"./errors\"\nimport {\n advanceProjectionTelemetry,\n assertGenericProgressDoesNotAdvanceTelemetry,\n assertProjectionMissingTarget,\n assertProjectionRunAttempt,\n assertProjectionRunDurableExecution,\n assertProjectionRunIdentityMatches,\n assertProjectionRunListWindow,\n assertProjectionRunNonEmpty,\n assertProjectionRunQueueInput,\n assertProjectionRunRunning,\n assertProjectionRunStartInput,\n canRequeueProjectionRunAfterEnqueueFailure,\n createProjectionRunClaim,\n createProjectionRunRecord,\n failProjectionRunEnqueue,\n finishProjectionRunRecord,\n immutableDatasetVersionConflict,\n mergeProjectionRunProgress,\n planProjectionRunReclaim,\n projectionRunNotFound,\n publicProjectionRunRecord,\n requireTelemetryProjectionRun,\n type StoredProjectionRunRecord,\n staleProjectionRunExecution,\n} from \"./provider\"\nimport {\n type AdvanceProjectionTelemetryCheckpointInput,\n type FailProjectionRunEnqueueInput,\n type FinishProjectionRunInput,\n type ListLatestProjectionRunsInput,\n type ListLatestProjectionRunsResult,\n type ListProjectionRunsInput,\n type ListProjectionRunsResult,\n type LockProjectionRunForMaterializationInput,\n type ProjectionRunClaim,\n type ProjectionRunRecord,\n type ProjectionRunStorage,\n projectionRunObjectTypesVisible,\n type QueueProjectionRunInput,\n type RecordProjectionMissingTargetInput,\n type StartOrReclaimProjectionRunInput,\n type TelemetryProjectionRunRecord,\n type UpdateProjectionRunInput,\n} from \"./types\"\n\ntype RunRootOperation = <T>(run: () => Promise<T> | T) => Promise<T>\nconst runDirectly: RunRootOperation = async <T>(run: () => Promise<T> | T): Promise<T> => run()\n\nfunction projectionRunKey(projectId: string, id: string): string {\n return JSON.stringify([projectId, id])\n}\n\nfunction compareRuns(a: ProjectionRunRecord, b: ProjectionRunRecord, order: \"asc\" | \"desc\") {\n return compareStartedAt(a, b, order)\n}\n\nexport class InMemoryProjectionRunStorage implements ProjectionRunStorage {\n private readonly rows = new Map<string, StoredProjectionRunRecord>()\n /** Durable per-run history prevents a reclaimed execution token from becoming valid again. */\n private readonly executionTokensByRun = new Map<string, Set<string>>()\n private readonly runRootOperation: RunRootOperation\n private readonly createExecutionToken: () => string\n\n constructor(input: {\n readonly executions: ExecutionStorage\n readonly runRootOperation?: RunRootOperation\n readonly executionToken?: () => string\n }) {\n this.executions = input.executions\n this.runRootOperation = input.runRootOperation ?? runDirectly\n this.createExecutionToken = input.executionToken ?? randomUUID\n }\n\n private readonly executions: ExecutionStorage\n\n snapshot(): InMemoryProjectionRunStorageSnapshot {\n return structuredClone({\n rows: this.rows,\n executionTokensByRun: this.executionTokensByRun,\n })\n }\n\n restore(snapshot: InMemoryProjectionRunStorageSnapshot): void {\n this.rows.clear()\n this.executionTokensByRun.clear()\n for (const [key, record] of structuredClone(snapshot.rows)) this.rows.set(key, record)\n for (const [key, tokens] of structuredClone(snapshot.executionTokensByRun)) {\n this.executionTokensByRun.set(key, tokens)\n }\n }\n\n async queue(input: QueueProjectionRunInput): Promise<ProjectionRunRecord> {\n return this.runRootOperation(async () => {\n assertProjectionRunQueueInput(input)\n this.assertDatasetVersionIsImmutable(input)\n const key = projectionRunKey(input.projectId, input.id)\n const existing = this.rows.get(key)\n if (existing && !canRequeueProjectionRunAfterEnqueueFailure(existing, input)) {\n throw new ProjectionRunError(\n `[Sixb] Projection run '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n if (\n [...this.rows.values()].some(\n (run) =>\n run.projectId === input.projectId &&\n run.id !== input.id &&\n run.executionId === input.executionId\n )\n ) {\n throw new ProjectionRunError(\n `[Sixb] Execution '${input.executionId}' already belongs to another Projection run.`\n )\n }\n await assertProjectionRunDurableExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n projectionId: input.identity.projectionId,\n datasetId: input.identity.datasetVersion.datasetId,\n datasetVersionId: input.identity.datasetVersion.versionId,\n })\n const record = createProjectionRunRecord(input)\n this.rows.set(key, structuredClone(record))\n return publicProjectionRunRecord(record)\n })\n }\n\n async startOrReclaim(input: StartOrReclaimProjectionRunInput): Promise<ProjectionRunClaim> {\n return this.runRootOperation(() => {\n assertProjectionRunStartInput(input)\n const key = projectionRunKey(input.projectId, input.id)\n const existing = this.rows.get(key)\n if (!existing) throw projectionRunNotFound(input.projectId, input.id)\n const attempt = planProjectionRunReclaim(existing, input).attempt\n const executionToken = this.issueExecutionToken(key, input.id, existing.executionToken)\n const record: StoredProjectionRunRecord = {\n ...existing,\n status: \"running\",\n attempt,\n executionToken,\n startedAt: existing.startedAt ?? new Date(input.startedAt ?? new Date()),\n finishedAt: undefined,\n error: undefined,\n }\n\n this.rows.set(key, structuredClone(record))\n return createProjectionRunClaim(record)\n })\n }\n\n async failEnqueue(input: FailProjectionRunEnqueueInput): Promise<ProjectionRunRecord> {\n return this.runRootOperation(() => {\n const key = projectionRunKey(input.projectId, input.id)\n const existing = this.rows.get(key)\n if (!existing) throw projectionRunNotFound(input.projectId, input.id)\n const next = failProjectionRunEnqueue(existing, input)\n this.rows.set(key, structuredClone(next))\n return publicProjectionRunRecord(next)\n })\n }\n\n async lockForMaterialization(\n input: LockProjectionRunForMaterializationInput\n ): Promise<ProjectionRunRecord> {\n return this.runRootOperation(() => publicProjectionRunRecord(this.requireExecution(input)))\n }\n\n /** @internal The caller must already hold InMemoryStorage's root operation lock. */\n assertSourceMaterializationExecutionUnlocked(\n input: AssertSourceMaterializationExecutionInput\n ): void {\n assertProjectionRunNonEmpty(input.source.projectionId, \"projectionId\")\n assertProjectionRunNonEmpty(input.execution.executionToken, \"executionToken\")\n const record = this.requireRunning(input.projectId, input.execution.projectionRunId)\n if (\n record.identity.projectionId !== input.source.projectionId ||\n record.identity.protocol !== \"replacement\"\n ) {\n throw new ProjectionRunError(\n `[Sixb] Projection run '${record.id}' does not own replacement source '${input.source.projectionId}'.`\n )\n }\n if (record.executionToken !== input.execution.executionToken) {\n throw staleProjectionRunExecution(record.id)\n }\n if (input.identity) {\n assertProjectionRunIdentityMatches(record, {\n projectionId: input.source.projectionId,\n ...input.identity,\n })\n }\n }\n\n async update(input: UpdateProjectionRunInput): Promise<ProjectionRunRecord> {\n return this.runRootOperation(() => {\n const existing = this.requireExecution(input)\n assertGenericProgressDoesNotAdvanceTelemetry(existing, input.progress)\n const next = {\n ...existing,\n progress: mergeProjectionRunProgress(existing.progress, input.progress),\n }\n this.rows.set(projectionRunKey(input.projectId, input.id), structuredClone(next))\n return publicProjectionRunRecord(next)\n })\n }\n async advanceTelemetryCheckpoint(\n input: AdvanceProjectionTelemetryCheckpointInput\n ): Promise<TelemetryProjectionRunRecord> {\n return this.runRootOperation(() => {\n const existing = this.requireTelemetryExecution(input)\n const advance = advanceProjectionTelemetry(existing, input)\n const next: TelemetryProjectionRunRecord & { readonly executionToken: string } = {\n ...existing,\n progress: advance.progress,\n telemetryCheckpoint: advance.checkpoint,\n missingTarget: undefined,\n }\n this.rows.set(projectionRunKey(input.projectId, input.id), structuredClone(next))\n return publicProjectionRunRecord(next) as TelemetryProjectionRunRecord\n })\n }\n\n async recordMissingTarget(\n input: RecordProjectionMissingTargetInput\n ): Promise<TelemetryProjectionRunRecord> {\n return this.runRootOperation(() => {\n const existing = this.requireTelemetryExecution(input)\n const next: TelemetryProjectionRunRecord & { readonly executionToken: string } = {\n ...existing,\n missingTarget: assertProjectionMissingTarget(existing, input.missingTarget),\n }\n this.rows.set(projectionRunKey(input.projectId, input.id), structuredClone(next))\n return publicProjectionRunRecord(next) as TelemetryProjectionRunRecord\n })\n }\n\n async finish(input: FinishProjectionRunInput): Promise<ProjectionRunRecord> {\n return this.runRootOperation(() => {\n const existing = this.requireExecution(input)\n const next = finishProjectionRunRecord(existing, input)\n this.rows.set(projectionRunKey(input.projectId, input.id), structuredClone(next))\n return publicProjectionRunRecord(next)\n })\n }\n\n async getById(params: { projectId: string; id: string }): Promise<ProjectionRunRecord | null> {\n return this.runRootOperation(() => {\n const record = this.rows.get(projectionRunKey(params.projectId, params.id))\n return record ? publicProjectionRunRecord(record) : null\n })\n }\n\n async list(input: ListProjectionRunsInput): Promise<ListProjectionRunsResult> {\n return this.runRootOperation(() => {\n assertProjectionRunNonEmpty(input.projectId, \"projectId\")\n assertProjectionRunListWindow(input.limit, \"limit\")\n assertProjectionRunListWindow(input.offset, \"offset\")\n if (input.statuses?.length === 0) return { runs: [], hasMore: false, total: 0 }\n\n const order = input.order ?? \"desc\"\n const offset = input.offset ?? 0\n const limit = input.limit ?? this.rows.size\n const statuses = input.statuses ? new Set(input.statuses) : null\n const objectTypeIds = input.objectTypeIds ? new Set(input.objectTypeIds) : null\n const filtered = [...this.rows.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) =>\n input.projectionId ? record.identity.projectionId === input.projectionId : true\n )\n .filter((record) =>\n input.projectionKind ? record.identity.projectionKind === input.projectionKind : true\n )\n .filter((record) =>\n input.datasetId ? record.identity.datasetVersion.datasetId === input.datasetId : true\n )\n .filter((record) =>\n input.datasetVersionId\n ? record.identity.datasetVersion.versionId === input.datasetVersionId\n : true\n )\n .filter((record) =>\n objectTypeIds\n ? projectionRunObjectTypesVisible(record, (id) => objectTypeIds.has(id))\n : true\n )\n .filter((record) => (statuses ? statuses.has(record.status) : true))\n .filter((record) =>\n matchesRunListDateFilters(record, {\n statuses,\n startedAfter: input.startedAfter,\n startedBefore: input.startedBefore,\n })\n )\n .sort((left, right) => compareRuns(left, right, order))\n\n const total = filtered.length\n const runs = filtered.slice(offset, offset + limit).map(publicProjectionRunRecord)\n return { runs, hasMore: offset + runs.length < total, total }\n })\n }\n\n async listLatestByProjectionIds(\n input: ListLatestProjectionRunsInput\n ): Promise<ListLatestProjectionRunsResult> {\n return this.runRootOperation(() => {\n const runs = latestStartedAtByOwnerId(\n [...this.rows.values()].filter((record) => record.projectId === input.projectId),\n input.projectionIds,\n (record) => record.identity.projectionId\n )\n return { runs: runs.map(publicProjectionRunRecord) }\n })\n }\n\n private assertDatasetVersionIsImmutable(input: QueueProjectionRunInput): void {\n for (const candidate of this.rows.values()) {\n if (\n candidate.projectId === input.projectId &&\n candidate.id !== input.id &&\n candidate.identity.datasetVersion.datasetId === input.identity.datasetVersion.datasetId &&\n candidate.identity.datasetVersion.versionId === input.identity.datasetVersion.versionId &&\n candidate.identity.datasetVersion.createdAt !== input.identity.datasetVersion.createdAt\n ) {\n throw immutableDatasetVersionConflict(input.identity)\n }\n }\n }\n\n private issueExecutionToken(\n key: string,\n runId: string,\n currentToken: string | undefined\n ): string {\n const executionToken = this.createExecutionToken()\n assertProjectionRunNonEmpty(executionToken, \"executionToken\")\n const usedTokens = this.executionTokensByRun.get(key) ?? new Set<string>()\n if (currentToken) usedTokens.add(currentToken)\n if (usedTokens.has(executionToken)) {\n throw new ProjectionRunError(\n `[Sixb] Projection run '${runId}' execution token was already used.`\n )\n }\n usedTokens.add(executionToken)\n this.executionTokensByRun.set(key, usedTokens)\n return executionToken\n }\n\n private requireExecution(\n input: LockProjectionRunForMaterializationInput\n ): StoredProjectionRunRecord & { readonly executionToken: string } {\n const record = this.requireRunning(input.projectId, input.id)\n assertProjectionRunAttempt(record, input)\n return record\n }\n\n private requireTelemetryExecution(\n input: LockProjectionRunForMaterializationInput\n ): TelemetryProjectionRunRecord & { readonly executionToken: string } {\n const record = this.requireExecution(input)\n return requireTelemetryProjectionRun(record)\n }\n\n private requireRunning(projectId: string, id: string): StoredProjectionRunRecord {\n assertProjectionRunNonEmpty(projectId, \"projectId\")\n assertProjectionRunNonEmpty(id, \"id\")\n const record = this.rows.get(projectionRunKey(projectId, id))\n if (!record) {\n throw projectionRunNotFound(projectId, id)\n }\n assertProjectionRunRunning(record)\n return record\n }\n}\n\nexport interface InMemoryProjectionRunStorageSnapshot {\n readonly rows: Map<string, StoredProjectionRunRecord>\n readonly executionTokensByRun: Map<string, Set<string>>\n}\n",
|
|
43
|
+
"import type {\n RuleEventSubject,\n StoredRuleResolvedEvent,\n StoredRuleTriggeredEvent,\n} from \"../../events\"\nimport type {\n ListActiveRuleStatesInput,\n ListActiveRuleStatesResult,\n ListRuleStatesReconciliationPageInput,\n ListRuleStatesReconciliationPageResult,\n RuleStateCursor,\n RuleStateRecord,\n RuleStateTransitionEvent,\n RulesStorage,\n} from \"./types\"\n\nfunction stateKey(params: {\n readonly projectId: string\n readonly ruleId: string\n readonly subject: RuleEventSubject\n}): string {\n return JSON.stringify([\n params.projectId,\n params.ruleId,\n params.subject.kind,\n params.subject.objectTypeId,\n params.subject.primaryId,\n ])\n}\n\nfunction cloneRuleStateRecord(record: RuleStateRecord): RuleStateRecord {\n return structuredClone(record)\n}\n\nfunction compareRuleStateRecords(\n left: RuleStateRecord,\n right: RuleStateRecord,\n order: \"asc\" | \"desc\"\n): number {\n const direction = order === \"asc\" ? 1 : -1\n const fields = [\n left.triggeredAt.localeCompare(right.triggeredAt),\n left.ruleId.localeCompare(right.ruleId),\n left.subject.objectTypeId.localeCompare(right.subject.objectTypeId),\n left.subject.primaryId.localeCompare(right.subject.primaryId),\n ]\n\n for (const value of fields) {\n if (value !== 0) {\n return value * direction\n }\n }\n\n return 0\n}\n\nfunction compareRuleStateIdentity(left: RuleStateRecord, right: RuleStateRecord): number {\n return (\n left.ruleId.localeCompare(right.ruleId) ||\n left.subject.objectTypeId.localeCompare(right.subject.objectTypeId) ||\n left.subject.primaryId.localeCompare(right.subject.primaryId)\n )\n}\n\nfunction compareCursor(record: RuleStateRecord, cursor: RuleStateCursor): number {\n return (\n record.ruleId.localeCompare(cursor.ruleId) ||\n record.subject.objectTypeId.localeCompare(cursor.objectTypeId) ||\n record.subject.primaryId.localeCompare(cursor.primaryId)\n )\n}\n\nexport class InMemoryRulesStorage implements RulesStorage {\n private readonly active = new Map<string, RuleStateRecord>()\n\n snapshot(): InMemoryRulesStorageSnapshot {\n return structuredClone(this.active)\n }\n\n restore(snapshot: InMemoryRulesStorageSnapshot): void {\n this.active.clear()\n for (const [key, record] of structuredClone(snapshot)) {\n this.active.set(key, record)\n }\n }\n\n async getActive(params: {\n projectId: string\n ruleId: string\n subject: RuleEventSubject\n }): Promise<RuleStateRecord | null> {\n const record = this.active.get(stateKey(params))\n return record ? cloneRuleStateRecord(record) : null\n }\n\n async getActiveBatch(params: {\n projectId: string\n items: readonly { readonly ruleId: string; readonly subject: RuleEventSubject }[]\n }): Promise<readonly RuleStateRecord[]> {\n return params.items.flatMap((item) => {\n const record = this.active.get(stateKey({ projectId: params.projectId, ...item }))\n return record ? [cloneRuleStateRecord(record)] : []\n })\n }\n\n async listActive(input: ListActiveRuleStatesInput): Promise<ListActiveRuleStatesResult> {\n if (input.objectTypeIds?.length === 0) {\n return { states: [], hasMore: false, total: 0 }\n }\n\n const order = input.order ?? \"desc\"\n const offset = input.offset ?? 0\n const objectTypeIds = input.objectTypeIds ? new Set(input.objectTypeIds) : null\n const states = [...this.active.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) => !input.ruleId || record.ruleId === input.ruleId)\n .filter((record) => !input.objectTypeId || record.subject.objectTypeId === input.objectTypeId)\n .filter((record) => (objectTypeIds ? objectTypeIds.has(record.subject.objectTypeId) : true))\n .filter((record) => !input.primaryId || record.subject.primaryId === input.primaryId)\n .sort((left, right) => compareRuleStateRecords(left, right, order))\n\n const total = states.length\n const windowed =\n input.limit === undefined ? states.slice(offset) : states.slice(offset, offset + input.limit)\n\n return {\n states: windowed.map(cloneRuleStateRecord),\n hasMore: offset + windowed.length < total,\n total,\n }\n }\n\n async listReconciliationPage(\n input: ListRuleStatesReconciliationPageInput\n ): Promise<ListRuleStatesReconciliationPageResult> {\n const rows = [...this.active.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) => record.subject.kind === \"object\")\n .filter((record) => !input.after || compareCursor(record, input.after) > 0)\n .sort(compareRuleStateIdentity)\n .slice(0, input.limit + 1)\n const hasMore = rows.length > input.limit\n const states = rows.slice(0, input.limit).map(cloneRuleStateRecord)\n const last = states.at(-1)\n return {\n states,\n ...(hasMore && last\n ? {\n next: {\n ruleId: last.ruleId,\n objectTypeId: last.subject.objectTypeId,\n primaryId: last.subject.primaryId,\n },\n }\n : {}),\n }\n }\n\n async applyTriggered(event: StoredRuleTriggeredEvent): Promise<void> {\n const record: RuleStateRecord = {\n projectId: event.projectId,\n ruleId: event.payload.ruleId,\n subject: structuredClone(event.payload.subject),\n triggeredAt: event.payload.triggeredAt,\n }\n\n this.active.set(stateKey(record), cloneRuleStateRecord(record))\n }\n\n async applyResolved(event: StoredRuleResolvedEvent): Promise<void> {\n this.active.delete(\n stateKey({\n projectId: event.projectId,\n ruleId: event.payload.ruleId,\n subject: event.payload.subject,\n })\n )\n }\n\n async applyTransitions(events: readonly RuleStateTransitionEvent[]): Promise<void> {\n for (const event of events) {\n if (event.type === \"rule.triggered\") {\n await this.applyTriggered(event)\n } else {\n await this.applyResolved(event)\n }\n }\n }\n}\n\nexport type InMemoryRulesStorageSnapshot = Map<string, RuleStateRecord>\n",
|
|
44
|
+
"import { ShareGrantStorageError } from \"./errors\"\nimport {\n cloneShareGrantRecord,\n normalizeGetShareGrantByIdInput,\n normalizeListShareGrantsInput,\n normalizeRevokeShareGrantInput,\n normalizeShareGrantCreate,\n parseShareGrantRecord,\n} from \"./record\"\nimport type {\n CreateShareGrantInput,\n GetShareGrantByIdInput,\n ListShareGrantsInput,\n ListShareGrantsResult,\n RevokeShareGrantInput,\n ShareGrantRecord,\n ShareGrantStorage,\n} from \"./types\"\n\nexport class InMemoryShareGrantStorage implements ShareGrantStorage {\n private rows = new Map<string, ShareGrantRecord>()\n\n async create(input: CreateShareGrantInput): Promise<ShareGrantRecord> {\n const record = normalizeShareGrantCreate(input)\n const key = rowKey(record.projectId, record.id)\n const duplicateTokenHash = [...this.rows.values()].some(\n (current) => current.projectId === record.projectId && current.tokenHash === record.tokenHash\n )\n if (this.rows.has(key) || duplicateTokenHash) {\n throw new ShareGrantStorageError(\n \"duplicate\",\n `[Sixb] Share grant '${record.id}' conflicts with an existing record.`\n )\n }\n\n this.rows.set(key, record)\n return cloneShareGrantRecord(record)\n }\n\n async getById(input: GetShareGrantByIdInput): Promise<ShareGrantRecord | null> {\n const normalized = normalizeGetShareGrantByIdInput(input)\n const record = this.rows.get(rowKey(normalized.projectId, normalized.id))\n return record ? cloneShareGrantRecord(record) : null\n }\n\n async list(input: ListShareGrantsInput): Promise<ListShareGrantsResult> {\n const normalized = normalizeListShareGrantsInput(input)\n const matching = [...this.rows.values()]\n .filter(\n (record) =>\n record.projectId === normalized.projectId &&\n (normalized.definitionId === undefined ||\n record.definitionId === normalized.definitionId) &&\n (normalized.target === undefined ||\n (record.target.objectTypeId === normalized.target.objectTypeId &&\n record.target.primaryId === normalized.target.primaryId)) &&\n (normalized.includeRevoked || record.revokedAt === undefined) &&\n (normalized.includeExpired || record.expiresAt.getTime() > normalized.now.getTime())\n )\n .sort(compareShareGrants)\n\n const total = matching.length\n const grants = matching\n .slice(normalized.offset, normalized.offset + normalized.limit)\n .map(cloneShareGrantRecord)\n return {\n grants,\n total,\n hasMore: normalized.offset + grants.length < total,\n }\n }\n\n async revoke(input: RevokeShareGrantInput): Promise<ShareGrantRecord | null> {\n const normalized = normalizeRevokeShareGrantInput(input)\n const key = rowKey(normalized.projectId, normalized.id)\n const current = this.rows.get(key)\n if (!current) return null\n if (current.revokedAt) return cloneShareGrantRecord(current)\n\n const revocation = normalizeRevokeShareGrantInput(normalized, current.createdAt)\n const updated: ShareGrantRecord = {\n ...current,\n revokedAt: new Date(revocation.revokedAt),\n revokedBy: { ...revocation.revokedBy },\n }\n this.rows.set(key, updated)\n return cloneShareGrantRecord(updated)\n }\n\n snapshot(): ReadonlyMap<string, ShareGrantRecord> {\n return new Map([...this.rows].map(([key, record]) => [key, cloneShareGrantRecord(record)]))\n }\n\n restore(snapshot: ReadonlyMap<string, ShareGrantRecord>): void {\n this.rows = new Map([...snapshot].map(([key, record]) => [key, parseShareGrantRecord(record)]))\n }\n}\n\nfunction compareShareGrants(left: ShareGrantRecord, right: ShareGrantRecord): number {\n const created = right.createdAt.getTime() - left.createdAt.getTime()\n if (created !== 0) return created\n return left.id === right.id ? 0 : left.id < right.id ? 1 : -1\n}\n\nfunction rowKey(projectId: string, id: string): string {\n return `${projectId}\\0${id}`\n}\n",
|
|
45
|
+
"import type { ShareGrantStorage } from \"../share-grants\"\nimport { ShareSessionStorageError } from \"./errors\"\nimport {\n cloneShareSessionRecord,\n normalizeGetShareSessionByIdInput,\n normalizeRenewShareSessionIfValidInput,\n normalizeRevokeShareSessionInput,\n normalizeShareSessionCreate,\n parseShareSessionRecord,\n} from \"./record\"\nimport type {\n CreateShareSessionInput,\n GetShareSessionByIdInput,\n RenewShareSessionIfValidInput,\n RevokeShareSessionInput,\n ShareSessionRecord,\n ShareSessionStorage,\n} from \"./types\"\n\nexport class InMemoryShareSessionStorage implements ShareSessionStorage {\n private rows = new Map<string, ShareSessionRecord>()\n\n constructor(private readonly grants: Pick<ShareGrantStorage, \"getById\">) {}\n\n async create(input: CreateShareSessionInput): Promise<ShareSessionRecord> {\n const record = normalizeShareSessionCreate(input)\n const grant = await this.grants.getById({ projectId: record.projectId, id: record.grantId })\n if (!grant) {\n throw new ShareSessionStorageError(\n \"invalid_input\",\n `[Sixb] Share grant '${record.grantId}' does not exist in project '${record.projectId}'.`\n )\n }\n const key = rowKey(record.projectId, record.id)\n const duplicateTokenHash = [...this.rows.values()].some(\n (current) => current.projectId === record.projectId && current.tokenHash === record.tokenHash\n )\n if (this.rows.has(key) || duplicateTokenHash) {\n throw new ShareSessionStorageError(\n \"duplicate\",\n `[Sixb] Share session '${record.id}' conflicts with an existing record.`\n )\n }\n this.rows.set(key, record)\n return cloneShareSessionRecord(record)\n }\n\n async getById(input: GetShareSessionByIdInput): Promise<ShareSessionRecord | null> {\n const normalized = normalizeGetShareSessionByIdInput(input)\n const record = this.rows.get(rowKey(normalized.projectId, normalized.id))\n return record ? cloneShareSessionRecord(record) : null\n }\n\n async renewIfValid(input: RenewShareSessionIfValidInput): Promise<ShareSessionRecord | null> {\n const normalized = normalizeRenewShareSessionIfValidInput(input)\n const key = rowKey(normalized.projectId, normalized.id)\n const current = this.rows.get(key)\n if (\n !current ||\n current.grantId !== normalized.grantId ||\n current.tokenHash !== normalized.tokenHash ||\n current.revokedAt !== undefined ||\n current.createdAt.getTime() > normalized.now.getTime() ||\n current.expiresAt.getTime() <= normalized.now.getTime() ||\n current.absoluteExpiresAt.getTime() <= normalized.now.getTime()\n ) {\n return null\n }\n\n const nextExpiry = Math.min(\n current.absoluteExpiresAt.getTime(),\n Math.max(current.expiresAt.getTime(), normalized.expiresAt.getTime())\n )\n const updated = { ...current, expiresAt: new Date(nextExpiry) }\n this.rows.set(key, updated)\n return cloneShareSessionRecord(updated)\n }\n\n async revoke(input: RevokeShareSessionInput): Promise<ShareSessionRecord | null> {\n const normalized = normalizeRevokeShareSessionInput(input)\n const key = rowKey(normalized.projectId, normalized.id)\n const current = this.rows.get(key)\n if (!current) return null\n if (current.revokedAt) return cloneShareSessionRecord(current)\n\n const revocation = normalizeRevokeShareSessionInput(normalized, current.createdAt)\n const updated = { ...current, revokedAt: new Date(revocation.revokedAt) }\n this.rows.set(key, updated)\n return cloneShareSessionRecord(updated)\n }\n\n snapshot(): ReadonlyMap<string, ShareSessionRecord> {\n return new Map([...this.rows].map(([key, record]) => [key, cloneShareSessionRecord(record)]))\n }\n\n restore(snapshot: ReadonlyMap<string, ShareSessionRecord>): void {\n this.rows = new Map(\n [...snapshot].map(([key, record]) => [key, parseShareSessionRecord(record)])\n )\n }\n}\n\nfunction rowKey(projectId: string, id: string): string {\n return `${projectId}\\0${id}`\n}\n",
|
|
46
|
+
"import type { SixbErrorCode, SixbFailure } from \"../../errors/types\"\nimport type { JsonValue } from \"../../json\"\nimport type { DatasetVersionRef, DatasetWriteMode } from \"../../lake-storage\"\n\nexport type SyncRunMode = DatasetWriteMode | \"merge\"\n\nexport type SyncRunStatus = \"queued\" | \"running\" | \"succeeded\" | \"failed\" | \"cancelled\"\n/** Error codes a sync run can persist and expose through its public contract. */\nexport const SYNC_RUN_FAILURE_CODES = [\n \"internal.unexpected\",\n \"runtime.cancelled\",\n \"queue.enqueue_failed\",\n \"sync.execution_failed\",\n] as const satisfies readonly [SixbErrorCode, ...SixbErrorCode[]]\n\nexport type SyncRunFailureCode = (typeof SYNC_RUN_FAILURE_CODES)[number]\n\nexport interface SyncRunRecord {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly syncId: string\n readonly datasetId: string\n readonly mode: SyncRunMode\n readonly status: SyncRunStatus\n readonly queuedAt: Date\n readonly startedAt?: Date\n readonly finishedAt?: Date\n /** Source items successfully consumed. Merge runs count both upserts and deletes. */\n readonly rowsRead?: number\n readonly output?: DatasetVersionRef\n readonly expectedLatestVersionId?: string\n readonly commitMessage?: string\n readonly error?: SixbFailure<SyncRunFailureCode>\n readonly checkpoint?: JsonValue\n}\n\nexport interface QueueSyncRunInput {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly syncId: string\n readonly datasetId: string\n readonly mode: SyncRunMode\n readonly queuedAt?: Date\n readonly expectedLatestVersionId?: string\n readonly commitMessage?: string\n}\n\nexport interface StartSyncRunInput {\n readonly id: string\n readonly projectId: string\n readonly startedAt?: Date\n}\n\nexport type FinishSyncRunInput =\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"succeeded\"\n readonly finishedAt?: Date\n /** Source items successfully consumed. Merge runs count both upserts and deletes. */\n readonly rowsRead: number\n /** Absent when a successful run has no dataset version to reference. */\n readonly output?: DatasetVersionRef\n readonly checkpoint?: JsonValue\n }\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"failed\"\n readonly finishedAt?: Date\n /** Source items successfully consumed before the failure or cancellation. */\n readonly rowsRead?: number\n readonly error: SixbFailure<SyncRunFailureCode>\n }\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"cancelled\"\n readonly finishedAt?: Date\n /** Source items successfully consumed before cancellation. */\n readonly rowsRead?: number\n readonly error?: SixbFailure<SyncRunFailureCode>\n }\n\nexport interface ListSyncRunsInput {\n readonly projectId: string\n readonly syncId?: string\n readonly syncIds?: readonly string[]\n readonly datasetId?: string\n readonly statuses?: readonly SyncRunStatus[]\n readonly startedAfter?: Date\n readonly startedBefore?: Date\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListSyncRunsResult {\n readonly runs: readonly SyncRunRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\nexport interface ListLatestSyncRunsInput {\n readonly projectId: string\n readonly syncIds: readonly string[]\n}\n\nexport interface ListLatestSyncRunsResult {\n readonly runs: readonly SyncRunRecord[]\n}\n\nexport interface SyncRunStorage {\n queue(input: QueueSyncRunInput): Promise<SyncRunRecord>\n start(input: StartSyncRunInput): Promise<SyncRunRecord>\n finish(input: FinishSyncRunInput): Promise<SyncRunRecord>\n getById(params: { projectId: string; id: string }): Promise<SyncRunRecord | null>\n list(input: ListSyncRunsInput): Promise<ListSyncRunsResult>\n listLatestBySyncIds(input: ListLatestSyncRunsInput): Promise<ListLatestSyncRunsResult>\n}\n",
|
|
47
|
+
"import { parseSixbFailure } from \"../../errors/internal\"\nimport type { SixbFailure } from \"../../errors/types\"\nimport { cloneJsonValue, type JsonValue } from \"../../json\"\nimport type { ExecutionStorage } from \"../executions\"\nimport {\n compareStartedAt,\n hasEmptyStatuses,\n latestStartedAtByOwnerId,\n matchesRunListDateFilters,\n paginate,\n toStatusSet,\n} from \"../run-listing\"\nimport { SyncRunError } from \"./errors\"\nimport { canRequeueSyncRunAfterEnqueueFailure } from \"./idempotency\"\nimport { assertSyncRunExecution } from \"./provider\"\nimport type {\n FinishSyncRunInput,\n ListLatestSyncRunsInput,\n ListLatestSyncRunsResult,\n ListSyncRunsInput,\n ListSyncRunsResult,\n QueueSyncRunInput,\n StartSyncRunInput,\n SyncRunFailureCode,\n SyncRunRecord,\n SyncRunStorage,\n} from \"./types\"\nimport { SYNC_RUN_FAILURE_CODES } from \"./types\"\n\nfunction syncRunKey(projectId: string, id: string): string {\n return `${projectId}:${id}`\n}\n\nfunction cloneSyncRunRecord(record: SyncRunRecord): SyncRunRecord {\n return structuredClone(record)\n}\n\nfunction normalizeCheckpoint(checkpoint: JsonValue | undefined): JsonValue | undefined {\n return checkpoint !== undefined ? cloneJsonValue(checkpoint) : undefined\n}\n\nfunction normalizeError(\n error: SixbFailure<SyncRunFailureCode> | undefined\n): SixbFailure<SyncRunFailureCode> | undefined {\n return error ? parseSixbFailure(error, SYNC_RUN_FAILURE_CODES) : undefined\n}\n\nexport class InMemorySyncRunStorage implements SyncRunStorage {\n private readonly rows = new Map<string, SyncRunRecord>()\n\n constructor(private readonly executions: ExecutionStorage) {}\n\n snapshot(): InMemorySyncRunStorageSnapshot {\n return structuredClone(this.rows)\n }\n\n restore(snapshot: InMemorySyncRunStorageSnapshot): void {\n this.rows.clear()\n for (const [key, record] of structuredClone(snapshot)) {\n this.rows.set(key, record)\n }\n }\n\n async queue(input: QueueSyncRunInput): Promise<SyncRunRecord> {\n const key = syncRunKey(input.projectId, input.id)\n const existing = this.rows.get(key)\n if (existing && !canRequeueSyncRunAfterEnqueueFailure(existing, input)) {\n throw new SyncRunError(\n `[Sixb] Sync run '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n if (\n [...this.rows.values()].some(\n (run) =>\n run.projectId === input.projectId &&\n run.id !== input.id &&\n run.executionId === input.executionId\n )\n ) {\n throw new SyncRunError(\n `[Sixb] Execution '${input.executionId}' already belongs to another Sync run.`\n )\n }\n await assertSyncRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n syncId: input.syncId,\n })\n\n const queuedAt = new Date(input.queuedAt ?? new Date())\n if (existing) {\n const next: SyncRunRecord = {\n ...existing,\n status: \"queued\",\n queuedAt,\n startedAt: undefined,\n finishedAt: undefined,\n rowsRead: undefined,\n output: undefined,\n error: undefined,\n checkpoint: undefined,\n }\n this.rows.set(key, structuredClone(next))\n return cloneSyncRunRecord(next)\n }\n\n const record: SyncRunRecord = {\n id: input.id,\n projectId: input.projectId,\n executionId: input.executionId,\n syncId: input.syncId,\n datasetId: input.datasetId,\n mode: input.mode,\n status: \"queued\",\n queuedAt,\n expectedLatestVersionId: input.expectedLatestVersionId,\n commitMessage: input.commitMessage,\n }\n\n this.rows.set(key, structuredClone(record))\n return cloneSyncRunRecord(record)\n }\n\n async start(input: StartSyncRunInput): Promise<SyncRunRecord> {\n const key = syncRunKey(input.projectId, input.id)\n const existing = this.rows.get(key)\n if (!existing) {\n throw new SyncRunError(\n `[Sixb] Sync run '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n if (existing.status !== \"queued\") {\n throw new SyncRunError(\n `[Sixb] Sync run '${input.id}' cannot start from status '${existing.status}'.`\n )\n }\n\n const next: SyncRunRecord = {\n ...existing,\n status: \"running\",\n startedAt: new Date(input.startedAt ?? new Date()),\n error: undefined,\n }\n this.rows.set(key, structuredClone(next))\n return cloneSyncRunRecord(next)\n }\n\n async finish(input: FinishSyncRunInput): Promise<SyncRunRecord> {\n const key = syncRunKey(input.projectId, input.id)\n const existing = this.rows.get(key)\n\n if (!existing) {\n throw new SyncRunError(\n `[Sixb] Sync run '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n\n const enqueueFailure = input.status === \"failed\" && input.error.code === \"queue.enqueue_failed\"\n if (\n (enqueueFailure && existing.status !== \"queued\") ||\n (!enqueueFailure && existing.status !== \"running\")\n ) {\n throw new SyncRunError(\n `[Sixb] Sync run '${input.id}' cannot finish from status '${existing.status}'.`\n )\n }\n\n if (input.status === \"succeeded\") {\n if (input.output && input.output.datasetId !== existing.datasetId) {\n throw new SyncRunError(\n `[Sixb] Sync run '${input.id}' output dataset '${input.output.datasetId}' does not match '${existing.datasetId}'.`\n )\n }\n if (!input.output && input.rowsRead !== 0 && existing.mode !== \"merge\") {\n throw new SyncRunError(\n `[Sixb] Sync run '${input.id}' may omit its output with rows read only for an initial merge no-op.`\n )\n }\n }\n\n const base: SyncRunRecord = {\n ...existing,\n status: input.status,\n finishedAt: new Date(input.finishedAt ?? new Date()),\n }\n\n const next: SyncRunRecord =\n input.status === \"succeeded\"\n ? {\n ...base,\n rowsRead: input.rowsRead,\n output: input.output ? structuredClone(input.output) : undefined,\n error: undefined,\n checkpoint: normalizeCheckpoint(input.checkpoint),\n }\n : {\n ...base,\n rowsRead: input.rowsRead ?? existing.rowsRead,\n output: undefined,\n error: normalizeError(input.error),\n checkpoint: undefined,\n }\n\n this.rows.set(key, structuredClone(next))\n return cloneSyncRunRecord(next)\n }\n\n async getById(params: { projectId: string; id: string }): Promise<SyncRunRecord | null> {\n const record = this.rows.get(syncRunKey(params.projectId, params.id))\n return record ? cloneSyncRunRecord(record) : null\n }\n\n async list(input: ListSyncRunsInput): Promise<ListSyncRunsResult> {\n if (hasEmptyStatuses(input) || input.syncIds?.length === 0) {\n return {\n runs: [],\n hasMore: false,\n total: 0,\n }\n }\n\n const order = input.order ?? \"desc\"\n const statuses = toStatusSet(input.statuses)\n const syncIds = input.syncIds ? new Set(input.syncIds) : null\n\n const filtered = [...this.rows.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) => (input.syncId ? record.syncId === input.syncId : true))\n .filter((record) => (syncIds ? syncIds.has(record.syncId) : true))\n .filter((record) => (input.datasetId ? record.datasetId === input.datasetId : true))\n .filter((record) =>\n matchesRunListDateFilters(record, {\n statuses,\n startedAfter: input.startedAfter,\n startedBefore: input.startedBefore,\n })\n )\n .sort((left, right) => compareStartedAt(left, right, order))\n\n const { page, total, hasMore } = paginate(filtered, input)\n\n return {\n runs: page.map(cloneSyncRunRecord),\n hasMore,\n total,\n }\n }\n\n async listLatestBySyncIds(input: ListLatestSyncRunsInput): Promise<ListLatestSyncRunsResult> {\n const runs = latestStartedAtByOwnerId(\n [...this.rows.values()].filter((record) => record.projectId === input.projectId),\n input.syncIds,\n (record) => record.syncId\n )\n\n return {\n runs: runs.map(cloneSyncRunRecord),\n }\n }\n}\n\nexport type InMemorySyncRunStorageSnapshot = Map<string, SyncRunRecord>\n",
|
|
48
|
+
"import type { SixbErrorCode, SixbFailure } from \"../../errors/types\"\n\nexport type WebhookRunStatus = \"running\" | \"succeeded\" | \"failed\"\nexport type FinishWebhookRunStatus = Exclude<WebhookRunStatus, \"running\">\n\n/** Error codes a webhook run can persist and expose through its public contract. */\nexport const WEBHOOK_RUN_FAILURE_CODES = [\n \"internal.unexpected\",\n \"webhook.delivery_failed\",\n \"webhook.delivery_rejected\",\n] as const satisfies readonly [SixbErrorCode, ...SixbErrorCode[]]\n\nexport type WebhookRunFailureCode = (typeof WEBHOOK_RUN_FAILURE_CODES)[number]\n\nexport interface WebhookRunRecord {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly connectorId: string\n readonly webhookId: string\n readonly status: WebhookRunStatus\n readonly method: string\n readonly route: string\n readonly startedAt: Date\n readonly finishedAt?: Date\n readonly requestBodyBytes: number\n readonly requestBodySha256: string\n readonly responseStatus?: number\n readonly idempotencyKey?: string\n readonly error?: SixbFailure<WebhookRunFailureCode>\n}\n\nexport interface StartWebhookRunInput {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly connectorId: string\n readonly webhookId: string\n readonly method: string\n readonly route: string\n readonly requestBodyBytes: number\n readonly requestBodySha256: string\n readonly idempotencyKey?: string\n readonly startedAt?: Date\n}\n\nexport interface RestartWebhookRunInput {\n readonly id: string\n readonly projectId: string\n readonly startedAt?: Date\n}\n\ninterface FinishWebhookRunBaseInput {\n readonly id: string\n readonly projectId: string\n readonly finishedAt?: Date\n readonly responseStatus?: number\n}\n\nexport type FinishWebhookRunInput = FinishWebhookRunBaseInput &\n (\n | {\n readonly status: \"succeeded\"\n readonly error?: never\n }\n | {\n readonly status: \"failed\"\n readonly error: SixbFailure<WebhookRunFailureCode>\n }\n )\n\nexport interface GetWebhookRunByDeliveryInput {\n readonly projectId: string\n readonly connectorId: string\n readonly webhookId: string\n readonly idempotencyKey: string\n}\n\nexport interface ListWebhookRunsInput {\n readonly projectId: string\n readonly connectorId?: string\n readonly webhookId?: string\n readonly statuses?: readonly WebhookRunStatus[]\n readonly idempotencyKey?: string\n readonly startedAfter?: Date\n readonly startedBefore?: Date\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListWebhookRunsResult {\n readonly runs: readonly WebhookRunRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\nexport interface WebhookRunStorage {\n start(input: StartWebhookRunInput): Promise<WebhookRunRecord>\n restart(input: RestartWebhookRunInput): Promise<WebhookRunRecord>\n finish(input: FinishWebhookRunInput): Promise<WebhookRunRecord>\n getById(params: { projectId: string; id: string }): Promise<WebhookRunRecord | null>\n getByDelivery(input: GetWebhookRunByDeliveryInput): Promise<WebhookRunRecord | null>\n list(input: ListWebhookRunsInput): Promise<ListWebhookRunsResult>\n}\n\n/** Provider retries may reopen only failures classified as retryable by the shared error policy. */\nexport function canRetryWebhookRun(run: WebhookRunRecord): boolean {\n return run.status === \"failed\" && run.error?.retryable === true\n}\n",
|
|
49
|
+
"import { parseSixbFailure } from \"../../errors/internal\"\nimport type { ExecutionStorage } from \"../executions\"\nimport {\n cloneRecord,\n compareStartedAt,\n hasEmptyStatuses,\n matchesRunListDateFilters,\n paginate,\n storageKey,\n toStatusSet,\n} from \"../run-listing\"\nimport { WebhookRunError } from \"./errors\"\nimport { assertWebhookRunExecution } from \"./provider\"\nimport type {\n FinishWebhookRunInput,\n ListWebhookRunsInput,\n ListWebhookRunsResult,\n RestartWebhookRunInput,\n StartWebhookRunInput,\n WebhookRunRecord,\n WebhookRunStorage,\n} from \"./types\"\nimport { canRetryWebhookRun, WEBHOOK_RUN_FAILURE_CODES } from \"./types\"\n\nexport class InMemoryWebhookRunStorage implements WebhookRunStorage {\n private readonly runs = new Map<string, WebhookRunRecord>()\n\n constructor(private readonly executions: ExecutionStorage) {}\n\n snapshot(): InMemoryWebhookRunStorageSnapshot {\n return structuredClone(this.runs)\n }\n\n restore(snapshot: InMemoryWebhookRunStorageSnapshot): void {\n this.runs.clear()\n for (const [key, record] of structuredClone(snapshot)) {\n this.runs.set(key, record)\n }\n }\n\n async start(input: StartWebhookRunInput): Promise<WebhookRunRecord> {\n await assertWebhookRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n route: input.route,\n })\n const key = storageKey(input.projectId, input.id)\n if (this.runs.has(key) || this.findByDelivery(input)) {\n throw new WebhookRunError(\n `[Sixb] Webhook run '${input.id}' or delivery key already exists for project '${input.projectId}'.`,\n \"duplicate_run\"\n )\n }\n\n const record: WebhookRunRecord = {\n id: input.id,\n projectId: input.projectId,\n executionId: input.executionId,\n connectorId: input.connectorId,\n webhookId: input.webhookId,\n status: \"running\",\n method: input.method,\n route: input.route,\n startedAt: new Date(input.startedAt ?? new Date()),\n requestBodyBytes: input.requestBodyBytes,\n requestBodySha256: input.requestBodySha256,\n idempotencyKey: input.idempotencyKey,\n }\n\n this.runs.set(key, cloneRecord(record))\n return cloneRecord(record)\n }\n\n async restart(input: RestartWebhookRunInput): Promise<WebhookRunRecord> {\n const existing = this.requireWebhookRun(input.projectId, input.id)\n if (!canRetryWebhookRun(existing)) {\n throw new WebhookRunError(\n `[Sixb] Webhook run '${input.id}' cannot restart from status '${existing.status}'.`,\n \"invalid_transition\"\n )\n }\n const next: WebhookRunRecord = {\n ...existing,\n status: \"running\",\n startedAt: new Date(input.startedAt ?? new Date()),\n finishedAt: undefined,\n responseStatus: undefined,\n error: undefined,\n }\n this.runs.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async finish(input: FinishWebhookRunInput): Promise<WebhookRunRecord> {\n const existing = this.requireRunningWebhookRun(input.projectId, input.id)\n const next: WebhookRunRecord = {\n ...existing,\n status: input.status,\n finishedAt: new Date(input.finishedAt ?? new Date()),\n responseStatus: input.responseStatus,\n error:\n input.status === \"failed\"\n ? parseSixbFailure(input.error, WEBHOOK_RUN_FAILURE_CODES)\n : undefined,\n }\n\n this.runs.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async getById(params: { projectId: string; id: string }): Promise<WebhookRunRecord | null> {\n const record = this.runs.get(storageKey(params.projectId, params.id))\n return record ? cloneRecord(record) : null\n }\n\n async getByDelivery(input: {\n projectId: string\n connectorId: string\n webhookId: string\n idempotencyKey: string\n }): Promise<WebhookRunRecord | null> {\n const record = this.findByDelivery(input)\n return record ? cloneRecord(record) : null\n }\n\n async list(input: ListWebhookRunsInput): Promise<ListWebhookRunsResult> {\n if (hasEmptyStatuses(input)) {\n return {\n runs: [],\n hasMore: false,\n total: 0,\n }\n }\n\n const order = input.order ?? \"desc\"\n const statuses = toStatusSet(input.statuses)\n const filtered = [...this.runs.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) => (input.connectorId ? record.connectorId === input.connectorId : true))\n .filter((record) => (input.webhookId ? record.webhookId === input.webhookId : true))\n .filter((record) =>\n input.idempotencyKey ? record.idempotencyKey === input.idempotencyKey : true\n )\n .filter((record) =>\n matchesRunListDateFilters(record, {\n statuses,\n startedAfter: input.startedAfter,\n startedBefore: input.startedBefore,\n })\n )\n .sort((left, right) => compareStartedAt(left, right, order))\n\n const { page, total, hasMore } = paginate(filtered, input)\n\n return {\n runs: page.map(cloneRecord),\n hasMore,\n total,\n }\n }\n\n private requireWebhookRun(projectId: string, id: string): WebhookRunRecord {\n const record = this.runs.get(storageKey(projectId, id))\n if (!record) {\n throw new WebhookRunError(\n `[Sixb] Webhook run '${id}' not found for project '${projectId}'.`,\n \"not_found\"\n )\n }\n\n return record\n }\n\n private requireRunningWebhookRun(projectId: string, id: string): WebhookRunRecord {\n const record = this.requireWebhookRun(projectId, id)\n\n if (record.status !== \"running\") {\n throw new WebhookRunError(\n `[Sixb] Webhook run '${id}' for project '${projectId}' is already terminal.`,\n \"invalid_transition\"\n )\n }\n\n return record\n }\n\n private findByDelivery(input: {\n readonly projectId: string\n readonly connectorId: string\n readonly webhookId: string\n readonly idempotencyKey?: string\n }): WebhookRunRecord | undefined {\n if (input.idempotencyKey === undefined) return undefined\n return [...this.runs.values()].find(\n (run) =>\n run.projectId === input.projectId &&\n run.connectorId === input.connectorId &&\n run.webhookId === input.webhookId &&\n run.idempotencyKey === input.idempotencyKey\n )\n }\n}\n\nexport type InMemoryWebhookRunStorageSnapshot = Map<string, WebhookRunRecord>\n",
|
|
50
|
+
"/**\n * Base error for workflow-intervention storage operations.\n */\nexport class WorkflowInterventionError extends Error {\n readonly name = \"WorkflowInterventionError\"\n}\n",
|
|
51
|
+
"import { cloneRecord, hasEmptyStatuses, paginate, storageKey, toStatusSet } from \"../run-listing\"\nimport { WorkflowInterventionError } from \"./errors\"\nimport type {\n CancelWorkflowInterventionInput,\n CreateWorkflowInterventionInput,\n ExpireWorkflowInterventionInput,\n ListWorkflowInterventionsInput,\n ListWorkflowInterventionsResult,\n SubmitWorkflowInterventionInput,\n WorkflowInterventionRecord,\n WorkflowInterventionStorage,\n} from \"./types\"\n\nfunction assertNonNegativeInteger(value: number, fieldName: string): void {\n if (!Number.isInteger(value) || value < 0) {\n throw new WorkflowInterventionError(\n `[Sixb] Workflow intervention ${fieldName} must be a non-negative integer.`\n )\n }\n}\n\nexport class InMemoryWorkflowInterventionStorage implements WorkflowInterventionStorage {\n private readonly interventions = new Map<string, WorkflowInterventionRecord>()\n\n snapshot(): InMemoryWorkflowInterventionStorageSnapshot {\n return structuredClone(this.interventions)\n }\n\n restore(snapshot: InMemoryWorkflowInterventionStorageSnapshot): void {\n this.interventions.clear()\n for (const [key, record] of structuredClone(snapshot)) {\n this.interventions.set(key, record)\n }\n }\n\n async create(input: CreateWorkflowInterventionInput): Promise<WorkflowInterventionRecord> {\n assertNonNegativeInteger(input.nodeIndex, \"nodeIndex\")\n\n const key = storageKey(input.projectId, input.id)\n if (this.interventions.has(key)) {\n throw new WorkflowInterventionError(\n `[Sixb] Workflow intervention '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n const record: WorkflowInterventionRecord = {\n id: input.id,\n projectId: input.projectId,\n workflowId: input.workflowId,\n workflowRunId: input.workflowRunId,\n nodeRunId: input.nodeRunId,\n nodeIndex: input.nodeIndex,\n nodeId: input.nodeId,\n nodeKey: input.nodeKey,\n interventionId: input.interventionId,\n input: cloneRecord(input.input),\n defaultResponse: cloneRecord(input.defaultResponse),\n status: \"pending\",\n requestedAt: new Date(input.requestedAt ?? new Date()),\n expiresAt: input.expiresAt ? new Date(input.expiresAt) : undefined,\n }\n\n this.interventions.set(key, cloneRecord(record))\n return cloneRecord(record)\n }\n\n async submit(input: SubmitWorkflowInterventionInput): Promise<WorkflowInterventionRecord> {\n const existing = this.requirePendingIntervention(input.projectId, input.id)\n const next: WorkflowInterventionRecord = {\n ...existing,\n status: \"submitted\",\n submittedAt: new Date(input.submittedAt ?? new Date()),\n submittedBy: input.submittedBy ? cloneRecord(input.submittedBy) : undefined,\n response: cloneRecord(input.response),\n }\n\n this.interventions.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async cancel(input: CancelWorkflowInterventionInput): Promise<WorkflowInterventionRecord> {\n const existing = this.requirePendingIntervention(input.projectId, input.id)\n const next: WorkflowInterventionRecord = {\n ...existing,\n status: \"cancelled\",\n cancelledAt: new Date(input.cancelledAt ?? new Date()),\n cancelledBy: input.cancelledBy ? cloneRecord(input.cancelledBy) : undefined,\n }\n\n this.interventions.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async expire(input: ExpireWorkflowInterventionInput): Promise<WorkflowInterventionRecord> {\n const existing = this.requirePendingIntervention(input.projectId, input.id)\n const next: WorkflowInterventionRecord = {\n ...existing,\n status: \"expired\",\n expiredAt: new Date(input.expiredAt ?? new Date()),\n }\n\n this.interventions.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async getById(params: {\n projectId: string\n id: string\n }): Promise<WorkflowInterventionRecord | null> {\n const record = this.interventions.get(storageKey(params.projectId, params.id))\n return record ? cloneRecord(record) : null\n }\n\n async list(input: ListWorkflowInterventionsInput): Promise<ListWorkflowInterventionsResult> {\n if (hasEmptyStatuses(input) || input.workflowIds?.length === 0) {\n return {\n interventions: [],\n hasMore: false,\n total: 0,\n }\n }\n\n const order = input.order ?? \"desc\"\n const statuses = toStatusSet(input.statuses)\n const workflowIds = input.workflowIds ? new Set(input.workflowIds) : null\n const filtered = [...this.interventions.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) => (statuses ? statuses.has(record.status) : true))\n .filter((record) => (input.workflowId ? record.workflowId === input.workflowId : true))\n .filter((record) => (workflowIds ? workflowIds.has(record.workflowId) : true))\n .filter((record) =>\n input.workflowRunId ? record.workflowRunId === input.workflowRunId : true\n )\n .filter((record) => (input.nodeRunId ? record.nodeRunId === input.nodeRunId : true))\n .filter((record) => (input.nodeId ? record.nodeId === input.nodeId : true))\n .filter((record) => (input.nodeKey ? record.nodeKey === input.nodeKey : true))\n .filter((record) =>\n input.interventionId ? record.interventionId === input.interventionId : true\n )\n .filter((record) =>\n input.requestedAfter ? record.requestedAt >= input.requestedAfter : true\n )\n .filter((record) =>\n input.requestedBefore ? record.requestedAt <= input.requestedBefore : true\n )\n .sort((left, right) => compareRequestedAt(left, right, order))\n\n const { page, total, hasMore } = paginate(filtered, input)\n\n return {\n interventions: page.map(cloneRecord),\n hasMore,\n total,\n }\n }\n\n private requirePendingIntervention(projectId: string, id: string): WorkflowInterventionRecord {\n const record = this.interventions.get(storageKey(projectId, id))\n if (!record) {\n throw new WorkflowInterventionError(\n `[Sixb] Workflow intervention '${id}' not found for project '${projectId}'.`\n )\n }\n\n if (record.status !== \"pending\") {\n throw new WorkflowInterventionError(\n `[Sixb] Workflow intervention '${id}' for project '${projectId}' is not pending.`\n )\n }\n\n return record\n }\n}\n\nexport type InMemoryWorkflowInterventionStorageSnapshot = Map<string, WorkflowInterventionRecord>\n\nfunction compareRequestedAt(\n left: { readonly id: string; readonly requestedAt: Date },\n right: { readonly id: string; readonly requestedAt: Date },\n order: \"asc\" | \"desc\"\n): number {\n const delta = left.requestedAt.getTime() - right.requestedAt.getTime()\n if (delta !== 0) {\n return order === \"asc\" ? delta : -delta\n }\n\n if (left.id === right.id) {\n return 0\n }\n\n return order === \"asc\" ? left.id.localeCompare(right.id) : right.id.localeCompare(left.id)\n}\n",
|
|
52
|
+
"import type { AgentMessagePart } from \"../../agents/message\"\nimport type { SixbErrorCode, SixbFailure } from \"../../errors/types\"\nimport type { JsonValue } from \"../../json\"\nimport type { WorkflowIOSnapshot } from \"../../workflows/types\"\nimport type { AgentExecutionStatus, AgentRunFailureCode, AgentRunFinishReason } from \"../agents\"\n\nexport type { WorkflowIOSnapshot } from \"../../workflows/types\"\n\nexport type WorkflowRunStatus =\n | \"queued\"\n | \"running\"\n | \"waiting\"\n | \"succeeded\"\n | \"failed\"\n | \"cancelled\"\nexport type WorkflowNodeRunStatus = Exclude<WorkflowRunStatus, \"queued\">\nexport type WorkflowNodeRunType = \"step\" | \"action\" | \"intervention\" | \"agent\"\n\n/** Error codes a workflow or workflow-node run can persist and expose. */\nexport const WORKFLOW_RUN_FAILURE_CODES = [\n \"internal.unexpected\",\n \"runtime.cancelled\",\n \"workflow.node_failed\",\n \"ai.usage_limit_exceeded\",\n \"ai.usage_limit_unavailable\",\n] as const satisfies readonly [SixbErrorCode, ...SixbErrorCode[]]\n\nexport type WorkflowRunFailureCode = (typeof WORKFLOW_RUN_FAILURE_CODES)[number]\n\nexport interface WorkflowRunExecution {\n readonly token: string\n readonly queueLeaseExpiresAt: Date\n}\n\nexport type WorkflowAgentNodeRunStatus = AgentExecutionStatus\n\nexport interface WorkflowAgentNodeRunExecution {\n readonly token: string\n readonly queueLeaseExpiresAt: Date\n}\n\n/** Execution details for an agent workflow node. The generic node run owns business IO. */\nexport interface WorkflowAgentNodeRunRecord {\n readonly projectId: string\n readonly nodeRunId: string\n readonly executionId: string\n /** Stable managed actor for the workflow + Agent step, not the step definition id. */\n readonly actorId: string\n readonly status: WorkflowAgentNodeRunStatus\n readonly prompt: string\n readonly modelId?: string\n readonly finishReason?: AgentRunFinishReason\n readonly trace?: readonly AgentMessagePart[]\n readonly diagnostics?: readonly JsonValue[]\n readonly error?: SixbFailure<AgentRunFailureCode>\n readonly attempt: number\n readonly execution?: WorkflowAgentNodeRunExecution\n readonly createdAt: Date\n readonly startedAt?: Date\n readonly completedAt?: Date\n}\n\nexport interface CreateWorkflowAgentNodeRunInput {\n readonly projectId: string\n readonly nodeRunId: string\n readonly executionId: string\n readonly actorId: string\n readonly prompt: string\n readonly createdAt?: Date\n}\n\nexport interface StartWorkflowAgentNodeRunInput {\n readonly projectId: string\n readonly nodeRunId: string\n readonly modelId?: string\n readonly execution: WorkflowAgentNodeRunExecution\n readonly startedAt?: Date\n}\n\nexport interface ReclaimWorkflowAgentNodeRunInput {\n readonly projectId: string\n readonly nodeRunId: string\n readonly execution: WorkflowAgentNodeRunExecution\n}\n\nexport interface ConfirmWorkflowAgentNodeRunExecutionOwnershipInput {\n readonly projectId: string\n readonly nodeRunId: string\n readonly executionToken: string\n readonly queueLeaseExpiresAt: Date\n}\n\ninterface FinishWorkflowAgentNodeRunBaseInput {\n readonly projectId: string\n readonly nodeRunId: string\n readonly executionToken: string\n readonly modelId?: string\n readonly finishReason?: AgentRunFinishReason\n readonly trace?: readonly AgentMessagePart[]\n readonly diagnostics?: readonly JsonValue[]\n readonly completedAt?: Date\n}\n\nexport type FinishWorkflowAgentNodeRunInput =\n | (FinishWorkflowAgentNodeRunBaseInput & {\n readonly status: \"succeeded\"\n })\n | (FinishWorkflowAgentNodeRunBaseInput & {\n readonly status: \"failed\" | \"cancelled\"\n readonly error?: SixbFailure<AgentRunFailureCode>\n })\n\nexport interface CancelWorkflowAgentNodeRunInput {\n readonly projectId: string\n readonly nodeRunId: string\n readonly error?: SixbFailure<AgentRunFailureCode>\n readonly completedAt?: Date\n}\n\nexport interface ListWorkflowAgentNodeRunsInput {\n readonly projectId: string\n readonly actorId?: string\n readonly statuses?: readonly WorkflowAgentNodeRunStatus[]\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListWorkflowAgentNodeRunsResult {\n readonly runs: readonly WorkflowAgentNodeRunRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\nexport interface WorkflowRunRecord {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly workflowId: string\n readonly status: WorkflowRunStatus\n readonly input: WorkflowIOSnapshot\n readonly output?: WorkflowIOSnapshot\n readonly queuedAt?: Date\n readonly startedAt: Date\n readonly finishedAt?: Date\n readonly error?: SixbFailure<WorkflowRunFailureCode>\n readonly attempt: number\n readonly execution?: WorkflowRunExecution\n}\n\nexport interface WorkflowNodeRunRecord {\n readonly id: string\n readonly projectId: string\n readonly workflowRunId: string\n readonly workflowId: string\n readonly nodeIndex: number\n readonly nodeType: WorkflowNodeRunType\n readonly nodeId: string\n readonly nodeKey: string\n readonly status: WorkflowNodeRunStatus\n readonly input: WorkflowIOSnapshot\n readonly startedAt: Date\n readonly finishedAt?: Date\n readonly output?: WorkflowIOSnapshot\n readonly error?: SixbFailure<WorkflowRunFailureCode>\n}\n\nexport interface StartWorkflowRunInput {\n readonly id: string\n readonly projectId: string\n readonly startedAt?: Date\n readonly execution?: WorkflowRunExecution\n}\n\nexport interface QueueWorkflowRunInput {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly workflowId: string\n readonly input: WorkflowIOSnapshot\n readonly queuedAt?: Date\n}\n\nexport interface ReclaimWorkflowRunInput {\n readonly id: string\n readonly projectId: string\n readonly execution: WorkflowRunExecution\n}\n\nexport interface ConfirmWorkflowRunExecutionOwnershipInput {\n readonly id: string\n readonly projectId: string\n readonly executionToken: string\n readonly queueLeaseExpiresAt: Date\n}\n\nexport interface WaitWorkflowRunInput {\n readonly id: string\n readonly projectId: string\n readonly waitingAt?: Date\n readonly executionToken?: string\n}\n\nexport interface ResumeWorkflowRunInput {\n readonly id: string\n readonly projectId: string\n readonly resumedAt?: Date\n readonly execution?: WorkflowRunExecution\n}\n\nexport type FinishWorkflowRunInput =\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"succeeded\"\n readonly output: WorkflowIOSnapshot\n readonly finishedAt?: Date\n readonly executionToken?: string\n }\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"failed\" | \"cancelled\"\n readonly finishedAt?: Date\n readonly error?: SixbFailure<WorkflowRunFailureCode>\n readonly executionToken?: string\n }\n\nexport interface StartWorkflowNodeRunInput {\n readonly id: string\n readonly projectId: string\n readonly workflowRunId: string\n readonly workflowId: string\n readonly nodeIndex: number\n readonly nodeType: WorkflowNodeRunType\n readonly nodeId: string\n readonly nodeKey: string\n readonly input: WorkflowIOSnapshot\n readonly startedAt?: Date\n readonly executionToken?: string\n}\n\nexport interface WaitWorkflowNodeRunInput {\n readonly id: string\n readonly projectId: string\n readonly waitingAt?: Date\n readonly executionToken?: string\n}\n\nexport type FinishWorkflowNodeRunInput =\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"succeeded\"\n readonly finishedAt?: Date\n readonly output?: WorkflowIOSnapshot\n readonly executionToken?: string\n }\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"failed\" | \"cancelled\"\n readonly finishedAt?: Date\n readonly error?: SixbFailure<WorkflowRunFailureCode>\n readonly executionToken?: string\n }\n\nexport interface ListWorkflowRunsInput {\n readonly projectId: string\n readonly workflowId?: string\n readonly workflowIds?: readonly string[]\n readonly statuses?: readonly WorkflowRunStatus[]\n readonly startedAfter?: Date\n readonly startedBefore?: Date\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListWorkflowRunsResult {\n readonly runs: readonly WorkflowRunRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\nexport interface ListLatestWorkflowRunsInput {\n readonly projectId: string\n readonly workflowIds: readonly string[]\n}\n\nexport interface ListLatestWorkflowRunsResult {\n readonly runs: readonly WorkflowRunRecord[]\n}\n\nexport interface ListWorkflowNodeRunsInput {\n readonly projectId: string\n readonly workflowRunId?: string\n readonly workflowId?: string\n readonly nodeType?: WorkflowNodeRunType\n readonly nodeId?: string\n readonly nodeKey?: string\n readonly statuses?: readonly WorkflowNodeRunStatus[]\n readonly startedAfter?: Date\n readonly startedBefore?: Date\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListWorkflowNodeRunsResult {\n readonly nodes: readonly WorkflowNodeRunRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\nexport interface WorkflowRunStorage {\n readonly nodes: WorkflowNodeRunStorage\n readonly agentNodes: WorkflowAgentNodeRunStorage\n\n queue(input: QueueWorkflowRunInput): Promise<WorkflowRunRecord>\n /** Atomically claims a queued run by transitioning it to running; competing claims must fail. */\n start(input: StartWorkflowRunInput): Promise<WorkflowRunRecord>\n reclaim(input: ReclaimWorkflowRunInput): Promise<WorkflowRunRecord>\n confirmExecutionOwnership(\n input: ConfirmWorkflowRunExecutionOwnershipInput\n ): Promise<WorkflowRunRecord>\n wait(input: WaitWorkflowRunInput): Promise<WorkflowRunRecord>\n resume(input: ResumeWorkflowRunInput): Promise<WorkflowRunRecord>\n finish(input: FinishWorkflowRunInput): Promise<WorkflowRunRecord>\n getById(params: { projectId: string; id: string }): Promise<WorkflowRunRecord | null>\n list(input: ListWorkflowRunsInput): Promise<ListWorkflowRunsResult>\n listLatestByWorkflowIds(input: ListLatestWorkflowRunsInput): Promise<ListLatestWorkflowRunsResult>\n}\n\nexport interface WorkflowAgentNodeRunStorage {\n create(input: CreateWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord>\n start(input: StartWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord>\n reclaim(input: ReclaimWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord>\n confirmExecutionOwnership(\n input: ConfirmWorkflowAgentNodeRunExecutionOwnershipInput\n ): Promise<WorkflowAgentNodeRunRecord>\n cancel(input: CancelWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord>\n finish(input: FinishWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord>\n getByNodeRunId(params: {\n projectId: string\n nodeRunId: string\n }): Promise<WorkflowAgentNodeRunRecord | null>\n list(input: ListWorkflowAgentNodeRunsInput): Promise<ListWorkflowAgentNodeRunsResult>\n}\n\nexport interface WorkflowNodeRunStorage {\n start(input: StartWorkflowNodeRunInput): Promise<WorkflowNodeRunRecord>\n wait(input: WaitWorkflowNodeRunInput): Promise<WorkflowNodeRunRecord>\n finish(input: FinishWorkflowNodeRunInput): Promise<WorkflowNodeRunRecord>\n getById(params: { projectId: string; id: string }): Promise<WorkflowNodeRunRecord | null>\n list(input: ListWorkflowNodeRunsInput): Promise<ListWorkflowNodeRunsResult>\n}\n",
|
|
53
|
+
"import { parseSixbFailure } from \"../../errors/internal\"\nimport type { SixbFailure } from \"../../errors/types\"\nimport type { AgentRunFailureCode } from \"../agents\"\nimport { AGENT_RUN_FAILURE_CODES } from \"../agents\"\nimport type { ExecutionStorage } from \"../executions\"\nimport {\n cloneRecord,\n compareStartedAt,\n hasEmptyStatuses,\n latestStartedAtByOwnerId,\n matchesRunListDateFilters,\n paginate,\n storageKey,\n toStatusSet,\n} from \"../run-listing\"\nimport { WorkflowRunError } from \"./errors\"\nimport { assertWorkflowAgentNodeRunExecution, assertWorkflowRunExecution } from \"./provider\"\nimport type {\n CancelWorkflowAgentNodeRunInput,\n ConfirmWorkflowAgentNodeRunExecutionOwnershipInput,\n ConfirmWorkflowRunExecutionOwnershipInput,\n CreateWorkflowAgentNodeRunInput,\n FinishWorkflowAgentNodeRunInput,\n FinishWorkflowNodeRunInput,\n FinishWorkflowRunInput,\n ListLatestWorkflowRunsInput,\n ListLatestWorkflowRunsResult,\n ListWorkflowAgentNodeRunsInput,\n ListWorkflowAgentNodeRunsResult,\n ListWorkflowNodeRunsInput,\n ListWorkflowNodeRunsResult,\n ListWorkflowRunsInput,\n ListWorkflowRunsResult,\n QueueWorkflowRunInput,\n ReclaimWorkflowAgentNodeRunInput,\n ReclaimWorkflowRunInput,\n ResumeWorkflowRunInput,\n StartWorkflowAgentNodeRunInput,\n StartWorkflowNodeRunInput,\n StartWorkflowRunInput,\n WaitWorkflowNodeRunInput,\n WaitWorkflowRunInput,\n WorkflowAgentNodeRunRecord,\n WorkflowAgentNodeRunStorage,\n WorkflowNodeRunRecord,\n WorkflowNodeRunStorage,\n WorkflowRunFailureCode,\n WorkflowRunRecord,\n WorkflowRunStorage,\n} from \"./types\"\nimport { WORKFLOW_RUN_FAILURE_CODES } from \"./types\"\n\nfunction normalizeFailure(\n failure: SixbFailure<WorkflowRunFailureCode> | undefined\n): SixbFailure<WorkflowRunFailureCode> | undefined {\n return failure ? parseSixbFailure(failure, WORKFLOW_RUN_FAILURE_CODES) : undefined\n}\n\nfunction normalizeAgentFailure(\n failure: SixbFailure<AgentRunFailureCode> | undefined\n): SixbFailure<AgentRunFailureCode> | undefined {\n return failure ? parseSixbFailure(failure, AGENT_RUN_FAILURE_CODES) : undefined\n}\n\nfunction assertNonNegativeInteger(value: number, fieldName: string): void {\n if (!Number.isInteger(value) || value < 0) {\n throw new WorkflowRunError(`[Sixb] Workflow run ${fieldName} must be a non-negative integer.`)\n }\n}\n\nexport class InMemoryWorkflowRunStorage implements WorkflowRunStorage {\n readonly nodes: InMemoryWorkflowNodeRunStorage\n readonly agentNodes: InMemoryWorkflowAgentNodeRunStorage\n\n private readonly runs = new Map<string, WorkflowRunRecord>()\n\n constructor(private readonly executions: ExecutionStorage) {\n this.nodes = new InMemoryWorkflowNodeRunStorage({\n requireRunningWorkflowRun: (projectId, id) => this.requireRunningWorkflowRun(projectId, id),\n requireActiveWorkflowRun: (projectId, id) => this.requireActiveWorkflowRun(projectId, id),\n assertExecutionOwnership: (projectId, id, token) =>\n this.assertExecutionOwnership(projectId, id, token),\n })\n this.agentNodes = new InMemoryWorkflowAgentNodeRunStorage(\n {\n requireAgentNodeRun: (projectId, id) => this.nodes.requireAgentNodeRun(projectId, id),\n requireWorkflowRun: (projectId, id) => this.requireExistingWorkflowRun(projectId, id),\n },\n this.executions\n )\n }\n\n snapshot(): InMemoryWorkflowRunStorageSnapshot {\n return {\n runs: structuredClone(this.runs),\n nodes: this.nodes.snapshot(),\n agentNodes: this.agentNodes.snapshot(),\n }\n }\n\n restore(snapshot: InMemoryWorkflowRunStorageSnapshot): void {\n this.runs.clear()\n for (const [key, record] of structuredClone(snapshot.runs)) {\n this.runs.set(key, record)\n }\n this.nodes.restore(snapshot.nodes)\n this.agentNodes.restore(snapshot.agentNodes)\n }\n\n async queue(input: QueueWorkflowRunInput): Promise<WorkflowRunRecord> {\n const key = storageKey(input.projectId, input.id)\n if (this.runs.has(key)) {\n throw new WorkflowRunError(\n `[Sixb] Workflow run '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n if (\n [...this.runs.values()].some(\n (run) => run.projectId === input.projectId && run.executionId === input.executionId\n )\n ) {\n throw new WorkflowRunError(\n `[Sixb] Execution '${input.executionId}' already belongs to another workflow run.`\n )\n }\n await assertWorkflowRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n workflowId: input.workflowId,\n })\n\n const queuedAt = new Date(input.queuedAt ?? new Date())\n const record: WorkflowRunRecord = {\n id: input.id,\n projectId: input.projectId,\n executionId: input.executionId,\n workflowId: input.workflowId,\n status: \"queued\",\n input: cloneRecord(input.input),\n queuedAt,\n startedAt: queuedAt,\n attempt: 0,\n }\n\n this.runs.set(key, cloneRecord(record))\n return cloneRecord(record)\n }\n\n async start(input: StartWorkflowRunInput): Promise<WorkflowRunRecord> {\n const key = storageKey(input.projectId, input.id)\n const existing = this.runs.get(key)\n if (!existing || existing.status !== \"queued\") {\n throw new WorkflowRunError(\n existing\n ? `[Sixb] Workflow run '${input.id}' cannot start from status '${existing.status}'.`\n : `[Sixb] Workflow run '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n\n const next: WorkflowRunRecord = {\n ...existing,\n status: \"running\",\n startedAt: new Date(input.startedAt ?? new Date()),\n finishedAt: undefined,\n error: undefined,\n attempt: existing.attempt + 1,\n execution: input.execution ? cloneRecord(input.execution) : undefined,\n }\n\n this.runs.set(key, cloneRecord(next))\n return cloneRecord(next)\n }\n\n async finish(input: FinishWorkflowRunInput): Promise<WorkflowRunRecord> {\n const existing = this.requireFinishableWorkflowRun(input)\n this.assertRecordExecutionOwnership(existing, input.executionToken)\n const base: WorkflowRunRecord = {\n ...existing,\n status: input.status,\n finishedAt: new Date(input.finishedAt ?? new Date()),\n execution: undefined,\n }\n\n const next: WorkflowRunRecord =\n input.status === \"succeeded\"\n ? {\n ...base,\n output: cloneRecord(input.output),\n error: undefined,\n }\n : {\n ...base,\n output: undefined,\n error: normalizeFailure(input.error),\n }\n\n this.runs.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async wait(input: WaitWorkflowRunInput): Promise<WorkflowRunRecord> {\n const existing = this.requireRunningWorkflowRun(input.projectId, input.id)\n this.assertRecordExecutionOwnership(existing, input.executionToken)\n const next: WorkflowRunRecord = {\n ...existing,\n status: \"waiting\",\n finishedAt: undefined,\n error: undefined,\n execution: undefined,\n }\n\n this.runs.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async resume(input: ResumeWorkflowRunInput): Promise<WorkflowRunRecord> {\n const existing = this.requireWaitingWorkflowRun(input.projectId, input.id)\n const next: WorkflowRunRecord = {\n ...existing,\n status: \"running\",\n finishedAt: undefined,\n error: undefined,\n attempt: existing.attempt + 1,\n execution: input.execution ? cloneRecord(input.execution) : undefined,\n }\n\n this.runs.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async reclaim(input: ReclaimWorkflowRunInput): Promise<WorkflowRunRecord> {\n const existing = this.requireRunningWorkflowRun(input.projectId, input.id)\n const next: WorkflowRunRecord = {\n ...existing,\n attempt: existing.attempt + 1,\n execution: cloneRecord(input.execution),\n }\n this.runs.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async confirmExecutionOwnership(\n input: ConfirmWorkflowRunExecutionOwnershipInput\n ): Promise<WorkflowRunRecord> {\n const existing = this.requireRunningWorkflowRun(input.projectId, input.id)\n this.assertRecordExecutionOwnership(existing, input.executionToken)\n const next: WorkflowRunRecord = {\n ...existing,\n execution: {\n token: input.executionToken,\n queueLeaseExpiresAt: new Date(\n Math.max(\n existing.execution!.queueLeaseExpiresAt.getTime(),\n input.queueLeaseExpiresAt.getTime()\n )\n ),\n },\n }\n this.runs.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async getById(params: { projectId: string; id: string }): Promise<WorkflowRunRecord | null> {\n const record = this.runs.get(storageKey(params.projectId, params.id))\n return record ? cloneRecord(record) : null\n }\n\n async list(input: ListWorkflowRunsInput): Promise<ListWorkflowRunsResult> {\n if (hasEmptyStatuses(input) || input.workflowIds?.length === 0) {\n return {\n runs: [],\n hasMore: false,\n total: 0,\n }\n }\n\n const order = input.order ?? \"desc\"\n const statuses = toStatusSet(input.statuses)\n const workflowIds = input.workflowIds ? new Set(input.workflowIds) : null\n const filtered = [...this.runs.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) => (input.workflowId ? record.workflowId === input.workflowId : true))\n .filter((record) => (workflowIds ? workflowIds.has(record.workflowId) : true))\n .filter((record) =>\n matchesRunListDateFilters(record, {\n statuses,\n startedAfter: input.startedAfter,\n startedBefore: input.startedBefore,\n })\n )\n .sort((left, right) => compareStartedAt(left, right, order))\n\n const { page, total, hasMore } = paginate(filtered, input)\n\n return {\n runs: page.map(cloneRecord),\n hasMore,\n total,\n }\n }\n\n async listLatestByWorkflowIds(\n input: ListLatestWorkflowRunsInput\n ): Promise<ListLatestWorkflowRunsResult> {\n const runs = latestStartedAtByOwnerId(\n [...this.runs.values()].filter((record) => record.projectId === input.projectId),\n input.workflowIds,\n (record) => record.workflowId\n )\n\n return {\n runs: runs.map(cloneRecord),\n }\n }\n\n private requireExistingWorkflowRun(projectId: string, id: string): WorkflowRunRecord {\n const record = this.runs.get(storageKey(projectId, id))\n if (!record) {\n throw new WorkflowRunError(\n `[Sixb] Workflow run '${id}' not found for project '${projectId}'.`\n )\n }\n\n return record\n }\n\n private requireRunningWorkflowRun(projectId: string, id: string): WorkflowRunRecord {\n const record = this.requireExistingWorkflowRun(projectId, id)\n if (record.status !== \"running\") {\n throw new WorkflowRunError(\n `[Sixb] Workflow run '${id}' for project '${projectId}' must be running.`\n )\n }\n\n return record\n }\n\n private requireWaitingWorkflowRun(projectId: string, id: string): WorkflowRunRecord {\n const record = this.requireExistingWorkflowRun(projectId, id)\n if (record.status !== \"waiting\") {\n throw new WorkflowRunError(\n `[Sixb] Workflow run '${id}' for project '${projectId}' must be waiting.`\n )\n }\n\n return record\n }\n\n private requireActiveWorkflowRun(projectId: string, id: string): WorkflowRunRecord {\n const record = this.requireExistingWorkflowRun(projectId, id)\n if (record.status !== \"running\" && record.status !== \"waiting\") {\n throw new WorkflowRunError(\n `[Sixb] Workflow run '${id}' for project '${projectId}' is already terminal.`\n )\n }\n\n return record\n }\n\n private requireFinishableWorkflowRun(input: FinishWorkflowRunInput): WorkflowRunRecord {\n const record = this.requireExistingWorkflowRun(input.projectId, input.id)\n if (record.status === \"running\") {\n return record\n }\n\n if (record.status === \"waiting\" && input.status !== \"succeeded\") {\n return record\n }\n\n if (record.status === \"queued\" && input.status !== \"succeeded\") {\n return record\n }\n\n throw new WorkflowRunError(\n `[Sixb] Workflow run '${input.id}' for project '${input.projectId}' cannot be finished from status '${record.status}'.`\n )\n }\n\n private assertExecutionOwnership(projectId: string, id: string, token?: string): void {\n this.assertRecordExecutionOwnership(this.requireExistingWorkflowRun(projectId, id), token)\n }\n\n private assertRecordExecutionOwnership(record: WorkflowRunRecord, token?: string): void {\n if (record.execution?.token !== token) {\n throw new WorkflowRunError(\n `[Sixb] Execution token is no longer current on workflow run '${record.id}'.`\n )\n }\n }\n}\n\nexport class InMemoryWorkflowNodeRunStorage implements WorkflowNodeRunStorage {\n private readonly nodes = new Map<string, WorkflowNodeRunRecord>()\n\n constructor(\n private readonly workflowRuns: {\n requireRunningWorkflowRun(projectId: string, id: string): WorkflowRunRecord\n requireActiveWorkflowRun(projectId: string, id: string): WorkflowRunRecord\n assertExecutionOwnership(projectId: string, id: string, token?: string): void\n }\n ) {}\n\n snapshot(): InMemoryWorkflowNodeRunStorageSnapshot {\n return structuredClone(this.nodes)\n }\n\n restore(snapshot: InMemoryWorkflowNodeRunStorageSnapshot): void {\n this.nodes.clear()\n for (const [key, record] of structuredClone(snapshot)) {\n this.nodes.set(key, record)\n }\n }\n\n async start(input: StartWorkflowNodeRunInput): Promise<WorkflowNodeRunRecord> {\n assertNonNegativeInteger(input.nodeIndex, \"nodeIndex\")\n\n const workflowRun = this.workflowRuns.requireRunningWorkflowRun(\n input.projectId,\n input.workflowRunId\n )\n this.workflowRuns.assertExecutionOwnership(\n input.projectId,\n input.workflowRunId,\n input.executionToken\n )\n if (workflowRun.workflowId !== input.workflowId) {\n throw new WorkflowRunError(\n `[Sixb] Workflow node run '${input.id}' workflow '${input.workflowId}' does not match workflow run '${input.workflowRunId}' workflow '${workflowRun.workflowId}'.`\n )\n }\n\n const key = storageKey(input.projectId, input.id)\n if (this.nodes.has(key)) {\n throw new WorkflowRunError(\n `[Sixb] Workflow node run '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n const record: WorkflowNodeRunRecord = {\n id: input.id,\n projectId: input.projectId,\n workflowRunId: input.workflowRunId,\n workflowId: input.workflowId,\n nodeIndex: input.nodeIndex,\n nodeType: input.nodeType,\n nodeId: input.nodeId,\n nodeKey: input.nodeKey,\n status: \"running\",\n input: cloneRecord(input.input),\n startedAt: new Date(input.startedAt ?? new Date()),\n }\n\n this.nodes.set(key, cloneRecord(record))\n return cloneRecord(record)\n }\n\n async finish(input: FinishWorkflowNodeRunInput): Promise<WorkflowNodeRunRecord> {\n const existing = this.requireActiveNodeRun(input.projectId, input.id)\n this.workflowRuns.assertExecutionOwnership(\n input.projectId,\n existing.workflowRunId,\n input.executionToken\n )\n const base: WorkflowNodeRunRecord = {\n ...existing,\n status: input.status,\n finishedAt: new Date(input.finishedAt ?? new Date()),\n }\n\n const next: WorkflowNodeRunRecord =\n input.status === \"succeeded\"\n ? {\n ...base,\n output: input.output ? cloneRecord(input.output) : undefined,\n error: undefined,\n }\n : {\n ...base,\n output: undefined,\n error: normalizeFailure(input.error),\n }\n\n this.nodes.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async wait(input: WaitWorkflowNodeRunInput): Promise<WorkflowNodeRunRecord> {\n const existing = this.requireRunningNodeRun(input.projectId, input.id)\n this.workflowRuns.requireActiveWorkflowRun(input.projectId, existing.workflowRunId)\n this.workflowRuns.assertExecutionOwnership(\n input.projectId,\n existing.workflowRunId,\n input.executionToken\n )\n\n const next: WorkflowNodeRunRecord = {\n ...existing,\n status: \"waiting\",\n finishedAt: undefined,\n output: undefined,\n error: undefined,\n }\n\n this.nodes.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async getById(params: { projectId: string; id: string }): Promise<WorkflowNodeRunRecord | null> {\n const record = this.nodes.get(storageKey(params.projectId, params.id))\n return record ? cloneRecord(record) : null\n }\n\n async list(input: ListWorkflowNodeRunsInput): Promise<ListWorkflowNodeRunsResult> {\n if (hasEmptyStatuses(input)) {\n return {\n nodes: [],\n hasMore: false,\n total: 0,\n }\n }\n\n const order = input.order ?? \"desc\"\n const statuses = toStatusSet(input.statuses)\n const filtered = [...this.nodes.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) =>\n input.workflowRunId ? record.workflowRunId === input.workflowRunId : true\n )\n .filter((record) => (input.workflowId ? record.workflowId === input.workflowId : true))\n .filter((record) => (input.nodeType ? record.nodeType === input.nodeType : true))\n .filter((record) => (input.nodeId ? record.nodeId === input.nodeId : true))\n .filter((record) => (input.nodeKey ? record.nodeKey === input.nodeKey : true))\n .filter((record) =>\n matchesRunListDateFilters(record, {\n statuses,\n startedAfter: input.startedAfter,\n startedBefore: input.startedBefore,\n })\n )\n .sort((left, right) => compareStartedAt(left, right, order))\n\n const { page, total, hasMore } = paginate(filtered, input)\n\n return {\n nodes: page.map(cloneRecord),\n hasMore,\n total,\n }\n }\n\n private requireRunningNodeRun(projectId: string, id: string): WorkflowNodeRunRecord {\n const record = this.nodes.get(storageKey(projectId, id))\n if (!record) {\n throw new WorkflowRunError(\n `[Sixb] Workflow node run '${id}' not found for project '${projectId}'.`\n )\n }\n\n if (record.status !== \"running\") {\n throw new WorkflowRunError(\n `[Sixb] Workflow node run '${id}' for project '${projectId}' must be running.`\n )\n }\n\n return record\n }\n\n private requireActiveNodeRun(projectId: string, id: string): WorkflowNodeRunRecord {\n const record = this.nodes.get(storageKey(projectId, id))\n if (!record) {\n throw new WorkflowRunError(\n `[Sixb] Workflow node run '${id}' not found for project '${projectId}'.`\n )\n }\n\n if (record.status !== \"running\" && record.status !== \"waiting\") {\n throw new WorkflowRunError(\n `[Sixb] Workflow node run '${id}' for project '${projectId}' is already terminal.`\n )\n }\n\n return record\n }\n\n requireAgentNodeRun(projectId: string, id: string): WorkflowNodeRunRecord {\n const node = this.nodes.get(storageKey(projectId, id))\n if (!node) {\n throw new WorkflowRunError(\n `[Sixb] Workflow node run '${id}' not found for project '${projectId}'.`\n )\n }\n if (node.nodeType !== \"agent\") {\n throw new WorkflowRunError(`[Sixb] Workflow node run '${id}' is not an agent node.`)\n }\n return node\n }\n}\n\nexport class InMemoryWorkflowAgentNodeRunStorage implements WorkflowAgentNodeRunStorage {\n private readonly runs = new Map<string, WorkflowAgentNodeRunRecord>()\n\n constructor(\n private readonly nodes: {\n requireAgentNodeRun(projectId: string, id: string): WorkflowNodeRunRecord\n requireWorkflowRun(projectId: string, id: string): WorkflowRunRecord\n },\n private readonly executions: ExecutionStorage\n ) {}\n\n snapshot(): InMemoryWorkflowAgentNodeRunStorageSnapshot {\n return structuredClone(this.runs)\n }\n\n restore(snapshot: InMemoryWorkflowAgentNodeRunStorageSnapshot): void {\n this.runs.clear()\n for (const [key, record] of structuredClone(snapshot)) this.runs.set(key, record)\n }\n\n async create(input: CreateWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord> {\n const node = this.nodes.requireAgentNodeRun(input.projectId, input.nodeRunId)\n const workflowRun = this.nodes.requireWorkflowRun(input.projectId, node.workflowRunId)\n await assertWorkflowAgentNodeRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n nodeRunId: input.nodeRunId,\n actorId: input.actorId,\n workflowExecutionId: workflowRun.executionId,\n })\n if (node.status !== \"running\") {\n throw new WorkflowRunError(\n `[Sixb] Agent workflow node run '${input.nodeRunId}' must be running when queued.`\n )\n }\n const key = storageKey(input.projectId, input.nodeRunId)\n if (this.runs.has(key)) {\n throw new WorkflowRunError(\n `[Sixb] Agent execution already exists for workflow node run '${input.nodeRunId}'.`\n )\n }\n if (\n [...this.runs.values()].some(\n (run) => run.projectId === input.projectId && run.executionId === input.executionId\n )\n ) {\n throw new WorkflowRunError(\n `[Sixb] Execution '${input.executionId}' already belongs to another Workflow Agent-node run.`\n )\n }\n const record: WorkflowAgentNodeRunRecord = {\n projectId: input.projectId,\n nodeRunId: input.nodeRunId,\n executionId: input.executionId,\n actorId: input.actorId,\n status: \"queued\",\n prompt: input.prompt,\n attempt: 0,\n createdAt: new Date(input.createdAt ?? new Date()),\n }\n this.runs.set(key, cloneRecord(record))\n return cloneRecord(record)\n }\n\n async start(input: StartWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord> {\n const run = this.requireStatus(input.projectId, input.nodeRunId, \"queued\")\n const next: WorkflowAgentNodeRunRecord = {\n ...run,\n status: \"running\",\n ...(input.modelId ? { modelId: input.modelId } : {}),\n attempt: 1,\n execution: cloneRecord(input.execution),\n startedAt: new Date(input.startedAt ?? new Date()),\n }\n return this.save(next)\n }\n\n async reclaim(input: ReclaimWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord> {\n const run = this.requireStatus(input.projectId, input.nodeRunId, \"running\")\n return this.save({ ...run, attempt: run.attempt + 1, execution: cloneRecord(input.execution) })\n }\n\n async confirmExecutionOwnership(\n input: ConfirmWorkflowAgentNodeRunExecutionOwnershipInput\n ): Promise<WorkflowAgentNodeRunRecord> {\n const run = this.requireOwned(input.projectId, input.nodeRunId, input.executionToken)\n return this.save({\n ...run,\n execution: {\n token: input.executionToken,\n queueLeaseExpiresAt: new Date(\n Math.max(\n run.execution!.queueLeaseExpiresAt.getTime(),\n input.queueLeaseExpiresAt.getTime()\n )\n ),\n },\n })\n }\n\n async finish(input: FinishWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord> {\n const run = this.requireOwned(input.projectId, input.nodeRunId, input.executionToken)\n return this.save({\n ...run,\n status: input.status,\n ...(input.modelId === undefined ? {} : { modelId: input.modelId }),\n ...(input.finishReason === undefined ? {} : { finishReason: input.finishReason }),\n ...(input.trace === undefined ? {} : { trace: cloneRecord(input.trace) }),\n ...(input.diagnostics === undefined ? {} : { diagnostics: cloneRecord(input.diagnostics) }),\n ...(input.status === \"succeeded\" || input.error === undefined\n ? {}\n : { error: normalizeAgentFailure(input.error) }),\n execution: undefined,\n completedAt: new Date(input.completedAt ?? new Date()),\n })\n }\n\n async cancel(input: CancelWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord> {\n const run = this.requireExisting(input.projectId, input.nodeRunId)\n if (run.status !== \"queued\" && run.status !== \"running\") {\n throw new WorkflowRunError(\n `[Sixb] Agent workflow node run '${input.nodeRunId}' cannot be cancelled from status '${run.status}'.`\n )\n }\n return this.save({\n ...run,\n status: \"cancelled\",\n execution: undefined,\n error: normalizeAgentFailure(input.error),\n completedAt: new Date(input.completedAt ?? new Date()),\n })\n }\n\n async getByNodeRunId(params: {\n projectId: string\n nodeRunId: string\n }): Promise<WorkflowAgentNodeRunRecord | null> {\n const run = this.runs.get(storageKey(params.projectId, params.nodeRunId))\n return run ? cloneRecord(run) : null\n }\n\n async list(input: ListWorkflowAgentNodeRunsInput): Promise<ListWorkflowAgentNodeRunsResult> {\n const statuses = input.statuses ? new Set(input.statuses) : null\n const order = input.order ?? \"desc\"\n const filtered = [...this.runs.values()]\n .filter((run) => run.projectId === input.projectId)\n .filter((run) => (input.actorId ? run.actorId === input.actorId : true))\n .filter((run) => (statuses ? statuses.has(run.status) : true))\n .sort((a, b) =>\n order === \"asc\"\n ? a.createdAt.getTime() - b.createdAt.getTime()\n : b.createdAt.getTime() - a.createdAt.getTime()\n )\n const { page, total, hasMore } = paginate(filtered, input)\n return { runs: page.map(cloneRecord), total, hasMore }\n }\n\n private requireStatus(\n projectId: string,\n nodeRunId: string,\n status: WorkflowAgentNodeRunRecord[\"status\"]\n ): WorkflowAgentNodeRunRecord {\n const run = this.runs.get(storageKey(projectId, nodeRunId))\n if (!run) throw new WorkflowRunError(`[Sixb] Agent workflow node run '${nodeRunId}' not found.`)\n if (run.status !== status) {\n throw new WorkflowRunError(\n `[Sixb] Agent workflow node run '${nodeRunId}' must be ${status} (status '${run.status}').`\n )\n }\n return run\n }\n\n private requireExisting(projectId: string, nodeRunId: string): WorkflowAgentNodeRunRecord {\n const run = this.runs.get(storageKey(projectId, nodeRunId))\n if (!run) {\n throw new WorkflowRunError(\n `[Sixb] Agent workflow node run '${nodeRunId}' not found for project '${projectId}'.`\n )\n }\n return run\n }\n\n private requireOwned(\n projectId: string,\n nodeRunId: string,\n token: string\n ): WorkflowAgentNodeRunRecord {\n const run = this.requireStatus(projectId, nodeRunId, \"running\")\n if (run.execution?.token !== token) {\n throw new WorkflowRunError(\n `[Sixb] Execution token is no longer current on agent workflow node run '${nodeRunId}'.`\n )\n }\n return run\n }\n\n private save(record: WorkflowAgentNodeRunRecord): WorkflowAgentNodeRunRecord {\n this.runs.set(storageKey(record.projectId, record.nodeRunId), cloneRecord(record))\n return cloneRecord(record)\n }\n}\n\nexport interface InMemoryWorkflowRunStorageSnapshot {\n readonly runs: Map<string, WorkflowRunRecord>\n readonly nodes: InMemoryWorkflowNodeRunStorageSnapshot\n readonly agentNodes: InMemoryWorkflowAgentNodeRunStorageSnapshot\n}\n\nexport type InMemoryWorkflowNodeRunStorageSnapshot = Map<string, WorkflowNodeRunRecord>\nexport type InMemoryWorkflowAgentNodeRunStorageSnapshot = Map<string, WorkflowAgentNodeRunRecord>\n",
|
|
54
|
+
"import type { InMemoryStorageSnapshot } from \".\"\n\nexport interface InMemoryStorageTestingAdapter {\n snapshot(): InMemoryStorageSnapshot\n}\n\nconst testingAdapters = new WeakMap<object, InMemoryStorageTestingAdapter>()\n\nexport function registerInMemoryStorageTestingAdapter(\n storage: object,\n adapter: InMemoryStorageTestingAdapter\n): void {\n testingAdapters.set(storage, adapter)\n}\n\n/** @internal Relative test-only access; intentionally absent from every package barrel. */\nexport function getInMemoryStorageTestingAdapter(storage: object): InMemoryStorageTestingAdapter {\n const adapter = testingAdapters.get(storage)\n if (!adapter) throw new Error(\"[Sixb] In-memory storage testing adapter is unavailable.\")\n return adapter\n}\n",
|
|
55
|
+
"import type { Storage } from \"../types\"\nimport type { MigrationCapableStorage, MigrationReport, StorageMigrationResult } from \"./types\"\n\nexport function isMigrationCapableStorage(storage: Storage): storage is MigrationCapableStorage {\n return Array.isArray((storage as { migrators?: unknown }).migrators)\n}\n\n/** Runs storage adapter migrators when the configured storage exposes them. */\nexport async function migrateStorage(storage: Storage): Promise<StorageMigrationResult> {\n if (!isMigrationCapableStorage(storage) || storage.migrators.length === 0) {\n return { status: \"skipped\", reports: [] }\n }\n\n const reports: MigrationReport[] = []\n\n for (const migrator of storage.migrators) {\n reports.push(await migrator.migrate())\n }\n\n return {\n status: reports.some((report) => report.status === \"migrated\") ? \"migrated\" : \"current\",\n reports,\n }\n}\n",
|
|
56
|
+
"import type { Storage } from \"../types\"\nimport { isMigrationCapableStorage } from \"./migrate-storage\"\n\nexport interface StorageSchemaCheck {\n readonly ok: boolean\n /**\n * Whether anything was read. False when the storage exposes no migrators: usable on the\n * strength of having no schema rather than of a verified one.\n */\n readonly verified: boolean\n /** Absent only when `ok`. Names the adapter, the state, and what to do about it. */\n readonly reason?: string\n}\n\n/**\n * Reports whether the configured storage's schema is usable, without touching it.\n *\n * Storage with no migrators is usable by definition. Failures are returned rather than thrown,\n * because both callers report instead of aborting: `/ready` and `sixb check`.\n */\nexport async function checkStorageSchema(storage: Storage): Promise<StorageSchemaCheck> {\n if (!isMigrationCapableStorage(storage)) return { ok: true, verified: false }\n\n try {\n // `status()` is the only read-only member of the migrator contract: `migrate()` calls\n // `ensure()` first, so it runs DDL and takes an advisory lock. This serves `/ready`.\n const statuses = await Promise.all(storage.migrators.map((migrator) => migrator.status()))\n const unusable = statuses.filter((status) => status.state !== \"current\")\n\n if (unusable.length === 0) return { ok: true, verified: true }\n\n return {\n ok: false,\n verified: true,\n // Named, because \"could not be verified\" leaves an operator guessing between a missing\n // migration, a schema newer than the build, and no database at all.\n reason: unusable\n .map((status) => `${status.adapterId}: ${status.state} — ${status.reason ?? \"\"}`)\n .join(\"; \"),\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return {\n ok: false,\n verified: false,\n reason: `Storage schema could not be verified: ${message}`,\n }\n }\n}\n",
|
|
57
|
+
"import type {\n DefineMigrationsOptions,\n MigrationHistoryStore,\n MigrationPlan,\n MigrationRecord,\n MigrationReport,\n MigrationSet,\n MigrationStatus,\n MigrationStep,\n MigrationStepOptions,\n} from \"./types\"\n\nexport interface PlanMigrationSetParams<TContext> {\n readonly migrations: MigrationSet<TContext>\n readonly state: MigrationHistoryStore\n}\n\nexport interface RunMigrationSetParams<TContext> extends PlanMigrationSetParams<TContext> {\n readonly context: TContext\n readonly now?: () => string\n}\n\nexport function step<TContext>(\n id: string,\n up: (context: TContext) => void | Promise<void>,\n options: MigrationStepOptions = {}\n): MigrationStep<TContext> {\n const { version, name } = parseMigrationId(id)\n\n return {\n id,\n version,\n name,\n checksum: options.checksum,\n up,\n }\n}\n\nexport function defineMigrations<TContext>(\n options: DefineMigrationsOptions<TContext>\n): MigrationSet<TContext> {\n const steps = [...options.steps]\n assertValidSteps(options.adapterId, steps)\n\n return {\n adapterId: options.adapterId,\n latestVersion: steps.at(-1)?.version ?? 0,\n steps,\n }\n}\n\nasync function planMigrationSet<TContext>(\n params: PlanMigrationSetParams<TContext>\n): Promise<MigrationPlan<TContext>> {\n await params.state.ensure()\n\n const rows = await params.state.readHistory(params.migrations.adapterId)\n const applied = assertAppliedPrefix(params.migrations, rows)\n\n return {\n adapterId: params.migrations.adapterId,\n latestVersion: params.migrations.latestVersion,\n applied,\n pending: params.migrations.steps.slice(applied.length),\n }\n}\n\nexport async function runMigrationSet<TContext>(\n params: RunMigrationSetParams<TContext>\n): Promise<MigrationReport> {\n const now = params.now ?? (() => new Date().toISOString())\n const plan = await planMigrationSet(params)\n const applied: string[] = []\n\n for (const migration of plan.pending) {\n await params.state.transaction(async () => {\n await params.state.markStarted(plan.adapterId, migration, now())\n await migration.up(params.context)\n await params.state.markApplied(plan.adapterId, migration, now())\n })\n\n applied.push(migration.id)\n }\n\n return {\n adapterId: plan.adapterId,\n latestVersion: plan.latestVersion,\n status: applied.length > 0 ? \"migrated\" : \"current\",\n applied,\n skipped: plan.applied.map((migration) => migration.id),\n }\n}\n\nfunction parseMigrationId(id: string): { version: number; name: string } {\n const match = /^(\\d+)(?:[-_](.+))?$/.exec(id)\n\n if (!match) {\n throw new Error(`[Sixb] Migration id must start with a numeric prefix: ${id}`)\n }\n\n const version = Number(match[1])\n\n if (!Number.isInteger(version) || version < 1) {\n throw new Error(`[Sixb] Migration id must start with a positive version: ${id}`)\n }\n\n return {\n version,\n name: match[2] ?? id,\n }\n}\n\nfunction assertValidSteps<TContext>(\n adapterId: string,\n steps: readonly MigrationStep<TContext>[]\n): void {\n let previousVersion = 0\n\n for (const migration of steps) {\n if (migration.version <= previousVersion) {\n throw new Error(`[${adapterId}] Migrations must be ordered by ascending version.`)\n }\n\n previousVersion = migration.version\n }\n}\n\n/**\n * Classifies migration history without touching the database.\n *\n * The single source of truth for what a history means. `status()` reports the result\n * and `assertAppliedPrefix` throws on it, so the read-only probe and the migration\n * path can never disagree about whether a database is usable.\n *\n * `rows: null` means the history table itself is absent, which a probe must be able to\n * express without creating it.\n */\nexport function describeMigrationHistory<TContext>(params: {\n readonly migrations: MigrationSet<TContext>\n readonly rows: readonly MigrationRecord[] | null\n}): MigrationStatus {\n const { migrations, rows } = params\n const base = { adapterId: migrations.adapterId, latestVersion: migrations.latestVersion }\n\n // An adapter that declares no migrations and has recorded none is as current as it can\n // be. Reading that as `uninitialized` sent an operator to run `sixb db migrate`, which\n // would have applied nothing and reported the same state again. Only the empty history\n // qualifies: an adapter with no steps whose database recorded some is `ahead`, which\n // the walk below still finds.\n if (rows === null) {\n return migrations.steps.length === 0\n ? { ...base, appliedVersion: 0, state: \"current\" }\n : {\n ...base,\n appliedVersion: 0,\n state: \"uninitialized\",\n reason: \"No migration history exists. Run `sixb db migrate`.\",\n }\n }\n\n const applied = [...rows].sort((a, b) => a.version - b.version)\n const appliedVersion = applied.at(-1)?.version ?? 0\n const found = { ...base, appliedVersion }\n const seen = new Set<number>()\n\n for (const row of applied) {\n if (row.adapterId !== migrations.adapterId) {\n return {\n ...found,\n state: \"incompatible\",\n reason: `Migration state belongs to a different adapter: ${row.adapterId}`,\n }\n }\n\n if (row.status === \"started\") {\n return {\n ...found,\n state: \"dirty\",\n reason: `Migration '${row.id}' started and never finished. Resolve it by hand before serving traffic.`,\n }\n }\n\n if (row.status !== \"applied\") {\n return {\n ...found,\n state: \"incompatible\",\n reason: `Invalid migration status: ${row.status}`,\n }\n }\n\n if (seen.has(row.version)) {\n return {\n ...found,\n state: \"incompatible\",\n reason: `Duplicate applied migration: ${row.version}`,\n }\n }\n\n seen.add(row.version)\n }\n\n for (const [index, row] of applied.entries()) {\n const migration = migrations.steps[index]\n\n if (!migration || row.version > migrations.latestVersion) {\n return {\n ...found,\n state: \"ahead\",\n reason:\n \"Database schema is newer than this Sixb version. Downgrades are not supported; \" +\n \"deploy a build that knows this schema.\",\n }\n }\n\n if (row.version !== migration.version || row.id !== migration.id) {\n return {\n ...found,\n state: \"incompatible\",\n reason: \"Applied migration history does not match declared migrations\",\n }\n }\n\n if ((row.checksum ?? null) !== (migration.checksum ?? null)) {\n return {\n ...found,\n state: \"incompatible\",\n reason: `Applied migration checksum changed: ${row.id}`,\n }\n }\n }\n\n if (applied.length === 0) {\n return migrations.steps.length === 0\n ? { ...found, state: \"current\" }\n : {\n ...found,\n state: \"uninitialized\",\n reason: \"Migration history is empty. Run `sixb db migrate`.\",\n }\n }\n\n const pendingCount = migrations.steps.length - applied.length\n if (pendingCount > 0) {\n return {\n ...found,\n state: \"pending\",\n reason: `${pendingCount} migration(s) are not applied. Run \\`sixb db migrate\\`.`,\n }\n }\n\n return { ...found, state: \"current\" }\n}\n\nfunction assertAppliedPrefix<TContext>(\n migrations: MigrationSet<TContext>,\n rows: readonly MigrationRecord[]\n): readonly MigrationRecord[] {\n const status = describeMigrationHistory({ migrations, rows })\n\n // `uninitialized` and `pending` are the normal inputs to a migration, not failures.\n if (\n status.state !== \"current\" &&\n status.state !== \"uninitialized\" &&\n status.state !== \"pending\"\n ) {\n throw new Error(`[${migrations.adapterId}] ${status.reason}`)\n }\n\n return [...rows].sort((a, b) => a.version - b.version)\n}\n",
|
|
58
|
+
"import type { SixbFailure } from \"../../errors/types\"\nimport type { OntologyObjectRef } from \"../../materialization/model\"\nimport type { MaterializationSession } from \"./materializations\"\n\nexport const VECTOR_INDEXING_FAILURE_CODES = [\n \"vector.model_unavailable\",\n \"vector.response_invalid\",\n \"vector.outcome_unknown\",\n \"internal.unexpected\",\n] as const\n\nexport type VectorIndexingFailureCode = (typeof VECTOR_INDEXING_FAILURE_CODES)[number]\n\n/** Latest desired representation; replacing its id fences every older delivery. */\nexport interface VectorIndexingRequest {\n readonly id: string\n /** Set only by projection materialization; a bounded, immediately durable group. */\n readonly batchId?: string\n readonly ref: OntologyObjectRef\n readonly profile: string\n readonly configuration: string\n readonly sourceFingerprint: string\n readonly sourceCommitId: string\n}\n\nexport interface VectorIndexingWork extends VectorIndexingRequest {\n readonly status: \"pending\" | \"running\" | \"ready\" | \"failed\"\n readonly availableAt: string\n readonly values?: readonly number[]\n readonly error?: SixbFailure<VectorIndexingFailureCode>\n}\n\nexport interface VectorIndexingUpdate {\n readonly id: string\n readonly expectedStatus: VectorIndexingWork[\"status\"]\n readonly status: VectorIndexingWork[\"status\"]\n readonly availableAt: string\n readonly values?: readonly number[]\n readonly error?: SixbFailure<VectorIndexingFailureCode>\n}\n\n/** Durable intent belongs to ontology storage; delivery leases belong to Queues. */\nexport interface OntologyVectorIndexingStorage {\n /** Called inside the transaction that changes the effective object. */\n schedule(input: {\n projectId: string\n session: MaterializationSession\n requests: readonly VectorIndexingRequest[]\n deleted: readonly OntologyObjectRef[]\n availableAt: string\n }): Promise<void>\n /** Clear matching intent atomically with a successful automatic or explicit vector write. */\n complete(input: {\n projectId: string\n session: MaterializationSession\n entries: readonly Pick<\n VectorIndexingRequest,\n \"ref\" | \"profile\" | \"configuration\" | \"sourceFingerprint\"\n >[]\n }): Promise<void>\n dispatched(input: {\n projectId: string\n ids: readonly string[]\n nextDispatchAt: string\n }): Promise<void>\n get(input: { projectId: string; id: string }): Promise<VectorIndexingWork | null>\n getBatch(input: { projectId: string; batchId: string }): Promise<readonly VectorIndexingWork[]>\n /** Read only the result this kernel batch is allowed to publish. */\n getBatchMember(input: {\n projectId: string\n batchId: string\n ref: OntologyObjectRef\n profile: string\n }): Promise<VectorIndexingWork | null>\n /** Atomic transitions; requireAll prevents admission if any prepared member was superseded. */\n updateBatch(input: {\n projectId: string\n updates: readonly VectorIndexingUpdate[]\n requireAll?: boolean\n }): Promise<boolean>\n /** Bounded fair redispatch scan. Never scans objects or backfills existing data. */\n listDue(input: {\n projectId: string\n now: string\n limit: number\n }): Promise<readonly VectorIndexingWork[]>\n /** CAS also fences concurrent deliveries and source changes. */\n update(input: {\n projectId: string\n id: string\n expectedStatus: VectorIndexingWork[\"status\"]\n status: VectorIndexingWork[\"status\"]\n availableAt: string\n values?: readonly number[]\n error?: SixbFailure<VectorIndexingFailureCode>\n }): Promise<boolean>\n remove(input: { projectId: string; id: string }): Promise<void>\n}\n"
|
|
59
|
+
],
|
|
60
|
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