@superbee/core 0.2.0-pre.56 → 0.2.0-pre.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/backend.d.ts.map +1 -1
  2. package/dist/backend.js +4 -3
  3. package/dist/backend.js.map +1 -1
  4. package/dist/dependencies.d.ts +10 -0
  5. package/dist/dependencies.d.ts.map +1 -1
  6. package/dist/dependencies.js +27 -0
  7. package/dist/dependencies.js.map +1 -1
  8. package/dist/document-mutation.d.ts +4 -0
  9. package/dist/document-mutation.d.ts.map +1 -1
  10. package/dist/document-mutation.js +3 -0
  11. package/dist/document-mutation.js.map +1 -1
  12. package/dist/edge-harness/corpus.d.ts +9 -0
  13. package/dist/edge-harness/corpus.d.ts.map +1 -0
  14. package/dist/edge-harness/corpus.js +57 -0
  15. package/dist/edge-harness/corpus.js.map +1 -0
  16. package/dist/edge-harness/index.d.ts +21 -0
  17. package/dist/edge-harness/index.d.ts.map +1 -0
  18. package/dist/edge-harness/index.js +382 -0
  19. package/dist/edge-harness/index.js.map +1 -0
  20. package/dist/edges/find.d.ts +12 -0
  21. package/dist/edges/find.d.ts.map +1 -0
  22. package/dist/edges/find.js +42 -0
  23. package/dist/edges/find.js.map +1 -0
  24. package/dist/edges/index.d.ts +10 -0
  25. package/dist/edges/index.d.ts.map +1 -0
  26. package/dist/edges/index.js +3 -0
  27. package/dist/edges/index.js.map +1 -0
  28. package/dist/edges/memory-source.d.ts +8 -0
  29. package/dist/edges/memory-source.d.ts.map +1 -0
  30. package/dist/edges/memory-source.js +89 -0
  31. package/dist/edges/memory-source.js.map +1 -0
  32. package/dist/edges/source.d.ts +64 -0
  33. package/dist/edges/source.d.ts.map +1 -0
  34. package/dist/edges/source.js +2 -0
  35. package/dist/edges/source.js.map +1 -0
  36. package/dist/engine.d.ts +4 -0
  37. package/dist/engine.d.ts.map +1 -1
  38. package/dist/engine.js +13 -45
  39. package/dist/engine.js.map +1 -1
  40. package/dist/hosted-transport/answer-rows.d.ts +5 -2
  41. package/dist/hosted-transport/answer-rows.d.ts.map +1 -1
  42. package/dist/hosted-transport/answer-rows.js +4 -2
  43. package/dist/hosted-transport/answer-rows.js.map +1 -1
  44. package/dist/hosted-transport/whole-document-transport.d.ts.map +1 -1
  45. package/dist/hosted-transport/whole-document-transport.js +15 -4
  46. package/dist/hosted-transport/whole-document-transport.js.map +1 -1
  47. package/dist/index.d.ts +2 -2
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +2 -2
  50. package/dist/index.js.map +1 -1
  51. package/dist/kind-field-mutation.d.ts +1 -1
  52. package/dist/kind-field-mutation.d.ts.map +1 -1
  53. package/dist/kind-undeclared-fields.d.ts +2 -0
  54. package/dist/kind-undeclared-fields.d.ts.map +1 -1
  55. package/dist/kind-undeclared-fields.js +3 -0
  56. package/dist/kind-undeclared-fields.js.map +1 -1
  57. package/dist/local-search-index.d.ts +25 -1
  58. package/dist/local-search-index.d.ts.map +1 -1
  59. package/dist/local-search-index.js +340 -41
  60. package/dist/local-search-index.js.map +1 -1
  61. package/dist/recipe-lifecycle/index.d.ts +1 -0
  62. package/dist/recipe-lifecycle/index.d.ts.map +1 -1
  63. package/dist/recipe-lifecycle/index.js +1 -0
  64. package/dist/recipe-lifecycle/index.js.map +1 -1
  65. package/dist/relationships.d.ts +9 -2
  66. package/dist/relationships.d.ts.map +1 -1
  67. package/dist/relationships.js +33 -24
  68. package/dist/relationships.js.map +1 -1
  69. package/dist/search-index.d.ts +3 -1
  70. package/dist/search-index.d.ts.map +1 -1
  71. package/dist/search-index.js +3 -1
  72. package/dist/search-index.js.map +1 -1
  73. package/dist/source-profiles/index.d.ts +1 -1
  74. package/dist/source-profiles/index.js +1 -1
  75. package/dist/storage.d.ts +2 -2
  76. package/dist/storage.d.ts.map +1 -1
  77. package/dist/storage.js +2 -2
  78. package/dist/storage.js.map +1 -1
  79. package/package.json +9 -1
@@ -11,6 +11,11 @@
11
11
  * only records the new stamp. The index holds no corpus-size limit; `maxTermsPerDocument` still
12
12
  * skips and counts an over-long document.
13
13
  *
14
+ * The same file keeps the bundle's link facts, refreshed by the same pass: a document read again
15
+ * has its links derived again, in the same write transaction as its search row, and `edgeSource()`
16
+ * answers Core's `EdgeSource` with indexed queries over them, as `edgeSourceFromBackend` answers on
17
+ * the same folder.
18
+ *
14
19
  * The file is derived state: a missing, corrupt, foreign, older-schema or other-text-version file is
15
20
  * rebuilt. Several processes may share it: SQLite's WAL journal and a busy timeout serialize the
16
21
  * short write transactions, and each search reads one consistent snapshot.
@@ -20,15 +25,20 @@ import path from "node:path";
20
25
  import { FilesystemBackend, filesystemDocumentStamp } from "./backend.js";
21
26
  import { isConventionRecord } from "./convention-record.js";
22
27
  import { readManyExisting } from "./document-scan.js";
23
- import { readBundleOkfVersion } from "./engine.js";
28
+ import { deriveRelationshipSource, readBundleOkfVersion } from "./engine.js";
29
+ import { InvalidInputError } from "./errors.js";
24
30
  import { headsDigest } from "./heads-digest.js";
25
31
  import { sha256HexOfUtf8 } from "./sha256.js";
26
32
  import { SEARCH_LIMITS, SEARCH_MATCH_FIELDS, SIGNAL_INTERVAL, documentDescription, documentTags, documentTitle, documentType, } from "./search/contract.js";
27
33
  import { stopIfAsked } from "./search/errors.js";
28
34
  import { canonicalJson, codeUnitCompare } from "./search/identity.js";
29
35
  import { searchRowText, textVersion } from "./search/row-text.js";
30
- /** Bumped whenever the tables below change shape; an index of another schema is rebuilt. */
31
- const SCHEMA_VERSION = "1";
36
+ import { RELATIONSHIP_PROJECTION_VERSIONS, relationshipProjectionForEdition } from "./relationships.js";
37
+ /** Bumped whenever the tables below change shape; an index of another schema is rebuilt. 2: the
38
+ * link facts (`edges`, and the node columns of `docs`). */
39
+ const SCHEMA_VERSION = "2";
40
+ /** The link projections the `edges` rows were derived under; another set rebuilds the file. */
41
+ const LINKS_VERSION = RELATIONSHIP_PROJECTION_VERSIONS.join(" ");
32
42
  /**
33
43
  * Names what an index file was built by: this file's schema and `textVersion()` (the ranking
34
44
  * algorithm, the text revision and the runtime's normalizer fingerprint). Two builds with different
@@ -37,7 +47,7 @@ const SCHEMA_VERSION = "1";
37
47
  * Sixteen lowercase hex characters. The file still records and checks these inputs itself.
38
48
  */
39
49
  export function localSearchIndexFileKey() {
40
- return sha256HexOfUtf8(`local-search-index\u0000${SCHEMA_VERSION}\u0000${textVersion()}`).slice(0, 16);
50
+ return sha256HexOfUtf8(`local-search-index\u0000${SCHEMA_VERSION}\u0000${textVersion()}\u0000${LINKS_VERSION}`).slice(0, 16);
41
51
  }
42
52
  /** Documents read and derived between cancellation checks and memory bounds. */
43
53
  const BATCH = 128;
@@ -54,6 +64,9 @@ const INDEXED = 0;
54
64
  const OVER_TERM_CAP = 1;
55
65
  /** Unreadable: reported in `skipped` with its reason, as the in-memory path reports it. */
56
66
  const MALFORMED = 2;
67
+ /** The host refused to read it (EACCES, EPERM). Kept only by a link refresh, which skips such a
68
+ * file as Core's link reads do; never trusted, so a search reads it again and fails as before. */
69
+ const DENIED = 3;
57
70
  /** The local index cannot be used here. A caller can fall back to the in-memory source. */
58
71
  export class LocalSearchIndexUnavailableError extends Error {
59
72
  reason;
@@ -111,24 +124,63 @@ export async function openLocalSearchIndexWith(options, seams) {
111
124
  return body();
112
125
  }
113
126
  };
127
+ /** A busy, full, read-only or failing index is one typed condition a caller can fall back on. */
128
+ const typed = async (body) => {
129
+ if (closed)
130
+ throw new TypeError("the local search index is closed");
131
+ try {
132
+ return await body();
133
+ }
134
+ catch (error) {
135
+ if (isSqliteError(error))
136
+ throw new LocalSearchIndexUnavailableError("index-unusable", { cause: error });
137
+ throw error;
138
+ }
139
+ };
114
140
  const source = {
115
141
  async evidence(terms, filters, bounds, stop) {
116
142
  if (closed)
117
143
  throw new TypeError("the local search index is closed");
118
144
  stopIfAsked(stop);
119
- try {
120
- return await recovering(async () => {
121
- await refresh(db, backend, contentStamp, stop);
122
- stopIfAsked(stop);
123
- return readEvidence(db, terms, filters, bounds, stop);
124
- });
125
- }
126
- catch (error) {
127
- // A busy, full, read-only or failing index is one typed condition a caller can fall back on.
128
- if (isSqliteError(error))
129
- throw new LocalSearchIndexUnavailableError("index-unusable", { cause: error });
130
- throw error;
131
- }
145
+ return typed(() => recovering(async () => {
146
+ await refresh(db, backend, contentStamp, stop, false);
147
+ stopIfAsked(stop);
148
+ return readEvidence(db, terms, filters, bounds, stop);
149
+ }));
150
+ },
151
+ edgeSource(options = {}) {
152
+ let opened;
153
+ const snapshot = () => (opened ??= typed(() => recovering(async () => {
154
+ const listed = await refresh(db, backend, contentStamp, undefined, true);
155
+ return openEdgeSnapshot(db, backend, listed, options.onSkip);
156
+ })));
157
+ return Object.freeze({
158
+ async edges(selection, limit) {
159
+ if (!(limit === undefined || limit === Infinity || (Number.isSafeInteger(limit) && limit >= 0)))
160
+ throw new TypeError("An edge read's limit must be a non-negative integer");
161
+ const state = await snapshot();
162
+ return typed(() => readEdges(db, state, selection, limit));
163
+ },
164
+ async heads(ids) {
165
+ const state = await snapshot();
166
+ return typed(() => readHeads(db, state, ids));
167
+ },
168
+ });
169
+ },
170
+ async linksOf(documents, okfVersion) {
171
+ const projection = relationshipProjectionForEdition(okfVersion);
172
+ // Rows of exactly these versions were derived from exactly these bytes, so a file that already
173
+ // holds them answers without a refresh; one that does not is brought up to the folder first.
174
+ const read = () => readLinksOf(db, documents, projection);
175
+ return typed(() => recovering(async () => {
176
+ if (ownSchema(readMeta(db))) {
177
+ const held = read();
178
+ if (held !== undefined)
179
+ return held;
180
+ }
181
+ await refresh(db, backend, contentStamp, undefined, true);
182
+ return read();
183
+ }));
132
184
  },
133
185
  async text(hits) {
134
186
  if (closed)
@@ -321,7 +373,7 @@ const FTS_COLUMNS = SEARCH_MATCH_FIELDS;
321
373
  function dropOwnNames(db) {
322
374
  db.exec("DROP TABLE IF EXISTS temp.vocab_instance; DROP TABLE IF EXISTS temp.vocab_row;");
323
375
  const objects = db
324
- .prepare("SELECT type, name FROM main.sqlite_master WHERE name IN ('meta', 'docs', 'fts') OR name LIKE 'fts\\_%' ESCAPE '\\'")
376
+ .prepare("SELECT type, name FROM main.sqlite_master WHERE name IN ('meta', 'docs', 'fts', 'edges', 'edges_by_target') OR name LIKE 'fts\\_%' ESCAPE '\\'")
325
377
  .all();
326
378
  const order = ["trigger", "view", "index", "table"];
327
379
  objects.sort((a, b) => order.indexOf(a.type) - order.indexOf(b.type) || (a.name === "fts" ? -1 : b.name === "fts" ? 1 : 0));
@@ -346,14 +398,29 @@ function createSchema(db, edition) {
346
398
  type TEXT,
347
399
  tags TEXT NOT NULL,
348
400
  title_phrase TEXT NOT NULL,
349
- id_phrase TEXT NOT NULL
401
+ id_phrase TEXT NOT NULL,
402
+ node INTEGER NOT NULL,
403
+ head_title TEXT,
404
+ head_type TEXT,
405
+ link_error TEXT
350
406
  );
351
407
  CREATE VIRTUAL TABLE main.fts USING fts5(${FTS_COLUMNS.join(", ")}, tokenize = 'ascii', content = '', contentless_delete = 1, detail = full);
408
+ CREATE TABLE main.edges (
409
+ source TEXT NOT NULL,
410
+ ordinal INTEGER NOT NULL,
411
+ target TEXT NOT NULL,
412
+ text TEXT NOT NULL,
413
+ href TEXT NOT NULL,
414
+ PRIMARY KEY (source, ordinal)
415
+ ) WITHOUT ROWID;
416
+ CREATE INDEX main.edges_by_target ON edges (target, source, ordinal);
352
417
  `);
353
418
  const put = db.prepare("INSERT INTO main.meta (key, value) VALUES (?, ?)");
354
419
  put.run("schema", SCHEMA_VERSION);
355
420
  put.run("textVersion", textVersion());
421
+ put.run("links", LINKS_VERSION);
356
422
  put.run("edition", edition);
423
+ put.run("generation", "0");
357
424
  }
358
425
  function readMeta(db) {
359
426
  try {
@@ -368,11 +435,15 @@ function readMeta(db) {
368
435
  return undefined;
369
436
  }
370
437
  }
371
- function current(meta, edition) {
438
+ /** The file holds this schema's tables, derived by this build. */
439
+ function ownSchema(meta) {
372
440
  return (meta !== undefined &&
373
441
  meta.get("schema") === SCHEMA_VERSION &&
374
442
  meta.get("textVersion") === textVersion() &&
375
- meta.get("edition") === edition);
443
+ meta.get("links") === LINKS_VERSION);
444
+ }
445
+ function current(meta, edition) {
446
+ return ownSchema(meta) && meta.get("edition") === edition;
376
447
  }
377
448
  /** Rebuilds the tables when the file holds another schema, text version or bundle edition. */
378
449
  function ensureSchema(db, edition) {
@@ -411,13 +482,19 @@ function transaction(db, body) {
411
482
  throw error;
412
483
  }
413
484
  }
414
- /** Brings the index up to the bundle: re-reads every file whose stamp cannot vouch for its row. */
415
- async function refresh(db, backend, contentStamp, stop) {
485
+ /**
486
+ * Brings the index up to the bundle: re-reads every file whose stamp cannot vouch for its row, and
487
+ * derives its search row and its links together. `links`: a file the host refuses to read is kept
488
+ * as skipped, as Core's link reads skip it, rather than failing the refresh as a search does.
489
+ */
490
+ async function refresh(db, backend, contentStamp, stop, links) {
416
491
  // The edition decides how every document parses, so a change re-derives every row.
417
- const edition = JSON.stringify((await readBundleOkfVersion(backend, { allowMalformedRoot: true })) ?? null);
492
+ const okfVersion = await readBundleOkfVersion(backend, { allowMalformedRoot: true });
493
+ const edition = JSON.stringify(okfVersion ?? null);
494
+ const projection = relationshipProjectionForEdition(okfVersion);
418
495
  ensureSchema(db, edition);
419
496
  const manifest = new Map();
420
- for (const row of db.prepare("SELECT id, version, stamp, settled, state FROM main.docs").all())
497
+ for (const row of db.prepare("SELECT id, version, stamp, settled, state, reason FROM main.docs").all())
421
498
  manifest.set(row.id, row);
422
499
  const ids = await backend.list();
423
500
  const stale = [];
@@ -437,7 +514,7 @@ async function refresh(db, backend, contentStamp, stop) {
437
514
  let pending = [];
438
515
  let pendingText = 0;
439
516
  const flush = () => {
440
- apply(db, pending);
517
+ apply(db, pending, manifest);
441
518
  pending = [];
442
519
  pendingText = 0;
443
520
  };
@@ -453,14 +530,24 @@ async function refresh(db, backend, contentStamp, stop) {
453
530
  stopIfAsked(stop);
454
531
  const batch = stale.slice(start, start + BATCH);
455
532
  const malformed = new Map();
456
- const results = await readManyExisting(backend, batch.map((entry) => entry.id), (skip) => void malformed.set(skip.id, skip));
533
+ const denied = new Map();
534
+ const results = await readManyExisting(backend, batch.map((entry) => entry.id), (skip) => void malformed.set(skip.id, skip), undefined, links ? (skip) => void denied.set(skip.id, skip) : undefined);
457
535
  let next = 0;
458
536
  for (const [position, { id, stamp }] of batch.entries()) {
459
537
  if (position % SIGNAL_INTERVAL === 0)
460
538
  stopIfAsked(stop);
461
- const skip = malformed.get(id);
462
- if (skip !== undefined) {
463
- queue(malformedRow(id, stamp, skip.reason));
539
+ const unread = malformed.has(id)
540
+ ? [MALFORMED, malformed.get(id).reason, stamp]
541
+ : denied.has(id)
542
+ ? [DENIED, denied.get(id).reason, undefined]
543
+ : undefined;
544
+ if (unread !== undefined) {
545
+ const [state, reason, kept] = unread;
546
+ // Unreadable as recorded: nothing to write.
547
+ const row = manifest.get(id);
548
+ const same = row !== undefined && row.state === state && row.reason === reason && row.stamp === (kept?.value ?? null) && row.settled === (kept?.settled ? 1 : 0);
549
+ if (!same)
550
+ queue(unreadRow(id, kept, state, reason));
464
551
  continue;
465
552
  }
466
553
  const result = results[next];
@@ -477,7 +564,7 @@ async function refresh(db, backend, contentStamp, stop) {
477
564
  queue({ kind: "stamp", id, version: result.version, stamp });
478
565
  continue;
479
566
  }
480
- queue(derivedRow({ ...result.doc, version: result.version }, stamp));
567
+ queue(derivedRow({ ...result.doc, version: result.version }, stamp, projection));
481
568
  }
482
569
  if (next !== results.length)
483
570
  throw new TypeError("Search backend returned a different document identity.");
@@ -487,11 +574,48 @@ async function refresh(db, backend, contentStamp, stop) {
487
574
  if (!listed.has(id))
488
575
  queue({ kind: "delete", id });
489
576
  flush();
577
+ return { ids, edition: okfVersion };
490
578
  }
491
- function malformedRow(id, stamp, reason) {
492
- return { kind: "row", id, version: null, stamp, state: MALFORMED, reason, title: null, type: null, tags: "[]", titlePhrase: "", idPhrase: "" };
579
+ function unreadRow(id, stamp, state, reason) {
580
+ return {
581
+ kind: "row",
582
+ id,
583
+ version: null,
584
+ stamp,
585
+ state,
586
+ reason,
587
+ title: null,
588
+ type: null,
589
+ tags: "[]",
590
+ titlePhrase: "",
591
+ idPhrase: "",
592
+ node: 0,
593
+ headTitle: null,
594
+ headType: null,
595
+ linkError: null,
596
+ links: [],
597
+ };
598
+ }
599
+ /** A document's links as Core's link reads derive them (`deriveRelationshipSource`): its node
600
+ * status, head and occurrences, or the error that fails a link read. */
601
+ function derivedLinks(document, projection) {
602
+ try {
603
+ const source = deriveRelationshipSource(document, projection);
604
+ const node = projection?.conceptsOnly ? source.concept === true : true;
605
+ return {
606
+ node: node ? 1 : 0,
607
+ headTitle: source.title,
608
+ headType: source.type ?? null,
609
+ linkError: null,
610
+ links: node ? source.links : [],
611
+ };
612
+ }
613
+ catch (error) {
614
+ // A search still indexes the document; only a link read fails, with Core's own error.
615
+ return { node: 0, headTitle: null, headType: null, linkError: error instanceof Error ? error.message : String(error), links: [] };
616
+ }
493
617
  }
494
- function derivedRow(document, stamp) {
618
+ function derivedRow(document, stamp, projection) {
495
619
  const text = searchRowText(document);
496
620
  const searched = text.bodyTermCount <= SEARCH_LIMITS.maxTermsPerDocument;
497
621
  const byField = {
@@ -515,35 +639,52 @@ function derivedRow(document, stamp) {
515
639
  titlePhrase: text.titlePhrase,
516
640
  idPhrase: text.idPhrase,
517
641
  ...(searched ? { columns: FTS_COLUMNS.map((field) => byField[field]) } : {}),
642
+ ...derivedLinks(document, projection),
518
643
  };
519
644
  }
520
645
  /**
521
- * One write transaction. Each change is applied against the row as it is now, not as this process
522
- * last saw it, so two processes refreshing at once both leave a row derived from a real read.
646
+ * One write transaction. A stored row is replaced only while it still has the version this refresh
647
+ * found in `manifest`: when another process wrote it in between, that write stands, so a slower
648
+ * process never puts back an older read over a newer one. A file changed again since is read on the
649
+ * next refresh, as its stamp no longer matches.
523
650
  */
524
- function apply(db, changes) {
651
+ function apply(db, changes, manifest) {
525
652
  if (changes.length === 0)
526
653
  return;
527
- const find = db.prepare("SELECT rowid, state FROM main.docs WHERE id = ?");
654
+ const find = db.prepare("SELECT rowid, state, version FROM main.docs WHERE id = ?");
528
655
  const stampOnly = db.prepare("UPDATE main.docs SET stamp = ?, settled = ? WHERE id = ? AND version = ? AND state != ?");
529
- const update = db.prepare("UPDATE main.docs SET version = ?, stamp = ?, settled = ?, state = ?, reason = ?, title = ?, type = ?, tags = ?, title_phrase = ?, id_phrase = ? WHERE rowid = ?");
530
- const insert = db.prepare("INSERT INTO main.docs (id, version, stamp, settled, state, reason, title, type, tags, title_phrase, id_phrase) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING rowid");
656
+ const update = db.prepare("UPDATE main.docs SET version = ?, stamp = ?, settled = ?, state = ?, reason = ?, title = ?, type = ?, tags = ?, title_phrase = ?, id_phrase = ?, node = ?, head_title = ?, head_type = ?, link_error = ? WHERE rowid = ?");
657
+ const insert = db.prepare("INSERT INTO main.docs (id, version, stamp, settled, state, reason, title, type, tags, title_phrase, id_phrase, node, head_title, head_type, link_error) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING rowid");
531
658
  const remove = db.prepare("DELETE FROM main.docs WHERE rowid = ?");
532
659
  const unindex = db.prepare("DELETE FROM main.fts WHERE rowid = ?");
533
660
  const index = db.prepare(`INSERT INTO main.fts (rowid, ${FTS_COLUMNS.join(", ")}) VALUES (?, ${FTS_COLUMNS.map(() => "?").join(", ")})`);
661
+ const dropLinks = db.prepare("DELETE FROM main.edges WHERE source = ?");
662
+ const addLink = db.prepare("INSERT INTO main.edges (source, ordinal, target, text, href) VALUES (?, ?, ?, ?, ?)");
663
+ // A change to any row moves the generation, so an edge source that read before it can tell; a
664
+ // new stamp alone changes no answer.
665
+ const advance = db.prepare("UPDATE main.meta SET value = CAST(CAST(value AS INTEGER) + 1 AS TEXT) WHERE key = 'generation'");
534
666
  // A write through FTS5 can report a shadow-table rowid past 2^53 as its last insert rowid, which
535
667
  // Node 26 refuses to convert to a number; nothing here reads it.
536
- for (const statement of [stampOnly, update, insert, remove, unindex, index])
668
+ for (const statement of [stampOnly, update, insert, remove, unindex, index, dropLinks, addLink, advance])
537
669
  statement.setReadBigInts(true);
538
670
  transaction(db, () => {
671
+ let changed = false;
539
672
  for (const change of changes) {
540
673
  const existing = find.get(change.id);
541
674
  if (change.kind === "stamp") {
542
675
  stampOnly.run(change.stamp?.value ?? null, change.stamp?.settled ? 1 : 0, change.id, change.version, MALFORMED);
543
676
  continue;
544
677
  }
678
+ // Another process wrote this row since the manifest was read: its write stands. A missing row is
679
+ // always written (a file every reader lists must have one, even after another rebuilt the file).
680
+ const seen = manifest.get(change.id);
681
+ if (existing !== undefined && (seen === undefined || existing.version !== seen.version))
682
+ continue;
683
+ changed = true;
545
684
  if (existing !== undefined && existing.state === INDEXED)
546
685
  unindex.run(existing.rowid);
686
+ // A document's links change with its row, in this transaction.
687
+ dropLinks.run(change.id);
547
688
  if (change.kind === "delete") {
548
689
  if (existing !== undefined)
549
690
  remove.run(existing.rowid);
@@ -560,6 +701,10 @@ function apply(db, changes) {
560
701
  change.tags,
561
702
  change.titlePhrase,
562
703
  change.idPhrase,
704
+ change.node,
705
+ change.headTitle,
706
+ change.headType,
707
+ change.linkError,
563
708
  ];
564
709
  let rowid;
565
710
  if (existing !== undefined) {
@@ -571,7 +716,11 @@ function apply(db, changes) {
571
716
  }
572
717
  if (change.columns !== undefined)
573
718
  index.run(rowid, ...change.columns);
719
+ for (const [ordinal, occurrence] of change.links.entries())
720
+ addLink.run(change.id, ordinal, occurrence.to, occurrence.text, occurrence.href);
574
721
  }
722
+ if (changed)
723
+ advance.run();
575
724
  });
576
725
  }
577
726
  /** One read transaction: the corpus identity and sizes, the volume and the evidence agree. */
@@ -673,6 +822,156 @@ function readEvidence(db, terms, filters, bounds, stop) {
673
822
  db.exec("COMMIT");
674
823
  }
675
824
  }
825
+ /** Inside one read transaction; `pending` once another refresh has changed the file since `state`. */
826
+ function readSnapshot(db, state, body) {
827
+ db.exec("BEGIN");
828
+ try {
829
+ if (generationOf(db) !== state.generation)
830
+ return { status: "pending" };
831
+ return body();
832
+ }
833
+ finally {
834
+ db.exec("COMMIT");
835
+ }
836
+ }
837
+ function generationOf(db) {
838
+ return db.prepare("SELECT value FROM main.meta WHERE key = 'generation'").get().value;
839
+ }
840
+ /**
841
+ * Pins an edge source to the file as its own refresh left it, and reports the unreadable documents
842
+ * in listing order. As Core's in-memory link read, it fails on the first document (in listing
843
+ * order) whose links cannot be derived, or that cannot be read when nobody takes `onSkip`: that
844
+ * document is read again here, so the failure is Core's own error.
845
+ */
846
+ async function openEdgeSnapshot(db, backend, listed, onSkip) {
847
+ db.exec("BEGIN");
848
+ let generation;
849
+ let unread;
850
+ let failed;
851
+ try {
852
+ generation = generationOf(db);
853
+ const rows = db
854
+ .prepare("SELECT id, state, reason, link_error FROM main.docs WHERE state IN (?, ?) OR link_error IS NOT NULL")
855
+ .all(MALFORMED, DENIED);
856
+ unread = new Map(rows.filter((row) => row.link_error === null).map((row) => [row.id, row.reason ?? ""]));
857
+ failed = new Map(rows.filter((row) => row.link_error !== null).map((row) => [row.id, row.link_error]));
858
+ }
859
+ finally {
860
+ db.exec("COMMIT");
861
+ }
862
+ const projection = relationshipProjectionForEdition(listed.edition);
863
+ for (const id of listed.ids) {
864
+ const message = failed.get(id);
865
+ if (message === undefined && (onSkip !== undefined || !unread.has(id)))
866
+ continue;
867
+ const { doc } = await backend.read(id);
868
+ if (message !== undefined)
869
+ deriveRelationshipSource(doc, projection);
870
+ // Readable and derivable now: it changed after the refresh, which a later read picks up.
871
+ throw new InvalidInputError(message ?? `'${id}' changed while its links were read. Read again.`);
872
+ }
873
+ if (onSkip !== undefined)
874
+ for (const id of listed.ids)
875
+ if (unread.has(id))
876
+ onSkip({ id, reason: unread.get(id) });
877
+ return { generation, conceptsOnly: projection?.conceptsOnly === true };
878
+ }
879
+ /** The least string above every string that starts with `prefix`, in code point (UTF-8 byte) order;
880
+ * undefined when there is none. */
881
+ function prefixEnd(prefix) {
882
+ const points = [...prefix];
883
+ while (points.length > 0) {
884
+ const last = points.pop().codePointAt(0);
885
+ if (last === 0x10ffff)
886
+ continue;
887
+ return points.join("") + String.fromCodePoint(last === 0xd7ff ? 0xe000 : last + 1);
888
+ }
889
+ return undefined;
890
+ }
891
+ /** A facet as SQL over `column`: exact ids, and each prefix as a range seek under BINARY collation
892
+ * (exact bytes: no case folding, no wildcards). An empty facet matches nothing. */
893
+ function facetSql(column, facet, params) {
894
+ const terms = [];
895
+ if (facet.ids.length > 0) {
896
+ terms.push(`e.${column} IN (SELECT value FROM json_each(?))`);
897
+ params.push(JSON.stringify(facet.ids));
898
+ }
899
+ for (const prefix of facet.prefixes) {
900
+ const end = prefixEnd(prefix);
901
+ terms.push(end === undefined ? `e.${column} >= ?` : `(e.${column} >= ? AND e.${column} < ?)`);
902
+ params.push(prefix, ...(end === undefined ? [] : [end]));
903
+ }
904
+ return terms.length === 0 ? "0" : `(${terms.join(" OR ")})`;
905
+ }
906
+ function readEdges(db, state, selection, limit) {
907
+ const params = [];
908
+ const where = [];
909
+ if (selection.from !== undefined)
910
+ where.push(facetSql("source", selection.from, params));
911
+ if (selection.to !== undefined)
912
+ where.push(facetSql("target", selection.to, params));
913
+ if (selection.text !== undefined) {
914
+ where.push("e.text = ?");
915
+ params.push(selection.text);
916
+ }
917
+ // In OKF 0.3 a link counts only between nodes; only a node's links are stored.
918
+ if (state.conceptsOnly)
919
+ where.push("EXISTS (SELECT 1 FROM main.docs n WHERE n.id = e.target AND n.node = 1)");
920
+ const bounded = limit !== undefined && limit !== Infinity;
921
+ const sql = `SELECT e.source AS "from", e.target AS "to", e.text AS text, e.href AS href FROM main.edges e` +
922
+ (where.length === 0 ? "" : ` WHERE ${where.join(" AND ")}`) +
923
+ ` ORDER BY e.source, e.ordinal${bounded ? ` LIMIT ${limit + 1}` : ""}`;
924
+ return readSnapshot(db, state, () => {
925
+ const rows = db.prepare(sql).all(...params);
926
+ const more = bounded && rows.length > limit;
927
+ const edges = (more ? rows.slice(0, limit) : rows).map(({ from, to, text, href }) => ({ from, to, text, href }));
928
+ return { status: "ready", edges, more };
929
+ });
930
+ }
931
+ /** In one read transaction: every link, when the file holds exactly `documents`, all derived under
932
+ * `projection`'s link rule. */
933
+ function readLinksOf(db, documents, projection) {
934
+ db.exec("BEGIN");
935
+ try {
936
+ // Derived under another edition's link rule: not these documents' links.
937
+ const edition = readMeta(db)?.get("edition");
938
+ if (edition === undefined || relationshipProjectionForEdition(JSON.parse(edition) ?? undefined) !== projection)
939
+ return undefined;
940
+ const conceptsOnly = projection?.conceptsOnly === true;
941
+ const rows = db.prepare("SELECT id, version, link_error FROM main.docs").all();
942
+ if (rows.length !== documents.length)
943
+ return undefined;
944
+ const held = new Map(rows.map((row) => [row.id, row]));
945
+ for (const { id, version } of documents) {
946
+ const row = held.get(id);
947
+ if (row === undefined || row.version !== version || row.link_error !== null)
948
+ return undefined;
949
+ }
950
+ const node = conceptsOnly ? " WHERE EXISTS (SELECT 1 FROM main.docs n WHERE n.id = e.target AND n.node = 1)" : "";
951
+ const links = db
952
+ .prepare(`SELECT e.source AS "from", e.target AS "to", e.text AS text, e.href AS href FROM main.edges e${node} ORDER BY e.source, e.ordinal`)
953
+ .all();
954
+ return links.map(({ from, to, text, href }) => ({ from, to, text, href }));
955
+ }
956
+ finally {
957
+ db.exec("COMMIT");
958
+ }
959
+ }
960
+ function readHeads(db, state, ids) {
961
+ return readSnapshot(db, state, () => {
962
+ const rows = db
963
+ .prepare("SELECT id, head_title, head_type FROM main.docs WHERE node = 1 AND id IN (SELECT value FROM json_each(?))")
964
+ .all(JSON.stringify(ids));
965
+ const found = new Map(rows.map((row) => [row.id, row]));
966
+ const heads = new Map();
967
+ for (const id of ids) {
968
+ const row = found.get(id);
969
+ if (row !== undefined)
970
+ heads.set(id, Object.freeze({ id, title: row.head_title, type: row.head_type }));
971
+ }
972
+ return { status: "ready", heads };
973
+ });
974
+ }
676
975
  /** Description and body of the hits, read again; a file changed since its evidence gives none. */
677
976
  async function readTexts(backend, hits) {
678
977
  const texts = new Map();