@substrat-run/adapter-sqlite 0.217.0 → 0.219.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.
package/dist/index.js CHANGED
@@ -2,8 +2,8 @@ import { createHash } from 'node:crypto';
2
2
  import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, rmSync, writeFileSync, writeSync } from 'node:fs';
3
3
  import { dirname, join } from 'node:path';
4
4
  import Database from 'better-sqlite3';
5
- import { accessLogEntry, adminLogEntry, delegatedReadParams, operationSeriesCount, opsFailureEntry, opsFailureFingerprint, issueEntry, FRESHNESS_HEARTBEAT_MINUTES, sweepRunEntry, modelUsageEntry, ATTACHMENT_ADDED, ATTACHMENT_REMOVED, createTenantInput, domainEvent, domainEventInput, exportReadInput, importBatch, importCursorMove, exportsOfManifestJson, assertNoBindingShapeBreak, importsOfManifestJson, connectionLandingsOfManifestJson, connectorsOfManifestJson, entitlementGrant, entitlementGrantInput, eventId, meterReading, platformRequestInput, platformRequestId, identityLink, identityPool, instant, isSubstratError, connection, capabilityGrant, connectionGrant, connectionRevoke, connectionGrantRecord, connectionSecret, systemGrant, systemSwitch, systemSwitchRecord, peerSwitch, verticalCaller, verticalSlug as verticalSlugOf, subjectRef, requestFingerprint, createConnectionInput, connectLinkFilter, connectLinkKey, consumeConnectLinkInput, mintConnectLinkInput, projectedConnectionGrant, projectedConnectionKey, moduleManifest, createOrgInput, promotionAcknowledgement, bindAcknowledgement, bindHostnameInput, channelHistoryEntry, hostnameBinding, publishVersionInput, AUTO_ADMISSION_NOTE, routeTarget, ROUTE_SCOPE_HOSTNAMES_MAX, registerVerticalInput, vertical as verticalSchema, verticalChannel, verticalVersion, objectRef, entityObjectRef, assertModuleEmittableType, assertKernelAuthoredType, grantRefFromProof, org as orgSchema, orgMembership, principalId, resolvedIdentity, identityMembership, roleDefinition, scope as scopeSchema, tenant as tenantSchema, tenantRole, principalBecomeCapabilityInput, principalBindLinkInput, subjectShredReceipt, subjectAccessReceipt, SCOPE_TABLE_PAGE_DEFAULT, SCOPE_TABLE_PAGE_MAX, SCOPE_QUERY_ROW_MAX, verticalServingState, verticalTraceSampling, deploymentWireAuth, callsOfManifestJson, outboundOfManifestJson, listLimitOf, pageOf, countedPageOf, SCOPE_GATE_REASONS, substratError, assertReplayableDump, DUMP_OBJECTS_QUERY, dumpObjectsAudit, dumpObjectsOf, replayDumpObjects, delegatedReadRecord, ownerTransferAudit, memberChangeAudit, peerBindingAudit, connectionBindingAudit, copyMarkAudit, orphanSweepAudit, deliveryRedriveAudit, redrainEventsInput, REDRAIN_BATCH, errorCodeOf, storeDriverDumpPageBytes, } from '@substrat-run/contracts';
6
- import { actorOf, asPrincipal, assertAllowed, assertNoSecret, assertPermissionKey, CAPABILITY_DDL, UPLOAD_LINK_DDL, DOWNLOAD_LINK_DDL, createAttachmentVerbs, inspectUploadLink, resolveDownloadLink, redeemUploadLinkInTransaction, redeemOrReplayUploadLink, COPY_ORIGIN_DDL, ENTITY_STATE_MOVES_DDL, CAPABILITY_EXCHANGE_OPERATION, CAPABILITY_BECOME_MINT_OPERATION, CAPABILITY_BIND_MINT_OPERATION, bindLinkMintCheck, mintBindLinkAsPrincipal, becomeMintCheck, mintBecomeCapabilityAsPrincipal, revokeBecomeCapabilityAsPrincipal, readBecomeLinkStates, ENTITY_UNBIND_OPERATION, allowedFor, unbindEntityHolderBounded, capabilityAttachmentWriteRefused, capabilityTokenHash, createCapabilityVerbs, createEntityEdgeVerbs, createEntityStateVerbs, createTrashedReads, CONTINUATION_POSITION_CAP, visibleContinuation, searchStateWhere, uncheckedView, addStatePlans, addUpdatedStampPlans, watchUpdatedStamps, entityStateMigrations, assertNoCallerPurge, assertPlatformRequestRoom, isUnreachableParent, heldPurgePass, purgeDueOf, purgeHeldBy, lifecycleRefusal, scopeNotHeldRefusal, purgeOnlyKeysOf, purgeReportOf, purgeStillDue, refuseTrashedTarget, assertBoundOperations, checkHeldOperationsOf, countChecks, noteUncheckedCompletion, registerTrashTargets, runPurgePass, withheldKeysFor, capCoverage, delegationCeilingOf, delegationStampOf, outsideCeiling, heldKeysOf, parseScopeDelegation, statefulTablesOf, afterMigration, afterRuntimeDdl, derivesAnything, repairDerivedObjects, StateColumnLost, exchangeCapability as exchangeCapabilitySecret, exchangeBecomeLinkById, guardSecrets, mintBecomeCapability, plausibleSessionToken, readCapabilityPage, redactSecrets, redactSecretText, moduleLog, consoleLogSink, asyncInvocationId, asyncLinePass, consoleInvocationLineSink, resolveCapabilitySession, revokeCapabilityAsPlatform, assertReadOnlyQuery, attachmentBlobKey, attachmentSha256, isSizedByteStream, knownLengthStream, openAttachmentByteStream, putAttachmentBytes, refuseEntitlement, requiredEntitlementFor, foldMeterReading, guardSpine, guardSqlLimits, DO_SQL_LIMITS, tooManyResultColumns, tooManyTableColumns, parseValidationRecords, readableScopes, resolveScopeRecord, ulid, ISSUE_RETENTION_DAYS, telemetryRetentionStatements, FINDINGS_DDL, ATTACHMENT_BYTES_SQL, SCOPE_STORAGE_DDL, forgetScopeStorage, listScopeAttachmentStorageRows, retireScopeStorage, listScopeStorageAttemptRows, listScopeStorageRows, 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, DIRECTORY_LAKE_DDL, ACCESS_SUMMARY_METHOD, AccessSummary, openAccessSummary, ackDirectoryOutbox, ensureDirectoryLakeTriggers, advanceDirectoryLakeBackfill, pruneDirectoryLakeWindow, readDirectoryLakeBackfill, readDirectoryLakeCapture, readDirectoryOutbox, setDirectoryLakeCapture, STALE_SCOPES_DDL, listStaleScopeRows, listStaleScopeTakeRows, recordStaleScopeRows, VERTICAL_OWNERS_BACKFILL, VERTICAL_OWNERS_DDL, closeVerticalOwnerRow, listVerticalOwnerRows, openVerticalOwnerRow, verticalOwnerNow, listMeterDayRows, listMeterDayTakeRows, pruneMeterDayRows, recordMeterDayRows, CONNECT_LINKS_DDL, consumeConnectLinkRow, insertConnectLink, listConnectLinks as listConnectLinkRows, readConnectLink, restoreConnectLinkRow, revokeConnectLinkRow, createFindingRule, findingOfOpsFailure, findingOfSweepRun, pruneFindings, listFindingRules, listFindings, observeFinding, revokeFindingRule, setFindingStatus, assertRowLimit, assertRowOffset, OPS_FAILURE_RETENTION_DAYS, SWEEP_RUN_RETENTION_DAYS, SWEEP_RUNS_INTENT_INDEX, sweepRunsIntentHasKind, CONNECTIONS_LIVE_INDEX, connectionsLiveIndexHasOwner, BUILD_USAGE_RETENTION_DAYS, MODEL_USAGE_RETENTION_DAYS, foldModelUsage, backoffAt, platformRequestHistoryQuery, platformRequestOf, PLATFORM_REQUEST_COLUMNS, PLATFORM_REQUEST_REDACTION_SQL, platformRequestRedactionParams, platformRequestRedactionQuery, intentPayloadCarriesSubject, redactSubjectJobRuns, eraseSubjectFromModules, readSubjectPage, moduleRowsErased, moduleErasurePlan, redactSubjectScopeText, redactSubjectDirectoryText, ISSUE_EXEMPLAR_OWNER_BACKFILL_SQL, issueExemplarOwner, JOB_RUN_PATCH_SQL, JOB_RUN_CLAIM_SQL, JOB_RUN_RENEW_SQL, JOB_RUN_BEGIN_SQL, JOB_RUN_MISS_SQL, JOB_RUN_MISS_SETTLE_SQL, admissionMissOutcome, JOB_STEP_RECORD_SQL, JOB_LEASE_EXPIRED_NOTE, assertLeaseMs, DELIVERY_ERROR_REDACTION_SQL, REDACTED_DELIVERY_NOTE, seatScopeTuple, applyScopeRoleChange, changeScopeRole, revokeScopeRoles, scopeRoleHolders, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, dumpRoleRefusal, reservedGrantRefusal, reservedRoleDefinitionRefusal, reservedRoleRefusal, reservedShapeRefusal, SCOPE_SEATED_ROLES_SQL, SEAT_HOLDING_SCOPE_STATUSES, TENANT_SEATED_ROLES_SQL, admitPeer, boundToPeerDeclarations, peerCallerAt, collectPeers, peerSeats, resolveVerticalInstanceFrom, resolvePeerInstanceFrom, peerVerticalSpellings, samePeerVertical, peerGrantsStatus, systemGrantsStatus, systemScheduleState, systemSwitchedOff, systemSwitchedOffMessage, tenantSystemSwitchedOffMessage, PEER_SWITCHES_DDL, PEER_BINDINGS_DDL, SWITCH_OWED_DDL, SWITCH_FENCES_DDL, TABLE_OWNERS_DDL, assertMigrationLeavesLedgerAlone, recordOwnershipSteps, runMigrationStatements, executableSqlStatements, blankSqlComments, recordWriteSuperseded, switchFencesOf, switchSupersededMessage, SWITCH_KINDS, SYSTEM_SWITCHES_DDL, forgetSwitchesOf, listSystemSwitchRecords, moveSwitch, reassertActionOf, reassertEntry, reassertOffRow, recordSwitchedOff, recordSwitchedOn, restoreSwitchRecord, scopesSwitchedOffFor, switchActionOf, switchAuditSubject, recordAuditOutcome, auditedCapabilityRevoke, auditedScopePermissionWrite, auditWarningOf, switchNotFoundMessage, switchRecordsOf, switchedOffOf, switchesBackfillSqlOf, switchesTableExists, tenantHeldOf, tenantHoldsGrant, inUnitMovesToAudit, staleCarryRevertRow, staleCarryReverts, withRecorded, VERSION_MIGRATIONS_DDL, VERTICAL_SCOPE_STORES_DDL, forgetVerticalScopeStores, DEPLOYMENT_WIRE_AUTH_DDL, assertWireAuthFilter, deploymentWireAuthOf, forgetVerticalWireAuth, wireAuthAccessTarget, writeDeploymentWireAuth, indexVersionScopeStores, driverDeclarationsOf, verticalScopeStoresOf, STORE_DRIVER_RELEASES_DDL, approveStoreDriverReleaseIn, legacyStoreDriverConflict, legacyStoreDriverRenames, beginStoreDriverRolloutIn, finishStoreDriverRolloutIn, holdStoreDriverIn, advanceStoreDriverRebuildIn, claimStoreDriverRebuildIn, storeDriverRebuildIn, recordStoreDriverReleaseIn, recordStoreDriverRevokeWalkIn, releaseStoreDriverHoldIn, revokeStoreDriverReleaseIn, liveStoreDriverApprovalIn, storeDriverApprovalsIn, storeDriverRevokeWalkIn, storeDriverReleaseIn, storeDriverStateIn, storeDriverRolloutPendingIn, storeDriverRolloutWalkedIn, splitManifestMigrations, splitVersionMigrationsBatch, versionMigrationsOf, versionMigrationsExtractedOf, recordVersionMigrationsExtracted, deriveVersionMigrationDigest, publishedMigrationDigest, migrationChangeRefusal, writeVersionMigrations, OUTBOX_PRUNED_DDL, outboxSubscribersOf, pruneDrainedOutbox, pruneInputOf, denialListQuery, refusalListQuery, mapRefusalRow, denialSummaryQuery, denialTotalsQuery, DENIAL_WINDOW_QUERY, mapDenialRow, mapDenialSummaryBuckets, IMPERSONATION_COLUMNS, IMPERSONATION_DDL, ImpersonationRefused, assertImpersonationAdmitted, assertImpersonationWrites, assertModuleEnqueueableKind, assertSessionUsable, impersonationByIdQuery, impersonationListQuery, impersonationRowValues, impersonationStampOf, mapImpersonationRow, newImpersonationSession, resolveRetryPolicy, executorOutcomeOf, isDeliveryRefusal, refusalJournalText, membershipFencesBackfillSql, MEMBERSHIP_FENCES_DDL, membershipFencesTableExists, MEMBERSHIP_FENCE_SINCE_SQL, RAISE_MEMBERSHIP_FENCE_SQL, memberAddedAudit, orgChangeBound, tenantCoverage, isSecretBoxConfigured, unconfiguredSecretBox, createSubjectKeys, generateSealingKeyPair, noSealingKeyMessage, openSealed, sealTo, ConnectionSealingKeyUnavailableError, PermissionDenied, createAtomic, NotSearchable, NotListable, listIndexMigrations, listIndexPlans, listQuery, cursorOf, moduleMigrations, MIGRATION_DIGEST_FENCE_DDL, MIGRATION_DIGEST_MARK_LEGACY, assertJournalDumpCoherent, assertMigrationSql, migrationDivergence, migrationFailedError, migrationSetDivergence, migrationSteps, planMigrations, isSearchIndexTable, rowCountTable, searchIndexMigrations, searchIndexPlans, searchLimit, searchMatchExpression, searchQuery, ATTACHMENT_TEXT_DDL, ATTACHMENT_CONDEMNED_DDL, ATTACHMENT_SWEEP_LICENCE_DDL, ATTACHMENT_SWEEP_LICENCE_TABLE, clearOrphanSweepLicence, condemnLicensedOrphanAttachments, consumeOrphanSweepLicence, licensedOrphanIds, recordOrphanSweepLicence, refuseUnlicensedOrphanSweep, fenceAttachmentSweep, refuseCondemnedAttachment, refuseCondemnedInDump, rowlessAttachmentIds, sweepOrphanAttachments, missingAttachmentStore, SETTLED_COPY_STATES, unsettledCopyRefusal, assertAttachmentExtractors, resolveAttachmentTextBounds, assertJobRegistrable, attachmentRecordOfRow, attachmentTextJob, enqueueAttachmentText, ATTACHMENT_TEXT_BACKFILL_JOB, ATTACHMENT_TEXT_JOB, kernelJobFor, queueAttachmentTextBackfill, startAttachmentTextBackfill, attachmentTextBackfillJob, reconcileAttachmentText, recordAttachmentText, searchAttachments, entityVersionQuery, entityVersionOf, assertIfMatch, OUTBOX_ENTITY_INDEX, SCHEDULE_STATE_DDL, SCHEDULE_STATE_REBUILD, scheduleStateHasKind, VERTICAL_EVENTS_DDL, EXPORT_HOPS_SQL, emptyImportResult, IMPORT_CURSORS_SQL, IMPORT_CURSOR_OF_SQL, OUTBOX_MARK_SQL, emittedSinceQuery, emittedReportOf, EMITTED_REPORT_CAP, noteTransitionInto, withTransitions, exportedSinceQuery, IMPORT_CURSOR_ADVANCE_SQL, IMPORT_RECORD_SQL, moveImportCursor, importCursorSourceOf, exportBreaksOf, exportBreakRefusal, assertPromoteReviewCurrent, promoteRaceRefusal, servingRaceRefusal, autoAdmittedProdRefusal, listedPromoteRefusal, rebindRaceRefusal, SERVES_NOW_CONDITION, SERVES_NOW_PREDICATE, servesNowParams, migratesFrom, servedFromRow, servesAsFrom, bindExportBreaksOf, bindExportBreakRefusal, scopeMoveOf, runningVersionOf, isPrimaryScope, PROVISIONED_VERSIONS_SQL, installsReconciledOf, strandJudgmentsOf, provisionedVersionsParams, boundShapesColumn, boundShapesOfColumn, installReconciled, CrossVerticalRegistry, exportReadPlan, exportReadQuery, planExportBatch, withheldNote, WIRE_NONCE_DDL, WIRE_NONCE_FULL, claimWireNonceIn, isWireNonceTable, JOB_RUN_DDL, JOB_RUN_DUE_AT, jobRunListLimit, jobRunOf, runDueJobRuns, startJobRun, IDEMPOTENCY_DDL, REFUSALS_TABLE_DDL, REFUSALS_INDEX, refusalInsert, refusalOf, markGuardRefusal, REFUSALS_REBUILD, refusalsAdmitGuards, assertIdempotencyKey, idempotencyLookupQuery, idempotencyPruneStatement, idempotencyRecordStatement, idempotencyOptedOutMessage, replayFor, globalFetch, fetchLikeOf, deadlineFetch, createUlid, facetEvents, readHistory, walkEventCause, walkEventEffects, assertRedrainWindow, readInvocation, readDeadLetters, readLifecycleFlow, readOperationSeries, domainEventOf, readUndrainedOutbox, undrainedEventsOf, connectorCallRecord, noopConnectorCallRecorder, recordConnectorCall, settleConnectionUse, unknownRoleError, callReservedStoreOperation, storesFencedRefusal, readStoreDump, writeStoreDump, callScopeStore, observeStoreCall, replayStoreErasures, scopeStoreLifecycleOf, scopeStoreRunnersOf, } from '@substrat-run/kernel';
5
+ import { accessLogEntry, adminLogEntry, delegatedReadParams, operationSeriesCount, opsFailureEntry, opsFailureFingerprint, issueEntry, FRESHNESS_HEARTBEAT_MINUTES, sweepRunEntry, modelUsageEntry, ATTACHMENT_ADDED, ATTACHMENT_REMOVED, createTenantInput, domainEvent, domainEventInput, exportReadInput, importBatch, importCursorMove, exportsOfManifestJson, assertNoBindingShapeBreak, importsOfManifestJson, connectionLandingsOfManifestJson, connectorsOfManifestJson, entitlementGrant, entitlementGrantInput, eventId, meterReading, platformRequestInput, platformRequestId, identityLink, identityPool, instant, isSubstratError, connection, capabilityGrant, connectionGrant, connectionRevoke, connectionGrantRecord, connectionSecret, systemGrant, systemSwitch, systemSwitchRecord, peerSwitch, verticalCaller, verticalSlug as verticalSlugOf, subjectRef, requestFingerprint, createConnectionInput, connectLinkFilter, connectLinkKey, consumeConnectLinkInput, mintConnectLinkInput, projectedConnectionGrant, projectedConnectionKey, moduleManifest, createOrgInput, promotionAcknowledgement, bindAcknowledgement, bindHostnameInput, channelHistoryEntry, hostnameBinding, publishVersionInput, AUTO_ADMISSION_NOTE, routeTarget, ROUTE_SCOPE_HOSTNAMES_MAX, registerVerticalInput, vertical as verticalSchema, verticalChannel, verticalVersion, objectRef, entityObjectRef, assertModuleEmittableType, assertKernelAuthoredType, grantRefFromProof, org as orgSchema, orgMembership, principalId, resolvedIdentity, identityMembership, roleDefinition, scope as scopeSchema, tenant as tenantSchema, tenantRole, principalBecomeCapabilityInput, principalBindLinkInput, mergeDumpPages, subjectShredReceipt, subjectAccessReceipt, SCOPE_TABLE_PAGE_DEFAULT, SCOPE_TABLE_PAGE_MAX, SCOPE_QUERY_ROW_MAX, verticalServingState, verticalTraceSampling, deploymentWireAuth, callsOfManifestJson, outboundOfManifestJson, listLimitOf, pageOf, countedPageOf, SCOPE_GATE_REASONS, substratError, assertReplayableDump, DUMP_OBJECTS_QUERY, dumpObjectsAudit, dumpObjectsOf, isRuntimeTable, replayDumpObjects, delegatedReadRecord, ownerTransferAudit, memberChangeAudit, peerBindingAudit, connectionBindingAudit, copyMarkAudit, orphanSweepAudit, deliveryRedriveAudit, brokerDeadLetterAudit, redrainEventsInput, REDRAIN_BATCH, errorCodeOf, storeDriverDumpPageBytes, } from '@substrat-run/contracts';
6
+ import { actorOf, asPrincipal, assertAllowed, assertNoSecret, assertPermissionKey, CAPABILITY_DDL, UPLOAD_LINK_DDL, DOWNLOAD_LINK_DDL, createAttachmentVerbs, inspectUploadLink, resolveDownloadLink, redeemUploadLinkInTransaction, redeemOrReplayUploadLink, COPY_ORIGIN_DDL, ENTITY_STATE_MOVES_DDL, CAPABILITY_EXCHANGE_OPERATION, CAPABILITY_BECOME_MINT_OPERATION, CAPABILITY_BIND_MINT_OPERATION, bindLinkMintCheck, mintBindLinkAsPrincipal, becomeMintCheck, mintBecomeCapabilityAsPrincipal, revokeBecomeCapabilityAsPrincipal, readBecomeLinkStates, ENTITY_UNBIND_OPERATION, allowedFor, unbindEntityHolderBounded, capabilityAttachmentWriteRefused, capabilityTokenHash, createCapabilityVerbs, createEntityEdgeVerbs, createEntityStateVerbs, createTrashedReads, CONTINUATION_POSITION_CAP, visibleContinuation, searchStateWhere, uncheckedView, addStatePlans, addUpdatedStampPlans, watchUpdatedStamps, entityStateMigrations, assertNoCallerPurge, assertPlatformRequestRoom, isUnreachableParent, heldPurgePass, purgeDueOf, purgeHeldBy, lifecycleRefusal, scopeNotHeldRefusal, purgeOnlyKeysOf, purgeReportOf, purgeStillDue, refuseTrashedTarget, assertBoundOperations, checkHeldOperationsOf, countChecks, noteUncheckedCompletion, registerTrashTargets, runPurgePass, withheldKeysFor, capCoverage, delegationCeilingOf, delegationStampOf, outsideCeiling, heldKeysOf, parseScopeDelegation, statefulTablesOf, afterMigration, afterRuntimeDdl, derivesAnything, repairDerivedObjects, StateColumnLost, exchangeCapability as exchangeCapabilitySecret, exchangeBecomeLinkById, guardSecrets, mintBecomeCapability, plausibleSessionToken, readCapabilityPage, redactSecrets, redactSecretText, moduleLog, consoleLogSink, asyncInvocationId, asyncLinePass, consoleInvocationLineSink, resolveCapabilitySession, revokeCapabilityAsPlatform, assertReadOnlyQuery, attachmentBlobKey, attachmentSha256, isSizedByteStream, knownLengthStream, openAttachmentByteStream, putAttachmentBytes, refuseEntitlement, requiredEntitlementFor, foldMeterReading, guardSpine, guardSqlLimits, DO_SQL_LIMITS, tooManyResultColumns, tooManyTableColumns, parseValidationRecords, readableScopes, resolveScopeRecord, ulid, ISSUE_RETENTION_DAYS, telemetryRetentionStatements, FINDINGS_DDL, ATTACHMENT_BYTES_SQL, SCOPE_STORAGE_DDL, forgetScopeStorage, listScopeAttachmentStorageRows, retireScopeStorage, listScopeStorageAttemptRows, listScopeStorageRows, 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, DIRECTORY_LAKE_DDL, ACCESS_SUMMARY_METHOD, AccessSummary, openAccessSummary, ackDirectoryOutbox, ensureDirectoryLakeTriggers, advanceDirectoryLakeBackfill, pruneDirectoryLakeWindow, readDirectoryLakeBackfill, readDirectoryLakeCapture, readDirectoryOutbox, setDirectoryLakeCapture, STALE_SCOPES_DDL, listStaleScopeRows, listStaleScopeTakeRows, recordStaleScopeRows, VERTICAL_OWNERS_BACKFILL, VERTICAL_OWNERS_DDL, closeVerticalOwnerRow, listVerticalOwnerRows, openVerticalOwnerRow, verticalOwnerNow, listMeterDayRows, listMeterDayTakeRows, pruneMeterDayRows, recordMeterDayRows, CONNECT_LINKS_DDL, consumeConnectLinkRow, insertConnectLink, listConnectLinks as listConnectLinkRows, readConnectLink, restoreConnectLinkRow, revokeConnectLinkRow, createFindingRule, findingOfOpsFailure, findingOfSweepRun, pruneFindings, listFindingRules, listFindings, observeFinding, revokeFindingRule, setFindingStatus, assertRowLimit, assertRowOffset, OPS_FAILURE_RETENTION_DAYS, SWEEP_RUN_RETENTION_DAYS, SWEEP_RUNS_INTENT_INDEX, sweepRunsIntentHasKind, CONNECTIONS_LIVE_INDEX, connectionsLiveIndexHasOwner, BUILD_USAGE_RETENTION_DAYS, MODEL_USAGE_RETENTION_DAYS, foldModelUsage, backoffAt, platformRequestHistoryQuery, platformRequestOf, PLATFORM_REQUEST_COLUMNS, PLATFORM_REQUEST_REDACTION_SQL, platformRequestRedactionParams, platformRequestRedactionQuery, intentPayloadCarriesSubject, redactSubjectJobRuns, eraseSubjectFromModules, readSubjectPage, moduleRowsErased, moduleErasurePlan, redactSubjectScopeText, redactSubjectDirectoryText, ISSUE_EXEMPLAR_OWNER_BACKFILL_SQL, issueExemplarOwner, JOB_RUN_PATCH_SQL, JOB_RUN_CLAIM_SQL, JOB_RUN_RENEW_SQL, JOB_RUN_BEGIN_SQL, JOB_RUN_MISS_SQL, JOB_RUN_MISS_SETTLE_SQL, admissionMissOutcome, JOB_STEP_RECORD_SQL, JOB_LEASE_EXPIRED_NOTE, assertLeaseMs, DELIVERY_ERROR_REDACTION_SQL, REDACTED_DELIVERY_NOTE, seatScopeTuple, applyScopeRoleChange, changeScopeRole, revokeScopeRoles, scopeRoleHolders, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, dumpRoleRefusal, reservedGrantRefusal, reservedRoleDefinitionRefusal, reservedRoleRefusal, reservedShapeRefusal, SCOPE_SEATED_ROLES_SQL, SEAT_HOLDING_SCOPE_STATUSES, TENANT_SEATED_ROLES_SQL, admitPeer, boundToPeerDeclarations, peerCallerAt, collectPeers, peerSeats, resolveVerticalInstanceFrom, resolvePeerInstanceFrom, peerVerticalSpellings, samePeerVertical, peerGrantsStatus, systemGrantsStatus, systemScheduleState, systemSwitchedOff, systemSwitchedOffMessage, tenantSystemSwitchedOffMessage, PEER_SWITCHES_DDL, PEER_BINDINGS_DDL, SWITCH_OWED_DDL, SWITCH_FENCES_DDL, TABLE_OWNERS_DDL, assertMigrationLeavesLedgerAlone, recordOwnershipSteps, runMigrationStatements, executableSqlStatements, blankSqlComments, recordWriteSuperseded, switchFencesOf, switchSupersededMessage, SWITCH_KINDS, SYSTEM_SWITCHES_DDL, forgetSwitchesOf, listSystemSwitchRecords, moveSwitch, reassertActionOf, reassertEntry, reassertOffRow, recordSwitchedOff, recordSwitchedOn, restoreSwitchRecord, scopesSwitchedOffFor, switchActionOf, switchAuditSubject, recordAuditOutcome, auditedCapabilityRevoke, auditedScopePermissionWrite, auditWarningOf, switchNotFoundMessage, switchRecordsOf, switchedOffOf, switchesBackfillSqlOf, switchesTableExists, tenantHeldOf, tenantHoldsGrant, inUnitMovesToAudit, staleCarryRevertRow, staleCarryReverts, withRecorded, VERSION_MIGRATIONS_DDL, VERTICAL_SCOPE_STORES_DDL, forgetVerticalScopeStores, DEPLOYMENT_WIRE_AUTH_DDL, assertWireAuthFilter, deploymentWireAuthOf, forgetVerticalWireAuth, wireAuthAccessTarget, writeDeploymentWireAuth, indexVersionScopeStores, driverDeclarationsOf, verticalScopeStoresOf, STORE_DRIVER_RELEASES_DDL, approveStoreDriverReleaseIn, legacyStoreDriverConflict, legacyStoreDriverRenames, beginStoreDriverRolloutIn, finishStoreDriverRolloutIn, holdStoreDriverIn, advanceStoreDriverRebuildIn, claimStoreDriverRebuildIn, storeDriverRebuildIn, recordStoreDriverReleaseIn, recordStoreDriverRevokeWalkIn, releaseStoreDriverHoldIn, revokeStoreDriverReleaseIn, liveStoreDriverApprovalIn, storeDriverApprovalsIn, storeDriverRevokeWalkIn, storeDriverReleaseIn, storeDriverStateIn, storeDriverRolloutPendingIn, storeDriverRolloutWalkedIn, splitManifestMigrations, splitVersionMigrationsBatch, versionMigrationsOf, versionMigrationsExtractedOf, recordVersionMigrationsExtracted, deriveVersionMigrationDigest, publishedMigrationDigest, migrationChangeRefusal, writeVersionMigrations, OUTBOX_PRUNED_DDL, outboxSubscribersOf, pruneDrainedOutbox, pruneInputOf, denialListQuery, refusalListQuery, mapRefusalRow, denialSummaryQuery, denialTotalsQuery, DENIAL_WINDOW_QUERY, mapDenialRow, mapDenialSummaryBuckets, IMPERSONATION_COLUMNS, IMPERSONATION_DDL, ImpersonationRefused, assertImpersonationAdmitted, assertImpersonationWrites, assertModuleEnqueueableKind, assertSessionUsable, impersonationByIdQuery, impersonationListQuery, impersonationRowValues, impersonationStampOf, mapImpersonationRow, newImpersonationSession, resolveRetryPolicy, executorOutcomeOf, isDeliveryRefusal, refusalJournalText, membershipFencesBackfillSql, MEMBERSHIP_FENCES_DDL, membershipFencesTableExists, MEMBERSHIP_FENCE_SINCE_SQL, RAISE_MEMBERSHIP_FENCE_SQL, memberAddedAudit, orgChangeBound, tenantCoverage, isSecretBoxConfigured, unconfiguredSecretBox, createSubjectKeys, generateSealingKeyPair, noSealingKeyMessage, openSealed, sealTo, ConnectionSealingKeyUnavailableError, PermissionDenied, createAtomic, NotSearchable, NotListable, listIndexMigrations, listIndexPlans, listQuery, cursorOf, moduleMigrations, MIGRATION_DIGEST_FENCE_DDL, MIGRATION_DIGEST_MARK_LEGACY, assertJournalDumpCoherent, assertMigrationSql, migrationDivergence, migrationFailedError, migrationSetDivergence, migrationSteps, planMigrations, isSearchIndexTable, rowCountTable, searchIndexMigrations, searchIndexPlans, searchLimit, searchMatchExpression, searchQuery, ATTACHMENT_TEXT_DDL, ATTACHMENT_CONDEMNED_DDL, ATTACHMENT_SWEEP_LICENCE_DDL, ATTACHMENT_SWEEP_LICENCE_TABLE, clearOrphanSweepLicence, condemnLicensedOrphanAttachments, consumeOrphanSweepLicence, licensedOrphanIds, recordOrphanSweepLicence, refuseUnlicensedOrphanSweep, fenceAttachmentSweep, refuseCondemnedAttachment, refuseCondemnedInDump, rowlessAttachmentIds, sweepOrphanAttachments, missingAttachmentStore, SETTLED_COPY_STATES, unsettledCopyRefusal, assertAttachmentExtractors, resolveAttachmentTextBounds, assertJobRegistrable, attachmentRecordOfRow, attachmentTextJob, enqueueAttachmentText, ATTACHMENT_TEXT_BACKFILL_JOB, ATTACHMENT_TEXT_JOB, ATTACHMENT_TEXT_RECHECK_JOB, kernelJobFor, queueAttachmentTextBackfill, startAttachmentTextBackfill, attachmentTextBackfillJob, attachmentExtractorSetKey, attachmentTextRecheckJob, readAttachmentTextRecheckPage, requeueUnsupportedAttachmentText, startAttachmentTextRecheck, reconcileAttachmentText, recordAttachmentText, searchAttachments, entityVersionQuery, entityVersionOf, assertIfMatch, OUTBOX_ENTITY_INDEX, SCHEDULE_STATE_DDL, SCHEDULE_STATE_REBUILD, scheduleStateHasKind, VERTICAL_EVENTS_DDL, EXPORT_HOPS_SQL, emptyImportResult, IMPORT_CURSORS_SQL, IMPORT_CURSOR_OF_SQL, OUTBOX_MARK_SQL, emittedSinceQuery, emittedReportOf, EMITTED_REPORT_CAP, noteTransitionInto, withTransitions, exportedSinceQuery, IMPORT_CURSOR_ADVANCE_SQL, IMPORT_RECORD_SQL, moveImportCursor, importCursorSourceOf, exportBreaksOf, exportBreakRefusal, assertPromoteReviewCurrent, promoteRaceRefusal, servingRaceRefusal, autoAdmittedProdRefusal, listedPromoteRefusal, rebindRaceRefusal, SERVES_NOW_CONDITION, SERVES_NOW_PREDICATE, servesNowParams, migratesFrom, servedFromRow, servesAsFrom, bindExportBreaksOf, bindExportBreakRefusal, scopeMoveOf, runningVersionOf, isPrimaryScope, PROVISIONED_VERSIONS_SQL, installsReconciledOf, strandJudgmentsOf, provisionedVersionsParams, boundShapesColumn, boundShapesOfColumn, installReconciled, CrossVerticalRegistry, exportReadPlan, exportReadQuery, planExportBatch, withheldNote, WIRE_NONCE_DDL, WIRE_NONCE_FULL, claimWireNonceIn, isWireNonceTable, JOB_RUN_DDL, JOB_RUN_DUE_AT, jobRunListLimit, jobRunOf, runDueJobRuns, startJobRun, IDEMPOTENCY_DDL, REFUSALS_TABLE_DDL, REFUSALS_INDEX, refusalInsert, refusalOf, markGuardRefusal, REFUSALS_REBUILD, refusalsAdmitGuards, assertIdempotencyKey, idempotencyLookupQuery, idempotencyPruneStatement, idempotencyRecordStatement, idempotencyOptedOutMessage, replayFor, globalFetch, fetchLikeOf, deadlineFetch, createUlid, facetEvents, readHistory, walkEventCause, walkEventEffects, assertRedrainWindow, readInvocation, readDeadLetters, readLifecycleFlow, readOperationSeries, domainEventOf, readUndrainedOutbox, undrainedEventsOf, connectorCallRecord, noopConnectorCallRecorder, recordConnectorCall, settleConnectionUse, unknownRoleError, callReservedStoreOperation, storesFencedRefusal, readStoreDump, writeStoreDump, callScopeStore, observeStoreCall, replayStoreErasures, scopeStoreLifecycleOf, scopeStoreRunnersOf, } from '@substrat-run/kernel';
7
7
  import { handoffOutcome, reportHandoff, traceIdOf } from '@substrat-run/kernel';
8
8
  import { currentTraceparent } from '@substrat-run/kernel/invocation-line';
9
9
  import { attributedView, delegatedRevokeSql, writeExplicitTupleIn, grantEntityShapeIn, shapeTopUpBatch, topUpEntityGrantShapes, settlePlatformRequestIn, } from '@substrat-run/kernel';
@@ -11,6 +11,7 @@ import { assertSameAttachmentGate, attachmentGateOf, decideAttachmentRemove, } f
11
11
  import { DIRECTORY_CLAIMS_DDL, DIRECTORY_CROSSINGS_DDL, oneDatabaseDirectoryObjects, } from '@substrat-run/kernel';
12
12
  import { canonicalInstant } from '@substrat-run/kernel';
13
13
  import { advanceMarks, handoffQueries, messagesOf } from '@substrat-run/kernel';
14
+ import { intentStateOf, intentStateQuery, witnessesOf, witnessQueries, } from '@substrat-run/kernel';
14
15
  import { MARKUP_INSERT_SQL, MARKUP_SELECT_FOR_TENANT_SQL, MARKUP_SELECT_SQL, markupRecordValues, markupScheduleOf, newMarkupRow, } from '@substrat-run/kernel';
15
16
  import { prePromoteSnapshotExpiresAt } from '@substrat-run/kernel';
16
17
  import { ADMIN_LOG_INDEXES_SQL, SETTLE_INTENT_SQL, SETTLE_OUTCOME_SQL, settleOutcomeParamsOf, readAuditedOperations, unknownOutcomeOf, } from '@substrat-run/kernel';
@@ -175,7 +176,9 @@ const builtColumnsOf = (db, name) => {
175
176
  // A table, not a view or an index `pragma_table_info` would also answer for, and not one of
176
177
  // SQLite's own, which this code never built and an export never dumps: a dump naming one is
177
178
  // refused by name rather than failing on its write (#1912). `pragma_table_info` alone would
178
- // call `sqlite_master` built.
179
+ // call `sqlite_master` built. Nor a runtime's own table (#3499), for the same reason.
180
+ if (isRuntimeTable(name))
181
+ return undefined;
179
182
  const built = db
180
183
  .prepare(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ? COLLATE NOCASE AND name NOT GLOB 'sqlite_*'`)
181
184
  .get(name);
@@ -647,13 +650,19 @@ const PROCESS_HOST_DIRS = new Map();
647
650
  const databaseBytesOf = (db) => db.pragma('page_count', { simple: true }) * db.pragma('page_size', { simple: true });
648
651
  /** What a scope database's attachment rows sum to (#2501). */
649
652
  const attachmentBytesOf = (db) => db.prepare(ATTACHMENT_BYTES_SQL).get().bytes;
653
+ /** Every table in `db` by name, without a runtime's own (`isRuntimeTable`, #3499: a replicated file holds Litestream's). */
654
+ function tableNamesOf(db) {
655
+ return db.prepare(`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name`).all()
656
+ .map((r) => r.name)
657
+ .filter((name) => !isRuntimeTable(name));
658
+ }
650
659
  /**
651
660
  * The introspection reads, over an already-resolved connection: the bodies behind both the
652
661
  * directory-checked admin verbs and the `*Local` verbs a vertical's `/internal/*` routes call by
653
662
  * scope id alone (#2544). How the connection was reached, and what is recorded, stay with the caller.
654
663
  */
655
664
  function scopeTablesOf(db) {
656
- const names = db.prepare(`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name`).all().map((r) => r.name);
665
+ const names = tableNamesOf(db);
657
666
  const known = new Set(names);
658
667
  const count = (sql) => db.prepare(sql).get().c;
659
668
  const tombstones = (name) => db.prepare(`SELECT name FROM pragma_table_info(?)`).all(name).some((c) => c.name === 'revoked_at');
@@ -669,7 +678,7 @@ function scopeTablePageOf(db, input) {
669
678
  // Validate the table against the LIVE schema — an unknown name throws, it is
670
679
  // never interpolated blind. That validated name is the only thing that reaches
671
680
  // the query, so the quoted identifier below carries no user input.
672
- const known = new Set(db.prepare(`SELECT name FROM sqlite_master WHERE type = 'table'`).all().map((r) => r.name));
681
+ const known = new Set(tableNamesOf(db));
673
682
  if (!known.has(input.table))
674
683
  throw substratError('not_found', `unknown table '${input.table}'`);
675
684
  // The ceiling clamps; a bound SQLite would misread (NaN, non-finite, fractional,
@@ -982,6 +991,9 @@ export class SqliteScopeHost {
982
991
  brokerTelemetry;
983
992
  /** K-74: each scope's handoff marks, a cache of what its broker holds (`DeliveryBroker.marks`). */
984
993
  handoffMarks = new Map();
994
+ /** A5: `deliveryHandoff`, and each scope's mode with its window start (in memory, as the marks are). */
995
+ deliveryHandoff;
996
+ deliveryModes = new Map();
985
997
  migrationsDigest;
986
998
  /** #1746: where `ctx.log` lines go — the console unless a caller (a test) says otherwise. */
987
999
  logSink;
@@ -1005,6 +1017,7 @@ export class SqliteScopeHost {
1005
1017
  this.clock = options.clock ?? (() => instant.parse(new Date().toISOString()));
1006
1018
  this.versionId = options.versionId ?? null;
1007
1019
  this.deliveryBroker = options.deliveryBroker ?? null;
1020
+ this.deliveryHandoff = options.deliveryHandoff ?? 'always';
1008
1021
  this.brokerTelemetry = options.brokerTelemetry ?? null;
1009
1022
  this.migrationsDigest = options.migrationsDigest;
1010
1023
  this.permissions = options.permissions;
@@ -1752,6 +1765,70 @@ export class SqliteScopeHost {
1752
1765
  // K-70: a capture trigger held to its table as this code built it (a column added above ships).
1753
1766
  ensureDirectoryLakeTriggers(redactionSqlOf(this.directory));
1754
1767
  }
1768
+ /** `restoreDirectory`'s body (#40), shared with `restoreDirectoryPaged` (#3494). `after` joins the audit row's after-state. */
1769
+ restoreDirectoryFrom(actor, dump, after = {}, opts = {}) {
1770
+ // Counted before the replace — afterwards the old directory is gone, and
1771
+ // "restored over N tenants" is the fact the audit entry exists to carry.
1772
+ const before = this.directory.prepare('SELECT COUNT(*) AS n FROM tenants').get().n;
1773
+ // #3494: a paged restore's consent, judged here, synchronously with the replacement below: no
1774
+ // await separates them, so a tenant created while the pages were read is seen and not dropped.
1775
+ if (opts.requireEmpty && before > 0) {
1776
+ throw substratError('conflict', 'the directory is not empty — a restore REPLACES it, so anything created since this copy was taken would be lost; pass overwrite=true to confirm');
1777
+ }
1778
+ // The dump is untrusted input, as it is on the DO path (#1143). Its names reach SQL
1779
+ // as identifiers, and its `ddl`, never executed here since #1912, is still held to one
1780
+ // CREATE TABLE. Judged as a whole before the first DROP, so a refused dump leaves the
1781
+ // directory untouched.
1782
+ // Older backup producers and local migration fixtures may include these
1783
+ // tables. Ignore them entirely: neither their DDL nor their rows may set
1784
+ // a restored key epoch or make an old hidden locator valid again.
1785
+ const publicTables = dump.tables.filter((table) => !['private_continuation_keys', 'private_continuation_positions'].includes(table.name.toLowerCase()));
1786
+ assertReplayableDump(publicTables);
1787
+ // One transaction, foreign keys deferred to commit: the dump is ordered by table NAME
1788
+ // (which says nothing about references — a `tenants` row can name another as
1789
+ // `provisioned_by_tenant`), and the DROPs themselves delete rows a populated child would
1790
+ // still be referencing. better-sqlite3 runs the function synchronously inside
1791
+ // BEGIN/COMMIT, and rolls back if it throws.
1792
+ this.directory.pragma('defer_foreign_keys = ON');
1793
+ this.directory.transaction(() => {
1794
+ const existing = this.directory
1795
+ .prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT GLOB 'sqlite_*'`)
1796
+ .all();
1797
+ for (const { name } of existing) {
1798
+ if (!isRuntimeTable(name))
1799
+ this.directory.exec(`DROP TABLE IF EXISTS "${name}"`);
1800
+ }
1801
+ // The dump contributes rows only (#1912, extending #1898's spine rule to every table).
1802
+ // Every directory table is built by the pass a cold start runs, never from the dump's
1803
+ // DDL: these are the platform's own registries, so a dump's `DEFAULT 1` on
1804
+ // `verticals.tenant_provisioner`, a `COLLATE NOCASE` on `tenants.slug` or an extra
1805
+ // table that `REFERENCES tenants` would otherwise decide how the platform behaves
1806
+ // after the restore. A copy taken before a directory migration carries the OLD shape;
1807
+ // its rows go in by column name, so a column it lacks takes the running code's default.
1808
+ this.buildDirectorySchema();
1809
+ // Refuses a table this code does not build, adds unknown columns bare, loads the rows
1810
+ // by name, then the legacy scope and #1674 backfills, all inside this transaction.
1811
+ loadDirectoryDump(publicTables, {
1812
+ columnsOf: (name) => builtColumnsOf(this.directory, name),
1813
+ exec: (sql) => this.directory.exec(sql),
1814
+ now: () => this.clock(),
1815
+ insert: (sql, rows) => {
1816
+ const insert = this.directory.prepare(sql);
1817
+ for (const row of rows)
1818
+ insert.run(...row);
1819
+ },
1820
+ });
1821
+ // The dump's rows have landed in the rebuilt tables. Append this restore's
1822
+ // own row before commit, so a failed insert rolls the imported state back.
1823
+ this.recordAdmin(actor, 'restoreDirectory', { tenantId: null }, { tenants: before }, { capturedAt: dump.capturedAt, tables: dump.tables.length, ...after });
1824
+ })();
1825
+ // #1764's split, over any version the dump stored before it.
1826
+ this.splitVersionMigrations();
1827
+ // Roles are held in memory (`loadRoles`), so a restore that only rewrote the
1828
+ // table would leave every permission check reading the PRE-restore roles until
1829
+ // the process restarted — the exact silent-divergence a recovery must not have.
1830
+ this.loadRoles();
1831
+ }
1755
1832
  /**
1756
1833
  * The directory's tables as this code builds them, carrying whatever the directory already
1757
1834
  * holds forward to that shape: a cold start's pass, and a restore's (#1898, #1912), which runs
@@ -3021,7 +3098,7 @@ export class SqliteScopeHost {
3021
3098
  // Matched without case, as SQLite resolves a table name (#1883 review).
3022
3099
  // The wire nonce store is this store's own (RFC wire-signing §4): a dump that carries it is not
3023
3100
  // replayed, so a load starts it empty, as it starts a vertical's search index.
3024
- const replayable = dumped.filter((t) => !isSearchIndexTable(t.name.toLowerCase()) && !isWireNonceTable(t.name));
3101
+ const replayable = dumped.filter((t) => !isRuntimeTable(t.name) && !isSearchIndexTable(t.name.toLowerCase()) && !isWireNonceTable(t.name));
3025
3102
  // A Durable Object's dump carries spine tables this adapter keeps in its directory, or does
3026
3103
  // not keep at all; they are skipped by name, and any other unknown spine table is refused.
3027
3104
  const loadable = replayable.filter((t) => !DO_SCOPE_ONLY_SPINE_TABLES.has(t.name.toLowerCase()));
@@ -3038,7 +3115,7 @@ export class SqliteScopeHost {
3038
3115
  // shadow table directly is an error, and dropping them in `sqlite_master` order
3039
3116
  // would reach one before its virtual table.
3040
3117
  for (const { name } of existing) {
3041
- if (isSearchIndexTable(name.toLowerCase()))
3118
+ if (isRuntimeTable(name) || isSearchIndexTable(name.toLowerCase()))
3042
3119
  continue;
3043
3120
  db.exec(`DROP TABLE IF EXISTS "${name}"`);
3044
3121
  }
@@ -5224,7 +5301,8 @@ export class SqliteScopeHost {
5224
5301
  await this.dispatch(rt, rt.invocationId);
5225
5302
  await this.dispatchExecutors(rt, rt.invocationId, executorOutcomes);
5226
5303
  // K-74: after the consumers and executors, whose own emits and intents count too.
5227
- await this.handOffCommitted(rt);
5304
+ // #3474: the rows this call wrote carry its trace.
5305
+ await this.handOffCommitted(rt, { invocationId: rt.invocationId ?? null, traceId: traceIdOf(currentTraceparent()) });
5228
5306
  }
5229
5307
  if (exportMark !== null && !replayed) {
5230
5308
  const q = exportedSinceQuery(exportTypes, exportMark);
@@ -5754,12 +5832,22 @@ export class SqliteScopeHost {
5754
5832
  // #1575: the kernel's extraction jobs are this host's own, bound to this scope — no
5755
5833
  // deployment registers them, and none can shadow them. The backfill starts here, on
5756
5834
  // the drive, so a scope's first request never pays for attachments that predate it.
5757
- await rt.actor.enqueue(() => startAttachmentTextBackfill(spineSql(rt.db), ulid(), this.clock()));
5835
+ // The recheck likewise, in the same turn, once per change of extractor set: what an older
5836
+ // set recorded `unsupported` and this one reads is queued again (`startAttachmentTextRecheck`).
5837
+ const extractorSet = attachmentExtractorSetKey(this.attachmentExtractors);
5838
+ await rt.actor.enqueue(() => {
5839
+ startAttachmentTextBackfill(spineSql(rt.db), ulid(), this.clock());
5840
+ startAttachmentTextRecheck(spineSql(rt.db), extractorSet, ulid(), this.clock());
5841
+ });
5758
5842
  const kernelJobs = {
5759
5843
  [ATTACHMENT_TEXT_JOB]: this.attachmentTextHandler(rt),
5760
5844
  [ATTACHMENT_TEXT_BACKFILL_JOB]: attachmentTextBackfillJob({
5761
5845
  queueBatch: (after) => rt.actor.enqueue(() => rt.db.transaction(() => queueAttachmentTextBackfill(spineSql(rt.db), after, ulid, this.clock()))()),
5762
5846
  }),
5847
+ [ATTACHMENT_TEXT_RECHECK_JOB]: attachmentTextRecheckJob({
5848
+ page: (after) => rt.actor.enqueue(() => readAttachmentTextRecheckPage(spineSql(rt.db), after)),
5849
+ requeue: (ids) => rt.actor.enqueue(() => rt.db.transaction(() => requeueUnsupportedAttachmentText(spineSql(rt.db), ids, ulid, this.clock()))()),
5850
+ }, this.attachmentExtractors),
5763
5851
  };
5764
5852
  return runDueJobRuns({
5765
5853
  store: this.jobStore(rt),
@@ -5955,11 +6043,20 @@ export class SqliteScopeHost {
5955
6043
  * the dispatch does. Never throws: a handoff that fails is retried by the next commit, or by
5956
6044
  * `retryHandoffs`, and the broker drops what it already holds.
5957
6045
  */
5958
- async handOffCommitted(rt) {
6046
+ async handOffCommitted(rt,
6047
+ /** #3474: the invocation whose commit this follows, and its trace: its own rows carry the trace. */
6048
+ commit) {
5959
6049
  if (!this.deliveryBroker)
5960
6050
  return;
5961
6051
  const ids = { tenantId: rt.tenantId, scopeId: rt.scopeId };
5962
6052
  const key = `${rt.tenantId}/${rt.scopeId}`;
6053
+ // A5 (#3471): under `by-mode`, only while the scope's mode is on, and under it.
6054
+ const mode = this.deliveryModes.get(key);
6055
+ if (this.deliveryHandoff === 'by-mode' && !mode)
6056
+ return;
6057
+ const options = mode
6058
+ ? { mode: mode.mode, ...(mode.startPending ? { start: { ...ids, after: mode.start } } : {}) }
6059
+ : {};
5963
6060
  /** #3474: the round now with the broker, so a throw reports what it tried. */
5964
6061
  let inFlight = null;
5965
6062
  try {
@@ -5967,11 +6064,23 @@ export class SqliteScopeHost {
5967
6064
  let marks = this.handoffMarks.get(key) ?? (await broker.marks(rt.tenantId, rt.scopeId));
5968
6065
  // A backlog larger than one batch follows in the next round; bounded, so a commit never spins.
5969
6066
  for (let round = 0; round < 20; round++) {
5970
- const sent = handoffQueries(marks).flatMap((q) => messagesOf(q.kind, rt.db.prepare(q.sql).all(...q.params), ids));
5971
- if (sent.length === 0)
6067
+ const sent = handoffQueries(marks).flatMap((q) => messagesOf(q.kind, rt.db.prepare(q.sql).all(...q.params), ids, commit));
6068
+ if (sent.length === 0) {
6069
+ // A5: a window's start the broker has not acknowledged goes on its own.
6070
+ if (options.start) {
6071
+ await broker.handOff([], options);
6072
+ if (mode)
6073
+ mode.startPending = false;
6074
+ }
5972
6075
  break;
6076
+ }
5973
6077
  inFlight = { sent, startedAt: Date.now() };
5974
- const answer = await broker.handOff(sent);
6078
+ const answer = await broker.handOff(sent, options);
6079
+ if (options.start) {
6080
+ if (mode)
6081
+ mode.startPending = false;
6082
+ delete options.start;
6083
+ }
5975
6084
  const next = advanceMarks(marks, sent, answer);
5976
6085
  this.reportHandoffRound(rt, inFlight, handoffOutcome(sent, answer));
5977
6086
  inFlight = null;
@@ -6003,6 +6112,53 @@ export class SqliteScopeHost {
6003
6112
  console.error('substrat: delivery telemetry failed; the handoff continues', err);
6004
6113
  }
6005
6114
  }
6115
+ /**
6116
+ * A5 (#3471): the delivery mode for one scope, as a hosted scope's control plane answers it. Going
6117
+ * on from off seeds the handoff at what the scope holds now, so nothing committed while it was off
6118
+ * is handed off, and a new comparison window starts there. Off stops the handoff. Only under
6119
+ * `deliveryHandoff: 'by-mode'` does it decide what is handed off; it is recorded either way.
6120
+ */
6121
+ async applyDeliveryMode(tenantId, scopeId, mode) {
6122
+ const key = `${tenantId}/${scopeId}`;
6123
+ const rt = await this.openActiveScope(tenantId, scopeId);
6124
+ await rt.actor.enqueue(async () => {
6125
+ const prior = this.deliveryModes.get(key);
6126
+ if (mode === 'off') {
6127
+ this.deliveryModes.delete(key);
6128
+ return;
6129
+ }
6130
+ if (prior) {
6131
+ prior.mode = mode;
6132
+ return;
6133
+ }
6134
+ const newest = (sql) => rt.db.prepare(sql).get()?.id;
6135
+ const seed = {};
6136
+ const event = newest(`SELECT id FROM _substrat_outbox WHERE ${emittedHere()} ORDER BY id DESC LIMIT 1`);
6137
+ const intent = newest(`SELECT id FROM _substrat_platform_requests WHERE ${emittedHere()} ORDER BY id DESC LIMIT 1`);
6138
+ if (event)
6139
+ seed.event = event;
6140
+ if (intent)
6141
+ seed.intent = intent;
6142
+ const known = this.handoffMarks.get(key) ?? {};
6143
+ this.handoffMarks.set(key, {
6144
+ ...((known.event ?? '') > (seed.event ?? '') ? { event: known.event } : seed.event ? { event: seed.event } : {}),
6145
+ ...((known.intent ?? '') > (seed.intent ?? '') ? { intent: known.intent } : seed.intent ? { intent: seed.intent } : {}),
6146
+ });
6147
+ this.deliveryModes.set(key, { mode, start: seed, startPending: true });
6148
+ await this.handOffCommitted(rt);
6149
+ });
6150
+ }
6151
+ /** A5: the drain's witness for the shadow comparison: this scope's own messages past `after` (`witnessQueries`). */
6152
+ async deliveryWitness(tenantId, scopeId, after, before, limit) {
6153
+ const rt = await this.openActiveScope(tenantId, scopeId);
6154
+ return witnessQueries(after, before, limit).flatMap((q) => witnessesOf(q.kind, rt.db.prepare(q.sql).all(...q.params)));
6155
+ }
6156
+ /** A5: an intent's state, for a broker's live receiver. */
6157
+ async intentDeliveryState(tenantId, scopeId, id) {
6158
+ const rt = await this.openActiveScope(tenantId, scopeId);
6159
+ const q = intentStateQuery(id);
6160
+ return intentStateOf(rt.db.prepare(q.sql).all(...q.params));
6161
+ }
6006
6162
  /**
6007
6163
  * K-74: hand off again whatever a scope's earlier handoff left unacknowledged — the pure host's
6008
6164
  * stand-in for the scope alarm that retries it on the Durable Object. Runs in the scope's actor.
@@ -8701,7 +8857,7 @@ export class SqliteScopeHost {
8701
8857
  // K-74: with a broker bound, only what it has acknowledged may go. Its marks are read
8702
8858
  // before the turn, which cannot await; a mark read early is only ever lower than the
8703
8859
  // truth, so the prune keeps more, never less.
8704
- const handedOffThrough = this.deliveryBroker
8860
+ const handedOffThrough = this.deliveryBroker && (this.deliveryHandoff === 'always' || this.deliveryModes.has(`${tenantId}/${scopeId}`))
8705
8861
  ? (this.handoffMarks.get(`${tenantId}/${scopeId}`) ??
8706
8862
  (await this.deliveryBroker({ tenantId, scopeId }).marks(tenantId, scopeId).catch(() => ({})))).event ?? null
8707
8863
  : undefined;
@@ -9420,7 +9576,7 @@ export class SqliteScopeHost {
9420
9576
  .prepare(`SELECT name, sql FROM sqlite_master
9421
9577
  WHERE type = 'table' AND name NOT GLOB 'sqlite_*' AND sql IS NOT NULL
9422
9578
  ORDER BY name`)
9423
- .all().filter(({ name }) => !isSearchIndexTable(name) && !isWireNonceTable(name));
9579
+ .all().filter(({ name }) => !isRuntimeTable(name) && !isSearchIndexTable(name) && !isWireNonceTable(name));
9424
9580
  // #2820: each module table's own indexes and triggers ride with it; a spine table has none.
9425
9581
  const objects = dumpObjectsOf(db.prepare(DUMP_OBJECTS_QUERY).all());
9426
9582
  const tables = defs.map(({ name, sql }) => {
@@ -9453,7 +9609,8 @@ export class SqliteScopeHost {
9453
9609
  ORDER BY name`)
9454
9610
  .all();
9455
9611
  const privateTables = new Set(['private_continuation_keys', 'private_continuation_positions']);
9456
- const tables = defs.filter(({ name }) => !privateTables.has(name)).map(({ name, sql }) => {
9612
+ const carried = defs.filter(({ name }) => !privateTables.has(name) && !isRuntimeTable(name));
9613
+ const tables = carried.map(({ name, sql }) => {
9457
9614
  const stmt = this.directory.prepare(`SELECT * FROM "${name}"`).raw(true);
9458
9615
  const rows = stmt.all();
9459
9616
  const columns = stmt.columns().map((c) => c.name);
@@ -9464,60 +9621,17 @@ export class SqliteScopeHost {
9464
9621
  return { capturedAt: new Date().toISOString(), tables };
9465
9622
  },
9466
9623
  restoreDirectory: async (actor, dump) => {
9467
- // Counted before the replace — afterwards the old directory is gone, and
9468
- // "restored over N tenants" is the fact the audit entry exists to carry.
9469
- const before = this.directory.prepare('SELECT COUNT(*) AS n FROM tenants').get().n;
9470
- // The dump is untrusted input, as it is on the DO path (#1143). Its names reach SQL
9471
- // as identifiers, and its `ddl`, never executed here since #1912, is still held to one
9472
- // CREATE TABLE. Judged as a whole before the first DROP, so a refused dump leaves the
9473
- // directory untouched.
9474
- // Older backup producers and local migration fixtures may include these
9475
- // tables. Ignore them entirely: neither their DDL nor their rows may set
9476
- // a restored key epoch or make an old hidden locator valid again.
9477
- const publicTables = dump.tables.filter((table) => !['private_continuation_keys', 'private_continuation_positions'].includes(table.name.toLowerCase()));
9478
- assertReplayableDump(publicTables);
9479
- // One transaction, foreign keys deferred to commit: the dump is ordered by table NAME
9480
- // (which says nothing about references — a `tenants` row can name another as
9481
- // `provisioned_by_tenant`), and the DROPs themselves delete rows a populated child would
9482
- // still be referencing. better-sqlite3 runs the function synchronously inside
9483
- // BEGIN/COMMIT, and rolls back if it throws.
9484
- this.directory.pragma('defer_foreign_keys = ON');
9485
- this.directory.transaction(() => {
9486
- const existing = this.directory
9487
- .prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT GLOB 'sqlite_*'`)
9488
- .all();
9489
- for (const { name } of existing)
9490
- this.directory.exec(`DROP TABLE IF EXISTS "${name}"`);
9491
- // The dump contributes rows only (#1912, extending #1898's spine rule to every table).
9492
- // Every directory table is built by the pass a cold start runs, never from the dump's
9493
- // DDL: these are the platform's own registries, so a dump's `DEFAULT 1` on
9494
- // `verticals.tenant_provisioner`, a `COLLATE NOCASE` on `tenants.slug` or an extra
9495
- // table that `REFERENCES tenants` would otherwise decide how the platform behaves
9496
- // after the restore. A copy taken before a directory migration carries the OLD shape;
9497
- // its rows go in by column name, so a column it lacks takes the running code's default.
9498
- this.buildDirectorySchema();
9499
- // Refuses a table this code does not build, adds unknown columns bare, loads the rows
9500
- // by name, then the legacy scope and #1674 backfills, all inside this transaction.
9501
- loadDirectoryDump(publicTables, {
9502
- columnsOf: (name) => builtColumnsOf(this.directory, name),
9503
- exec: (sql) => this.directory.exec(sql),
9504
- now: () => this.clock(),
9505
- insert: (sql, rows) => {
9506
- const insert = this.directory.prepare(sql);
9507
- for (const row of rows)
9508
- insert.run(...row);
9509
- },
9510
- });
9511
- // The dump's rows have landed in the rebuilt tables. Append this restore's
9512
- // own row before commit, so a failed insert rolls the imported state back.
9513
- this.recordAdmin(actor, 'restoreDirectory', { tenantId: null }, { tenants: before }, { capturedAt: dump.capturedAt, tables: dump.tables.length });
9514
- })();
9515
- // #1764's split, over any version the dump stored before it.
9516
- this.splitVersionMigrations();
9517
- // Roles are held in memory (`loadRoles`), so a restore that only rewrote the
9518
- // table would leave every permission check reading the PRE-restore roles until
9519
- // the process restarted — the exact silent-divergence a recovery must not have.
9520
- this.loadRoles();
9624
+ this.restoreDirectoryFrom(actor, dump);
9625
+ },
9626
+ // #3494: one local database and no RPC to cross, so the pages are joined and restored whole,
9627
+ // the audit row saying it was paged as the Durable Object host's does.
9628
+ restoreDirectoryPaged: async (actor, copy) => {
9629
+ const pages = [];
9630
+ for await (const page of copy.pages)
9631
+ pages.push(page);
9632
+ if (pages.length === 0)
9633
+ throw substratError('validation_failed', `directory copy ${copy.capturedAt} has no pages to restore`);
9634
+ this.restoreDirectoryFrom(actor, { capturedAt: copy.capturedAt, tables: mergeDumpPages(pages) }, { paged: true, stagedPages: pages.length }, { requireEmpty: copy.overwrite !== true });
9521
9635
  },
9522
9636
  activateScope: async (actor, tenantId, scopeId) => {
9523
9637
  // Idempotent on `active`, unaudited because nothing changed. Provisioning is
@@ -10515,6 +10629,11 @@ export class SqliteScopeHost {
10515
10629
  const { tenantId, scopeId, ...after } = deliveryRedriveAudit.parse(entry);
10516
10630
  this.recordAdmin(actor, 'redriveDelivery', { tenantId, scopeId }, null, after);
10517
10631
  },
10632
+ /** #3474: one resend or discard of a broker dead letter, written after the broker's own move. */
10633
+ recordBrokerDeadLetter: async (actor, entry) => {
10634
+ const { tenantId, scopeId, action, ...after } = brokerDeadLetterAudit.parse(entry);
10635
+ this.recordAdmin(actor, action === 'resend' ? 'resendBrokerDeadLetter' : 'discardBrokerDeadLetter', { tenantId, scopeId }, null, after);
10636
+ },
10518
10637
  /** #2314: one orphan-attachment pass over a scope, written after the vertical's own pass. */
10519
10638
  recordOrphanSweep: async (actor, entry) => {
10520
10639
  const { tenantId, scopeId, ...after } = orphanSweepAudit.parse(entry);