@substrat-run/adapter-sqlite 0.216.0 → 0.217.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,11 +2,15 @@ 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, 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';
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
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';
7
+ import { handoffOutcome, reportHandoff, traceIdOf } from '@substrat-run/kernel';
8
+ import { currentTraceparent } from '@substrat-run/kernel/invocation-line';
7
9
  import { attributedView, delegatedRevokeSql, writeExplicitTupleIn, grantEntityShapeIn, shapeTopUpBatch, topUpEntityGrantShapes, settlePlatformRequestIn, } from '@substrat-run/kernel';
10
+ import { assertSameAttachmentGate, attachmentGateOf, decideAttachmentRemove, } from '@substrat-run/kernel';
8
11
  import { DIRECTORY_CLAIMS_DDL, DIRECTORY_CROSSINGS_DDL, oneDatabaseDirectoryObjects, } from '@substrat-run/kernel';
9
12
  import { canonicalInstant } from '@substrat-run/kernel';
13
+ import { advanceMarks, handoffQueries, messagesOf } from '@substrat-run/kernel';
10
14
  import { MARKUP_INSERT_SQL, MARKUP_SELECT_FOR_TENANT_SQL, MARKUP_SELECT_SQL, markupRecordValues, markupScheduleOf, newMarkupRow, } from '@substrat-run/kernel';
11
15
  import { prePromoteSnapshotExpiresAt } from '@substrat-run/kernel';
12
16
  import { ADMIN_LOG_INDEXES_SQL, SETTLE_INTENT_SQL, SETTLE_OUTCOME_SQL, settleOutcomeParamsOf, readAuditedOperations, unknownOutcomeOf, } from '@substrat-run/kernel';
@@ -19,6 +23,7 @@ import { ScopeActor } from './actor.js';
19
23
  import { createTupleChecker, directoryTenantReader } from './checker.js';
20
24
  import { decidedByOf, entityString, forgetInvocationTrace, invocationTrace, tracedSql } from './trace.js';
21
25
  export { scopeStoreRunnersFor } from './scope-store-runners.js';
26
+ export { InProcessDeliveryBroker } from './delivery-broker.js';
22
27
  export { devMailOutbox, MAIL_OUTBOX_ENV } from './dev-mail-outbox.js';
23
28
  /**
24
29
  * A fault in the database itself (full, corrupt, I/O), as opposed to one statement failing.
@@ -579,6 +584,8 @@ function modelUsageEntryOf(r) {
579
584
  listUsd: r.list_usd,
580
585
  at: r.at,
581
586
  elapsedMs: r.elapsed_ms,
587
+ unit: r.unit ?? null,
588
+ quantity: r.quantity ?? null,
582
589
  });
583
590
  }
584
591
  /**
@@ -970,6 +977,11 @@ export class SqliteScopeHost {
970
977
  connectorCalls;
971
978
  clock;
972
979
  versionId;
980
+ /** K-74: the broker each scope hands off to, or null (off). */
981
+ deliveryBroker;
982
+ brokerTelemetry;
983
+ /** K-74: each scope's handoff marks, a cache of what its broker holds (`DeliveryBroker.marks`). */
984
+ handoffMarks = new Map();
973
985
  migrationsDigest;
974
986
  /** #1746: where `ctx.log` lines go — the console unless a caller (a test) says otherwise. */
975
987
  logSink;
@@ -992,6 +1004,8 @@ export class SqliteScopeHost {
992
1004
  this.connectorCalls = options.connectorCalls ?? noopConnectorCallRecorder;
993
1005
  this.clock = options.clock ?? (() => instant.parse(new Date().toISOString()));
994
1006
  this.versionId = options.versionId ?? null;
1007
+ this.deliveryBroker = options.deliveryBroker ?? null;
1008
+ this.brokerTelemetry = options.brokerTelemetry ?? null;
995
1009
  this.migrationsDigest = options.migrationsDigest;
996
1010
  this.permissions = options.permissions;
997
1011
  // #2430: what the declared surface reserves holds here too, whatever is registered under its ids.
@@ -1261,6 +1275,10 @@ export class SqliteScopeHost {
1261
1275
  -- plane's /internal/email/send relay and have transactional mail sent for them. A staff
1262
1276
  -- grant (set_vertical_email_sender), never set on insert or re-push.
1263
1277
  email_sender INTEGER NOT NULL DEFAULT 0,
1278
+ -- The owner's Workers trace rates (#3358), 0–1, for the serving script and for each
1279
+ -- version's archive (preview) script, NULL read as 0. Read at upload; set_vertical_trace_sampling only.
1280
+ trace_sampling REAL,
1281
+ preview_trace_sampling REAL,
1264
1282
  -- The ONE stable serving script (#286): the name every new scope's data DO
1265
1283
  -- lives in, the version it currently runs, and the DO-class/migration-tag
1266
1284
  -- base the next in-place upload diffs against.
@@ -2049,15 +2067,8 @@ export class SqliteScopeHost {
2049
2067
  // tolerated (idempotent); with different gates it is refused — ambiguous authority
2050
2068
  // over who may read an entity's attachments must not depend on registration order.
2051
2069
  for (const target of manifest.attachmentTargets) {
2052
- const gate = {
2053
- read: target.readPermission,
2054
- write: target.writePermission ?? target.readPermission,
2055
- };
2056
- const existing = this.attachmentTargets.get(target.entityType);
2057
- if (existing && (existing.read !== gate.read || existing.write !== gate.write)) {
2058
- throw new Error(`conflicting attachmentTargets for '${target.entityType}': ` +
2059
- `(${existing.read}/${existing.write}) vs (${gate.read}/${gate.write})`);
2060
- }
2070
+ const gate = attachmentGateOf(target);
2071
+ assertSameAttachmentGate(target.entityType, this.attachmentTargets.get(target.entityType), gate);
2061
2072
  this.attachmentTargets.set(target.entityType, gate);
2062
2073
  if (target.uploadLinks) {
2063
2074
  const known = this.uploadLinkPolicies.get(target.entityType);
@@ -2623,15 +2634,16 @@ export class SqliteScopeHost {
2623
2634
  });
2624
2635
  }
2625
2636
  async getSystemAttachments(moduleId, tenantId, scopeId) {
2626
- // The same registered-module and lifecycle gate as a system invoke. The
2627
- // attachment surface checks the target's read key as system:<moduleId>.
2637
+ // The same registered-module and lifecycle gate as a system invoke. The attachment
2638
+ // surface checks the target's keys as system:<moduleId>: the read key for `open`, the
2639
+ // write or remove key for `remove` (#3434), whose event is attributed to the module.
2628
2640
  await this.getSystemScope(moduleId, tenantId, scopeId);
2629
2641
  const rt = this.runtime(tenantId, scopeId);
2630
2642
  const row = this.directory
2631
2643
  .prepare('SELECT vertical FROM scopes WHERE scope_id = ?')
2632
2644
  .get(scopeId);
2633
2645
  const surface = this.buildAttachments(rt, { kind: 'system', id: moduleId }, this.attachmentStore(tenantId, row?.vertical ?? null));
2634
- return { open: surface.open };
2646
+ return { open: surface.open, remove: surface.remove };
2635
2647
  }
2636
2648
  /**
2637
2649
  * The attachment surface (#473) — `attachmentTargets` consumed at last. Metadata facts
@@ -2656,6 +2668,11 @@ export class SqliteScopeHost {
2656
2668
  }
2657
2669
  : authority;
2658
2670
  const node = { tenantId: rt.tenantId, scopeId: rt.scopeId };
2671
+ // #119 / #3434: a module's purge-only keys are withheld from its system principal on every
2672
+ // check but the purge sweep's own invoke, so an attachment verb made as the module (`open`,
2673
+ // `remove`) is never admitted by one: holding the purge key is not a licence over the files.
2674
+ const withheldFor = (subject) => subject.kind === 'system' ? withheldKeysFor(this.modules.get(subject.id)?.purgeOnlyKeys, undefined, false) : undefined;
2675
+ const contextFor = (subject, operation) => this.operationContext(rt, subject, undefined, undefined, undefined, operation, [], this.clock(), undefined, withheldFor(subject));
2659
2676
  const targetGate = (entityType) => {
2660
2677
  const gate = this.attachmentTargets.get(entityType);
2661
2678
  if (!gate) {
@@ -2669,7 +2686,7 @@ export class SqliteScopeHost {
2669
2686
  // the events it emitted).
2670
2687
  const serialized = (operation, fn) => rt.actor.enqueue(async () => {
2671
2688
  const subject = actingAs(operation);
2672
- const ctx = this.operationContext(rt, subject, undefined, undefined, undefined, operation);
2689
+ const ctx = contextFor(subject, operation);
2673
2690
  rt.db.exec('BEGIN IMMEDIATE');
2674
2691
  let result;
2675
2692
  try {
@@ -2697,6 +2714,8 @@ export class SqliteScopeHost {
2697
2714
  catch (err) {
2698
2715
  console.error('substrat: consumer drain failed after an attachment committed', err);
2699
2716
  }
2717
+ // K-74: what the attachment's commit and its consumers emitted (never throws).
2718
+ await this.handOffCommitted(rt);
2700
2719
  return result;
2701
2720
  });
2702
2721
  /**
@@ -2715,7 +2734,7 @@ export class SqliteScopeHost {
2715
2734
  const reentrant = async (operation, fn) => {
2716
2735
  const subject = actingAs(operation);
2717
2736
  try {
2718
- return await fn(this.operationContext(rt, subject, undefined, undefined, undefined, operation), subject);
2737
+ return await fn(contextFor(subject, operation), subject);
2719
2738
  }
2720
2739
  catch (err) {
2721
2740
  // #1525: the ENCLOSING call's id, deliberately. This runner takes no turn of its
@@ -2863,8 +2882,8 @@ export class SqliteScopeHost {
2863
2882
  }
2864
2883
  if (!row)
2865
2884
  return null;
2866
- const gate = targetGate(row.entity_type);
2867
- assertAllowed(await ctx.check(gate.write, { entityType: row.entity_type, entityId: row.entity_id }));
2885
+ // #3434: the write key, or the target's remove key when it declares one.
2886
+ assertAllowed(await decideAttachmentRemove((permission, entity) => ctx.check(permission, entity), targetGate(row.entity_type), { entityType: row.entity_type, entityId: row.entity_id }));
2868
2887
  rt.db.prepare('DELETE FROM _substrat_attachments WHERE id = ?').run(attachmentId);
2869
2888
  const record = attachmentRecordOfRow(row);
2870
2889
  kernelEmit(ctx, {
@@ -4009,6 +4028,8 @@ export class SqliteScopeHost {
4009
4028
  if (outcome) {
4010
4029
  await this.dispatch(rt, null);
4011
4030
  await this.dispatchExecutors(rt, null);
4031
+ // K-74: what the exchange's commit and its consumers emitted (never throws).
4032
+ await this.handOffCommitted(rt);
4012
4033
  }
4013
4034
  return outcome;
4014
4035
  });
@@ -5202,6 +5223,8 @@ export class SqliteScopeHost {
5202
5223
  // this call's own work — the same tail its consumers' emits are stamped in.
5203
5224
  await this.dispatch(rt, rt.invocationId);
5204
5225
  await this.dispatchExecutors(rt, rt.invocationId, executorOutcomes);
5226
+ // K-74: after the consumers and executors, whose own emits and intents count too.
5227
+ await this.handOffCommitted(rt);
5205
5228
  }
5206
5229
  if (exportMark !== null && !replayed) {
5207
5230
  const q = exportedSinceQuery(exportTypes, exportMark);
@@ -5743,6 +5766,8 @@ export class SqliteScopeHost {
5743
5766
  handlerFor: (run) => kernelJobFor(run, kernelJobs) ?? this.jobs.get(`${run.module_id}/${run.job}`),
5744
5767
  now: this.clock,
5745
5768
  openScope: (run) => this.getSystemScope(run.module_id, tenantId, scopeId),
5769
+ // #3443: the run's module's files, through the same gate `getSystemAttachments` opens.
5770
+ openAttachments: (run) => this.getSystemAttachments(run.module_id, tenantId, scopeId),
5746
5771
  maxPasses: options?.maxPasses,
5747
5772
  limit: options?.limit,
5748
5773
  });
@@ -5920,8 +5945,72 @@ export class SqliteScopeHost {
5920
5945
  await this.dispatch(rt, null);
5921
5946
  await this.dispatchExecutors(rt, null);
5922
5947
  }
5948
+ // K-74: the settle's outcome event, and what its consumers emitted (never throws).
5949
+ await this.handOffCommitted(rt);
5923
5950
  });
5924
5951
  }
5952
+ /**
5953
+ * K-74: hand off what the scope's commits left to its delivery broker, past the scope's marks, and
5954
+ * move the marks over what the broker acknowledged. Runs inside the actor task after a commit, as
5955
+ * the dispatch does. Never throws: a handoff that fails is retried by the next commit, or by
5956
+ * `retryHandoffs`, and the broker drops what it already holds.
5957
+ */
5958
+ async handOffCommitted(rt) {
5959
+ if (!this.deliveryBroker)
5960
+ return;
5961
+ const ids = { tenantId: rt.tenantId, scopeId: rt.scopeId };
5962
+ const key = `${rt.tenantId}/${rt.scopeId}`;
5963
+ /** #3474: the round now with the broker, so a throw reports what it tried. */
5964
+ let inFlight = null;
5965
+ try {
5966
+ const broker = this.deliveryBroker(ids);
5967
+ let marks = this.handoffMarks.get(key) ?? (await broker.marks(rt.tenantId, rt.scopeId));
5968
+ // A backlog larger than one batch follows in the next round; bounded, so a commit never spins.
5969
+ 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)
5972
+ break;
5973
+ inFlight = { sent, startedAt: Date.now() };
5974
+ const answer = await broker.handOff(sent);
5975
+ const next = advanceMarks(marks, sent, answer);
5976
+ this.reportHandoffRound(rt, inFlight, handoffOutcome(sent, answer));
5977
+ inFlight = null;
5978
+ // An answer that acknowledges nothing new: stop; the next commit or `retryHandoffs` tries again.
5979
+ if (next.event === marks.event && next.intent === marks.intent)
5980
+ break;
5981
+ marks = next;
5982
+ this.handoffMarks.set(key, marks);
5983
+ }
5984
+ this.handoffMarks.set(key, marks);
5985
+ }
5986
+ catch (err) {
5987
+ if (inFlight)
5988
+ this.reportHandoffRound(rt, inFlight, 'failed');
5989
+ console.error('substrat: delivery handoff failed; the next commit retries it', err);
5990
+ }
5991
+ }
5992
+ /** #3474: one point per handoff round, when `brokerTelemetry` is given. */
5993
+ reportHandoffRound(rt, round, outcome) {
5994
+ const t = this.brokerTelemetry;
5995
+ if (!t)
5996
+ return;
5997
+ const ids = { tenantId: rt.tenantId, scopeId: rt.scopeId };
5998
+ // Telemetry never fails the handoff it follows: the harness's `appOf` may throw.
5999
+ try {
6000
+ reportHandoff(t.sink, { ...ids, app: t.appOf(ids) }, { ...round, outcome, at: Date.now(), traceId: traceIdOf(currentTraceparent()) });
6001
+ }
6002
+ catch (err) {
6003
+ console.error('substrat: delivery telemetry failed; the handoff continues', err);
6004
+ }
6005
+ }
6006
+ /**
6007
+ * K-74: hand off again whatever a scope's earlier handoff left unacknowledged — the pure host's
6008
+ * stand-in for the scope alarm that retries it on the Durable Object. Runs in the scope's actor.
6009
+ */
6010
+ async retryHandoffs(tenantId, scopeId) {
6011
+ const rt = await this.openActiveScope(tenantId, scopeId);
6012
+ await rt.actor.enqueue(() => this.handOffCommitted(rt));
6013
+ }
5925
6014
  async dispatch(rt,
5926
6015
  /**
5927
6016
  * #1525: the call this drain is running in, or null — PASSED, for the reason
@@ -6189,6 +6278,20 @@ export class SqliteScopeHost {
6189
6278
  ? { keyId: row.key_id, wrappedDek: row.wrapped_dek, shreddedAt: row.shredded_at }
6190
6279
  : undefined;
6191
6280
  },
6281
+ // One statement per chunk of a sealed batch (#3464), under the bound parameter limit.
6282
+ readMany: (subjectIds) => {
6283
+ const out = new Map();
6284
+ for (let i = 0; i < subjectIds.length; i += 90) {
6285
+ const chunk = subjectIds.slice(i, i + 90);
6286
+ const rows = this.directory
6287
+ .prepare(`SELECT subject_id, key_id, wrapped_dek, shredded_at FROM _substrat_subject_keys
6288
+ WHERE scope_id = ? AND subject_id IN (${chunk.map(() => '?').join(', ')})`)
6289
+ .all(scopeId, ...chunk);
6290
+ for (const r of rows)
6291
+ out.set(r.subject_id, { keyId: r.key_id, wrappedDek: r.wrapped_dek, shreddedAt: r.shredded_at });
6292
+ }
6293
+ return out;
6294
+ },
6192
6295
  insert: (subjectId, row) => {
6193
6296
  // `OR IGNORE` rather than `OR REPLACE`: two concurrent exports of the same subject
6194
6297
  // both mint, and the loser must not overwrite the winner's key — a replaced key
@@ -6479,6 +6582,8 @@ export class SqliteScopeHost {
6479
6582
  installsBlocked: !!r.installs_blocked,
6480
6583
  tenantProvisioner: !!r.tenant_provisioner,
6481
6584
  emailSender: !!r.email_sender,
6585
+ traceSampling: r.trace_sampling ?? 0,
6586
+ previewTraceSampling: r.preview_trace_sampling ?? 0,
6482
6587
  ...(r.serving_ref ? { servingRef: r.serving_ref } : {}),
6483
6588
  ...(r.serving_version_id ? { servingVersionId: r.serving_version_id } : {}),
6484
6589
  createdAt: r.created_at,
@@ -7882,6 +7987,10 @@ export class SqliteScopeHost {
7882
7987
  setVerticalEmailSender: async (actor, slug, granted) => {
7883
7988
  updateVertical(actor, 'setVerticalEmailSender', slug, 'email_sender = ?', [granted ? 1 : 0], (existing) => ({ emailSender: existing.emailSender }), { emailSender: granted });
7884
7989
  },
7990
+ setVerticalTraceSampling: async (actor, slug, input) => {
7991
+ const rates = verticalTraceSampling.parse(input);
7992
+ updateVertical(actor, 'setVerticalTraceSampling', slug, 'trace_sampling = ?, preview_trace_sampling = ?', [rates.serving, rates.previews], (existing) => ({ serving: existing.traceSampling, previews: existing.previewTraceSampling }), rates);
7993
+ },
7885
7994
  deleteVertical: async (actor, slug) => {
7886
7995
  // Deployed dispatch scripts are NOT reaped here — they become orphans for the
7887
7996
  // cleanup script (#248), never destroyed alongside a registry row.
@@ -8589,12 +8698,20 @@ export class SqliteScopeHost {
8589
8698
  const input = pruneInputOf(raw, new Date().toISOString());
8590
8699
  this.assertScopeReachable(tenantId, scopeId);
8591
8700
  const db = this.scopeDbFor(tenantId, scopeId);
8701
+ // K-74: with a broker bound, only what it has acknowledged may go. Its marks are read
8702
+ // before the turn, which cannot await; a mark read early is only ever lower than the
8703
+ // truth, so the prune keeps more, never less.
8704
+ const handedOffThrough = this.deliveryBroker
8705
+ ? (this.handoffMarks.get(`${tenantId}/${scopeId}`) ??
8706
+ (await this.deliveryBroker({ tenantId, scopeId }).marks(tenantId, scopeId).catch(() => ({})))).event ?? null
8707
+ : undefined;
8592
8708
  // On the scope actor, like the stamp: issued mid-invoke it would otherwise be a
8593
8709
  // SAVEPOINT inside the invoke's transaction, and roll back with it.
8594
8710
  const pruned = await this.runtime(tenantId, scopeId).actor.turn(() => db.transaction(() => pruneDrainedOutbox(switchSqlOf(db), {
8595
8711
  drainedBefore: input.drainedBefore,
8596
8712
  limit: input.limit,
8597
8713
  due: input.due ?? true,
8714
+ ...(handedOffThrough === undefined ? {} : { handedOffThrough }),
8598
8715
  subscribers: outboxSubscribersOf(this.modules.values(), this.executors),
8599
8716
  exportTypes: this.crossVertical.exportTypes(),
8600
8717
  }))());
@@ -9603,6 +9720,12 @@ export class SqliteScopeHost {
9603
9720
  // intents, an issue's exemplar, a sweep record's error. Before the key, for the
9604
9721
  // ordering reason above.
9605
9722
  redactSubjectDirectoryText(redactionSqlOf(this.directory), { tenantId, scopeId, subjectId, intentIds });
9723
+ // #3484: the delivery broker's copies, after the spine (the scope's actor serializes this
9724
+ // erasure's turn with its handoffs, so every later handoff reads the outbox redacted) and
9725
+ // before the key. A broker that throws refuses the erasure here, with the key untouched.
9726
+ if (this.deliveryBroker) {
9727
+ await this.deliveryBroker({ tenantId, scopeId }).eraseSubject({ tenantId, scopeId, subjectId, at });
9728
+ }
9606
9729
  // Scope stores after the scope-side redaction and before the key (#2068). A store
9607
9730
  // that errors throws here, so the key below is untouched and a retry converges.
9608
9731
  // An orchestrated caller passes the serving script's result and this host does
@@ -10860,9 +10983,10 @@ export class SqliteScopeHost {
10860
10983
  const res = this.directory
10861
10984
  .prepare(`INSERT OR IGNORE INTO _substrat_model_usage
10862
10985
  (id, request_id, tenant_id, scope_id, vertical, version, operation, model, provider, model_id,
10863
- reported, input_tokens, output_tokens, cached_input_tokens, cache_write_tokens, list_usd, at, elapsed_ms)
10864
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
10865
- .run(ulid(), input.requestId, l.attribution.tenant, l.attribution.scope, l.attribution.vertical, l.attribution.version, l.attribution.operation, l.model, l.provider, l.modelId, l.reported ? 1 : 0, l.inputTokens, l.outputTokens, l.cachedInputTokens, l.cacheWriteTokens, l.listUsd, l.at, l.elapsedMs);
10986
+ reported, input_tokens, output_tokens, cached_input_tokens, cache_write_tokens, list_usd, at, elapsed_ms,
10987
+ unit, quantity)
10988
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
10989
+ .run(ulid(), input.requestId, l.attribution.tenant, l.attribution.scope, l.attribution.vertical, l.attribution.version, l.attribution.operation, l.model, l.provider, l.modelId, l.reported ? 1 : 0, l.inputTokens, l.outputTokens, l.cachedInputTokens, l.cacheWriteTokens, l.listUsd, l.at, l.elapsedMs, l.unit ?? null, l.quantity ?? null);
10866
10990
  const horizon = new Date(Date.now() - MODEL_USAGE_RETENTION_DAYS * 86_400_000).toISOString();
10867
10991
  this.directory.prepare('DELETE FROM _substrat_model_usage WHERE at < ?').run(horizon);
10868
10992
  return { recorded: res.changes > 0 };
@@ -11293,6 +11417,11 @@ export class SqliteScopeHost {
11293
11417
  this.ensureColumn(this.directory, '_substrat_tenant_tuples', 'revoked_at', 'revoked_at TEXT');
11294
11418
  // #2444: old role rows keep NULL and retain the key-only platform door decision.
11295
11419
  this.ensureColumn(this.directory, '_substrat_roles', 'holder', 'holder TEXT');
11420
+ // #3321: a line counting something other than tokens; NULL on every token line.
11421
+ this.ensureColumn(this.directory, '_substrat_model_usage', 'unit', 'unit TEXT');
11422
+ this.ensureColumn(this.directory, '_substrat_model_usage', 'quantity', 'quantity INTEGER');
11423
+ // #3175: the foundation version a store-driver release brings; NULL on every older approval.
11424
+ this.ensureColumn(this.directory, 'store_driver_approvals', 'foundation', 'foundation INTEGER');
11296
11425
  // builder-plane.md Phase 1b: who owns a vertical (NULL = platform-owned).
11297
11426
  this.ensureColumn(this.directory, 'verticals', 'owner_tenant', 'owner_tenant TEXT');
11298
11427
  this.ensureColumn(this.directory, 'verticals', 'env_spec', 'env_spec TEXT');
@@ -11304,6 +11433,9 @@ export class SqliteScopeHost {
11304
11433
  // #412: the tenant-provisioner capability — a staff grant on the registry row.
11305
11434
  this.ensureColumn(this.directory, 'verticals', 'tenant_provisioner', 'tenant_provisioner INTEGER NOT NULL DEFAULT 0');
11306
11435
  this.ensureColumn(this.directory, 'verticals', 'email_sender', 'email_sender INTEGER NOT NULL DEFAULT 0');
11436
+ // #3358: the owner's Workers trace rates.
11437
+ this.ensureColumn(this.directory, 'verticals', 'trace_sampling', 'trace_sampling REAL');
11438
+ this.ensureColumn(this.directory, 'verticals', 'preview_trace_sampling', 'preview_trace_sampling REAL');
11307
11439
  // #286: the stable serving script + what the next in-place upload diffs against.
11308
11440
  this.ensureColumn(this.directory, 'verticals', 'serving_ref', 'serving_ref TEXT');
11309
11441
  this.ensureColumn(this.directory, 'verticals', 'serving_version_id', 'serving_version_id TEXT');
@@ -11734,7 +11866,7 @@ export class SqliteScopeHost {
11734
11866
  .prepare(`SELECT COUNT(*) AS c FROM _substrat_platform_requests WHERE status = 'pending'`)
11735
11867
  .get().c;
11736
11868
  assertPlatformRequestRoom(pending);
11737
- const id = platformRequestId.parse(ulid());
11869
+ const id = platformRequestId.parse(rt.mintIntentId());
11738
11870
  const requestedBy = overrideActor ?? actorOf(subject);
11739
11871
  rt.db
11740
11872
  .prepare(`INSERT INTO _substrat_platform_requests
@@ -12381,6 +12513,10 @@ export class SqliteScopeHost {
12381
12513
  const highest = db.prepare('SELECT MAX(id) AS id FROM _substrat_outbox').get()?.id;
12382
12514
  if (highest)
12383
12515
  mintEventId.seedFrom(highest);
12516
+ const mintIntentId = createUlid();
12517
+ const highestIntent = db.prepare('SELECT MAX(id) AS id FROM _substrat_platform_requests').get()?.id;
12518
+ if (highestIntent)
12519
+ mintIntentId.seedFrom(highestIntent);
12384
12520
  const created = {
12385
12521
  tenantId,
12386
12522
  scopeId,
@@ -12391,6 +12527,7 @@ export class SqliteScopeHost {
12391
12527
  appliedMigrations,
12392
12528
  derivedRepaired: false,
12393
12529
  mintEventId,
12530
+ mintIntentId,
12394
12531
  invocationId: null,
12395
12532
  logTally: null,
12396
12533
  };