@polycode-projects/the-mechanical-code-talker 6.0.0 → 6.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -52,7 +52,10 @@ import {
52
52
  } from "../../domain/memory/retraction.mjs";
53
53
  import { admittedNodes, stableRecordIds } from "../../domain/memory/causal-stability.mjs";
54
54
  import { assertIndividualValid } from "./shacl.mjs";
55
- import { BackendRejected, isRowBackend, rowBackendProblems, BOOKKEEPING_ROW_CLASS } from "./row-backend.mjs";
55
+ import {
56
+ BackendRejected, BackendUnavailable, isRowBackend, rowBackendProblems, assertValidRow,
57
+ BOOKKEEPING_ROW_CLASS, ROW_BACKEND_KIND, ROW_BACKEND_CONTRACT_VERSION,
58
+ } from "./row-backend.mjs";
56
59
  // The row-backend contract lives in its own module (a consumer imports it
57
60
  // without loading the engine); re-exported here so store consumers keep one
58
61
  // import site, the same way the trust and retraction vocabularies are.
@@ -684,9 +687,10 @@ function installSqliteWarningFilter() {
684
687
  }
685
688
 
686
689
  /** Open (creating if absent) a resident node:sqlite connection: a Backend C
687
- * handle `{ backend: "sqlite", db, dbPath }`. `node:sqlite` is imported
688
- * lazily — only opting into this backend ever loads it. Meant to be opened
689
- * once per session; close via closeSqliteMemoryStore at session end. */
690
+ * handle `{ backend: "sqlite", db, dbPath }`, carrying the row-backend methods
691
+ * over its own tables. `node:sqlite` is imported lazily — only opting into
692
+ * this backend ever loads it. Meant to be opened once per session; close via
693
+ * closeSqliteMemoryStore at session end. */
690
694
  export async function createSqliteMemoryStore(dbPath) {
691
695
  installSqliteWarningFilter();
692
696
  const { DatabaseSync } = await import("node:sqlite");
@@ -695,7 +699,7 @@ export async function createSqliteMemoryStore(dbPath) {
695
699
  db.exec("PRAGMA synchronous = NORMAL");
696
700
  db.exec(SQLITE_DDL);
697
701
  backfillFactsProjection(db);
698
- const handle = { backend: BACKEND_SQLITE, db, dbPath };
702
+ const handle = attachSqliteRowMethods({ backend: BACKEND_SQLITE, db, dbPath });
699
703
  backfillFactHeads(handle);
700
704
  return handle;
701
705
  }
@@ -985,28 +989,13 @@ function buildSqlitePayloadFromRows(handle) {
985
989
  const individuals = db.prepare("SELECT json FROM individuals ORDER BY ord").all()
986
990
  .map((r) => JSON.parse(r.json));
987
991
 
988
- const edgesForProp = db.prepare(
989
- "SELECT subject, object, subject_label, object_label, extra FROM edges WHERE prop = ? ORDER BY rowid",
990
- );
991
- const objectProperties = db.prepare("SELECT prop, predicate, count FROM relations ORDER BY ord").all()
992
- .map((r) => ({
993
- predicate: r.predicate,
994
- prop: r.prop,
995
- count: r.count,
996
- examples: edgesForProp.all(r.prop).map((e) => {
997
- const edge = { subject: e.subject, object: e.object, subjectLabel: e.subject_label, objectLabel: e.object_label };
998
- if (e.extra) Object.assign(edge, JSON.parse(e.extra));
999
- return edge;
1000
- }),
1001
- }));
1002
-
1003
992
  return {
1004
993
  generated_at: getMeta("generated_at", empty.generated_at),
1005
994
  memory: getMeta("memory", empty.memory),
1006
995
  prefixes: getMeta("prefixes", empty.prefixes),
1007
996
  vocabulary: getMeta("vocabulary", empty.vocabulary),
1008
997
  classes: getMeta("classes", empty.classes),
1009
- objectProperties,
998
+ objectProperties: sqliteEdgeGroups(db).map((entry) => entry.group),
1010
999
  individuals,
1011
1000
  proseIndex: getMeta("proseIndex", empty.proseIndex),
1012
1001
  };
@@ -1026,10 +1015,10 @@ function cacheUpsertIndividual(cache, ind) {
1026
1015
  else cache.individuals.push(clone);
1027
1016
  }
1028
1017
 
1029
- /** Mirrors the individuals delete loop: drop any cached individual whose id
1030
- * isn't in the just-persisted payload's full id set. */
1031
- function cacheDropIndividualsExcept(cache, seenIds) {
1032
- cache.individuals = cache.individuals.filter((i) => seenIds.has(i?.id));
1018
+ /** Mirrors `DELETE FROM individuals`: drop every cached individual the write
1019
+ * just removed. */
1020
+ function cacheDropIndividuals(cache, droppedIds) {
1021
+ cache.individuals = cache.individuals.filter((i) => !droppedIds.has(i?.id));
1033
1022
  }
1034
1023
 
1035
1024
  /** Find-or-create the cached edge group for `prop` — mirrors a relation row
@@ -1064,16 +1053,370 @@ function cacheDropEdgesExcept(group, newKeys) {
1064
1053
  group.examples = group.examples.filter((e) => newKeys.has(`${e.subject}\u0000${e.object}`));
1065
1054
  }
1066
1055
 
1067
- /** Mirrors the relations delete loop: drop any cached edge group whose prop
1068
- * wasn't in the just-persisted payload's `objectProperties`. */
1069
- function cacheDropGroupsExcept(cache, seenProps) {
1070
- cache.objectProperties = cache.objectProperties.filter((g) => seenProps.has(g?.prop));
1056
+ /** Mirrors `DELETE FROM relations`: drop every cached edge group the write just
1057
+ * removed. */
1058
+ function cacheDropGroups(cache, droppedProps) {
1059
+ cache.objectProperties = cache.objectProperties.filter((g) => !droppedProps.has(g?.prop));
1060
+ }
1061
+
1062
+ // ---- Backend C as a row store ---------------------------------------------
1063
+ // The store's own tables ALREADY hold rows: an individual is a row keyed by its
1064
+ // id, an edge group a row keyed by its prop, and the payload's scalars are meta
1065
+ // values. The projection below says so in both directions, so one set of
1066
+ // writers serves both callers — persistSqlitePayload, which diffs a mutated
1067
+ // payload into rows, and the published row-backend contract (row-backend.mjs)
1068
+ // the same handle answers.
1069
+ //
1070
+ // A row the tables cannot hand back byte for byte goes to `unmapped_rows`
1071
+ // verbatim instead: a record whose class no row class covers, an index term the
1072
+ // record itself does not imply, a bookkeeping entry, anything carrying its own
1073
+ // TTL. That table is created the first time such a row arrives, so a store
1074
+ // holding only tmct's own payload never grows one.
1075
+
1076
+ const EDGE_GROUP_ROW_CLASS = "edge-group";
1077
+ const EDGE_GROUP_KEY_PREFIX = "edge-group:";
1078
+
1079
+ const ROW_CLASS_BY_INDIVIDUAL_CLASS = new Map([
1080
+ [FACT_CLASS, "fact"],
1081
+ [SOURCE_CLASS, "source"],
1082
+ [UTTERANCE_CLASS, "utterance"],
1083
+ [MEMORY_SESSION_CLASS, "session"],
1084
+ [RULE_CLASS, "rule"],
1085
+ [RETRACTION_CLASS, "retraction"],
1086
+ ]);
1087
+
1088
+ const UNMAPPED_ROWS_TABLE = "unmapped_rows";
1089
+ const UNMAPPED_ROWS_DDL = `CREATE TABLE IF NOT EXISTS ${UNMAPPED_ROWS_TABLE} (
1090
+ row_key TEXT PRIMARY KEY, row_class TEXT NOT NULL, term TEXT NOT NULL, json TEXT NOT NULL, expires_at INTEGER
1091
+ )`;
1092
+ const UNMAPPED_ROWS_PRESENT_SQL = "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?";
1093
+
1094
+ const individualRowJson = (ord, json) => `{"ord":${ord},"individual":${json}}`;
1095
+ const ROW_ORD_RE = /^\{"ord":(-?\d+),/;
1096
+
1097
+ /** The ord a row carries, read off the front of its own json. */
1098
+ function ordOfRow(row) {
1099
+ const match = ROW_ORD_RE.exec(row?.json || "");
1100
+ if (match) return Number(match[1]);
1101
+ try {
1102
+ const ord = Number(JSON.parse(row.json).ord);
1103
+ return Number.isFinite(ord) ? ord : 0;
1104
+ } catch { return 0; }
1105
+ }
1106
+
1107
+ /** One stored individual as a row. `json` is the blob the `individuals` table
1108
+ * holds, passed in so the row and the table can never disagree about it. */
1109
+ function individualRow(ind, ord, json) {
1110
+ const rowClass = ROW_CLASS_BY_INDIVIDUAL_CLASS.get(ind?.class) || "";
1111
+ return {
1112
+ rowKey: String(ind.id),
1113
+ rowClass,
1114
+ term: rowClass === "fact" ? normFactTerm(individualKey(ind, "subject")) : "",
1115
+ json: individualRowJson(ord, json),
1116
+ };
1117
+ }
1118
+
1119
+ /** One edge with its four columns first and any other key after, so a group
1120
+ * projected from a payload and the same group read back off the tables
1121
+ * serialize to the same bytes. */
1122
+ function canonicalEdge(edge) {
1123
+ const canonical = {
1124
+ subject: edge.subject,
1125
+ object: edge.object,
1126
+ subjectLabel: edge.subjectLabel ?? null,
1127
+ objectLabel: edge.objectLabel ?? null,
1128
+ };
1129
+ for (const key of Object.keys(edge)) if (!STD_EDGE_KEYS.has(key)) canonical[key] = edge[key];
1130
+ return canonical;
1131
+ }
1132
+
1133
+ /** One edge group as a row, examples in stored order — that order is recency,
1134
+ * since a changed edge moves to the end of its group. */
1135
+ function edgeGroupRow(group, ord) {
1136
+ const examples = (group.examples || []).map(canonicalEdge);
1137
+ return {
1138
+ rowKey: `${EDGE_GROUP_KEY_PREFIX}${group.prop}`,
1139
+ rowClass: EDGE_GROUP_ROW_CLASS,
1140
+ term: "",
1141
+ json: JSON.stringify({
1142
+ ord,
1143
+ group: {
1144
+ predicate: group.predicate ?? null,
1145
+ prop: group.prop,
1146
+ count: Number.isFinite(group.count) ? group.count : examples.length,
1147
+ examples,
1148
+ },
1149
+ }),
1150
+ };
1151
+ }
1152
+
1153
+ /** Every edge group in the store, each with the `relations` ord it sorts by.
1154
+ * Edges come back in rowid order, which is the order they were last written. */
1155
+ function sqliteEdgeGroups(db) {
1156
+ const byProp = new Map();
1157
+ for (const r of db.prepare("SELECT prop, ord, predicate, count FROM relations ORDER BY ord, prop").all()) {
1158
+ byProp.set(r.prop, {
1159
+ ord: r.ord,
1160
+ group: { predicate: r.predicate, prop: r.prop, count: r.count, examples: [] },
1161
+ });
1162
+ }
1163
+ if (!byProp.size) return [];
1164
+ for (const e of db.prepare("SELECT prop, subject, object, subject_label, object_label, extra FROM edges ORDER BY rowid").all()) {
1165
+ const entry = byProp.get(e.prop);
1166
+ if (!entry) continue;
1167
+ const edge = { subject: e.subject, object: e.object, subjectLabel: e.subject_label, objectLabel: e.object_label };
1168
+ if (e.extra) Object.assign(edge, JSON.parse(e.extra));
1169
+ entry.group.examples.push(edge);
1170
+ }
1171
+ return [...byProp.values()];
1172
+ }
1173
+
1174
+ /** The rows the store's tables hold for the payload — its individuals and edge
1175
+ * groups, and nothing else. This is what a payload write diffs against, so a
1176
+ * verbatim row a consumer stored beside them is never in the diff and never
1177
+ * deleted as absent-from-payload. Classes and terms come off the columns, so
1178
+ * reading them parses no blob. */
1179
+ function sqlitePayloadStoreRows(handle) {
1180
+ const rows = [];
1181
+ const stored = handle.db.prepare(
1182
+ "SELECT i.id AS id, i.ord AS ord, i.class AS class, i.json AS json, f.subject AS subject"
1183
+ + " FROM individuals i LEFT JOIN facts f ON f.id = i.id ORDER BY i.ord, i.id",
1184
+ ).all();
1185
+ for (const r of stored) {
1186
+ const rowClass = ROW_CLASS_BY_INDIVIDUAL_CLASS.get(r.class) || "";
1187
+ rows.push({
1188
+ rowKey: r.id,
1189
+ rowClass,
1190
+ term: rowClass === "fact" ? normFactTerm(r.subject || "") : "",
1191
+ json: individualRowJson(r.ord, r.json),
1192
+ });
1193
+ }
1194
+ for (const entry of sqliteEdgeGroups(handle.db)) rows.push(edgeGroupRow(entry.group, entry.ord));
1195
+ return rows;
1196
+ }
1197
+
1198
+ /** A mutated payload as rows, plus what a write needs to apply each of them. An
1199
+ * existing key keeps the ord it already had; a new one takes the next free
1200
+ * number in its own sequence, since individuals and relations number
1201
+ * separately, exactly as their tables do. */
1202
+ function sqlitePayloadRows(payload, priorRows) {
1203
+ const priorOrd = new Map();
1204
+ let nextIndividualOrd = 0;
1205
+ let nextGroupOrd = 0;
1206
+ for (const row of priorRows) {
1207
+ const ord = ordOfRow(row);
1208
+ priorOrd.set(row.rowKey, ord);
1209
+ if (row.rowClass === EDGE_GROUP_ROW_CLASS) {
1210
+ if (ord >= nextGroupOrd) nextGroupOrd = ord + 1;
1211
+ } else if (ord >= nextIndividualOrd) nextIndividualOrd = ord + 1;
1212
+ }
1213
+
1214
+ const rows = [];
1215
+ const partsByKey = new Map();
1216
+ for (const ind of payload.individuals || []) {
1217
+ if (!ind?.id) continue;
1218
+ const json = JSON.stringify(ind);
1219
+ const rowKey = String(ind.id);
1220
+ const ord = priorOrd.get(rowKey) ?? nextIndividualOrd++;
1221
+ rows.push(individualRow(ind, ord, json));
1222
+ partsByKey.set(rowKey, { kind: "individual", ord, individual: ind, json });
1223
+ }
1224
+ for (const group of payload.objectProperties || []) {
1225
+ if (!group?.prop) continue;
1226
+ const rowKey = `${EDGE_GROUP_KEY_PREFIX}${group.prop}`;
1227
+ const ord = priorOrd.get(rowKey) ?? nextGroupOrd++;
1228
+ const row = edgeGroupRow(group, ord);
1229
+ rows.push(row);
1230
+ partsByKey.set(rowKey, { kind: EDGE_GROUP_ROW_CLASS, ord, group: JSON.parse(row.json).group });
1231
+ }
1232
+ return { rows, partsByKey };
1233
+ }
1234
+
1235
+ /** What a row is as far as the store's own tables are concerned: an individual
1236
+ * or an edge group when they can hand it back byte for byte, null when only
1237
+ * the verbatim table can hold it. */
1238
+ function nativeRowParts(row) {
1239
+ if (row.expiresAt !== undefined) return null; // no column carries a TTL stamp
1240
+ let record;
1241
+ try { record = JSON.parse(row.json); } catch { return null; }
1242
+ if (!record || typeof record !== "object" || !Number.isFinite(record.ord)) return null;
1243
+
1244
+ if (row.rowClass === EDGE_GROUP_ROW_CLASS) {
1245
+ const group = record.group;
1246
+ if (!group?.prop) return null;
1247
+ const rebuilt = edgeGroupRow(group, record.ord);
1248
+ if (rebuilt.rowKey !== row.rowKey || rebuilt.term !== row.term || rebuilt.json !== row.json) return null;
1249
+ return { kind: EDGE_GROUP_ROW_CLASS, ord: record.ord, group };
1250
+ }
1251
+
1252
+ const ind = record.individual;
1253
+ if (!ind?.id) return null;
1254
+ const json = JSON.stringify(ind);
1255
+ const rebuilt = individualRow(ind, record.ord, json);
1256
+ if (rebuilt.rowKey !== row.rowKey || rebuilt.rowClass !== row.rowClass) return null;
1257
+ if (rebuilt.term !== row.term || rebuilt.json !== row.json) return null;
1258
+ return { kind: "individual", ord: record.ord, individual: ind, json };
1259
+ }
1260
+
1261
+ /** The state one write transaction carries: the statements it reuses, the cache
1262
+ * it patches in lockstep, and the groups and (subject, predicate) pairs it
1263
+ * touched, so the two derived tables re-materialise for exactly what moved and
1264
+ * nothing else. A group whose records are all untouched cannot have moved —
1265
+ * its base carries no recency, so only its own records can change it. */
1266
+ function sqliteWriteContext(handle, { cache = null } = {}) {
1267
+ const db = handle.db;
1268
+ return {
1269
+ db,
1270
+ cache,
1271
+ touchedGroups: new Set(),
1272
+ touchedPairs: new Set(),
1273
+ hasUnmappedRows: !!db.prepare(UNMAPPED_ROWS_PRESENT_SQL).get(UNMAPPED_ROWS_TABLE),
1274
+ unmapped: null,
1275
+ upsertInd: db.prepare("INSERT OR REPLACE INTO individuals(id, ord, class, label, json) VALUES (?, ?, ?, ?, ?)"),
1276
+ upsertFact: db.prepare(FACT_PROJECTION_UPSERT_SQL),
1277
+ deleteInd: db.prepare("DELETE FROM individuals WHERE id = ?"),
1278
+ deleteFact: db.prepare("DELETE FROM facts WHERE id = ?"),
1279
+ getFact: db.prepare("SELECT triple_hash, subject, predicate FROM facts WHERE id = ?"),
1280
+ upsertRel: db.prepare("INSERT OR REPLACE INTO relations(prop, ord, predicate, count) VALUES (?, ?, ?, ?)"),
1281
+ edgesForProp: db.prepare("SELECT subject, object, subject_label, object_label, extra FROM edges WHERE prop = ?"),
1282
+ upsertEdge: db.prepare("INSERT OR REPLACE INTO edges(prop, subject, object, subject_label, object_label, extra) VALUES (?, ?, ?, ?, ?, ?)"),
1283
+ deleteEdge: db.prepare("DELETE FROM edges WHERE prop = ? AND subject = ? AND object = ?"),
1284
+ deleteGroupEdges: db.prepare("DELETE FROM edges WHERE prop = ?"),
1285
+ deleteRel: db.prepare("DELETE FROM relations WHERE prop = ?"),
1286
+ };
1287
+ }
1288
+
1289
+ /** The verbatim table's statements, creating the table the first time a write
1290
+ * actually needs it. */
1291
+ function unmappedStatements(ctx) {
1292
+ if (!ctx.unmapped) {
1293
+ ctx.db.exec(UNMAPPED_ROWS_DDL);
1294
+ ctx.hasUnmappedRows = true;
1295
+ ctx.unmapped = {
1296
+ upsert: ctx.db.prepare(`INSERT OR REPLACE INTO ${UNMAPPED_ROWS_TABLE}(row_key, row_class, term, json, expires_at) VALUES (?, ?, ?, ?, ?)`),
1297
+ remove: ctx.db.prepare(`DELETE FROM ${UNMAPPED_ROWS_TABLE} WHERE row_key = ?`),
1298
+ };
1299
+ }
1300
+ return ctx.unmapped;
1301
+ }
1302
+
1303
+ /** Drop a key from the verbatim table, so no key ever lives in both lanes.
1304
+ * Skipped whole for a store that has never held a verbatim row. */
1305
+ function dropUnmappedRow(ctx, rowKey) {
1306
+ if (ctx.hasUnmappedRows) unmappedStatements(ctx).remove.run(rowKey);
1307
+ }
1308
+
1309
+ function writeIndividualRow(ctx, { ord, individual, json }) {
1310
+ ctx.upsertInd.run(individual.id, ord, individual.class ?? null, individual.label ?? null, json);
1311
+ // The queryable projection of the blob just written, same transaction — every
1312
+ // write path that reaches a Fact (teach, corpus seed, entailment, migration, a
1313
+ // trust recompute) lands here, so none can leave the two out of step.
1314
+ if (individual.class === FACT_CLASS) {
1315
+ ctx.upsertFact.run(...factProjectionValues(individual, json));
1316
+ ctx.touchedGroups.add(factGroupId(individual.id));
1317
+ ctx.touchedPairs.add(subjectPredicateKey(individualKey(individual, "subject"), individualKey(individual, "predicate")));
1318
+ }
1319
+ dropUnmappedRow(ctx, String(individual.id));
1320
+ if (ctx.cache) cacheUpsertIndividual(ctx.cache, individual);
1321
+ }
1322
+
1323
+ /** A group's edges, diffed WITHIN the group and scoped to its own rows
1324
+ * (edges_by_prop) rather than the whole edges table — a group that gains one
1325
+ * new edge (statedBy, touched by nearly every appendFact call) writes exactly
1326
+ * that one row, not the group's entire history. */
1327
+ function writeEdgeGroupRow(ctx, { ord, group }) {
1328
+ const existingByKey = new Map(
1329
+ ctx.edgesForProp.all(group.prop).map((r) => [`${r.subject}${r.object}`, r]),
1330
+ );
1331
+ const newKeys = new Set();
1332
+ const cacheGroup = ctx.cache ? cacheGroupFor(ctx.cache, group.prop) : null;
1333
+ for (const e of group.examples || []) {
1334
+ const key = `${e.subject}${e.object}`;
1335
+ newKeys.add(key);
1336
+ const extraKeys = Object.keys(e).filter((k) => !STD_EDGE_KEYS.has(k));
1337
+ const extra = extraKeys.length ? JSON.stringify(Object.fromEntries(extraKeys.map((k) => [k, e[k]]))) : null;
1338
+ const existing = existingByKey.get(key);
1339
+ const unchanged = existing
1340
+ && (existing.subject_label ?? null) === (e.subjectLabel ?? null)
1341
+ && (existing.object_label ?? null) === (e.objectLabel ?? null)
1342
+ && (existing.extra ?? null) === (extra ?? null);
1343
+ if (unchanged) continue;
1344
+ ctx.upsertEdge.run(group.prop, e.subject, e.object, e.subjectLabel ?? null, e.objectLabel ?? null, extra);
1345
+ if (cacheGroup) cacheUpsertEdge(cacheGroup, e, extraKeys);
1346
+ }
1347
+ for (const key of existingByKey.keys()) {
1348
+ if (newKeys.has(key)) continue;
1349
+ const [s, o] = key.split("");
1350
+ ctx.deleteEdge.run(group.prop, s, o);
1351
+ }
1352
+ if (cacheGroup) cacheDropEdgesExcept(cacheGroup, newKeys);
1353
+ const count = Number.isFinite(group.count) ? group.count : (group.examples || []).length;
1354
+ ctx.upsertRel.run(group.prop, ord, group.predicate ?? null, count);
1355
+ dropUnmappedRow(ctx, `${EDGE_GROUP_KEY_PREFIX}${group.prop}`);
1356
+ if (cacheGroup) { cacheGroup.predicate = group.predicate ?? null; cacheGroup.count = count; }
1357
+ }
1358
+
1359
+ function writeUnmappedRow(ctx, row) {
1360
+ unmappedStatements(ctx).upsert.run(row.rowKey, row.rowClass, row.term, row.json, row.expiresAt ?? null);
1361
+ }
1362
+
1363
+ /** Apply rows to the store's tables. `knownParts` is what the payload
1364
+ * projection already worked out for the rows it minted, so the write path does
1365
+ * not re-derive what it just built. */
1366
+ function writeSqliteRows(ctx, rows, knownParts = null) {
1367
+ for (const row of rows) {
1368
+ const parts = knownParts?.get(row.rowKey) || nativeRowParts(row);
1369
+ if (!parts) { writeUnmappedRow(ctx, row); continue; }
1370
+ if (parts.kind === EDGE_GROUP_ROW_CLASS) writeEdgeGroupRow(ctx, parts);
1371
+ else writeIndividualRow(ctx, parts);
1372
+ }
1373
+ }
1374
+
1375
+ /** Remove rows by key from whichever lane holds them. A retracted record's own
1376
+ * group and (subject, predicate) are read off the projection BEFORE the row
1377
+ * goes, since once it is gone there is nothing left to read them off. */
1378
+ function deleteSqliteRows(ctx, rowKeys) {
1379
+ const droppedIndividuals = new Set();
1380
+ const droppedProps = new Set();
1381
+ for (const rowKey of rowKeys) {
1382
+ if (rowKey.startsWith(EDGE_GROUP_KEY_PREFIX)) {
1383
+ const prop = rowKey.slice(EDGE_GROUP_KEY_PREFIX.length);
1384
+ ctx.deleteGroupEdges.run(prop);
1385
+ ctx.deleteRel.run(prop);
1386
+ droppedProps.add(prop);
1387
+ } else {
1388
+ const gone = ctx.getFact.get(rowKey);
1389
+ if (gone) {
1390
+ ctx.touchedGroups.add(gone.triple_hash);
1391
+ ctx.touchedPairs.add(subjectPredicateKey(gone.subject, gone.predicate));
1392
+ }
1393
+ ctx.deleteInd.run(rowKey);
1394
+ ctx.deleteFact.run(rowKey); // a no-op for a non-Fact id; keeps the projection from outliving its blob
1395
+ droppedIndividuals.add(rowKey);
1396
+ }
1397
+ dropUnmappedRow(ctx, rowKey);
1398
+ }
1399
+ if (ctx.cache && droppedIndividuals.size) cacheDropIndividuals(ctx.cache, droppedIndividuals);
1400
+ if (ctx.cache && droppedProps.size) cacheDropGroups(ctx.cache, droppedProps);
1401
+ }
1402
+
1403
+ /** Re-materialise the derived tables for what a write touched, inside that
1404
+ * write's own transaction, so no reader can ever see one without the other. */
1405
+ function recomputeDerivedTables(ctx, foldSource, headIndex) {
1406
+ if (!ctx.touchedGroups.size) return;
1407
+ const foldCtx = factFoldContext(foldSource);
1408
+ recomputeFactHeads(ctx.db, foldCtx, ctx.touchedGroups, headIndex);
1409
+ recordObjectSupersessions(ctx.db, foldCtx, ctx.touchedPairs);
1071
1410
  }
1072
1411
 
1073
- /** Persist a mutated payload into a Backend C handle: per-row
1074
- * INSERT/REPLACE/DELETE diffed against what's already stored, in one
1075
- * transaction. Patches `handle.cachedPayload` in lockstep; a rolled-back
1076
- * write invalidates the cache instead of leaving a partial patch. */
1412
+ /** Persist a mutated payload into a Backend C handle: the payload projected to
1413
+ * rows, diffed against the rows already stored, and only the difference
1414
+ * written, in one transaction. Patches `handle.cachedPayload` in lockstep; a
1415
+ * rolled-back write invalidates the cache instead of leaving a partial patch.
1416
+ *
1417
+ * The 4 KB wire cap the row contract enforces is not applied here: it protects
1418
+ * a network hop, and a local file store holds a seed's whole statedBy group in
1419
+ * one row. */
1077
1420
  function persistSqlitePayload(handle, payload) {
1078
1421
  const db = handle.db;
1079
1422
  const empty = emptyMemory();
@@ -1096,124 +1439,19 @@ function persistSqlitePayload(handle, payload) {
1096
1439
  cache.proseIndex = cloneJson(payload.proseIndex ?? empty.proseIndex);
1097
1440
  }
1098
1441
 
1099
- // individuals: a real per-row upsert, only for an id that is new or whose
1100
- // JSON actually changed since the last persist — every other row is left
1101
- // untouched (no whole-table rewrite).
1102
- const getInd = db.prepare("SELECT ord, json FROM individuals WHERE id = ?");
1103
- const maxOrd = db.prepare("SELECT COALESCE(MAX(ord), -1) AS m FROM individuals").get().m;
1104
- let nextOrd = maxOrd + 1;
1105
- const upsertInd = db.prepare("INSERT OR REPLACE INTO individuals(id, ord, class, label, json) VALUES (?, ?, ?, ?, ?)");
1106
- const upsertFact = db.prepare(FACT_PROJECTION_UPSERT_SQL);
1107
- const seenIds = new Set();
1108
- // Every group and every (subject, predicate) this write reaches, so the two
1109
- // derived tables are re-materialised for exactly what moved and nothing
1110
- // else. A group whose records are all untouched cannot have moved: its base
1111
- // carries no recency, so only its own records can change it.
1112
- const touchedGroups = new Set();
1113
- const touchedPairs = new Set();
1114
- for (const ind of payload.individuals || []) {
1115
- seenIds.add(ind.id);
1116
- const json = JSON.stringify(ind);
1117
- const existing = getInd.get(ind.id);
1118
- if (existing && existing.json === json) continue; // unchanged — skip the write entirely (cache already matches)
1119
- const ord = existing ? existing.ord : nextOrd++;
1120
- upsertInd.run(ind.id, ord, ind.class ?? null, ind.label ?? null, json);
1121
- // The queryable projection of the blob just written, same transaction —
1122
- // every write path that reaches a Fact (teach, corpus seed, entailment,
1123
- // migration, a trust recompute) lands here, so none can leave the two
1124
- // out of step.
1125
- if (ind.class === FACT_CLASS) {
1126
- upsertFact.run(...factProjectionValues(ind, json));
1127
- touchedGroups.add(factGroupId(ind.id));
1128
- touchedPairs.add(subjectPredicateKey(individualKey(ind, "subject"), individualKey(ind, "predicate")));
1129
- }
1130
- if (cache) cacheUpsertIndividual(cache, ind);
1131
- }
1132
- // Removal (what removeFacts' retraction lands as — every append path only
1133
- // ever adds): a cheap index-only scan of the primary-key column, never the
1134
- // JSON payload.
1135
- const deleteInd = db.prepare("DELETE FROM individuals WHERE id = ?");
1136
- const deleteFact = db.prepare("DELETE FROM facts WHERE id = ?");
1137
- const getFact = db.prepare("SELECT triple_hash, subject, predicate FROM facts WHERE id = ?");
1138
- for (const row of db.prepare("SELECT id FROM individuals").all()) {
1139
- if (seenIds.has(row.id)) continue;
1140
- // Read the projection before dropping it: a retracted record's own group
1141
- // and (subject, predicate) still have to be re-materialised, and once the
1142
- // row is gone there is nothing left to read them off.
1143
- const gone = getFact.get(row.id);
1144
- if (gone) {
1145
- touchedGroups.add(gone.triple_hash);
1146
- touchedPairs.add(subjectPredicateKey(gone.subject, gone.predicate));
1147
- }
1148
- deleteInd.run(row.id);
1149
- deleteFact.run(row.id); // a no-op for a non-Fact id; keeps the projection from outliving its blob
1150
- }
1151
- if (cache) cacheDropIndividualsExcept(cache, seenIds);
1152
-
1153
- // objectProperties/edges: per-edge diff WITHIN each group, scoped to that
1154
- // group's own rows (edges_by_prop) rather than the whole edges table — a
1155
- // group that gains one new edge (e.g. statedBy, touched by nearly every
1156
- // appendFact call) writes exactly that one new row, not the group's
1157
- // entire history.
1158
- const getRelOrd = db.prepare("SELECT ord FROM relations WHERE prop = ?");
1159
- const maxRelOrd = db.prepare("SELECT COALESCE(MAX(ord), -1) AS m FROM relations").get().m;
1160
- let nextRelOrd = maxRelOrd + 1;
1161
- const upsertRel = db.prepare("INSERT OR REPLACE INTO relations(prop, ord, predicate, count) VALUES (?, ?, ?, ?)");
1162
- const edgesForProp = db.prepare("SELECT subject, object, subject_label, object_label, extra FROM edges WHERE prop = ?");
1163
- const upsertEdge = db.prepare("INSERT OR REPLACE INTO edges(prop, subject, object, subject_label, object_label, extra) VALUES (?, ?, ?, ?, ?, ?)");
1164
- const deleteEdge = db.prepare("DELETE FROM edges WHERE prop = ? AND subject = ? AND object = ?");
1165
- const seenProps = new Set();
1166
- for (const group of payload.objectProperties || []) {
1167
- seenProps.add(group.prop);
1168
- const existingRows = edgesForProp.all(group.prop);
1169
- const existingByKey = new Map(existingRows.map((r) => [`${r.subject}\u0000${r.object}`, r]));
1170
- const newKeys = new Set();
1171
- const cacheGroup = cache ? cacheGroupFor(cache, group.prop) : null;
1172
- for (const e of group.examples || []) {
1173
- const key = `${e.subject}\u0000${e.object}`;
1174
- newKeys.add(key);
1175
- const extraKeys = Object.keys(e).filter((k) => !STD_EDGE_KEYS.has(k));
1176
- const extra = extraKeys.length ? JSON.stringify(Object.fromEntries(extraKeys.map((k) => [k, e[k]]))) : null;
1177
- const existing = existingByKey.get(key);
1178
- const unchanged = existing
1179
- && (existing.subject_label ?? null) === (e.subjectLabel ?? null)
1180
- && (existing.object_label ?? null) === (e.objectLabel ?? null)
1181
- && (existing.extra ?? null) === (extra ?? null);
1182
- if (unchanged) continue;
1183
- upsertEdge.run(group.prop, e.subject, e.object, e.subjectLabel ?? null, e.objectLabel ?? null, extra);
1184
- if (cacheGroup) cacheUpsertEdge(cacheGroup, e, extraKeys);
1185
- }
1186
- for (const key of existingByKey.keys()) {
1187
- if (newKeys.has(key)) continue;
1188
- const [s, o] = key.split("\u0000");
1189
- deleteEdge.run(group.prop, s, o);
1190
- }
1191
- if (cacheGroup) cacheDropEdgesExcept(cacheGroup, newKeys);
1192
- const relCount = Number.isFinite(group.count) ? group.count : (group.examples || []).length;
1193
- const relOrd = getRelOrd.get(group.prop)?.ord ?? nextRelOrd++;
1194
- upsertRel.run(group.prop, relOrd, group.predicate ?? null, relCount);
1195
- if (cacheGroup) { cacheGroup.predicate = group.predicate ?? null; cacheGroup.count = relCount; }
1196
- }
1197
- for (const row of db.prepare("SELECT prop FROM relations").all()) {
1198
- if (seenProps.has(row.prop)) continue;
1199
- db.prepare("DELETE FROM edges WHERE prop = ?").run(row.prop);
1200
- db.prepare("DELETE FROM relations WHERE prop = ?").run(row.prop);
1201
- }
1202
- if (cache) cacheDropGroupsExcept(cache, seenProps);
1203
-
1204
- // The derived tables, re-materialised in the SAME transaction as the
1205
- // records they summarise, so no reader can ever see one without the other.
1206
- if (touchedGroups.size) {
1207
- const ctx = factFoldContext(payload);
1208
- recomputeFactHeads(db, ctx, touchedGroups, handle.cachedFactHeads);
1209
- recordObjectSupersessions(db, ctx, touchedPairs);
1210
- }
1442
+ const ctx = sqliteWriteContext(handle, { cache });
1443
+ const before = sqlitePayloadStoreRows(handle);
1444
+ const { rows: after, partsByKey } = sqlitePayloadRows(payload, before);
1445
+ const { puts, deletes } = diffRows(before, after);
1446
+ writeSqliteRows(ctx, puts, partsByKey);
1447
+ deleteSqliteRows(ctx, deletes);
1448
+ recomputeDerivedTables(ctx, payload, handle.cachedFactHeads);
1211
1449
 
1212
1450
  db.exec("COMMIT");
1213
1451
  } catch (e) {
1214
1452
  db.exec("ROLLBACK");
1215
1453
  // The cache may hold a partially-applied patch at this point (some of the
1216
- // loop bodies above already mutated it before the failure) that was never
1454
+ // writes above already mutated it before the failure) that was never
1217
1455
  // actually committed to SQLite — never trust it silently. Drop it so the
1218
1456
  // next loadMemory() call does an honest full rebuild instead.
1219
1457
  handle.cachedPayload = undefined;
@@ -1222,6 +1460,144 @@ function persistSqlitePayload(handle, payload) {
1222
1460
  }
1223
1461
  }
1224
1462
 
1463
+ // ---- The row-backend contract, over the same tables ------------------------
1464
+
1465
+ /** Every verbatim row still live, expired ones filtered out the way the
1466
+ * reference backend filters its own. */
1467
+ function readUnmappedRows(db) {
1468
+ if (!db.prepare(UNMAPPED_ROWS_PRESENT_SQL).get(UNMAPPED_ROWS_TABLE)) return [];
1469
+ const now = Math.floor(Date.now() / 1000);
1470
+ const rows = [];
1471
+ for (const r of db.prepare(`SELECT row_key, row_class, term, json, expires_at FROM ${UNMAPPED_ROWS_TABLE}`).all()) {
1472
+ if (r.expires_at !== null && r.expires_at <= now) continue;
1473
+ const row = { rowKey: r.row_key, rowClass: r.row_class, term: r.term, json: r.json };
1474
+ if (r.expires_at !== null) row.expiresAt = r.expires_at;
1475
+ rows.push(row);
1476
+ }
1477
+ return rows;
1478
+ }
1479
+
1480
+ /** Run `write` in one transaction, then drop the caches: a row write reaches
1481
+ * the tables without going through the payload those caches mirror, so the
1482
+ * next read rebuilds from the tables rather than from a payload that no longer
1483
+ * describes them. */
1484
+ function inSqliteRowTransaction(handle, write) {
1485
+ const db = handle.db;
1486
+ db.exec("BEGIN IMMEDIATE");
1487
+ try {
1488
+ write(sqliteWriteContext(handle));
1489
+ db.exec("COMMIT");
1490
+ } catch (e) {
1491
+ db.exec("ROLLBACK");
1492
+ throw e;
1493
+ } finally {
1494
+ handle.cachedPayload = null;
1495
+ handle.cachedFactHeads = null;
1496
+ }
1497
+ }
1498
+
1499
+ const SQLITE_TABLES = Object.freeze([
1500
+ "meta", "individuals", "relations", "edges", "facts", "fact_heads", "fact_object_supersessions",
1501
+ ]);
1502
+
1503
+ /** Give a Backend C handle the published row-backend methods (row-backend.mjs).
1504
+ * They read and write the same seven tables the payload path does, so a
1505
+ * consumer holding the store as a row backend and tmct holding it as a memory
1506
+ * store see one store rather than two. */
1507
+ function attachSqliteRowMethods(handle) {
1508
+ return Object.assign(handle, {
1509
+ async readRows() {
1510
+ return [...sqlitePayloadStoreRows(handle), ...readUnmappedRows(handle.db)];
1511
+ },
1512
+
1513
+ async readRowsByTerm(term) {
1514
+ return (await handle.readRows()).filter((row) => row.term === term);
1515
+ },
1516
+
1517
+ async putRows(candidateRows) {
1518
+ // Validate every row before writing any of them, so a batch carrying one
1519
+ // malformed row is refused whole rather than half-applied.
1520
+ const validated = (candidateRows || []).map((row) => assertValidRow(row));
1521
+ if (!validated.length) return;
1522
+ inSqliteRowTransaction(handle, (ctx) => {
1523
+ writeSqliteRows(ctx, validated);
1524
+ recomputeDerivedTables(ctx, buildSqlitePayloadFromRows(handle), null);
1525
+ });
1526
+ },
1527
+
1528
+ async deleteRows(rowKeys) {
1529
+ const keys = [...(rowKeys || [])];
1530
+ if (!keys.length) return;
1531
+ inSqliteRowTransaction(handle, (ctx) => {
1532
+ deleteSqliteRows(ctx, keys);
1533
+ recomputeDerivedTables(ctx, buildSqlitePayloadFromRows(handle), null);
1534
+ });
1535
+ },
1536
+
1537
+ async readMeta(key) {
1538
+ const row = handle.db.prepare("SELECT v FROM meta WHERE k = ?").get(key);
1539
+ return row ? row.v : null;
1540
+ },
1541
+
1542
+ async putMeta(key, value) {
1543
+ handle.db.prepare("INSERT OR REPLACE INTO meta(k, v) VALUES (?, ?)").run(key, String(value));
1544
+ handle.cachedPayload = null;
1545
+ handle.cachedFactHeads = null;
1546
+ },
1547
+
1548
+ async deleteAll() {
1549
+ const db = handle.db;
1550
+ db.exec("BEGIN IMMEDIATE");
1551
+ try {
1552
+ for (const table of SQLITE_TABLES) db.exec(`DELETE FROM ${table}`);
1553
+ if (db.prepare(UNMAPPED_ROWS_PRESENT_SQL).get(UNMAPPED_ROWS_TABLE)) db.exec(`DELETE FROM ${UNMAPPED_ROWS_TABLE}`);
1554
+ db.exec("COMMIT");
1555
+ } catch (e) {
1556
+ db.exec("ROLLBACK");
1557
+ throw e;
1558
+ } finally {
1559
+ handle.cachedPayload = null;
1560
+ handle.cachedFactHeads = null;
1561
+ }
1562
+ },
1563
+
1564
+ async close() {
1565
+ closeSqliteMemoryStore(handle);
1566
+ },
1567
+ });
1568
+ }
1569
+
1570
+ /** A sqlite file as an injectable row backend: the same store
1571
+ * `createSqliteMemoryStore` opens, presented under the published contract. The
1572
+ * connection opens on the first call, so constructing one touches no disk and
1573
+ * needs no await. */
1574
+ export function createSqliteRowBackend(dbPath) {
1575
+ let opening = null;
1576
+ let closed = false;
1577
+ const handle = () => {
1578
+ if (closed) throw new BackendUnavailable("this row backend was closed and can no longer be used");
1579
+ opening = opening || createSqliteMemoryStore(dbPath);
1580
+ return opening;
1581
+ };
1582
+ const through = (method) => async (...args) => (await handle())[method](...args);
1583
+ return {
1584
+ kind: ROW_BACKEND_KIND,
1585
+ contractVersion: ROW_BACKEND_CONTRACT_VERSION,
1586
+ readRows: through("readRows"),
1587
+ readRowsByTerm: through("readRowsByTerm"),
1588
+ putRows: through("putRows"),
1589
+ deleteRows: through("deleteRows"),
1590
+ readMeta: through("readMeta"),
1591
+ putMeta: through("putMeta"),
1592
+ deleteAll: through("deleteAll"),
1593
+ async close() {
1594
+ const open = opening ? await opening : null;
1595
+ closed = true;
1596
+ if (open) closeSqliteMemoryStore(open);
1597
+ },
1598
+ };
1599
+ }
1600
+
1225
1601
  /** Atomic write of raw text (temp in the same dir + rename) — the discipline
1226
1602
  * every writer in this module (and fold.mjs/sessions.mjs's own copies) uses:
1227
1603
  * a crash never destroys the previous file, a concurrent reader never sees a