@substrat-run/adapter-cloudflare 0.210.0 → 0.212.0

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.
@@ -1,8 +1,9 @@
1
1
  import { DurableObject } from 'cloudflare:workers';
2
- import { membershipFencesBackfillSql, MEMBERSHIP_FENCES_DDL, MEMBERSHIP_FENCES_TABLE, membershipFencesTableExists, MEMBERSHIP_FENCE_SINCE_SQL, RAISE_MEMBERSHIP_FENCE_SQL, memberAddedAudit, orgChangeBound, reservedRoleDefinitionRefusal, reservedRoleRefusal, TENANT_SEATED_ROLES_SQL, tenantCoverage, IMPERSONATION_COLUMNS, IMPERSONATION_DDL, impersonationByIdQuery, impersonationListQuery, impersonationRowValues, ISSUE_RETENTION_DAYS, telemetryRetentionStatements, FINDINGS_DDL, SCOPE_STORAGE_DDL, forgetScopeStorage, retireScopeStorage, listScopeStorageAttemptRows, listScopeStorageRows, listScopeAttachmentStorageRows, listScopeStoreStorageRows, pruneScopeStorageRows, recordScopeStorageRows, readBoundedTenantStorageGauge, REQUEST_ROLLUP_DDL, listRequestDayRows, listRequestRollupDayRows, pruneRequestDayRows, recordRequestDayRows, readTenantRequestMeterRows, readRequestMeterDayRows, COST_ROLLUP_DDL, listCostDayRows, listCostRollupDayRows, sumCostDayRows, pruneCostDayRows, recordCostDayRows, recordCostContainerRows, recordScopeObjectRow, scopeObjectsDueRows, METER_DAYS_DDL, VERTICAL_OWNERS_BACKFILL, VERTICAL_OWNERS_DDL, closeVerticalOwnerRow, listVerticalOwnerRows, openVerticalOwnerRow, verticalOwnerNow, listMeterDayRows, listMeterDayTakeRows, pruneMeterDayRows, recordMeterDayRows, CONNECT_LINKS_DDL, consumeConnectLinkRow, insertConnectLink as insertConnectLinkRow, listConnectLinks as listConnectLinkRows, readConnectLink as readConnectLinkRow, restoreConnectLinkRow, revokeConnectLinkRow, createFindingRule, findingOfOpsFailure, findingOfSweepRun, pruneFindings, listFindingRules, listFindings, observeFinding, revokeFindingRule, setFindingStatus, assertRowLimit, OPS_FAILURE_RETENTION_DAYS, SWEEP_RUN_RETENTION_DAYS, SWEEP_RUNS_INTENT_INDEX, sweepRunsIntentHasKind, CONNECTIONS_LIVE_INDEX, connectionsLiveIndexHasOwner, PEER_SWITCHES_DDL, PEER_BINDINGS_DDL, SWITCH_OWED_DDL, clearSwitchOwed, markSwitchOwed, scopeOwesSwitch, switchesOwedOf, SWITCH_KINDS, SYSTEM_SWITCHES_DDL, forgetSwitchesOf, listSystemSwitchRecords, recordSwitchedOff, recordSwitchedOn, recordWriteSuperseded, restoreSwitchRecord, scopesSwitchedOffFor, switchRecordStatesOf, switchRecordsOf, switchesBackfillSqlOf, switchesDdlOf, switchesTableExists, switchesTableOf, tenantHeldOf, VERSION_MIGRATIONS_DDL, VERTICAL_SCOPE_STORES_DDL, DEPLOYMENT_WIRE_AUTH_DDL, deploymentWireAuthOf, forgetVerticalWireAuth, writeDeploymentWireAuth, STORE_DRIVER_RELEASES_DDL, approveStoreDriverReleaseIn, legacyStoreDriverConflict, legacyStoreDriverRenames, beginStoreDriverRolloutIn, finishStoreDriverRolloutIn, holdStoreDriverIn, advanceStoreDriverRebuildIn, claimStoreDriverRebuildIn, storeDriverRebuildIn, driverDeclarationsOf, recordStoreDriverReleaseIn, recordStoreDriverRevokeWalkIn, releaseStoreDriverHoldIn, revokeStoreDriverReleaseIn, liveStoreDriverApprovalIn, storeDriverApprovalsIn, storeDriverRevokeWalkIn, storeDriverReleaseIn, storeDriverStateIn, storeDriverRolloutPendingIn, storeDriverRolloutWalkedIn, forgetVerticalScopeStores, indexVersionScopeStores, verticalScopeStoresOf, splitVersionMigrationsBatch, versionMigrationsOf, versionMigrationsExtractedOf, recordVersionMigrationsExtracted, versionsAwaitSplit, versionsAwaitDigest, deriveMigrationDigestsBatch, deriveVersionMigrationDigest, writeVersionMigrations, MODEL_USAGE_RETENTION_DAYS, BUILD_USAGE_RETENTION_DAYS, DO_SQL_LIMITS, ulid, isPrimaryScopeRow, samePeerVertical, peerVerticalSpellings, resolveVerticalInstanceFrom, resolvePeerInstanceFrom, LEGACY_SCOPE_ROWS_BACKFILL, loadDirectoryDump, storesFencedRefusal, redactSubjectDirectoryText, ISSUE_EXEMPLAR_OWNER_BACKFILL_SQL, issueExemplarOwner, SETTLE_INTENT_SQL, SETTLE_OUTCOME_SQL, settleOutcomeParamsOf, unknownOutcomeOf, ADMIN_LOG_INDEX_DDL, ADMIN_LOG_INDEXES_SQL, readAuditedOperations, } from '@substrat-run/kernel';
2
+ import { membershipFencesBackfillSql, MEMBERSHIP_FENCES_DDL, MEMBERSHIP_FENCES_TABLE, membershipFencesTableExists, MEMBERSHIP_FENCE_SINCE_SQL, RAISE_MEMBERSHIP_FENCE_SQL, memberAddedAudit, orgChangeBound, reservedRoleDefinitionRefusal, reservedRoleRefusal, TENANT_SEATED_ROLES_SQL, tenantCoverage, IMPERSONATION_COLUMNS, IMPERSONATION_DDL, impersonationByIdQuery, impersonationListQuery, impersonationRowValues, ISSUE_RETENTION_DAYS, telemetryRetentionStatements, FINDINGS_DDL, SCOPE_STORAGE_DDL, forgetScopeStorage, retireScopeStorage, listScopeStorageAttemptRows, listScopeStorageRows, listScopeAttachmentStorageRows, listScopeStoreStorageRows, pruneScopeStorageRows, recordScopeStorageRows, readBoundedTenantStorageGauge, REQUEST_ROLLUP_DDL, listRequestDayRows, listRequestRollupDayRows, pruneRequestDayRows, recordRequestDayRows, readTenantRequestMeterRows, readRequestMeterDayRows, COST_ROLLUP_DDL, listCostDayRows, listCostRollupDayRows, sumCostDayRows, pruneCostDayRows, recordCostDayRows, recordCostContainerRows, recordScopeObjectRow, scopeObjectsDueRows, METER_DAYS_DDL, STALE_SCOPES_DDL, listStaleScopeRows, listStaleScopeTakeRows, recordStaleScopeRows, VERTICAL_OWNERS_BACKFILL, VERTICAL_OWNERS_DDL, closeVerticalOwnerRow, listVerticalOwnerRows, openVerticalOwnerRow, verticalOwnerNow, listMeterDayRows, listMeterDayTakeRows, pruneMeterDayRows, recordMeterDayRows, DIRECTORY_LAKE_DDL, ackDirectoryOutbox, ensureDirectoryLakeTriggers, advanceDirectoryLakeBackfill, readDirectoryLakeBackfill, readDirectoryLakeCapture, readDirectoryOutbox, setDirectoryLakeCapture, CONNECT_LINKS_DDL, consumeConnectLinkRow, insertConnectLink as insertConnectLinkRow, listConnectLinks as listConnectLinkRows, readConnectLink as readConnectLinkRow, restoreConnectLinkRow, revokeConnectLinkRow, createFindingRule, findingOfOpsFailure, findingOfSweepRun, pruneFindings, listFindingRules, listFindings, observeFinding, revokeFindingRule, setFindingStatus, assertRowLimit, OPS_FAILURE_RETENTION_DAYS, SWEEP_RUN_RETENTION_DAYS, SWEEP_RUNS_INTENT_INDEX, sweepRunsIntentHasKind, CONNECTIONS_LIVE_INDEX, connectionsLiveIndexHasOwner, PEER_SWITCHES_DDL, PEER_BINDINGS_DDL, SWITCH_OWED_DDL, clearSwitchOwed, markSwitchOwed, scopeOwesSwitch, switchesOwedOf, SWITCH_KINDS, SYSTEM_SWITCHES_DDL, forgetSwitchesOf, listSystemSwitchRecords, recordSwitchedOff, recordSwitchedOn, recordWriteSuperseded, restoreSwitchRecord, scopesSwitchedOffFor, switchRecordStatesOf, switchRecordsOf, switchesBackfillSqlOf, switchesDdlOf, switchesTableExists, switchesTableOf, tenantHeldOf, VERSION_MIGRATIONS_DDL, VERTICAL_SCOPE_STORES_DDL, DEPLOYMENT_WIRE_AUTH_DDL, deploymentWireAuthOf, forgetVerticalWireAuth, writeDeploymentWireAuth, STORE_DRIVER_RELEASES_DDL, approveStoreDriverReleaseIn, legacyStoreDriverConflict, legacyStoreDriverRenames, beginStoreDriverRolloutIn, finishStoreDriverRolloutIn, holdStoreDriverIn, advanceStoreDriverRebuildIn, claimStoreDriverRebuildIn, storeDriverRebuildIn, driverDeclarationsOf, recordStoreDriverReleaseIn, recordStoreDriverRevokeWalkIn, releaseStoreDriverHoldIn, revokeStoreDriverReleaseIn, liveStoreDriverApprovalIn, storeDriverApprovalsIn, storeDriverRevokeWalkIn, storeDriverReleaseIn, storeDriverStateIn, storeDriverRolloutPendingIn, storeDriverRolloutWalkedIn, forgetVerticalScopeStores, indexVersionScopeStores, verticalScopeStoresOf, splitVersionMigrationsBatch, versionMigrationsOf, versionMigrationsExtractedOf, recordVersionMigrationsExtracted, versionsAwaitSplit, versionsAwaitDigest, deriveMigrationDigestsBatch, deriveVersionMigrationDigest, writeVersionMigrations, MODEL_USAGE_RETENTION_DAYS, BUILD_USAGE_RETENTION_DAYS, DO_SQL_LIMITS, ulid, isPrimaryScopeRow, samePeerVertical, peerVerticalSpellings, resolveVerticalInstanceFrom, resolvePeerInstanceFrom, LEGACY_SCOPE_ROWS_BACKFILL, loadDirectoryDump, storesFencedRefusal, redactSubjectDirectoryText, ISSUE_EXEMPLAR_OWNER_BACKFILL_SQL, issueExemplarOwner, SETTLE_INTENT_SQL, SETTLE_OUTCOME_SQL, settleOutcomeParamsOf, unknownOutcomeOf, ADMIN_LOG_INDEX_DDL, ADMIN_LOG_INDEXES_SQL, readAuditedOperations, } from '@substrat-run/kernel';
3
3
  import { MARKUP_INSERT_SQL, MARKUP_SELECT_FOR_TENANT_SQL, MARKUP_SELECT_SQL, } from '@substrat-run/kernel';
4
4
  import { replyOf } from './do-reply.js';
5
5
  import { rowBytes, switchSqlOver } from './scope-do.js';
6
+ import { DIRECTORY_COPY_BY_REFERENCE, quoteIdent, referenceCompareSql, referenceExtraSql, } from './directory-copy-reference.js';
6
7
  import { blankSqlComments, boundShapesColumn, executableSqlStatements, installsReconciledOf, PROVISIONED_VERSIONS_SQL, provisionedVersionsParams, } from '@substrat-run/kernel';
7
8
  import { COPY_BACKFILL_SCOPE_SQL, COPY_BACKFILL_SQL, COPY_BACKFILL_SUPERSEDE_SQL, COPY_CLAIM_SQL, COPY_EXPIRED_SQL, COPY_MOVE_RENEW_SQL, copyMoveRenewParams, PENDING_COPY_KEEP_ALIVE_SQL, pendingCopyKeepAliveParams, copyBackfillParams, copyBackfillRefusal, SUBJECT_ERASURE_CLAIM_SQL, subjectErasureClaimParams, COPY_MOVE_CONFIRM_SQL, COPY_MOVE_LIVE_PREDICATE, SCOPE_COPY_LEASE_MS, SERVES_NOW_CONDITION, SERVES_NOW_PREDICATE, servesNowParams, servesAsFrom, SCOPE_SCRIPT_COPY_COLUMNS, copyMoveConfirmParams, copyMoveLiveParams, } from '@substrat-run/kernel';
8
9
  import { autoAdmittedProdRefusal, listedPromoteRefusal, opsFailureReferenceWhere } from '@substrat-run/kernel';
@@ -705,6 +706,9 @@ const DIRECTORY_DDL = `
705
706
  ${COST_ROLLUP_DDL}
706
707
  -- #2501: the daily meter snapshot — one row per (UTC day, tenant), kernel-owned DDL.
707
708
  ${METER_DAYS_DDL}
709
+ ${DIRECTORY_LAKE_DDL}
710
+ -- #3313: the daily stale-scopes report — one row per (scope, finding), kernel-owned DDL.
711
+ ${STALE_SCOPES_DDL}
708
712
  -- #2501: who owned each vertical slug, period by period — kernel-owned DDL.
709
713
  ${VERTICAL_OWNERS_DDL}
710
714
  CREATE INDEX IF NOT EXISTS scopes_tenant ON scopes (tenant_id, scope_id);
@@ -925,6 +929,10 @@ export const REPLIED_METHODS = [
925
929
  'unlinkIdentityAndAudit',
926
930
  'markAccessLogDrainedAndAudit',
927
931
  'pruneAccessLogAndAudit',
932
+ // K-70: the directory outbox's writes, each with its admin row in the same transaction.
933
+ 'setDirectoryLakeCapture',
934
+ 'ackDirectoryOutbox',
935
+ 'advanceDirectoryLakeBackfill',
928
936
  'writeImpersonationAndAudit',
929
937
  'endImpersonationAndAudit',
930
938
  'setIssueStatusAndAudit',
@@ -1077,6 +1085,9 @@ export class ControlPlaneDO extends DurableObject {
1077
1085
  this.sql.exec(membershipFencesBackfillSql(new Date().toISOString()));
1078
1086
  });
1079
1087
  }
1088
+ // K-70: a capture trigger held to its table as built (a column a deploy added ships from the
1089
+ // first write). Writes nothing while capture is off, or when every trigger already matches.
1090
+ ensureDirectoryLakeTriggers(doRedactionSql(this.sql));
1080
1091
  }
1081
1092
  /**
1082
1093
  * The directory's tables as this code builds them, carrying whatever the directory already
@@ -1408,30 +1419,50 @@ export class ControlPlaneDO extends DurableObject {
1408
1419
  * or removed while the pages are read, or a column added by a deploy in between, is not seen by
1409
1420
  * any of them. The last page drops the snapshot. `copiedTables` (first page only) is how many
1410
1421
  * tables the copy holds, for the access log.
1422
+ *
1423
+ * #3325: with `byReference: 'on'` the tables of `DIRECTORY_COPY_BY_REFERENCE` are not copied but
1424
+ * read live up to the rowid each held at the first page, which is most of what the snapshot
1425
+ * wrote; with `'verify'` they are copied as before and the last page reports what a by-reference
1426
+ * read would have held (`referenceCheck`). The first page also returns the directory's PITR
1427
+ * bookmark at the copy's instant (`bookmark`), whatever the mode.
1411
1428
  */
1412
- exportDumpPage(cursor, opts = {}) {
1429
+ async exportDumpPage(cursor, opts = {}) {
1413
1430
  const maxBytes = opts.maxBytes ?? SCOPE_DUMP_PAGE_MAX_BYTES;
1414
- const taken = cursor === null ? this.snapshotDirectory() : null;
1431
+ const taken = cursor === null ? this.snapshotDirectory(opts.byReference ?? 'off') : null;
1432
+ // Right after the snapshot's transaction: the storage call holds this object's input gate, so
1433
+ // no write lands between the copy's instant and the bookmark's.
1434
+ const bookmark = taken ? await this.currentBookmark() : undefined;
1415
1435
  const at = taken?.cursor ?? decodeDirectoryDumpCursor(cursor);
1416
1436
  const copy = this.hasCopyTable()
1417
- ? this.sql.exec(`SELECT copy_id AS copyId, captured_at AS capturedAt FROM ${COPY_TABLE}`).toArray()[0]
1437
+ ? this.sql.exec(`SELECT * FROM ${COPY_TABLE}`).toArray()[0]
1418
1438
  : undefined;
1419
- if (!copy || copy.copyId !== at.copyId) {
1439
+ if (!copy || copy.copy_id !== at.copyId) {
1420
1440
  throw substratError('conflict', 'this directory copy is gone: a later copy replaced it, or a restore cleared it; start again');
1421
1441
  }
1442
+ const mode = copy.mode ?? 'off';
1443
+ // `SELECT *`: a copy begun by the code before #3325 has no reference columns, and reads as `off`.
1422
1444
  const defs = this.sql
1423
- .exec(`SELECT ord, name, ddl, columns FROM ${COPY_TABLES_TABLE} WHERE ord >= ? ORDER BY ord`, at.ord)
1445
+ .exec(`SELECT * FROM ${COPY_TABLES_TABLE} WHERE ord >= ? ORDER BY ord`, at.ord)
1424
1446
  .toArray();
1425
1447
  const tables = [];
1426
1448
  let bytes = 0;
1427
1449
  let next = null;
1428
- for (const { ord, name, ddl, columns } of defs) {
1450
+ for (const def of defs) {
1451
+ const { ord, name, ddl } = def;
1452
+ const columns = JSON.parse(def.columns);
1453
+ const live = mode === 'on' && def.reference != null;
1454
+ if (live)
1455
+ this.assertReferenceUnaltered(def);
1456
+ const readSql = live
1457
+ ? `SELECT rowid, ${columns.map(quoteIdent).join(', ')} FROM ${quoteIdent(name)}
1458
+ WHERE rowid > ? AND rowid <= ${Number(def.horizon)} AND (${directoryDumpWhere(name)}) ORDER BY rowid LIMIT ?`
1459
+ : `SELECT rowid, * FROM "${copyRowsTable(ord)}" WHERE rowid > ? ORDER BY rowid LIMIT ?`;
1429
1460
  let last = ord === at.ord ? at.after : 0;
1430
1461
  const rows = [];
1431
1462
  let full = false;
1432
1463
  for (;;) {
1433
1464
  // In batches, each read to its end: a part-read cursor keeps its table locked.
1434
- const read = Array.from(this.sql.exec(`SELECT rowid, * FROM "${copyRowsTable(ord)}" WHERE rowid > ? ORDER BY rowid LIMIT ?`, last, DIRECTORY_READ_BATCH).raw(), (raw) => raw);
1465
+ const read = Array.from(this.sql.exec(readSql, last, DIRECTORY_READ_BATCH).raw(), (raw) => raw);
1435
1466
  for (const cells of read) {
1436
1467
  const row = cells.slice(1);
1437
1468
  rows.push(row);
@@ -1445,7 +1476,10 @@ export class ControlPlaneDO extends DurableObject {
1445
1476
  if (full || read.length < DIRECTORY_READ_BATCH)
1446
1477
  break;
1447
1478
  }
1448
- tables.push({ name, ddl, columns: JSON.parse(columns), rows });
1479
+ // Read to its end: an append-only table must still hold every row it held at the copy's instant.
1480
+ if (live && !full && def.reference === 'append-only')
1481
+ this.assertReferenceComplete(def);
1482
+ tables.push({ name, ddl, columns, rows });
1449
1483
  if (full) {
1450
1484
  next = JSON.stringify({ copyId: at.copyId, ord, after: last });
1451
1485
  break;
@@ -1453,9 +1487,77 @@ export class ControlPlaneDO extends DurableObject {
1453
1487
  }
1454
1488
  // A full page that ended on the last row of the last table still says `next`; the page after
1455
1489
  // it is empty, and is the one that drops the snapshot.
1456
- if (next === null)
1490
+ let referenceCheck;
1491
+ if (next === null) {
1492
+ if (mode === 'verify')
1493
+ referenceCheck = this.checkReferences();
1457
1494
  this.dropDirectorySnapshot();
1458
- return { capturedAt: copy.capturedAt, tables, next, ...(taken ? { copiedTables: taken.tables } : {}) };
1495
+ }
1496
+ return {
1497
+ capturedAt: copy.captured_at,
1498
+ tables,
1499
+ next,
1500
+ ...(taken ? { copiedTables: taken.tables, bookmark } : {}),
1501
+ ...(referenceCheck ? { referenceCheck } : {}),
1502
+ };
1503
+ }
1504
+ /** The storage's PITR bookmark now, or null where there is no PITR (local dev, tests) or it failed. */
1505
+ async currentBookmark() {
1506
+ const storage = this.ctx.storage;
1507
+ if (typeof storage.getCurrentBookmark !== 'function')
1508
+ return null;
1509
+ try {
1510
+ return await storage.getCurrentBookmark();
1511
+ }
1512
+ catch {
1513
+ return null;
1514
+ }
1515
+ }
1516
+ /** #3325: a by-reference table is read across pages only while no deploy has altered or rebuilt it. */
1517
+ assertReferenceUnaltered(def) {
1518
+ const now = this.sql.exec(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?`, def.name).toArray()[0];
1519
+ if (now?.sql !== def.ddl) {
1520
+ throw substratError('conflict', `directory table ${def.name} was altered while this copy was read; start again`);
1521
+ }
1522
+ }
1523
+ /** #3325: an append-only table read by reference lost no row under its horizon while it was read. */
1524
+ assertReferenceComplete(def) {
1525
+ const { n } = this.sql
1526
+ .exec(`SELECT count(*) AS n FROM ${quoteIdent(def.name)} WHERE rowid <= ? AND (${directoryDumpWhere(def.name)})`, Number(def.horizon))
1527
+ .one();
1528
+ if (n !== Number(def.row_count)) {
1529
+ throw substratError('conflict', `directory table ${def.name} lost ${Number(def.row_count) - n} row(s) while this copy was read; start again`);
1530
+ }
1531
+ }
1532
+ /**
1533
+ * #3325, `verify`: each by-reference table's snapshot, keyed by the source rowid, against the live
1534
+ * table now, the latest any by-reference page could have read it. Run on the last page, before the
1535
+ * snapshot is dropped.
1536
+ */
1537
+ checkReferences() {
1538
+ const defs = this.sql
1539
+ .exec(`SELECT * FROM ${COPY_TABLES_TABLE} WHERE reference IS NOT NULL ORDER BY ord`)
1540
+ .toArray();
1541
+ return defs.map((def) => {
1542
+ const columns = JSON.parse(def.columns);
1543
+ const kind = def.reference;
1544
+ const now = this.sql.exec(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?`, def.name).toArray()[0];
1545
+ if (now?.sql !== def.ddl) {
1546
+ return { table: def.name, kind, snapshotRows: Number(def.row_count), missing: 0, changed: 0, changedColumns: {}, extra: 0, ddlChanged: true };
1547
+ }
1548
+ const copy = copyRowsTable(def.ord);
1549
+ const r = this.sql.exec(referenceCompareSql(copy, def.name, columns)).one();
1550
+ const changedColumns = {};
1551
+ columns.forEach((col, i) => {
1552
+ if (Number(r[`d${i}`]) > 0)
1553
+ changedColumns[col] = Number(r[`d${i}`]);
1554
+ });
1555
+ const extra = this.sql.exec(referenceExtraSql(copy, def.name), Number(def.horizon)).one().n;
1556
+ return {
1557
+ table: def.name, kind, snapshotRows: Number(r.snapshotRows), missing: Number(r.missing),
1558
+ changed: Number(r.changed), changedColumns, extra: Number(extra), ddlChanged: false,
1559
+ };
1560
+ });
1459
1561
  }
1460
1562
  hasCopyTable() {
1461
1563
  return this.sql.exec(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?`, COPY_TABLE).toArray().length > 0;
@@ -1464,25 +1566,43 @@ export class ControlPlaneDO extends DurableObject {
1464
1566
  * Copy every dumped table into a fresh snapshot (#2868), replacing any a copy left unfinished,
1465
1567
  * and return the cursor of its first page and how many tables it holds. One synchronous
1466
1568
  * transaction, so no write lands between two tables' reads.
1569
+ *
1570
+ * #3325: under `on`, a by-reference table is not copied; its horizon (largest rowid) and row
1571
+ * count are recorded instead, which costs no row written. Under `verify` it is copied as before,
1572
+ * each row at its source rowid, so the last page can compare it with the live table.
1467
1573
  */
1468
- snapshotDirectory() {
1574
+ snapshotDirectory(mode) {
1469
1575
  const copyId = crypto.randomUUID();
1470
1576
  const capturedAt = new Date().toISOString();
1471
1577
  return this.ctx.storage.transactionSync(() => {
1472
1578
  this.dropDirectorySnapshot();
1473
- this.sql.exec(`CREATE TABLE ${COPY_TABLE} (copy_id TEXT NOT NULL, captured_at TEXT NOT NULL)`);
1474
- this.sql.exec(`INSERT INTO _directory_copy (copy_id, captured_at) VALUES (?, ?)`, copyId, capturedAt);
1475
- this.sql.exec(`CREATE TABLE ${COPY_TABLES_TABLE} (ord INTEGER PRIMARY KEY, name TEXT NOT NULL, ddl TEXT NOT NULL, columns TEXT NOT NULL)`);
1579
+ this.sql.exec(`CREATE TABLE ${COPY_TABLE} (copy_id TEXT NOT NULL, captured_at TEXT NOT NULL, mode TEXT NOT NULL)`);
1580
+ this.sql.exec(`INSERT INTO _directory_copy (copy_id, captured_at, mode) VALUES (?, ?, ?)`, copyId, capturedAt, mode);
1581
+ this.sql.exec(`CREATE TABLE ${COPY_TABLES_TABLE} (ord INTEGER PRIMARY KEY, name TEXT NOT NULL, ddl TEXT NOT NULL, columns TEXT NOT NULL,
1582
+ reference TEXT, horizon INTEGER, row_count INTEGER)`);
1476
1583
  const defs = this.dumpTableDefs();
1477
1584
  defs.forEach(({ name, sql }, ord) => {
1478
1585
  const probe = this.sql.exec(`SELECT * FROM "${name}" WHERE 0`);
1479
1586
  probe.toArray();
1480
1587
  const columns = probe.columnNames;
1481
- // Untyped columns: no affinity, so every value is copied exactly as the table holds it.
1482
- const neutral = columns.map((_, i) => `c${i}`).join(', ');
1483
- this.sql.exec(`CREATE TABLE "${copyRowsTable(ord)}" (${neutral})`);
1484
- this.sql.exec(`INSERT INTO "${copyRowsTable(ord)}" SELECT * FROM "${name}" WHERE ${directoryDumpWhere(name)}`);
1485
- this.sql.exec(`INSERT INTO _directory_copy_tables (ord, name, ddl, columns) VALUES (?, ?, ?, ?)`, ord, name, sql, JSON.stringify(columns));
1588
+ const where = directoryDumpWhere(name);
1589
+ const reference = mode === 'off' ? undefined : DIRECTORY_COPY_BY_REFERENCE[name]?.kind;
1590
+ let horizon = null;
1591
+ let rowCount = null;
1592
+ if (reference) {
1593
+ const r = this.sql.exec(`SELECT coalesce(max(rowid), 0) AS h, count(*) AS n FROM "${name}" WHERE ${where}`).one();
1594
+ horizon = Number(r.h);
1595
+ rowCount = Number(r.n);
1596
+ }
1597
+ if (!reference || mode === 'verify') {
1598
+ // Untyped columns: no affinity, so every value is copied exactly as the table holds it.
1599
+ const neutral = columns.map((_, i) => `c${i}`).join(', ');
1600
+ this.sql.exec(`CREATE TABLE "${copyRowsTable(ord)}" (${neutral})`);
1601
+ // A by-reference table under `verify` keeps each row at its source rowid, for the last page's join.
1602
+ const rows = reference ? `(rowid, ${neutral}) SELECT rowid, *` : 'SELECT *';
1603
+ this.sql.exec(`INSERT INTO "${copyRowsTable(ord)}" ${rows} FROM "${name}" WHERE ${where}`);
1604
+ }
1605
+ this.sql.exec(`INSERT INTO _directory_copy_tables (ord, name, ddl, columns, reference, horizon, row_count) VALUES (?, ?, ?, ?, ?, ?, ?)`, ord, name, sql, JSON.stringify(columns), reference ?? null, horizon, rowCount);
1486
1606
  });
1487
1607
  return { cursor: { copyId, ord: 0, after: 0 }, tables: defs.length };
1488
1608
  });
@@ -3764,6 +3884,17 @@ export class ControlPlaneDO extends DurableObject {
3764
3884
  pruneMeterDays(limit, retentionMonths) {
3765
3885
  return this.ctx.storage.transactionSync(() => pruneMeterDayRows(doRedactionSql(this.sql), Date.now(), limit, retentionMonths));
3766
3886
  }
3887
+ // -- the daily stale-scopes report (#3313) — kernel `stale-scopes.ts` ------------
3888
+ // One transaction: the report's reads and its rows are one instant of the directory.
3889
+ recordStaleScopes(input) {
3890
+ return this.ctx.storage.transactionSync(() => recordStaleScopeRows(doRedactionSql(this.sql), input));
3891
+ }
3892
+ listStaleScopes(filter) {
3893
+ return listStaleScopeRows(doRedactionSql(this.sql), filter);
3894
+ }
3895
+ listStaleScopeTakes(filter) {
3896
+ return listStaleScopeTakeRows(doRedactionSql(this.sql), filter);
3897
+ }
3767
3898
  // -- identity pools (K-23) --------------------------------------------------
3768
3899
  readPool(provider) {
3769
3900
  return this.sql
@@ -4341,6 +4472,42 @@ export class ControlPlaneDO extends DurableObject {
4341
4472
  }, audit ? () => ({ ...audit, after: { drained, upToId, drainedAt } }) : undefined);
4342
4473
  return drained;
4343
4474
  }
4475
+ // -- K-70: the directory's outbox to the lake (`directory-lake.ts`) --------
4476
+ // The writers take their admin entry as a required argument: a name an old DO does not know is
4477
+ // refused by `reply`, so none of them can be called on one that would drop the row.
4478
+ setDirectoryLakeCapture(datasets, audit) {
4479
+ let result;
4480
+ this.writeAndAudit(() => {
4481
+ result = setDirectoryLakeCapture(doRedactionSql(this.sql), datasets, new Date().toISOString());
4482
+ return result.enabled.length > 0 || result.disabled.length > 0;
4483
+ }, () => ({ ...audit, after: { enabled: result.enabled, disabled: result.disabled, capturing: result.current.map((c) => c.dataset) } }));
4484
+ return result;
4485
+ }
4486
+ directoryLakeCapture() {
4487
+ return readDirectoryLakeCapture(doRedactionSql(this.sql));
4488
+ }
4489
+ directoryOutbox(limit) {
4490
+ return readDirectoryOutbox(doRedactionSql(this.sql), limit);
4491
+ }
4492
+ ackDirectoryOutbox(upToSeq, ref, audit) {
4493
+ let acked = 0;
4494
+ this.writeAndAudit(() => {
4495
+ acked = ackDirectoryOutbox(doRedactionSql(this.sql), upToSeq);
4496
+ return acked > 0;
4497
+ }, () => ({ ...audit, after: { acked, upToSeq, ref } }));
4498
+ return acked;
4499
+ }
4500
+ directoryLakeBackfill(dataset, after, limit) {
4501
+ return readDirectoryLakeBackfill(doRedactionSql(this.sql), dataset, after, limit);
4502
+ }
4503
+ advanceDirectoryLakeBackfill(dataset, page, audit) {
4504
+ let result;
4505
+ this.writeAndAudit(() => {
4506
+ result = advanceDirectoryLakeBackfill(doRedactionSql(this.sql), dataset, page, new Date().toISOString());
4507
+ return result.changed;
4508
+ }, () => ({ ...audit, after: { dataset, ...page } }));
4509
+ return result.state;
4510
+ }
4344
4511
  /** ONLY drained rows. Age alone is not a licence to delete evidence (K-24). */
4345
4512
  pruneAccessLog(limit, audit) {
4346
4513
  let pruned = 0;