@noy-db/hub 0.7.0-pre.11 → 0.7.0-pre.13
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/CHANGELOG.md +142 -0
- package/dist/as/index.js +3 -2
- package/dist/as/index.js.map +1 -1
- package/dist/{backup-VASRVLDZ.js → backup-R6A4VZRX.js} +4 -4
- package/dist/cargo/index.js +2 -2
- package/dist/chunk-66TQOPFM.js +37 -0
- package/dist/chunk-66TQOPFM.js.map +1 -0
- package/dist/{chunk-OEA5NVSU.js → chunk-AJQY44CE.js} +86 -6
- package/dist/chunk-AJQY44CE.js.map +1 -0
- package/dist/{chunk-S5AMPTNE.js → chunk-BMELYFHU.js} +2 -2
- package/dist/{chunk-T6PSWLAR.js → chunk-BUE2D7PX.js} +25 -2
- package/dist/chunk-BUE2D7PX.js.map +1 -0
- package/dist/chunk-BWXGSSFX.js +1589 -0
- package/dist/chunk-BWXGSSFX.js.map +1 -0
- package/dist/{chunk-HN4FNA4X.js → chunk-COTPDJR5.js} +8 -8
- package/dist/{chunk-E3EBMC4G.js → chunk-E2MYJGSG.js} +2 -2
- package/dist/{chunk-JJR2JIN4.js → chunk-FFBYRWDJ.js} +2 -2
- package/dist/{chunk-WQF3QABE.js → chunk-IHFXR2VQ.js} +9 -79
- package/dist/chunk-IHFXR2VQ.js.map +1 -0
- package/dist/chunk-MGOXJIBV.js +176 -0
- package/dist/chunk-MGOXJIBV.js.map +1 -0
- package/dist/chunk-PDD75NUZ.js +87 -0
- package/dist/chunk-PDD75NUZ.js.map +1 -0
- package/dist/chunk-RTBJ5IOO.js +87 -0
- package/dist/chunk-RTBJ5IOO.js.map +1 -0
- package/dist/chunk-RXLYKVTF.js +17 -0
- package/dist/chunk-RXLYKVTF.js.map +1 -0
- package/dist/{chunk-ESVREVWN.js → chunk-SXCYYMVS.js} +2 -2
- package/dist/chunk-TFMM5DBB.js +20 -0
- package/dist/chunk-TFMM5DBB.js.map +1 -0
- package/dist/chunk-TPHAGLUH.js +30 -0
- package/dist/chunk-TPHAGLUH.js.map +1 -0
- package/dist/{chunk-THNJ3IKU.js → chunk-ULUMAZ5S.js} +2 -2
- package/dist/{chunk-NO272T7Q.js → chunk-V4PXLYWM.js} +2 -31
- package/dist/chunk-V4PXLYWM.js.map +1 -0
- package/dist/{chunk-A5WZEPXJ.js → chunk-VGICZPVE.js} +5 -3
- package/dist/{chunk-A5WZEPXJ.js.map → chunk-VGICZPVE.js.map} +1 -1
- package/dist/{chunk-KHKKD62N.js → chunk-VYYM3MEN.js} +2 -16
- package/dist/chunk-VYYM3MEN.js.map +1 -0
- package/dist/{chunk-SWVNZQVR.js → chunk-YPXNAP72.js} +2 -169
- package/dist/chunk-YPXNAP72.js.map +1 -0
- package/dist/{chunk-I6DGKPTY.js → chunk-ZVCC36XQ.js} +101 -1273
- package/dist/chunk-ZVCC36XQ.js.map +1 -0
- package/dist/{collection-facade-MGGHQ3HU.js → collection-facade-4ACKIDDY.js} +4 -3
- package/dist/derivations/index.js +21 -6
- package/dist/dispatch-MSTR5VBI.js +255 -0
- package/dist/dispatch-MSTR5VBI.js.map +1 -0
- package/dist/{dispatch-44J4TL72.js → dispatch-PDP5TA73.js} +5 -5
- package/dist/{executor-KSPGNVDO.js → executor-YDDC5XGY.js} +4 -3
- package/dist/index.d.ts +2 -2
- package/dist/index.js +39 -35
- package/dist/index.js.map +1 -1
- package/dist/introspection/index.js +3 -2
- package/dist/kernel/collection.d.ts +11 -6
- package/dist/kernel/match-pairs.d.ts +30 -0
- package/dist/lazy/index.js +3 -2
- package/dist/materialized-views/index.js +4 -3
- package/dist/{noydb-QJFZAH34.js → noydb-2C6QQJ5S.js} +17 -12
- package/dist/pod/index.js +17 -12
- package/dist/registry-D2YXKRYC.js +33 -0
- package/dist/search/index.js +1 -1
- package/dist/{stale-KSPG6LFX.js → stale-2CHKZTMK.js} +2 -2
- package/dist/{walk-G3CZIL4L.js → walk-P3E6QSNC.js} +4 -3
- package/dist/with-formula/derivations/dispatch.d.ts +16 -1
- package/dist/with-formula/derivations/registry.d.ts +20 -6
- package/dist/with-formula/derivations/trigger-match.d.ts +52 -0
- package/dist/with-formula/derivations/types.d.ts +23 -0
- package/dist/with-shape/introspection/behaviors.d.ts +7 -0
- package/dist/with-shape/introspection/describe.d.ts +30 -0
- package/package.json +3 -3
- package/dist/chunk-I6DGKPTY.js.map +0 -1
- package/dist/chunk-KHKKD62N.js.map +0 -1
- package/dist/chunk-NO272T7Q.js.map +0 -1
- package/dist/chunk-OEA5NVSU.js.map +0 -1
- package/dist/chunk-SWVNZQVR.js.map +0 -1
- package/dist/chunk-T6PSWLAR.js.map +0 -1
- package/dist/chunk-UB5CRTFF.js +0 -344
- package/dist/chunk-UB5CRTFF.js.map +0 -1
- package/dist/chunk-WQF3QABE.js.map +0 -1
- package/dist/chunk-YPMW26SL.js +0 -81
- package/dist/chunk-YPMW26SL.js.map +0 -1
- package/dist/dispatch-IM52HDXT.js +0 -194
- package/dist/dispatch-IM52HDXT.js.map +0 -1
- package/dist/registry-FZXPQRAB.js +0 -18
- /package/dist/{backup-VASRVLDZ.js.map → backup-R6A4VZRX.js.map} +0 -0
- /package/dist/{chunk-S5AMPTNE.js.map → chunk-BMELYFHU.js.map} +0 -0
- /package/dist/{chunk-HN4FNA4X.js.map → chunk-COTPDJR5.js.map} +0 -0
- /package/dist/{chunk-E3EBMC4G.js.map → chunk-E2MYJGSG.js.map} +0 -0
- /package/dist/{chunk-JJR2JIN4.js.map → chunk-FFBYRWDJ.js.map} +0 -0
- /package/dist/{chunk-ESVREVWN.js.map → chunk-SXCYYMVS.js.map} +0 -0
- /package/dist/{chunk-THNJ3IKU.js.map → chunk-ULUMAZ5S.js.map} +0 -0
- /package/dist/{collection-facade-MGGHQ3HU.js.map → collection-facade-4ACKIDDY.js.map} +0 -0
- /package/dist/{dispatch-44J4TL72.js.map → dispatch-PDP5TA73.js.map} +0 -0
- /package/dist/{executor-KSPGNVDO.js.map → executor-YDDC5XGY.js.map} +0 -0
- /package/dist/{noydb-QJFZAH34.js.map → noydb-2C6QQJ5S.js.map} +0 -0
- /package/dist/{registry-FZXPQRAB.js.map → registry-D2YXKRYC.js.map} +0 -0
- /package/dist/{stale-KSPG6LFX.js.map → stale-2CHKZTMK.js.map} +0 -0
- /package/dist/{walk-G3CZIL4L.js.map → walk-P3E6QSNC.js.map} +0 -0
|
@@ -10,7 +10,7 @@ import {
|
|
|
10
10
|
} from "./chunk-VXANTWBJ.js";
|
|
11
11
|
import {
|
|
12
12
|
putDerivedOutput
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-MGOXJIBV.js";
|
|
14
14
|
import {
|
|
15
15
|
DEFAULT_JOIN_MAX_ROWS
|
|
16
16
|
} from "./chunk-ZORTV6NH.js";
|
|
@@ -342,4 +342,4 @@ async function listOutputIds(outputColl) {
|
|
|
342
342
|
export {
|
|
343
343
|
MaterializedViewExecutor
|
|
344
344
|
};
|
|
345
|
-
//# sourceMappingURL=chunk-
|
|
345
|
+
//# sourceMappingURL=chunk-FFBYRWDJ.js.map
|
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
import {
|
|
2
|
+
decodeVecId,
|
|
3
|
+
embeddingSourceText,
|
|
4
|
+
encodeVecId,
|
|
5
|
+
isVecIdFor
|
|
6
|
+
} from "./chunk-RTBJ5IOO.js";
|
|
1
7
|
import {
|
|
2
8
|
buildBlobFieldEntries,
|
|
3
9
|
buildDictKeyFieldEntries,
|
|
@@ -5,12 +11,11 @@ import {
|
|
|
5
11
|
buildStringFieldEntries,
|
|
6
12
|
extractSnippet,
|
|
7
13
|
searchScan
|
|
8
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-COTPDJR5.js";
|
|
9
15
|
import {
|
|
10
16
|
fuseRetrieval
|
|
11
17
|
} from "./chunk-AURFOK3D.js";
|
|
12
18
|
import {
|
|
13
|
-
getAtPath,
|
|
14
19
|
isStaticDictDescriptor,
|
|
15
20
|
stripI18nFilled
|
|
16
21
|
} from "./chunk-TRGTKX5E.js";
|
|
@@ -18,82 +23,9 @@ import {
|
|
|
18
23
|
liveRecordIsElevated
|
|
19
24
|
} from "./chunk-JMGDHKQF.js";
|
|
20
25
|
import {
|
|
21
|
-
EmbeddingDimMismatchError
|
|
22
|
-
EmbeddingModelMismatchError
|
|
26
|
+
EmbeddingDimMismatchError
|
|
23
27
|
} from "./chunk-7O3Y4PPD.js";
|
|
24
28
|
|
|
25
|
-
// src/with-lookup/embeddings/cosine.ts
|
|
26
|
-
function cosine(a, b) {
|
|
27
|
-
if (a.length !== b.length) return 0;
|
|
28
|
-
let dot = 0, na = 0, nb = 0;
|
|
29
|
-
for (let i = 0; i < a.length; i++) {
|
|
30
|
-
const x = a[i], y = b[i];
|
|
31
|
-
dot += x * y;
|
|
32
|
-
na += x * x;
|
|
33
|
-
nb += y * y;
|
|
34
|
-
}
|
|
35
|
-
if (na === 0 || nb === 0) return 0;
|
|
36
|
-
return dot / (Math.sqrt(na) * Math.sqrt(nb));
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
// src/with-lookup/embeddings/descriptor.ts
|
|
40
|
-
function embeddingSourceText(record, source) {
|
|
41
|
-
const fields = typeof source === "string" ? [source] : source;
|
|
42
|
-
const parts = [];
|
|
43
|
-
for (const f of fields) {
|
|
44
|
-
for (const leaf of getAtPath(record, f)) {
|
|
45
|
-
if (typeof leaf === "string" && leaf !== "") parts.push(leaf);
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
return parts.join(" ");
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
// src/with-lookup/embeddings/vector-set.ts
|
|
52
|
-
var VectorSet = class {
|
|
53
|
-
vectors;
|
|
54
|
-
get loaded() {
|
|
55
|
-
return this.vectors !== void 0;
|
|
56
|
-
}
|
|
57
|
-
async ensureLoaded(load) {
|
|
58
|
-
if (this.vectors === void 0) this.vectors = await load();
|
|
59
|
-
}
|
|
60
|
-
markDirty() {
|
|
61
|
-
this.vectors = void 0;
|
|
62
|
-
}
|
|
63
|
-
cosineTopK(query, k, opts = {}) {
|
|
64
|
-
const all = this.vectors ?? [];
|
|
65
|
-
const minScore = opts.minScore ?? -Infinity;
|
|
66
|
-
const hits = [];
|
|
67
|
-
for (const v of all) {
|
|
68
|
-
if (opts.expectModel !== void 0 && v.model !== opts.expectModel) {
|
|
69
|
-
throw new EmbeddingModelMismatchError(opts.expectModel, v.model);
|
|
70
|
-
}
|
|
71
|
-
const score = cosine(query, v.vec);
|
|
72
|
-
if (score >= minScore) hits.push({ id: v.id, score });
|
|
73
|
-
}
|
|
74
|
-
hits.sort((a, b) => b.score - a.score);
|
|
75
|
-
return hits.slice(0, k);
|
|
76
|
-
}
|
|
77
|
-
};
|
|
78
|
-
|
|
79
|
-
// src/with-lookup/embeddings/vec-id.ts
|
|
80
|
-
function encodeVecId(collection, recordId) {
|
|
81
|
-
if (collection.includes("/")) {
|
|
82
|
-
throw new Error(
|
|
83
|
-
`encodeVecId: collection name "${collection}" must not contain "/" \u2014 it would make the "${collection}/${recordId}" _vec id ambiguous against another collection's rows.`
|
|
84
|
-
);
|
|
85
|
-
}
|
|
86
|
-
return `${collection}/${recordId}`;
|
|
87
|
-
}
|
|
88
|
-
function decodeVecId(collection, vecId) {
|
|
89
|
-
const prefix = `${collection}/`;
|
|
90
|
-
if (!vecId.startsWith(prefix)) return null;
|
|
91
|
-
return vecId.slice(prefix.length);
|
|
92
|
-
}
|
|
93
|
-
function isVecIdFor(collection, vecId) {
|
|
94
|
-
return vecId.startsWith(`${collection}/`);
|
|
95
|
-
}
|
|
96
|
-
|
|
97
29
|
// src/with-lookup/search/collection-facade.ts
|
|
98
30
|
async function search(ctx, field, query, opts = {}) {
|
|
99
31
|
if (ctx.lazy) {
|
|
@@ -380,8 +312,6 @@ async function syncTierSearch(ctx, id, record, version) {
|
|
|
380
312
|
}
|
|
381
313
|
|
|
382
314
|
export {
|
|
383
|
-
VectorSet,
|
|
384
|
-
encodeVecId,
|
|
385
315
|
search,
|
|
386
316
|
buildRetrievalDocs,
|
|
387
317
|
hasIndexedBlobFields,
|
|
@@ -394,4 +324,4 @@ export {
|
|
|
394
324
|
rebuildEmbeddings,
|
|
395
325
|
syncTierSearch
|
|
396
326
|
};
|
|
397
|
-
//# sourceMappingURL=chunk-
|
|
327
|
+
//# sourceMappingURL=chunk-IHFXR2VQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/with-lookup/search/collection-facade.ts"],"sourcesContent":["/**\n * Collection-level search / retrieval (`search` / `retrieve` / `similarTo` +\n * the lexical-index build/flush/warm machinery).\n *\n * This is the retrieval surface: a pure client-side lexical scan\n * (`search`), the persisted-or-in-memory inverted-index lifecycle\n * (`flushIndex` / `warmIndex` / `buildRetrievalDocs` + the dict-label / blob-\n * filename resolvers that feed it), and the lexical / semantic / hybrid\n * `retrieve` fan-out plus raw-vector kNN (`similarTo`). None of it touches the\n * write path — it reads the live eager cache and the encrypted `_vec` / `_ftindex`\n * side-cars.\n *\n * Every function takes a small {@link SearchContext} instead of `this`,\n * mirroring the `record-keys/` siblings.\n *\n * The `cache` is the SAME `Map` reference `Collection` owns (passed by\n * reference, never copied) so the index always builds over the live working\n * set. {@link buildPersistedIndexCallbacks} is special: it is invoked from the\n * `Collection` constructor *before* `this.codec` exists, so it takes a context\n * THUNK and resolves the context lazily at each callback invocation.\n *\n * Internal service — not exported as a `@noy-db/hub/*` subpath.\n */\nimport type { NoydbStore } from '../../kernel/types.js'\nimport type { RecordCodec } from '../../kernel/enclave/index.js'\nimport { stripI18nFilled, type I18nTextDescriptor } from '../../via/i18n/core.js'\nimport { isStaticDictDescriptor, type DictKeyDescriptor, type StaticDictDescriptor, type DictionaryHandle } from '../../via/i18n/dictionary.js'\nimport type { BlobSet } from '../../with-shape/blobs/blob-set.js'\nimport type { BlobFieldsConfig } from '../../with-shape/blobs/blob-compaction.js'\nimport type { Query } from '../../kernel/query/index.js'\nimport { embeddingSourceText, type VectorSet, type EmbeddingDescriptor, type StoredVector } from '../embeddings/index.js'\nimport { encodeVecId, decodeVecId, isVecIdFor } from '../embeddings/vec-id.js'\nimport { EmbeddingDimMismatchError } from '../../kernel/errors.js'\nimport { liveRecordIsElevated } from '../../kernel/tier-visibility.js'\nimport { searchScan, fuseRetrieval, type SearchOptions, type SearchResult } from './index.js'\nimport type { IndexStore } from './index-store.js'\nimport type { PersistedIndexCallbacks } from './persisted-index-store.js'\nimport { extractSnippet } from './snippet.js'\nimport { buildStringFieldEntries, buildI18nFieldEntries, buildDictKeyFieldEntries, buildBlobFieldEntries } from './build-docs.js'\nimport type { IndexDoc, IndexHit } from './inverted-index.js'\nimport type { RetrieveOptions, RetrieveHit } from './retrieve-types.js'\n\n/** Everything the moving search/retrieval methods touched on `this.*`. */\nexport interface SearchContext<T> {\n /** Collection name — error context + `_ftindex` row key. */\n readonly name: string\n /** Vault namespace the side-cars (`_vec`, `_ftindex`) live under. */\n readonly vault: string\n /** The ciphertext store. */\n readonly adapter: NoydbStore\n /** The record codec — decrypts the `_vec` / `_ftindex` side-car bodies. */\n readonly codec: RecordCodec<T>\n /** The eager working-set cache (SHARED `Map` reference, never copied). */\n readonly cache: Map<string, { record: T; version: number }>\n /** True in lazy mode — search/retrieve/warm require eager mode. */\n readonly lazy: boolean\n /** Declared text-index fields, or undefined. */\n readonly textIndexes: readonly string[] | undefined\n /** Declared i18n fields, or undefined. */\n readonly i18nFields: Record<string, I18nTextDescriptor> | undefined\n /** Declared dictionary-key fields, or undefined. */\n readonly dictKeyFields: Record<string, DictKeyDescriptor | StaticDictDescriptor> | undefined\n /** Declared blob fields, or undefined. */\n readonly blobFields: BlobFieldsConfig | undefined\n /** Dictionary handle resolver (dynamic dict-key labels), or undefined. */\n readonly getDictionary: ((name: string) => Promise<DictionaryHandle>) | undefined\n /** The lexical inverted-index store (in-memory or persisted), or undefined. */\n readonly searchIndexStore: IndexStore | undefined\n /** The vector set for semantic retrieval, or undefined. */\n readonly vectorSet: VectorSet | undefined\n /** The embeddings descriptor, or undefined. */\n readonly embeddings: EmbeddingDescriptor | undefined\n /** Hydrate the eager cache before reading it. */\n ensureHydrated(): Promise<void>\n /** Open the blob facade for a record (used to list indexed blob filenames). */\n blob(id: string): BlobSet\n}\n\n/**\n * Client-side lexical scan over the live eager cache. Eager mode only;\n * nothing searchable is written to the store.\n */\nexport async function search<T>(ctx: SearchContext<T>, field: string, query: string, opts: SearchOptions = {}): Promise<SearchResult<T>[]> {\n if (ctx.lazy) {\n throw new Error(\n `Collection \"${ctx.name}\": search() (scan mode) requires eager mode (prefetch: true). ` +\n `A store-usable blind index for lazy / at-scale search is a separate gated opt-in (#308).`,\n )\n }\n await ctx.ensureHydrated()\n const entries: { id: string; record: T }[] = []\n // Strip the internal densify marker from the user-facing records.\n // Non-mutating: never touches the cached record object. The search index\n // is built over the same (marker-free) record, which is fine — the marker\n // is never a searchable field.\n for (const [id, e] of ctx.cache) entries.push({ id, record: stripI18nFilled(e.record as Record<string, unknown>) as T })\n return searchScan(entries, field, query, opts)\n}\n\n/** L1 — build IndexDoc[] for the configured text fields over the live cache. */\nexport function buildRetrievalDocs<T>(\n ctx: SearchContext<T>,\n labelMaps: Map<string, Map<string, Record<string, string>>>,\n blobFilenames: Map<string, Map<string, string[]>>,\n only?: readonly string[],\n): IndexDoc[] {\n const docs: IndexDoc[] = []\n for (const [id, e] of ctx.cache) {\n const rec = stripI18nFilled(e.record as Record<string, unknown>)\n const fields = buildStringFieldEntries(rec, ctx.textIndexes ?? [], only)\n if (ctx.i18nFields) fields.push(...buildI18nFieldEntries(rec, ctx.i18nFields, ctx.textIndexes ?? [], only))\n if (ctx.dictKeyFields) fields.push(...buildDictKeyFieldEntries(rec, ctx.dictKeyFields, labelMaps, ctx.textIndexes ?? [], only))\n const blobNames = blobFilenames.get(id)\n if (blobNames) fields.push(...buildBlobFieldEntries(blobNames))\n if (fields.length > 0) docs.push({ id, fields })\n }\n return docs\n}\n\n/** L1 — true iff any configured text index is also a blob field (gates ALL slot I/O). */\nexport function hasIndexedBlobFields<T>(ctx: SearchContext<T>, only?: readonly string[]): boolean {\n if (!ctx.blobFields || !ctx.textIndexes) return false\n const fields = only ? ctx.textIndexes.filter((f) => only.includes(f)) : ctx.textIndexes\n return fields.some((f) => f in ctx.blobFields!)\n}\n\n/**\n * L1 — resolve `recordId -> (blobField -> filenames[])` by listing slots\n * for the configured blob fields of each cached record. Blob slot metadata is\n * NOT inline on the record: it lives in a separate `_blob_slots_*` collection,\n * so this costs ONE `blob(id).list()` (a `listSlots`) per record at build time\n * — the heaviest indexing source. Fully gated by {@link hasIndexedBlobFields};\n * non-blob (and blob-but-not-indexed) collections do ZERO slot I/O.\n */\nasync function resolveBlobFilenames<T>(ctx: SearchContext<T>, only?: readonly string[]): Promise<Map<string, Map<string, string[]>>> {\n const out = new Map<string, Map<string, string[]>>()\n if (!hasIndexedBlobFields(ctx, only)) return out\n const indexed = (only ? ctx.textIndexes!.filter((f) => only.includes(f)) : ctx.textIndexes!)\n .filter((f) => f in ctx.blobFields!)\n const indexedSet = new Set(indexed)\n for (const id of ctx.cache.keys()) {\n let slots\n try {\n slots = await ctx.blob(id).list()\n } catch {\n continue\n }\n let byField: Map<string, string[]> | undefined\n for (const slot of slots) {\n if (!indexedSet.has(slot.name) || !slot.filename) continue\n if (!byField) { byField = new Map(); out.set(id, byField) }\n const names = byField.get(slot.name)\n if (names) names.push(slot.filename)\n else byField.set(slot.name, [slot.filename])\n }\n }\n return out\n}\n\n/** L1 — field -> (key -> {locale->label}) for dictKey fields; static from table, dynamic via getDictionary().list(). */\nasync function resolveDictLabelMaps<T>(ctx: SearchContext<T>): Promise<Map<string, Map<string, Record<string, string>>>> {\n const maps = new Map<string, Map<string, Record<string, string>>>()\n if (!ctx.dictKeyFields || !ctx.textIndexes) return maps\n for (const field of ctx.textIndexes) {\n const desc = ctx.dictKeyFields[field]\n if (!desc) continue\n const m = new Map<string, Record<string, string>>()\n if (isStaticDictDescriptor(desc)) {\n for (const [key, labels] of Object.entries(desc.table)) m.set(key, labels as Record<string, string>)\n } else {\n if (ctx.getDictionary) {\n const handle = await ctx.getDictionary(desc.name)\n for (const e of await handle.list()) m.set(e.key, e.labels)\n }\n }\n maps.set(field, m)\n }\n return maps\n}\n\n/** L1.5 — force-persist the lexical index now (e.g. on save/idle). Persists only when textIndexPersist is enabled; a no-op otherwise. */\nexport async function flushIndex<T>(ctx: SearchContext<T>): Promise<void> {\n if (!ctx.searchIndexStore) return\n await ctx.ensureHydrated()\n const labelMaps = await resolveDictLabelMaps(ctx)\n const blobFilenames = await resolveBlobFilenames(ctx)\n await ctx.searchIndexStore.ensureBuilt(() => buildRetrievalDocs(ctx, labelMaps, blobFilenames))\n await ctx.searchIndexStore.flush?.()\n}\n\n/** L2 — load + decrypt all _vec sidecars into StoredVector[] for the VectorSet. */\nfunction buildVectorLoad<T>(ctx: SearchContext<T>): () => Promise<StoredVector[]> {\n return async () => {\n const ids = await ctx.adapter.list(ctx.vault, '_vec')\n const out: StoredVector[] = []\n for (const vecId of ids) {\n // #726: _vec is a vault-wide bucket namespaced by collection prefix —\n // skip rows belonging to other collections before touching this one's.\n if (!isVecIdFor(ctx.name, vecId)) continue\n const id = decodeVecId(ctx.name, vecId)!\n // #721 defense-in-depth: a _vec row carries no _tier of its own; the purge\n // on elevate is best-effort and cannot reach a legacy sidecar, so gate on\n // the owning record's live tier. Envelope peek, no decryption.\n if (await liveRecordIsElevated(ctx.adapter, ctx.vault, ctx.name, id)) continue\n const env = await ctx.adapter.get(ctx.vault, '_vec', vecId)\n if (!env) continue\n // #726 fails-safe: a row can pass isVecIdFor's prefix filter yet still\n // be undecryptable under THIS collection's DEK — a surviving legacy\n // bare-id row whose record id happens to start with `<thisCollection>/`,\n // or plain corruption. _vec sidecars are derived, re-derivable\n // artifacts (embedOnWrite regenerates them on the record's next put()),\n // so best-effort skip is correct: never let one poison row crash\n // similarTo()/retrieve() for the whole collection.\n let body: string | null\n try {\n body = await ctx.codec.decryptJsonString({ collection: '_vec', id: vecId }, env)\n } catch {\n continue\n }\n if (body === null) continue\n const parsed = JSON.parse(body) as { vec: number[]; model: string }\n out.push({ id, vec: new Float32Array(parsed.vec), model: parsed.model })\n }\n return out\n }\n}\n\n/**\n * L1.5 — build the PersistedIndexCallbacks bridge: crypto lives here\n * (collection has getDEK / encryptJsonString / decryptJsonString / adapter),\n * the index store itself is crypto-free.\n *\n * Fingerprint encoding: body-wrap approach — save(json, fp) stores\n * JSON.stringify({ fp, idx: json }) as the encrypted body so the standard\n * EncryptedEnvelope shape is never extended. load() decrypts and JSON.parses\n * the wrapper back out.\n *\n * Cache shape: ctx.cache stores { record, version } — currentFingerprint()\n * iterates over e.version.\n *\n * NOTE: this factory is invoked from the `Collection` constructor *before*\n * `this.codec` is assigned, so it takes a context THUNK and resolves the\n * context lazily inside each callback — by the time a callback actually runs,\n * the codec and cache are fully wired.\n */\nexport function buildPersistedIndexCallbacks<T>(provideCtx: () => SearchContext<T>): PersistedIndexCallbacks {\n const FT = '_ftindex'\n return {\n load: async () => {\n const ctx = provideCtx()\n const env = await ctx.adapter.get(ctx.vault, FT, ctx.name)\n if (!env) return null\n const body = await ctx.codec.decryptJsonString({ collection: FT, id: ctx.name }, env)\n if (body === null) return null\n try {\n const wrapped = JSON.parse(body) as { fp: { count: number; maxVersion: number }; idx: string }\n return { json: wrapped.idx, fingerprint: wrapped.fp }\n } catch {\n return null\n }\n },\n save: async (json, fp, isStale) => {\n const ctx = provideCtx()\n const body = JSON.stringify({ fp, idx: json })\n const env = await ctx.codec.encryptJsonString({ collection: FT, id: ctx.name }, body, fp.count)\n // #725 review: a purge (removePersisted) can land while the encrypt above was\n // in flight — check right before the write and skip it rather than resurrect a\n // purged/forgotten record's blob. PersistedIndexStore's own post-save epoch\n // check is the backstop for every other ordering (incl. a purge landing during\n // this very put).\n if (isStale()) return\n await ctx.adapter.put(ctx.vault, FT, ctx.name, env)\n },\n remove: async () => { const ctx = provideCtx(); await ctx.adapter.delete(ctx.vault, FT, ctx.name) },\n currentFingerprint: () => {\n const ctx = provideCtx()\n let maxVersion = 0\n for (const e of ctx.cache.values()) if (e.version > maxVersion) maxVersion = e.version\n return { count: ctx.cache.size, maxVersion }\n },\n }\n}\n\n/** L1 — pre-build the lexical index (e.g. on open) so the first retrieve() pays no build scan. */\nexport async function warmIndex<T>(ctx: SearchContext<T>): Promise<void> {\n if (!ctx.searchIndexStore) return\n if (ctx.lazy) {\n throw new Error(\n `Collection \"${ctx.name}\": warmIndex() requires eager mode (prefetch: true).`,\n )\n }\n await ctx.ensureHydrated()\n const built = ctx.searchIndexStore.built\n const labelMaps = built ? new Map() : await resolveDictLabelMaps(ctx)\n const blobFilenames = built ? new Map() : await resolveBlobFilenames(ctx)\n await ctx.searchIndexStore.ensureBuilt(() => buildRetrievalDocs(ctx, labelMaps, blobFilenames))\n}\n\n/** Retrieval. mode: 'lexical' (default) | 'semantic' (L2) | 'hybrid' (L3). */\nexport async function retrieve<T>(ctx: SearchContext<T>, query: string, opts: RetrieveOptions<T> = {}): Promise<RetrieveHit<T>[]> {\n const hits =\n opts.mode === 'semantic' ? await retrieveSemantic(ctx, query, opts)\n : opts.mode === 'hybrid' ? await retrieveHybrid(ctx, query, opts)\n : await retrieveLexical(ctx, query, opts)\n return opts.within ? applyWithin(hits, opts.within) : hits\n}\n\n/** L3 — keep only hits whose id matches the structured query, re-rank 1-based. */\nfunction applyWithin<T>(hits: RetrieveHit<T>[], within: Query<T>): RetrieveHit<T>[] {\n const ids = new Set(within._idArray())\n return hits.filter(h => ids.has(h.id)).map((h, i) => ({ ...h, rank: i + 1 }))\n}\n\n/** L1 — client-side lexical retrieval; ranked { id, score, field, snippet, locale? }. */\nasync function retrieveLexical<T>(ctx: SearchContext<T>, query: string, opts: RetrieveOptions<T>): Promise<RetrieveHit<T>[]> {\n if (!ctx.searchIndexStore) {\n throw new Error(`Collection \"${ctx.name}\": retrieve() requires a textIndexes config.`)\n }\n if (ctx.lazy) {\n throw new Error(\n `Collection \"${ctx.name}\": retrieve() requires eager mode (prefetch: true).`,\n )\n }\n await ctx.ensureHydrated()\n const built = ctx.searchIndexStore.built\n const labelMaps = built ? new Map() : await resolveDictLabelMaps(ctx)\n const blobFilenames = built ? new Map() : await resolveBlobFilenames(ctx)\n const index = await ctx.searchIndexStore.ensureBuilt(() => buildRetrievalDocs(ctx, labelMaps, blobFilenames))\n const hits = index.query(query, {\n ...(opts.limit !== undefined ? { limit: opts.limit } : {}),\n ...(opts.match ? { match: opts.match } : {}),\n ...(opts.prefix ? { prefix: opts.prefix } : {}),\n ...(opts.fields ? { fields: opts.fields } : {}),\n })\n const window = opts.snippetWindow ?? 80\n return hits.map((h: IndexHit, i: number) => {\n const base: RetrieveHit<T> = {\n id: h.id,\n score: h.score,\n rank: i + 1,\n field: h.field,\n snippet: extractSnippet(h.text, h.offset, window),\n ...(h.locale !== undefined ? { locale: h.locale } : {}),\n ...(opts.includeRecord\n ? (() => {\n const e = ctx.cache.get(h.id)\n return e ? { record: stripI18nFilled(e.record as Record<string, unknown>) as T } : {}\n })()\n : {}),\n }\n return base\n })\n}\n\n/** L3 — hybrid: fuse lexical (L1) + semantic (L2) by RRF. Requires embeddings. */\nasync function retrieveHybrid<T>(ctx: SearchContext<T>, query: string, opts: RetrieveOptions<T>): Promise<RetrieveHit<T>[]> {\n if (!ctx.embeddings) {\n throw new Error(`Collection \"${ctx.name}\": retrieve({mode:'hybrid'}) requires an embeddings config.`)\n }\n const [lex, sem] = await Promise.all([\n retrieveLexical(ctx, query, opts),\n retrieveSemantic(ctx, query, opts),\n ])\n return fuseRetrieval([lex, sem], opts.limit !== undefined ? { limit: opts.limit } : {})\n}\n\n/** L2 — semantic branch of retrieve(): encode query → similarTo(). */\nasync function retrieveSemantic<T>(ctx: SearchContext<T>, query: string, opts: RetrieveOptions<T>): Promise<RetrieveHit<T>[]> {\n if (!ctx.embeddings) throw new Error(`Collection \"${ctx.name}\": retrieve({mode:'semantic'}) requires an embeddings config.`)\n if (ctx.lazy) throw new Error(`Collection \"${ctx.name}\": retrieve() requires eager mode (prefetch: true).`)\n const qVec = await ctx.embeddings.encode(query)\n return similarTo(ctx, qVec, {\n ...(opts.limit !== undefined ? { k: opts.limit } : {}),\n ...(opts.minScore !== undefined ? { minScore: opts.minScore } : {}),\n ...(opts.includeRecord ? { includeRecord: true } : {}),\n })\n}\n\n/** L2 — raw-vector kNN over the encrypted vector set (decrypted in the trusted tier).\n * Snippet is '' for vector hits in v1 (semantic match isn't span-located). */\nexport async function similarTo<T>(ctx: SearchContext<T>, vector: Float32Array, opts: { k?: number; minScore?: number; includeRecord?: boolean } = {}): Promise<RetrieveHit<T>[]> {\n if (!ctx.embeddings || !ctx.vectorSet) throw new Error(`Collection \"${ctx.name}\": similarTo() requires an embeddings config.`)\n if (ctx.lazy) throw new Error(`Collection \"${ctx.name}\": similarTo() requires eager mode (prefetch: true).`)\n await ctx.ensureHydrated()\n await ctx.vectorSet.ensureLoaded(buildVectorLoad(ctx))\n const hits = ctx.vectorSet.cosineTopK(vector, opts.k ?? 10, {\n ...(opts.minScore !== undefined ? { minScore: opts.minScore } : {}),\n expectModel: ctx.embeddings.model,\n })\n return hits.map((h, i) => {\n const base: RetrieveHit<T> = { id: h.id, score: h.score, rank: i + 1, field: '(vector)', snippet: '' }\n if (opts.includeRecord) { const e = ctx.cache.get(h.id); if (e) (base as { record?: T }).record = stripI18nFilled(e.record as Record<string, unknown>) as T }\n return base\n })\n}\n\n/**\n * L2 — the embedding write-hook: derive a record's embedding vector at\n * write and persist it as the encrypted `_vec` side-car. Routed through the\n * search strategy so it runs only when `withSearch()` is opted in — computing\n * vectors that no gated `similarTo` / semantic `retrieve` could query would be\n * dead weight, so the compute is paired with the search capability. The caller\n * (`Collection.put`) only invokes this when `embeddings` is declared.\n */\nexport async function embedOnWrite<T>(ctx: SearchContext<T>, id: string, record: T, version: number): Promise<void> {\n if (!ctx.embeddings) return\n const text = embeddingSourceText(record as Record<string, unknown>, ctx.embeddings.source)\n const vec = await ctx.embeddings.encode(text)\n if (vec.length !== ctx.embeddings.dim) throw new EmbeddingDimMismatchError('embeddings', ctx.embeddings.dim, vec.length)\n const body = JSON.stringify({ vec: Array.from(vec), model: ctx.embeddings.model, dim: ctx.embeddings.dim })\n const vecEnv = await ctx.codec.encryptJsonString({ collection: '_vec', id: encodeVecId(ctx.name, id) }, body, version)\n await ctx.adapter.put(ctx.vault, '_vec', encodeVecId(ctx.name, id), vecEnv)\n ctx.vectorSet?.markDirty()\n}\n\n/**\n * Force-re-derive every eligible tier-0 record's `_vec` sidecar once (#788).\n * Opt-in bulk repair for the #726 re-namespace: legacy bare-id rows are\n * unreachable to `buildVectorLoad` (it only recognises `<collection>/<id>`\n * keys) and otherwise self-heal only when a record is next `put()` — this\n * lets an adopter recover recall immediately instead of waiting on writes.\n *\n * **Skips elevated records** (`liveRecordIsElevated`) rather than refusing\n * the whole walk — the OPPOSITE of `_applyCutoverTransform`'s\n * `assertCutoverTierSafe` refuse-whole-batch precedent. An elevated record is\n * SUPPOSED to have no `_vec` (`syncTierSearch` purges it on elevate);\n * re-embedding one here would write searchable plaintext-derived data above\n * tier 0. Load-bearing: never write a `_vec` row for an elevated record.\n *\n * Tombstones, delete markers, and a raw `get` racing a delete between `list`\n * and `get` all decrypt to `null` (`decryptRecord` already folds\n * tombstone/delete-marker into that null) and are skipped the same way.\n * Unconditional re-derive, no already-migrated check — safe to re-run after\n * a partial failure (each id is independently idempotent).\n */\nexport async function rebuildEmbeddings<T>(ctx: SearchContext<T>): Promise<{ rebuilt: number; skipped: number }> {\n if (!ctx.embeddings) return { rebuilt: 0, skipped: 0 }\n const ids = await ctx.adapter.list(ctx.vault, ctx.name)\n let rebuilt = 0\n let skipped = 0\n for (const id of ids) {\n if (await liveRecordIsElevated(ctx.adapter, ctx.vault, ctx.name, id)) { skipped++; continue }\n const env = await ctx.adapter.get(ctx.vault, ctx.name, id)\n if (!env) { skipped++; continue }\n const decoded = await ctx.codec.decryptRecord({ collection: ctx.name, id }, env)\n if (decoded === null) { skipped++; continue }\n await embedOnWrite(ctx, id, decoded, env._v ?? 1)\n rebuilt++\n }\n return { rebuilt, skipped }\n}\n\n/**\n * Sync the collection's SEARCH artifacts after a tier move (#721). Both the\n * lexical `_ftindex` blob and the `_vec/<id>` embedding are encrypted under\n * the tier-0 DEK and hold the record's derived plaintext (full field text /\n * a text-invertible vector), so leaving them means elevation never hid what\n * the record was searchable by — the `forget()` precedent, unapplied to\n * elevate. `null` → the record left tier 0: purge its `_vec` sidecar (mirrors\n * `Collection._purgeVector`), and invalidate the `_ftindex` blob (mirrors\n * `Collection._purgeSearchIndex`: deletes the persisted blob when persisted,\n * else drops the in-memory index) so the next `retrieve()` rebuilds from the\n * elevated-free `ctx.cache`. A record → it is tier-0 again: re-embed it via\n * {@link embedOnWrite}, then invalidate `_ftindex` so the rebuild includes it\n * again. No-op fast when the collection has neither a lexical index nor a\n * vector set.\n */\nexport async function syncTierSearch<T>(\n ctx: SearchContext<T>,\n id: string,\n record: T | null,\n version?: number,\n): Promise<void> {\n if (!ctx.searchIndexStore && !ctx.vectorSet) return\n if (record === null) {\n await ctx.adapter.delete(ctx.vault, '_vec', encodeVecId(ctx.name, id))\n ctx.vectorSet?.markDirty()\n } else {\n await embedOnWrite(ctx, id, record, version ?? 1)\n }\n const store = ctx.searchIndexStore\n if (store && 'removePersisted' in store) await (store as { removePersisted(): Promise<void> }).removePersisted()\n else store?.markDirty()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkFA,eAAsB,OAAU,KAAuB,OAAe,OAAe,OAAsB,CAAC,GAA+B;AACzI,MAAI,IAAI,MAAM;AACZ,UAAM,IAAI;AAAA,MACR,eAAe,IAAI,IAAI;AAAA,IAEzB;AAAA,EACF;AACA,QAAM,IAAI,eAAe;AACzB,QAAM,UAAuC,CAAC;AAK9C,aAAW,CAAC,IAAI,CAAC,KAAK,IAAI,MAAO,SAAQ,KAAK,EAAE,IAAI,QAAQ,gBAAgB,EAAE,MAAiC,EAA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C5B;AAiBA,eAAsB,eACpB,KACA,IACA,QACA,SACe;AACf,MAAI,CAAC,IAAI,oBAAoB,CAAC,IAAI,UAAW;AAC7C,MAAI,WAAW,MAAM;AACnB,UAAM,IAAI,QAAQ,OAAO,IAAI,OAAO,QAAQ,YAAY,IAAI,MAAM,EAAE,CAAC;AACrE,QAAI,WAAW,UAAU;AAAA,EAC3B,OAAO;AACL,UAAM,aAAa,KAAK,IAAI,QAAQ,WAAW,CAAC;AAAA,EAClD;AACA,QAAM,QAAQ,IAAI;AAClB,MAAI,SAAS,qBAAqB,MAAO,OAAO,MAA+C,gBAAgB;AAAA,MAC1G,QAAO,UAAU;AACxB;","names":[]}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import {
|
|
2
|
+
matchesReferencingValue
|
|
3
|
+
} from "./chunk-YPXNAP72.js";
|
|
4
|
+
import {
|
|
5
|
+
PeriodClosedError
|
|
6
|
+
} from "./chunk-7O3Y4PPD.js";
|
|
7
|
+
|
|
8
|
+
// src/kernel/via/dispatch.ts
|
|
9
|
+
function touchFor(batch, collection) {
|
|
10
|
+
let t = batch.get(collection);
|
|
11
|
+
if (!t) {
|
|
12
|
+
t = { puts: /* @__PURE__ */ new Set(), deletes: /* @__PURE__ */ new Map() };
|
|
13
|
+
batch.set(collection, t);
|
|
14
|
+
}
|
|
15
|
+
return t;
|
|
16
|
+
}
|
|
17
|
+
function resolveRollupDeleteIntents(registry, collectionName, deleted) {
|
|
18
|
+
if (!registry) return [];
|
|
19
|
+
const intents = [];
|
|
20
|
+
for (const { spec } of registry.strategiesForSource(collectionName)) {
|
|
21
|
+
if (!spec.rollup || spec.rollup.from !== collectionName) continue;
|
|
22
|
+
const kv = deleted[spec.rollup.key];
|
|
23
|
+
if (typeof kv === "string" || typeof kv === "number") intents.push({ into: spec.source, parentId: String(kv), field: spec.rollup.field });
|
|
24
|
+
}
|
|
25
|
+
return intents;
|
|
26
|
+
}
|
|
27
|
+
function findRollupSpecForIntent(registry, collectionName, intent) {
|
|
28
|
+
return registry?.strategiesForSource(collectionName).find((s) => s.spec.source === intent.into && s.spec.rollup?.field === intent.field && s.spec.rollup?.from === collectionName)?.spec;
|
|
29
|
+
}
|
|
30
|
+
var WaveContext = class {
|
|
31
|
+
_seen = /* @__PURE__ */ new Set();
|
|
32
|
+
seen(targetKey) {
|
|
33
|
+
if (this._seen.has(targetKey)) return true;
|
|
34
|
+
this._seen.add(targetKey);
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
async function runGraphDispatchWave(vault, batch) {
|
|
39
|
+
const wave = new WaveContext();
|
|
40
|
+
for (const [collectionName, touch] of batch) {
|
|
41
|
+
if (vault.graph.dependentsOf(collectionName).length === 0) continue;
|
|
42
|
+
const coll = vault._getCollection(collectionName);
|
|
43
|
+
if (!coll) continue;
|
|
44
|
+
for (const id of touch.puts) {
|
|
45
|
+
try {
|
|
46
|
+
const stored = await coll._getStoredRecordForDispatch(id);
|
|
47
|
+
if (!stored) continue;
|
|
48
|
+
await coll.dispatchDerivations(id, stored.record, stored.version, wave);
|
|
49
|
+
await coll.dispatchMaterializedViews(id, stored.record, wave);
|
|
50
|
+
} catch (err) {
|
|
51
|
+
console.warn(`[via-dispatch] wave recompute failed for ${collectionName}/${id}:`, err);
|
|
52
|
+
vault._emit("derivation:wave-error", { collection: collectionName, id, error: err });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
for (const [id, intents] of touch.deletes) {
|
|
56
|
+
try {
|
|
57
|
+
await coll._recomputeDeletedRollups(intents, wave);
|
|
58
|
+
await coll.dispatchMaterializedViewsOnDelete(id);
|
|
59
|
+
await coll.dispatchArrayDerivationsOnDelete(id);
|
|
60
|
+
} catch (err) {
|
|
61
|
+
console.warn(`[via-dispatch] wave delete-recompute failed for ${collectionName}/${id}:`, err);
|
|
62
|
+
vault._emit("derivation:wave-error", { collection: collectionName, id, error: err });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
async function putDerivedOutput(outColl, id, value, ctx, options) {
|
|
68
|
+
try {
|
|
69
|
+
await outColl.put(id, value, options);
|
|
70
|
+
return "written";
|
|
71
|
+
} catch (err) {
|
|
72
|
+
if (!(err instanceof PeriodClosedError)) throw err;
|
|
73
|
+
const targetCollection = outColl.name;
|
|
74
|
+
const event = {
|
|
75
|
+
source: ctx.source,
|
|
76
|
+
target: { collection: targetCollection, id },
|
|
77
|
+
period: err.periodName,
|
|
78
|
+
endDate: err.endDate
|
|
79
|
+
};
|
|
80
|
+
ctx.emit("derivation:skipped-frozen", event);
|
|
81
|
+
if (ctx.audit) await ctx.audit(event);
|
|
82
|
+
return "skipped-frozen";
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function ledgerAuditHook(ledger, actor) {
|
|
86
|
+
if (!ledger) return void 0;
|
|
87
|
+
return async (e) => {
|
|
88
|
+
await ledger.append({
|
|
89
|
+
op: "lifecycle",
|
|
90
|
+
collection: e.target.collection,
|
|
91
|
+
id: e.target.id,
|
|
92
|
+
version: 0,
|
|
93
|
+
actor,
|
|
94
|
+
payloadHash: "",
|
|
95
|
+
reason: JSON.stringify({ event: "derivation-skipped-frozen", ...e })
|
|
96
|
+
});
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
async function forgetDerivedFanout(vault, ref, envelope, stats, lookupCompareKeys) {
|
|
100
|
+
const coll = vault._getCollection(ref.collection);
|
|
101
|
+
if (coll) {
|
|
102
|
+
const mv = await coll.dispatchMaterializedViewsOnDelete(ref.id);
|
|
103
|
+
stats.recordsErased += mv.deleted;
|
|
104
|
+
stats.derivedResidueUndecodable.push(...mv.residueUndecodable);
|
|
105
|
+
stats.derivedResidueDeclined.push(...mv.residueDeclined);
|
|
106
|
+
}
|
|
107
|
+
const edges = vault.graph.derivedArtifactsOf(ref.collection);
|
|
108
|
+
if (edges.length === 0 || !coll) return;
|
|
109
|
+
if (edges.some((e) => e.kind === "ref")) {
|
|
110
|
+
const { cascaded, nullified, residue } = await applyLookupRefsFanout(vault, ref.collection, ref.id, lookupCompareKeys);
|
|
111
|
+
stats.lookupReferencesCascaded += cascaded;
|
|
112
|
+
stats.lookupReferencesNullified += nullified;
|
|
113
|
+
stats.lookupReferencesResidue.push(...residue);
|
|
114
|
+
}
|
|
115
|
+
if (edges.some((e) => e.kind === "derivation")) {
|
|
116
|
+
stats.recordsErased += await coll.dispatchArrayDerivationsOnDelete(ref.id, true);
|
|
117
|
+
}
|
|
118
|
+
if (envelope && edges.some((e) => e.kind === "rollup")) {
|
|
119
|
+
const priorRecord = await coll._decodeEnvelope(envelope, ref.id);
|
|
120
|
+
if (priorRecord) {
|
|
121
|
+
for (const r of await coll.dispatchRollupsOnDelete(ref.id, priorRecord)) {
|
|
122
|
+
if (r.outcome === "written") stats.aggregatesRecomputed += 1;
|
|
123
|
+
else if (r.outcome === "skipped-frozen") stats.residueFrozen.push(`${r.into}:${r.parentId}`);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
async function applyLookupRefsFanout(vault, backing, key, compareKeys) {
|
|
129
|
+
let cascaded = 0;
|
|
130
|
+
let nullified = 0;
|
|
131
|
+
const residue = [];
|
|
132
|
+
for (const { referencing, onDelete, keyField } of vault.graph.referencingEdgesOf(backing)) {
|
|
133
|
+
if (onDelete === "restrict") continue;
|
|
134
|
+
const compareKey = keyField === "id" ? key : compareKeys.get(keyField);
|
|
135
|
+
if (compareKey === void 0) {
|
|
136
|
+
residue.push(`${backing}:${key}:${referencing.collection}.${referencing.field}`);
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
const coll = vault._getCollection(referencing.collection);
|
|
140
|
+
if (!coll) continue;
|
|
141
|
+
const matches = (await coll.list()).filter((rec) => matchesReferencingValue(rec, referencing.field, compareKey));
|
|
142
|
+
for (const rec of matches) {
|
|
143
|
+
const id = rec["id"];
|
|
144
|
+
if (id === void 0) continue;
|
|
145
|
+
if (onDelete === "cascade") {
|
|
146
|
+
await coll.delete(id);
|
|
147
|
+
cascaded++;
|
|
148
|
+
} else if (onDelete === "nullify") {
|
|
149
|
+
await coll.put(id, { ...rec, [referencing.field]: null });
|
|
150
|
+
nullified++;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return { cascaded, nullified, residue };
|
|
155
|
+
}
|
|
156
|
+
function selfWriteFieldEqual(a, b) {
|
|
157
|
+
if (a === b) return true;
|
|
158
|
+
if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
|
|
159
|
+
try {
|
|
160
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
161
|
+
} catch {
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export {
|
|
167
|
+
touchFor,
|
|
168
|
+
resolveRollupDeleteIntents,
|
|
169
|
+
findRollupSpecForIntent,
|
|
170
|
+
runGraphDispatchWave,
|
|
171
|
+
putDerivedOutput,
|
|
172
|
+
ledgerAuditHook,
|
|
173
|
+
forgetDerivedFanout,
|
|
174
|
+
selfWriteFieldEqual
|
|
175
|
+
};
|
|
176
|
+
//# sourceMappingURL=chunk-MGOXJIBV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/kernel/via/dispatch.ts"],"sourcesContent":["// kernel/via/dispatch.ts — the batched, origin-aware sync/cutover/restore dispatch wave\n// (Via port phase C, #638 Task 4, fixes #621).\n//\n// `Collection._onRecordMutated`'s `sync-apply`/`cutover`/`restore` cases feed touched\n// (collection, id) pairs into a per-session `GraphBatch` (owned by `Vault._collectGraphTouch`)\n// instead of dispatching inline — the `local-write` path keeps its own byte-identical inline\n// dispatch (`wave` stays `undefined` there, per the spec's behavior lock). At batch-flush time\n// `runGraphDispatchWave` decrypts each touched record (id threaded into the decrypt, matching\n// the phase-B at-rest contract) and re-runs the SAME `dispatchDerivations`/\n// `dispatchMaterializedViews` the local-write path uses, sharing one `WaveContext` so N touched\n// records feeding the SAME rollup/MV target recompute exactly once (per-target dedup).\n// See design-history/2026-07-11-via-phase-c-design.md §3.\n\nimport type { ViaGraph } from './graph.js'\nimport type { Collection } from '../collection.js'\nimport type { EncryptedEnvelope } from '../types.js'\nimport { PeriodClosedError } from '../errors.js'\nimport { matchesReferencingValue } from '../../port/with/lookup-strategy.js'\n\n/** One deleted child's resolved rollup PARENT intent (#640) — ids + a field name only. A\n * resolved `parentId` is an id, same class as any touched record id — never a stored value. */\nexport interface RollupDeleteIntent {\n readonly into: string\n readonly parentId: string\n readonly field: string\n}\n\n/** One collection's batched touches this session (#640 widens the #638 `Set<string>` shape):\n * `puts` — the original semantics, unchanged; `deletes` — a deleted record's id mapped to its\n * resolved rollup-parent intents, captured PRE-invalidation by `Collection._onRecordMutated`'s\n * sync-apply delete case (the FK is only readable there — see `kernel/collection.ts\n * #_rollupDeleteIntents`). */\nexport interface GraphTouch {\n readonly puts: Set<string>\n readonly deletes: Map<string, readonly RollupDeleteIntent[]>\n}\n\n/** Per-session touched set — collection → its `GraphTouch`. Metadata only — ids (collection\n * names, record ids INCLUDING resolved rollup parent ids) and field names; NEVER record payload\n * or key material. A resolved parentId is an id, same class as the touched ids — not a stored\n * value. */\nexport type GraphBatch = Map<string, GraphTouch>\n\n/** Get-or-create `batch`'s `GraphTouch` entry for `collection` (#640) — shared by\n * `Vault._collectGraphTouch`/`_collectGraphDelete` so each stays a one-line call. */\nexport function touchFor(batch: GraphBatch, collection: string): GraphTouch {\n let t = batch.get(collection)\n if (!t) {\n t = { puts: new Set(), deletes: new Map() }\n batch.set(collection, t)\n }\n return t\n}\n\n/** #640 — sync, I/O-free: `deleted`'s resolved rollup PARENT intents (the FK is only readable\n * NOW, before the record is gone) — a pure function so `Collection._rollupDeleteIntents` stays\n * a one-line delegator under the kernel-surface ceiling. `registry` is `this.derivationSource\n * ?.registry()`; `collectionName` is `this.name` (the CHILD/`rollup.from` side). Generic over\n * the registry's own spec shape so this file never imports a `with-formula` type (port-layering\n * — via/dispatch.ts must not gain a with-* import). */\nexport function resolveRollupDeleteIntents<S extends { source: string; rollup?: { from: string; key: string; field: string } }>(\n registry: { strategiesForSource(name: string): ReadonlyArray<{ spec: S }> } | undefined,\n collectionName: string,\n deleted: Record<string, unknown>,\n): RollupDeleteIntent[] {\n if (!registry) return []\n const intents: RollupDeleteIntent[] = []\n for (const { spec } of registry.strategiesForSource(collectionName)) {\n if (!spec.rollup || spec.rollup.from !== collectionName) continue\n const kv = deleted[spec.rollup.key]\n if (typeof kv === 'string' || typeof kv === 'number') intents.push({ into: spec.source, parentId: String(kv), field: spec.rollup.field })\n }\n return intents\n}\n\n/** #640 — resolve a `RollupDeleteIntent` back to its registry `spec`. The wave's per-intent\n * driver needs `spec.rollup.compute`, which `GraphBatch`'s metadata-only pin forbids batching —\n * so it's re-resolved here, post-boundary, instead of carried across it. `undefined` if the\n * intent's originating strategy was unregistered between collect time and wave time (residual\n * gap, freshness-only). */\nexport function findRollupSpecForIntent<S extends { source: string; rollup?: { from: string; field: string } }>(\n registry: { strategiesForSource(name: string): ReadonlyArray<{ spec: S }> } | undefined,\n collectionName: string,\n intent: RollupDeleteIntent,\n): S | undefined {\n return registry?.strategiesForSource(collectionName).find((s) => s.spec.source === intent.into && s.spec.rollup?.field === intent.field && s.spec.rollup?.from === collectionName)?.spec\n}\n\n/** One dedup ledger for a single wave — a target is recomputed at most once (mark-on-check). */\nexport class WaveContext {\n private readonly _seen = new Set<string>()\n seen(targetKey: string): boolean {\n if (this._seen.has(targetKey)) return true\n this._seen.add(targetKey)\n return false\n }\n}\n\n/** The slice of `Vault` the wave needs: the shared graph (the #553 zero-cost skip) and cached-\n * collection lookup — never constructs, since a touched collection is, by construction,\n * already open (it just fired `_onRecordMutated`). */\nexport interface VaultLike {\n readonly graph: ViaGraph\n _getCollection(name: string): Collection<Record<string, unknown>> | undefined\n /** #640 (#644 item 3) — structured wave-error surfacing, additive to the existing console.warn. */\n _emit(event: string, payload: unknown): void\n}\n\n/**\n * Run ONE dispatch wave for a completed batch: for each touched (collection, id), decrypt the\n * applied envelope (id threaded), then run the SAME `dispatchDerivations` +\n * `dispatchMaterializedViews` the local-write path uses — with a shared `WaveContext` so N\n * touched records feeding the SAME target recompute once. #553: a collection with no graph\n * out-edges (e.g. money-only) is skipped before any decrypt/dispatch async work.\n */\nexport async function runGraphDispatchWave(vault: VaultLike, batch: GraphBatch): Promise<void> {\n const wave = new WaveContext()\n for (const [collectionName, touch] of batch) {\n if (vault.graph.dependentsOf(collectionName).length === 0) continue\n const coll = vault._getCollection(collectionName)\n if (!coll) continue\n for (const id of touch.puts) {\n try {\n // Decrypt is INSIDE the per-id isolation boundary (whole-branch review Important\n // finding, #638): an undecryptable synced envelope (`TamperedError`) must not\n // escape `_getStoredRecordForDispatch` and abort the wave — that would propagate\n // through `_flushGraphBatch` and reject the surrounding `SyncEngine.pull`/`push`\n // AFTER records were already applied + meta persisted, starving every other\n // touched target in the same batch.\n const stored = await coll._getStoredRecordForDispatch(id)\n if (!stored) continue\n await coll.dispatchDerivations(id, stored.record, stored.version, wave)\n await coll.dispatchMaterializedViews(id, stored.record, wave)\n } catch (err) {\n // #638 Task 5 review mandate: one touched record's recompute must not abort the\n // whole wave (starving co-batched healthy targets) or the pull/push it's nested\n // inside. `PeriodClosedError` never reaches here — `putDerivedOutput` already\n // intercepts it at every output-write call site and turns it into a skip+event.\n // Anything else (a genuine decrypt failure, a derive()/executor bug, a schema\n // violation on the output, ...) is surfaced — not silently swallowed — via the\n // SAME console.warn channel `dispatchDerivations`/the MV executor already use for\n // their own non-strict-mode output failures, then isolated to just this one id.\n // #644 item 3: ADDITIVELY (never in place of the warn) emit a structured event too,\n // so a listener doesn't have to scrape console output to react to a wave failure.\n console.warn(`[via-dispatch] wave recompute failed for ${collectionName}/${id}:`, err)\n vault._emit('derivation:wave-error', { collection: collectionName, id, error: err })\n }\n }\n // #640 — delete-kind touches: the deleted child's rollup-parent intents, resolved (sync,\n // pre-invalidation) at collect time by `Collection._rollupDeleteIntents`. Same per-id\n // isolation as the puts loop above. #658: the wave now ALSO heals MV rows and array-shape\n // derivation output rows for the deleted child — parity with the local-delete boundary\n // (`Collection._doDelete`'s `!internal` block, which already calls all three). Still never\n // routed through `dispatchDerivations` (the mutation-choke-point.test.ts:85-99 pin — sync-\n // applied deletes never RE-DERIVE); `dispatchMaterializedViewsOnDelete`/\n // `dispatchArrayDerivationsOnDelete` only need `id` (MV refresh recomputes+diffs; array-\n // derivation reads its per-source sidecar) and never call `derive()`, so the pin holds.\n for (const [id, intents] of touch.deletes) {\n try {\n await coll._recomputeDeletedRollups(intents, wave)\n // #658: record-shape same-id outputs are left untouched (eraseRecordShapeToo defaults\n // false), matching local delete — the user deletes those directly if wanted.\n // #658: TODO dedup MV refresh per wave — `dispatchMaterializedViewsOnDelete` doesn't\n // accept a `WaveContext` (unlike the put-path `dispatchMaterializedViews`), so N deleted\n // children of one eager MV in a batch each trigger a full refresh pass. Threading `wave`\n // through would touch collection.ts's zero-slack kernel-surface ceiling for a perf-only\n // win; correctness doesn't depend on it (idempotent per source-id) — left as a follow-up.\n await coll.dispatchMaterializedViewsOnDelete(id)\n await coll.dispatchArrayDerivationsOnDelete(id)\n } catch (err) {\n console.warn(`[via-dispatch] wave delete-recompute failed for ${collectionName}/${id}:`, err)\n vault._emit('derivation:wave-error', { collection: collectionName, id, error: err })\n }\n }\n }\n}\n\n/** A record's post-freeze source mutation, for the `'derivation:skipped-frozen'` event\n * and the optional audit-trail entry. See {@link putDerivedOutput}. */\nexport interface DerivationSkippedFrozen {\n readonly source: { readonly collection: string; readonly id: string }\n readonly target: { readonly collection: string; readonly id: string }\n readonly period: string\n readonly endDate: string\n}\n\n/** The minimal put-capable shape `putDerivedOutput` needs. Any `Collection<T>` structurally\n * satisfies this — its real `options` type is a superset of what's declared here. */\nexport interface CollectionLike {\n put(id: string, value: unknown, options?: { readonly source?: string }): Promise<void>\n}\n\nexport interface PutDerivedOutputCtx {\n readonly emit: (ev: string, p: unknown) => void\n readonly source: { readonly collection: string; readonly id: string }\n readonly audit?: ((e: DerivationSkippedFrozen) => Promise<void>) | undefined\n}\n\n/**\n * Attempt a dispatch-driven output write. On `PeriodClosedError` (the closed-period\n * `beforePut` gate — `freezePeriod`/`archivePeriod` add no separate gate, per seam map\n * Part 7): SKIP (no `_ts` stamped — the gate throws before any write happens), emit\n * `'derivation:skipped-frozen'` on the event bus (ALWAYS), and append an audit-trail entry\n * when the with-history ledger is active. Returns `'written' | 'skipped-frozen'`. Any OTHER\n * error propagates unchanged — this helper narrows exactly one error class. The SOURCE\n * write is never wrapped through this helper — only derived-output writes are (§7).\n */\nexport async function putDerivedOutput(\n outColl: CollectionLike, id: string, value: unknown,\n ctx: PutDerivedOutputCtx,\n options?: { readonly source?: string },\n): Promise<'written' | 'skipped-frozen'> {\n try {\n await outColl.put(id, value, options)\n return 'written'\n } catch (err) {\n if (!(err instanceof PeriodClosedError)) throw err\n // Reach-around for the target collection's private `name` — the SAME pattern\n // `with-formula/materialized-views/executor.ts`'s `listOutputIds` already uses to\n // read a `Collection`'s private `adapter`/`vault`/`name` fields from outside the class.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const targetCollection = (outColl as any).name as string\n const event: DerivationSkippedFrozen = {\n source: ctx.source,\n target: { collection: targetCollection, id },\n period: err.periodName,\n endDate: err.endDate,\n }\n ctx.emit('derivation:skipped-frozen', event)\n if (ctx.audit) await ctx.audit(event)\n return 'skipped-frozen'\n }\n}\n\n/** Structural (no static import — kernel spine may not statically reach a with-* service,\n * the S4 gate recipe `check-architecture.mjs`'s port-layering check enforces) shape of the\n * with-history `LedgerStore.append` seam this helper needs. */\ninterface AuditLedgerLike {\n append(input: {\n readonly op: 'lifecycle'\n readonly collection: string\n readonly id: string\n readonly version: number\n readonly actor: string\n readonly payloadHash: string\n readonly reason?: string\n }): Promise<unknown>\n}\n\n/** @internal — the optional with-history ledger audit hook for `putDerivedOutput`, present\n * only when the ledger is active (mirrors every other kernel event's `if (this.ledger)`\n * gate). Encoded as a `'lifecycle'` entry — the existing \"non-data audit event\" op (the\n * same convention `forget`'s JSON-summary-in-`reason` entry uses; `ledger/entry.ts:88-104`). */\nexport function ledgerAuditHook(\n ledger: AuditLedgerLike | undefined, actor: string,\n): ((e: DerivationSkippedFrozen) => Promise<void>) | undefined {\n if (!ledger) return undefined\n return async (e) => {\n await ledger.append({\n op: 'lifecycle', collection: e.target.collection, id: e.target.id, version: 0, actor, payloadHash: '',\n reason: JSON.stringify({ event: 'derivation-skipped-frozen', ...e }),\n })\n }\n}\n\n/** `recomputeRollup`/`dispatchRollupsOnDelete`'s per-target write outcome (#638 Task 6):\n * `'written'`/`'skipped-frozen'` mirror {@link putDerivedOutput}'s result; `'noop'` covers\n * no-parent/no-change/deduped-by-wave — nothing to report either way. */\nexport type RollupOutcome = 'written' | 'skipped-frozen' | 'noop'\n\n/** Mutable accumulator `forgetDerivedFanout` writes into, one per `Vault.forget()` call — keeps\n * the per-ref loop's call site to a single line under vault.ts's tight kernel-surface ceiling.\n * Maps 1:1 onto `ForgetResult`'s additive fields (`with-audit/forget/strategy.ts`). */\nexport interface ForgetFanoutStats {\n recordsErased: number\n aggregatesRecomputed: number\n readonly residueFrozen: string[]\n /** #650 Task 5 (#648) — referencing records tombstoned via a `'ref'` edge's `cascade` policy. */\n lookupReferencesCascaded: number\n /** #650 Task 5 (#648) — referencing fields cleared via a `'ref'` edge's `nullify` policy. */\n lookupReferencesNullified: number\n /** #650 Task 5 review (Important fix) — `'ref'` edges whose compare-key could NOT be resolved,\n * even from the LIVE pre-shred row (the backing row itself is unreadable) — propagation was\n * skipped for these, reported here so the skip is never silent. `backing:key:collection.field`\n * entries, one per un-propagated edge. */\n readonly lookupReferencesResidue: string[]\n /** #776/#782/#785 — `outputCollection:id` MV-output rows that survived erasure invalidation\n * (eager tombstone leg AND lazy/manual `invalidateMVAtRest`) despite belonging to the\n * forgotten subject, because the ownership stamp could not be decoded (undecodable under\n * the default DEK — e.g. elevated above tier 0 on a tiered output collection). Ownership\n * UNCONFIRMED. Never erased, but surfaced here rather than silently skipped. */\n readonly derivedResidueUndecodable: string[]\n /** #782/#785 — `outputCollection:id` MV-output rows that decoded and stamp-matched but whose\n * `_internalDelete` declined (the #718 tier-elevation gate). Ownership CONFIRMED, erasure\n * declined — a real silent survival, surfaced here rather than silently skipped. */\n readonly derivedResidueDeclined: string[]\n}\n\n/**\n * #622 — after `_writeTombstone(ref.id, actor)` erases the forgotten subject's own record, fan\n * out to its derived residue via the graph (spec §5): record-grain artifacts (MV rows,\n * array-shape derivation rows, same-id record-shape derivation copies) are ERASED through the\n * SAME `!internal` housekeeping-bypass machinery the ordinary delete path uses (no user\n * `onDelete` re-fires — the shred-is-not-a-domain-delete property `_writeTombstone` protects);\n * aggregate-grain rollups are RECOMPUTED without the forgotten contribution in open periods, or\n * skip+audit (via `putDerivedOutput`, already wired into the rollup/MV output paths) in frozen\n * ones. Mutates `stats` in place. `envelope` is `ref`'s PRE-tombstone envelope, decoded only if\n * a rollup edge is actually present — the #553 zero-cost-skip discipline: no decrypt for the\n * common case of a forgotten record with no aggregate-grain consumer, and no work at all when\n * `ref.collection` has no graph out-edges. `lookupCompareKeys` is the `'ref'` edges' compare-key\n * map, resolved from the LIVE row BEFORE any shred (`VaultLinks.checkLookupRefsRestrict`'s return\n * value — `Vault.forget()`'s pre-shred restrict check doubles as the live-resolve pass) — see\n * {@link applyLookupRefsFanout}.\n */\nexport async function forgetDerivedFanout(\n vault: VaultLike,\n ref: { readonly collection: string; readonly id: string },\n envelope: EncryptedEnvelope | null,\n stats: ForgetFanoutStats,\n lookupCompareKeys: ReadonlyMap<string, string | undefined>,\n): Promise<void> {\n const coll = vault._getCollection(ref.collection)\n\n // #761 item 4 — drive the MV arm off `dispatchMaterializedViewsOnDelete` UNCONDITIONALLY,\n // ABOVE the `edges` check below: `registry.edges()` drops the same-collection\n // partition-disjoint MV edge (registry.ts's `sources.length === 0 → continue`), so a\n // same-collection MV's source collection never appears in `vault.graph`'s derived-artifact\n // edges even though the MV IS registered — forget() would otherwise never reach it.\n // `dispatchMaterializedViewsOnDelete` self-guards O(1) via `mvsForSource` (a no-op when\n // this collection isn't an MV source), so this is safe to call unconditionally. Safe to\n // route through the eager executor's tombstone leg ONLY because that leg is now\n // stamp-scoped (#762) — before that fix this would have opened a NEW forget-time\n // data-loss path into the unscoped tombstone diff.\n if (coll) {\n const mv = await coll.dispatchMaterializedViewsOnDelete(ref.id)\n stats.recordsErased += mv.deleted\n stats.derivedResidueUndecodable.push(...mv.residueUndecodable)\n stats.derivedResidueDeclined.push(...mv.residueDeclined)\n }\n\n const edges = vault.graph.derivedArtifactsOf(ref.collection)\n if (edges.length === 0 || !coll) return\n\n // #650 Task 5 (#648) — 'ref' cascade/nullify propagate ADDITIVELY, here, AFTER the shred\n // (restrict already refused BEFORE any shred — the caller's pre-tombstone check, spec §4).\n // The I/O shell (loop shape, collection accessor) is duplicated, not imported, from\n // `VaultLinks.applyLookupRefsPropagation`/`checkLookupRefsRestrict` (with-shape/links/\n // vault-facade.ts) — the kernel spine may not statically import a with-* service\n // (port-layering, the #638 Task 5 via/dispatch.ts precedent); `vault._getCollection` is\n // cached-only while `VaultLinks`' accessor constructs. The pure match predicate itself is\n // shared through the port seam (#651 Task 3 — `matchesReferencingValue`, `port/with/\n // lookup-strategy.ts`), so only the shell, not the coercion logic, stays duplicated. A\n // referencing edge whose dimension uses a non-default `key` (matrix tier only) needs the\n // backing row's OWN value at that field, not its PUT-id — the row is ALREADY tombstoned by\n // now, so it's read from `lookupCompareKeys`, resolved by the caller from the LIVE row\n // BEFORE the shred (#650 Task 5 review, Important fix — eliminates the post-shred\n // envelope-decode dependency this used to have, which silently skipped propagation whenever\n // that decode failed).\n if (edges.some((e) => e.kind === 'ref')) {\n const { cascaded, nullified, residue } = await applyLookupRefsFanout(vault, ref.collection, ref.id, lookupCompareKeys)\n stats.lookupReferencesCascaded += cascaded\n stats.lookupReferencesNullified += nullified\n stats.lookupReferencesResidue.push(...residue)\n }\n\n if (edges.some((e) => e.kind === 'derivation')) {\n // #622 review Finding 1: count REAL erasures (dispatchArrayDerivationsOnDelete's own\n // `_internalDelete`-backed tally), not the derivation EDGE count — an edge exists whenever\n // this collection is ANY trigger (source/sources[]/triggerBy), but the same-id record-shape\n // guard only erases for `spec.source === this.name`, and `derive()` may never have produced\n // an output row (optional-skip) in the first place. Both cases must contribute 0, not +1.\n stats.recordsErased += await coll.dispatchArrayDerivationsOnDelete(ref.id, true)\n }\n\n if (envelope && edges.some((e) => e.kind === 'rollup')) {\n const priorRecord = await coll._decodeEnvelope(envelope, ref.id)\n if (priorRecord) {\n for (const r of await coll.dispatchRollupsOnDelete(ref.id, priorRecord)) {\n if (r.outcome === 'written') stats.aggregatesRecomputed += 1\n else if (r.outcome === 'skipped-frozen') stats.residueFrozen.push(`${r.into}:${r.parentId}`)\n }\n }\n }\n}\n\n/**\n * Apply `cascade`/`nullify` propagation for `backing`'s non-restrict `'ref'` edges — the\n * forget-path counterpart of `VaultLinks.applyLookupRefsPropagation` (I/O shell duplicated, not\n * imported, match predicate shared via the port — see {@link forgetDerivedFanout}'s call site\n * comment). `restrict` edges are skipped here: the\n * forget loop's `checkLookupRefsRestrict`-equivalent call already refused (or the reference no\n * longer existed) BEFORE `_writeTombstone` ran, so by the time this runs only cascade/nullify\n * remain to propagate. `compareKeys` is the non-`'id'`-`keyField` compare-value map, resolved by\n * the caller from the LIVE row BEFORE the shred (#650 Task 5 review, Important fix) — the live row\n * is already shredded by the time THIS function runs, so it can no longer resolve one itself. A\n * `keyField` absent from (or `undefined` in) the map means that live resolve failed too — the edge\n * is reported as residue instead of silently skipped (never a bare `continue` with no trace).\n */\nasync function applyLookupRefsFanout(\n vault: VaultLike,\n backing: string,\n key: string,\n compareKeys: ReadonlyMap<string, string | undefined>,\n): Promise<{ cascaded: number; nullified: number; residue: string[] }> {\n let cascaded = 0\n let nullified = 0\n const residue: string[] = []\n for (const { referencing, onDelete, keyField } of vault.graph.referencingEdgesOf(backing)) {\n if (onDelete === 'restrict') continue\n const compareKey = keyField === 'id' ? key : compareKeys.get(keyField)\n if (compareKey === undefined) {\n residue.push(`${backing}:${key}:${referencing.collection}.${referencing.field}`)\n continue\n }\n const coll = vault._getCollection(referencing.collection)\n if (!coll) continue\n const matches = (await coll.list()).filter((rec) => matchesReferencingValue(rec, referencing.field, compareKey))\n for (const rec of matches) {\n const id = rec['id'] as string | undefined\n if (id === undefined) continue\n if (onDelete === 'cascade') {\n await coll.delete(id)\n cascaded++\n } else if (onDelete === 'nullify') {\n await coll.put(id, { ...rec, [referencing.field]: null })\n nullified++\n }\n }\n }\n return { cascaded, nullified, residue }\n}\n\n/**\n * Value-equality for a single self-write reverse-denorm field. Scalars\n * compare by identity; objects by canonical JSON (denorm values should be\n * deterministically shaped). Used as the cycle guard — when every denorm\n * field already matches, no write is issued and the self-write recursion ends.\n */\nexport function selfWriteFieldEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true\n if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false\n try {\n return JSON.stringify(a) === JSON.stringify(b)\n } catch {\n return false\n }\n}\n"],"mappings":";;;;;;;;AA6CO,SAAS,SAAS,OAAmB,YAAgC;AAC1E,MAAI,IAAI,MAAM,IAAI,UAAU;AAC5B,MAAI,CAAC,GAAG;AACN,QAAI,EAAE,MAAM,oBAAI,IAAI,GAAG,SAAS,oBAAI,IAAI,EAAE;AAC1C,UAAM,IAAI,YAAY,CAAC;AAAA,EACzB;AACA,SAAO;AACT;AAQO,SAAS,2BACd,UACA,gBACA,SACsB;AACtB,MAAI,CAAC,SAAU,QAAO,CAAC;AACvB,QAAM,UAAgC,CAAC;AACvC,aAAW,EAAE,KAAK,KAAK,SAAS,oBAAoB,cAAc,GAAG;AACnE,QAAI,CAAC,KAAK,UAAU,KAAK,OAAO,SAAS,eAAgB;AACzD,UAAM,KAAK,QAAQ,KAAK,OAAO,GAAG;AAClC,QAAI,OAAO,OAAO,YAA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B,UAAM,aAAa,aAAa,OAAO,MAAM,YAAY,IAAI,QAAQ;AACrE,QAAI,eAAe,QAAW;AAC5B,cAAQ,KAAK,GAAG,OAAO,IAAI,GAAG,IAAI,YAAY,UAAU,IAAI,YAAY,KAAK,EAAE;AAC/E;AAAA,IACF;AACA,UAAM,OAAO,MAAM,eAAe,YAAY,UAAU;AACxD,QAAI,CAAC,KAAM;AACX,UAAM,WAAW,MAAM,KAAK,KAAK,GAAG,OAAO,CAAC,QAAQ,wBAAwB,KAAK,YAAY,OAAO,UAAU,CAAC;AAC/G,eAAW,OAAO,SAAS;AACzB,YAAM,KAAK,IAAI,IAAI;AACnB,UAAI,OAAO,OAAW;AACtB,UAAI,aAAa,WAAW;AAC1B,cAAM,KAAK,OAAO,EAAE;AACpB;AAAA,MACF,WAAW,aAAa,WAAW;AACjC,cAAM,KAAK,IAAI,IAAI,EAAE,GAAG,KAAK,CAAC,YAAY,KAAK,GAAG,KAAK,CAAC;AACxD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,SAAO,EAAE,UAAU,WAAW,QAAQ;AACxC;AAQO,SAAS,oBAAoB,GAAY,GAAqB;AACnE,MAAI,MAAM,EAAG,QAAO;AACpB,MAAI,MAAM,QAAQ,MAAM,QAAQ,OAAO,MAAM,YAAY,OAAO,MAAM,SAAU,QAAO;AACvF,MAAI;AACF,WAAO,KAAK,UAAU,CAAC,MAAM,KAAK,UAAU,CAAC;AAAA,EAC/C,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import {
|
|
2
|
+
lazy
|
|
3
|
+
} from "./chunk-5D2ALSM5.js";
|
|
4
|
+
|
|
5
|
+
// src/with-formula/derivations/stale.ts
|
|
6
|
+
var loadDerivationExecutor = lazy(() => import("./executor-TOLPBHOC.js"));
|
|
7
|
+
var _staleByRegistry = /* @__PURE__ */ new WeakMap();
|
|
8
|
+
var keyFor = (source, sourceId) => `${source}/${sourceId}`;
|
|
9
|
+
async function markStale(registry, strategy, sourceId) {
|
|
10
|
+
let map = _staleByRegistry.get(registry);
|
|
11
|
+
if (!map) {
|
|
12
|
+
map = /* @__PURE__ */ new Map();
|
|
13
|
+
_staleByRegistry.set(registry, map);
|
|
14
|
+
}
|
|
15
|
+
const k = keyFor(strategy.source, sourceId);
|
|
16
|
+
let set = map.get(k);
|
|
17
|
+
if (!set) {
|
|
18
|
+
set = /* @__PURE__ */ new Set();
|
|
19
|
+
map.set(k, set);
|
|
20
|
+
}
|
|
21
|
+
set.add(strategy);
|
|
22
|
+
}
|
|
23
|
+
async function resolveStaleOnRead(accessor, outputCollection, id) {
|
|
24
|
+
const registry = accessor.registry();
|
|
25
|
+
const producers = registry.strategiesProducingOutput(outputCollection);
|
|
26
|
+
if (producers.length === 0) return;
|
|
27
|
+
const map = _staleByRegistry.get(registry);
|
|
28
|
+
if (!map) return;
|
|
29
|
+
let DerivationExecutor = null;
|
|
30
|
+
for (const { spec, strategyHash } of producers) {
|
|
31
|
+
const k = keyFor(spec.source, id);
|
|
32
|
+
const pending = map.get(k);
|
|
33
|
+
if (!pending || !pending.has(spec)) continue;
|
|
34
|
+
pending.delete(spec);
|
|
35
|
+
let failedNonStrict = false;
|
|
36
|
+
try {
|
|
37
|
+
const sourceColl = accessor.getCollection(spec.source);
|
|
38
|
+
const source = await sourceColl.get(id);
|
|
39
|
+
if (!source) {
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
const sourceWithId = { ...source, id };
|
|
43
|
+
DerivationExecutor ??= (await loadDerivationExecutor()).DerivationExecutor;
|
|
44
|
+
const ctx = { vault: accessor.getReadOnlyFacade() };
|
|
45
|
+
const result = await DerivationExecutor.run(spec, sourceWithId, 0, strategyHash, ctx);
|
|
46
|
+
for (const key of Object.keys(spec.outputs)) {
|
|
47
|
+
const out = result.outputs[key];
|
|
48
|
+
if (!out) continue;
|
|
49
|
+
if (out.kind === "failed") {
|
|
50
|
+
const err = out.error;
|
|
51
|
+
if (spec.strict) throw err;
|
|
52
|
+
console.warn(
|
|
53
|
+
`[derivation] lazy output "${key}" for source "${spec.source}" id="${id}" failed:`,
|
|
54
|
+
err
|
|
55
|
+
);
|
|
56
|
+
failedNonStrict = true;
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
if (out.kind === "array") {
|
|
60
|
+
console.warn(
|
|
61
|
+
`[derivation] unexpected array-shape output "${key}" in lazy resolve path; array-shape derivations require lifecycle: "eager".`
|
|
62
|
+
);
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
const outSpec = spec.outputs[key];
|
|
66
|
+
if (!outSpec) continue;
|
|
67
|
+
const outputColl = accessor.getCollection(outSpec.collection);
|
|
68
|
+
if (out.skipped === true) {
|
|
69
|
+
await outputColl._internalDelete(id, accessor.getActiveTxContext());
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
await outputColl.put(id, out.value);
|
|
73
|
+
}
|
|
74
|
+
if (failedNonStrict) pending.add(spec);
|
|
75
|
+
else pending.delete(spec);
|
|
76
|
+
} catch (e) {
|
|
77
|
+
pending.add(spec);
|
|
78
|
+
throw e;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export {
|
|
84
|
+
markStale,
|
|
85
|
+
resolveStaleOnRead
|
|
86
|
+
};
|
|
87
|
+
//# sourceMappingURL=chunk-PDD75NUZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/with-formula/derivations/stale.ts"],"sourcesContent":["import type { Collection } from '../../kernel/collection.js'\nimport type { DerivationExecutor as DerivationExecutorType } from './executor.js'\nimport type { ReadOnlyVaultFacade } from '../../with-audit/guards/types.js'\nimport type { TxContext } from '../../with-commit/tx/transaction.js'\nimport type { DerivationRegistry } from './registry.js'\n// Type-only — runtime class loaded via dynamic import in\n// `resolveStaleOnRead` only when a stale flag actually fires. Keeps\n// the executor chunk out of the floor bundle.\nimport type { DerivationSpec } from './types.js'\n\nimport { lazy } from '../../kernel/lazy.js'\n\n/** #846c — one memoized binding instead of a cast at the call site. */\nconst loadDerivationExecutor = lazy(() => import('./executor.js'))\n\n/**\n * Accessor shape passed through from the owning Vault. Provides the\n * registry (used to look up strategies and as the WeakMap key) and a\n * resolver from collection name to the live `Collection` instance.\n * Same shape as `Collection.derivationSource` so callers can pass it\n * through directly.\n */\nexport interface DerivationStaleAccessor {\n registry(): DerivationRegistry\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n getCollection(name: string): Collection<any>\n /**\n * Read-only vault facade handed to `derive(source, ctx)` on the lazy\n * resolve-on-read path. Same instance/shape as the eager path uses.\n */\n getReadOnlyFacade(): ReadOnlyVaultFacade\n /**\n * Active multi-record TxContext or `null`. The lazy resolve-on-read\n * path uses this to register tombstone deletes on `_executed` so a\n * later rollback restores the prior emission. Mirrors the eager\n * path's rollback tracking; the lazy `put` was historically\n * unregistered but the tombstone delete (a NEW write path)\n * matches the eager registration for symmetry.\n */\n getActiveTxContext(): TxContext | null\n}\n\n/**\n * In-memory stale map keyed by `DerivationRegistry` instance (stable\n * per vault). Maps `${source}/${sourceId}` → set of pending strategies.\n *\n * Persistence across vault close is NOT implemented in v1 (concern\n * flagged in the dim14 spec). On vault re-open, derived records'\n * `_derivedFrom.strategyHash` will still match the registered\n * strategies' hash, so an unset stale flag is interpreted as \"fresh.\"\n * `vault.deriveAll()` (Task D13) is the explicit recompute escape\n * hatch.\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst _staleByRegistry = new WeakMap<DerivationRegistry, Map<string, Set<DerivationSpec<any, any>>>>()\n\nconst keyFor = (source: string, sourceId: string): string => `${source}/${sourceId}`\n\n/** Mark every output of (strategy, sourceId) as stale. */\nexport async function markStale(\n registry: DerivationRegistry,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n strategy: DerivationSpec<any, any>,\n sourceId: string,\n): Promise<void> {\n let map = _staleByRegistry.get(registry)\n if (!map) {\n map = new Map()\n _staleByRegistry.set(registry, map)\n }\n const k = keyFor(strategy.source, sourceId)\n let set = map.get(k)\n if (!set) {\n set = new Set()\n map.set(k, set)\n }\n set.add(strategy)\n}\n\n/**\n * Called from `Collection.get` on lazy-mode output collections. If the\n * id has a pending stale flag for any strategy producing this output\n * collection, re-derive before returning the record. No-op when there\n * is no pending work — keeps the read fast path negligible.\n */\nexport async function resolveStaleOnRead(\n accessor: DerivationStaleAccessor,\n outputCollection: string,\n id: string,\n): Promise<void> {\n const registry = accessor.registry()\n const producers = registry.strategiesProducingOutput(outputCollection)\n if (producers.length === 0) return\n\n const map = _staleByRegistry.get(registry)\n if (!map) return\n\n // Dynamic-import the executor only when at least one stale flag\n // actually fires. Vaults with no derivation strategies never call\n // this function (gated on `derivationSource` in `Collection.get`);\n // vaults with strategies but no pending stale ids reach the\n // `pending.has(spec)` short-circuit below without ever touching\n // the executor chunk.\n let DerivationExecutor: typeof DerivationExecutorType | null = null\n\n for (const { spec, strategyHash } of producers) {\n const k = keyFor(spec.source, id)\n const pending = map.get(k)\n if (!pending || !pending.has(spec)) continue\n\n // Consume the pending flag BEFORE the source read, not after: for a\n // self-write output (output.collection === spec.source, e.g. a\n // reverse-denorm patch), `sourceColl.get(id)` below re-enters this\n // same collection/id and would otherwise still see this spec pending\n // — infinite recursion. Restored on a strict failure below so a\n // future read still retries.\n pending.delete(spec)\n\n // Everything from here on can throw (source read, executor, output\n // put/delete) — restore the consumed flag on ANY throw so a later\n // read still retries, not just on the strict-failure branch below\n // (which throws through this same catch, so it does not also\n // re-add — `Set.add` is idempotent, but the branch no longer needs\n // its own restore).\n // #1258 — a NON-STRICT output failure must not launder staleness into\n // freshness. `strict: false` means \"a failed derivation must not break the\n // read\", NOT \"report this output as current\". Tracked across the output\n // loop and re-marked below, so the record is still served (no throw) and\n // the next read retries — strict-mode behaviour minus the throw.\n let failedNonStrict = false\n try {\n // Read the source record from the source collection and re-derive.\n // We use the same getCollection accessor that eager dispatch uses\n // — it returns the live `Collection<any>` instance with full\n // crypto / keyring wiring.\n const sourceColl = accessor.getCollection(spec.source)\n const source = await sourceColl.get(id)\n if (!source) {\n continue\n }\n const sourceWithId = { ...(source as Record<string, unknown>), id } as Record<string, unknown> & { id: string }\n // sourceVersion: not tracked in v1 stale map; pass 0 — matches the\n // forthcoming v0 semantics, `_derivedFrom.sourceVersion` is\n // informational, not load-bearing for correctness.\n DerivationExecutor ??= (await loadDerivationExecutor()).DerivationExecutor\n const ctx = { vault: accessor.getReadOnlyFacade() }\n const result = await DerivationExecutor.run(spec, sourceWithId, 0, strategyHash, ctx)\n for (const key of Object.keys(spec.outputs)) {\n const out = result.outputs[key]\n if (!out) continue\n if (out.kind === 'failed') {\n const err = out.error\n if (spec.strict) throw err\n console.warn(\n `[derivation] lazy output \"${key}\" for source \"${spec.source}\" id=\"${id}\" failed:`,\n err,\n )\n failedNonStrict = true\n continue\n }\n if (out.kind === 'array') {\n // Defensive — array-shape requires `lifecycle: 'eager'`\n // (validated at withDerivation registration).\n // Reaching the lazy-resolve path for array-shape would mean\n // a registration check was bypassed. Log and skip.\n console.warn(\n `[derivation] unexpected array-shape output \"${key}\" in lazy resolve path; `\n + 'array-shape derivations require lifecycle: \"eager\".',\n )\n continue\n }\n const outSpec = spec.outputs[key]\n if (!outSpec) continue\n const outputColl = accessor.getCollection(outSpec.collection)\n if (out.skipped === true) {\n // Optional output skipped on lazy resolve — delete any\n // prior emission so the read returns null (matches eager-path\n // tombstone semantics). Routed through `_internalDelete` so a\n // user-registered `onDelete` on the output collection\n // does NOT fire. The active TxContext (if any) is forwarded:\n // `resolveStaleOnRead` is reachable from `Collection.get()`\n // which can be called from inside a transaction, so the\n // tombstone must be observable to `revertExecuted` on\n // rollback.\n await outputColl._internalDelete(id, accessor.getActiveTxContext())\n continue\n }\n await outputColl.put(id, out.value)\n }\n // Deliberate cost, stated so nobody \"optimises\" it away: a\n // permanently-failing non-strict derivation now re-runs on every read of\n // this id rather than once. Louder and more expensive than serving a\n // stale value forever, and the trade this project makes everywhere else.\n if (failedNonStrict) pending.add(spec)\n else pending.delete(spec)\n } catch (e) {\n // Restore the stale flag consumed above so a future read retries.\n pending.add(spec)\n throw e\n }\n }\n}\n"],"mappings":";;;;;AAaA,IAAM,yBAAyB,KAAK,MAAM,OAAO,wBAAe,CAAC;AA2CjE,IAAM,mBAAmB,oBAAI,QAAwE;AAErG,IAAM,SAAS,CAAC,QAAgB,aAA6B,GAAG,MAAM,IAAI,QAAQ;AAGlF,eAAsB,UACpB,UAEA,UACA,UACe;AACf,MAAI,MAAM,iBAAiB,IAAI,QAAQ;AACvC,MAAI,CAAC,KAAK;AACR,UAAM,oBAAI,IAAI;AACd,qBAAiB,IAAI,UAAU,GAAG;AAAA,EACpC;AACA,QAAM,IAAI,OAAO,SAAS,QAAQ,QAAQ;AAC1C,MAAI,MAAM,IAAI,IAAI,CAAC;AACnB,MAAI,CAAC,KAAK;AACR,UAAM,oBAAI,IAAI;AACd,QAAI,IAAI,GAAG,GAAG;AAAA,EAChB;AACA,MAAI,IAAI,QAAQ;AAClB;AAQA,eAAsB,mBACpB,UACA,kBACA,IACe;AACf,QAAM,WAAW,SAAS,SAAS;AACnC,QAAM,YAAY,SAAS,0BAA0B,gBAAgB;AACrE,MAAI,UAAU,WAAW,EAAG;AAE5B,QAAM,MAAM,iBAAiB,IAAI,QAAQ;AACzC,MAAI,CAAC,IAAK;AAQV,MAAI,qBAA2D;AAE/D,aAAW,EAAE,MAAM,aAAa,KAAK,WAAW;AAC9C,UAAM,IAAI,OAAO,KAAK,QAAQ,EAAE;AAChC,UAAM,UAAU,IAAI,IAAI,CAAC;AACzB,QAAI,CAAC,WAAW,CAAC,QAAQ,IAAI,IAAI,EAAG;AAQpC,YAAQ,OAAO,IAAI;AAanB,QAAI,kBAAkB;AACtB,QAAI;AAKF,YAAM,aAAa,SAAS,cAAc,KAAK,MAAM;AACrD,YAAM,SAAS,MAAM,WAAW,IAAI,EAAE;AACtC,UAAI,CA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