@substrat-run/adapter-cloudflare 0.204.0 → 0.206.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.
@@ -2,6 +2,7 @@ import { DurableObject } from 'cloudflare:workers';
2
2
  import { type TenantId } from '@substrat-run/contracts';
3
3
  import { type DeclaredPermissions, type SwitchSql, type ModuleRegistration, type OperationHandler } from '@substrat-run/kernel';
4
4
  import { type DoReply } from './do-reply.js';
5
+ import type { AnalyticsEngineDatasetLike } from './connector-calls.js';
5
6
  import { splitSqlStatements } from '@substrat-run/kernel';
6
7
  /**
7
8
  * `defineScopeDO` — one Durable Object per scope, the CF analogue of a single
@@ -40,6 +41,16 @@ export interface ScopeDoEnv {
40
41
  * version, a script uploaded before the binding, or a test worker compares nothing.
41
42
  */
42
43
  SUBSTRAT_MIGRATIONS_DIGEST?: string;
44
+ /**
45
+ * #3316: the Analytics Engine dataset each invocation's rows are counted into, by origin
46
+ * (`scope-work.ts`). Injected at upload; without it nothing is counted and no entry is wrapped
47
+ * at run time beyond one property read.
48
+ */
49
+ SUBSTRAT_SCOPE_WORK?: AnalyticsEngineDatasetLike;
50
+ /** #3316: the vertical's slug, injected at upload beside the dataset, stamped on each point. */
51
+ SUBSTRAT_VERTICAL?: string;
52
+ /** #3316: `live` on the serving script, `preview` on a version's own script, as the upload says. */
53
+ SUBSTRAT_SCRIPT_KIND?: string;
43
54
  }
44
55
  /** #2016: how a tenant reads against a scope's record (`ScopeDO.tenantVerdict`). */
45
56
  export type TenantVerdict = 'recorded' | 'inferred' | 'foreign' | 'unknown';
@@ -1 +1 @@
1
- {"version":3,"file":"scope-do.d.ts","sourceRoot":"","sources":["../src/scope-do.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAwDL,KAAK,QAAQ,EAmBd,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAgEL,KAAK,mBAAmB,EASxB,KAAK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;CAAE,CAAC;AAulBjG,kGAAkG;AAClG,wBAAgB,QAAQ,CAAC,GAAG,EAAE,SAAS,OAAO,EAAE,GAAG,MAAM,CAQxD;AAgQD;;;GAGG;AACH,MAAM,MAAM,yBAAyB,CAAC,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC;AAmBtD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,UAAU,GAAG,SAAS,CAOxD;AAED,gHAAgH;AAChH,OAAO,EAAE,kBAAkB,EAAE,CAAC;AA2B9B,wBAAgB,aAAa,CAC3B,OAAO,EAAE,kBAAkB,EAAE,EAC7B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;AACzD;;;;GAIG;AACH,OAAO,GAAE;IAAE,WAAW,CAAC,EAAE,mBAAmB,CAAA;CAAO,GAClD,KAAK,GAAG,EAAE,kBAAkB,EAAE,GAAG,EAAE,UAAU,KAAK,aAAa,CAAC,UAAU,CAAC,CA+1R7E"}
package/dist/scope-do.js CHANGED
@@ -2,10 +2,11 @@ import { REWIND_REFUSED } from './rewind-refusal.js';
2
2
  import { SYSTEM_DOOR_MOVED } from './system-door.js';
3
3
  import { DurableObject } from 'cloudflare:workers';
4
4
  import { ATTACHMENT_ADDED, ATTACHMENT_REMOVED, CAPTURE_REFUSALS, attachmentRecord, domainEvent, domainEventInput, eventId, instant, objectRef, entityObjectRef, assertModuleEmittableType, assertKernelAuthoredType, toWireFailure, grantRefFromProof, principalId, principalBecomeCapabilityInput, principalBindLinkInput, scopeId as scopeIdOf, tenantId as tenantIdOf, platformRequestInput, platformRequestId, MAX_PENDING_PLATFORM_REQUESTS, MAX_PENDING_SWEEP_RUNS, SWEEP_RUNS_KIND, SCOPE_DUMP_PAGE_MAX_BYTES, SCOPE_TABLE_PAGE_MAX, SCOPE_QUERY_ROW_MAX, listLimitOf, pageOf, countedPageOf, requestFingerprint, substratError, errorCodeOf, assertReplayableDump, DUMP_OBJECTS_QUERY, dumpObjectsOf, replayDumpObjects, dumpObjectsAudit, REDRAIN_BATCH, } from '@substrat-run/contracts';
5
- import { ulid, DO_SQL_LIMITS, unknownRoleError, createUlid, assertAllowed, ConnectionSealingKeyUnavailableError, noSealingKeyMessage, sealTo, assertReadOnlyQuery, refuseEntitlement, platformRequestHistoryQuery, platformRequestOf, PLATFORM_REQUEST_COLUMNS, PLATFORM_REQUEST_REDACTION_SQL, platformRequestRedactionParams, platformRequestRedactionQuery, intentPayloadCarriesSubject, redactSubjectJobRuns, eraseSubjectFromModules, moduleErasurePlan, redactSubjectScopeText, assertRowLimit, assertRowOffset, 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_LEASE_EXPIRED_NOTE, JOB_STEP_RECORD_SQL, DELIVERY_ERROR_REDACTION_SQL, REDACTED_DELIVERY_NOTE, seatScopeTuple, delegatedRevokeSql, writeExplicitTupleIn, grantEntityShapeIn, grantEntityShapeOnceIn, topUpEntityGrantShapes, applyScopeRoleChange, changeScopeRole, revokeScopeRoles, scopeRoleHolders, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, SCOPE_SEATED_ROLES_SQL, inUnitRoleRefusal, loadedRoleSetRefusedRole, reservedRoleSetRefusedRole, reservedGrantRefusal, reservedRoleRefusal, reservedShapeRefusal, effectiveRoleGrantQuery, switchRecordedOff, switchSystemSchedules, peerGrantsStatus, systemGrantsStatus, systemScheduleState, systemSwitchedOff, OUTBOX_PRUNED_DDL, outboxSubscribersOf, pruneDrainedOutbox, denialListQuery, refusalListQuery, mapRefusalRow, denialSummaryQuery, denialTotalsQuery, DENIAL_WINDOW_QUERY, mapDenialRow, mapDenialSummaryBuckets, PermissionDenied, assertImpersonationAdmitted, assertImpersonationWrites, assertModuleEnqueueableKind, impersonationStampOf, createAtomic, NotSearchable, isSearchIndexTable, rowCountTable, searchIndexPlans, NotListable, listIndexPlans, moduleMigrations, REGISTERED_MIGRATIONS, registeredMigrationsOf, MIGRATION_DIGEST_FENCE_DDL, MIGRATION_DIGEST_MARK_LEGACY, assertJournalDumpCoherent, assertMigrationSql, migrationDivergence, migrationFailedError, migrationSetDivergence, migrationSteps, planMigrations, listQuery, cursorOf, searchLimit, searchMatchExpression, searchQuery, ATTACHMENT_TEXT_DDL, ATTACHMENT_BYTES_SQL, ATTACHMENT_CONDEMNED_DDL, ATTACHMENT_SWEEP_LICENCE_DDL, ATTACHMENT_SWEEP_LICENCE_TABLE, WIRE_NONCE_DDL, WIRE_NONCE_FULL, claimWireNonceIn, isWireNonceTable, isWireNonceWrite, clearOrphanSweepLicence, condemnLicensedOrphanAttachments, consumeOrphanSweepLicence, licensedOrphanIds, recordOrphanSweepLicence, refuseUnlicensedOrphanSweep, refuseCondemnedAttachment, refuseCondemnedInDump, rowlessAttachmentIds, attachmentRecordOfRow, enqueueAttachmentText, reconcileAttachmentText, queueAttachmentTextBackfill, startAttachmentTextBackfill, recordAttachmentText, searchAttachments, IDEMPOTENCY_DDL, REFUSALS_TABLE_DDL, REFUSALS_INDEX, refusalInsert, refusalOf, markGuardRefusal, REFUSALS_REBUILD, refusalsAdmitGuards, assertIdempotencyKey, assertPermissionKey, idempotencyLookupQuery, idempotencyPruneStatement, idempotencyRecordStatement, idempotencyOptedOutMessage, replayFor, 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, exportedSinceQuery, emittedSinceQuery, emittedReportOf, EMITTED_REPORT_CAP, noteTransitionInto, withTransitions, IMPORT_CURSOR_ADVANCE_SQL, IMPORT_RECORD_SQL, moveImportCursor, CrossVerticalRegistry, exportReadPlan, exportReadQuery, planExportBatch, withheldNote, JOB_RUN_DDL, JOB_RUN_DUE_AT, jobRunListLimit, SYSTEM_DOOR_WAIT, ancestorsWithin, } from '@substrat-run/kernel';
5
+ import { ulid, DO_SQL_LIMITS, unknownRoleError, createUlid, assertAllowed, ConnectionSealingKeyUnavailableError, noSealingKeyMessage, sealTo, assertReadOnlyQuery, refuseEntitlement, platformRequestHistoryQuery, platformRequestOf, PLATFORM_REQUEST_COLUMNS, PLATFORM_REQUEST_REDACTION_SQL, platformRequestRedactionParams, platformRequestRedactionQuery, intentPayloadCarriesSubject, redactSubjectJobRuns, eraseSubjectFromModules, readSubjectPage, moduleErasurePlan, redactSubjectScopeText, assertRowLimit, assertRowOffset, 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_LEASE_EXPIRED_NOTE, JOB_STEP_RECORD_SQL, DELIVERY_ERROR_REDACTION_SQL, REDACTED_DELIVERY_NOTE, seatScopeTuple, delegatedRevokeSql, writeExplicitTupleIn, grantEntityShapeIn, grantEntityShapeOnceIn, topUpEntityGrantShapes, applyScopeRoleChange, changeScopeRole, revokeScopeRoles, scopeRoleHolders, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, SCOPE_SEATED_ROLES_SQL, inUnitRoleRefusal, loadedRoleSetRefusedRole, reservedRoleSetRefusedRole, reservedGrantRefusal, reservedRoleRefusal, reservedShapeRefusal, effectiveRoleGrantQuery, switchRecordedOff, switchSystemSchedules, peerGrantsStatus, systemGrantsStatus, systemScheduleState, systemSwitchedOff, OUTBOX_PRUNED_DDL, outboxSubscribersOf, pruneDrainedOutbox, denialListQuery, refusalListQuery, mapRefusalRow, denialSummaryQuery, denialTotalsQuery, DENIAL_WINDOW_QUERY, mapDenialRow, mapDenialSummaryBuckets, PermissionDenied, assertImpersonationAdmitted, assertImpersonationWrites, assertModuleEnqueueableKind, impersonationStampOf, createAtomic, NotSearchable, isSearchIndexTable, rowCountTable, searchIndexPlans, NotListable, listIndexPlans, moduleMigrations, REGISTERED_MIGRATIONS, registeredMigrationsOf, MIGRATION_DIGEST_FENCE_DDL, MIGRATION_DIGEST_MARK_LEGACY, assertJournalDumpCoherent, assertMigrationSql, migrationDivergence, migrationFailedError, migrationSetDivergence, migrationSteps, planMigrations, listQuery, cursorOf, searchLimit, searchMatchExpression, searchQuery, ATTACHMENT_TEXT_DDL, ATTACHMENT_BYTES_SQL, ATTACHMENT_CONDEMNED_DDL, ATTACHMENT_SWEEP_LICENCE_DDL, ATTACHMENT_SWEEP_LICENCE_TABLE, WIRE_NONCE_DDL, WIRE_NONCE_FULL, claimWireNonceIn, isWireNonceTable, isWireNonceWrite, clearOrphanSweepLicence, condemnLicensedOrphanAttachments, consumeOrphanSweepLicence, licensedOrphanIds, recordOrphanSweepLicence, refuseUnlicensedOrphanSweep, refuseCondemnedAttachment, refuseCondemnedInDump, rowlessAttachmentIds, attachmentRecordOfRow, enqueueAttachmentText, reconcileAttachmentText, queueAttachmentTextBackfill, startAttachmentTextBackfill, recordAttachmentText, searchAttachments, IDEMPOTENCY_DDL, REFUSALS_TABLE_DDL, REFUSALS_INDEX, refusalInsert, refusalOf, markGuardRefusal, REFUSALS_REBUILD, refusalsAdmitGuards, assertIdempotencyKey, assertPermissionKey, idempotencyLookupQuery, idempotencyPruneStatement, idempotencyRecordStatement, idempotencyOptedOutMessage, replayFor, 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, exportedSinceQuery, emittedSinceQuery, emittedReportOf, EMITTED_REPORT_CAP, noteTransitionInto, withTransitions, IMPORT_CURSOR_ADVANCE_SQL, IMPORT_RECORD_SQL, moveImportCursor, CrossVerticalRegistry, exportReadPlan, exportReadQuery, planExportBatch, withheldNote, JOB_RUN_DDL, JOB_RUN_DUE_AT, jobRunListLimit, SYSTEM_DOOR_WAIT, ancestorsWithin, } from '@substrat-run/kernel';
6
6
  import { isUpgradeRequest, readSubscription, LIVE_DECIDE_ATTEMPTS, LIVE_FANOUT_LIMIT, LIVE_PRINCIPAL_HEADER, LIVE_SCOPE_HEADER, LIVE_SUBSCRIBE_PATH, LIVE_TENANT_HEADER, LIVE_WITHIN_HEADER, LIVE_EXPIRES_HEADER, LIVE_CLOSE, LIVE_SOCKETS_PER_PRINCIPAL, decodeLiveWithin, liveInstant, liveRefusal, liveRefusalStatus, } from './live-reads.js';
7
7
  import { replyOf } from './do-reply.js';
8
8
  import { OperationQueue } from './serialization.js';
9
+ import { meterScopeWorkEntries, ScopeWorkMeter } from './scope-work.js';
9
10
  import { assertNoWorkerdStorage, doScopedSql, doBuiltColumnsOf, doRedactionSql, doSpineSql } from './sql.js';
10
11
  import { actorOf, admitPeer, boundToPeerDeclarations, collectPeers, switchPeer, peerSubjectRef, subjectGrantState, assertNoSecret, CAPABILITY_DDL, UPLOAD_LINK_DDL, DOWNLOAD_LINK_DDL, createAttachmentVerbs, inspectUploadLink, resolveDownloadLink, redeemUploadLinkInTransaction, COPY_ORIGIN_DDL, ENTITY_STATE_MOVES_DDL, SWITCH_FENCES_DDL, TABLE_OWNERS_DDL, assertMigrationLeavesLedgerAlone, recordOwnershipSteps, runMigrationStatements, splitSqlStatements, executableSqlStatements, blankSqlComments, CAPABILITY_EXCHANGE_OPERATION, CAPABILITY_BECOME_MINT_OPERATION, becomeMintCheck, mintBecomeCapabilityAsPrincipal, CAPABILITY_BIND_MINT_OPERATION, bindLinkMintCheck, mintBindLinkAsPrincipal, revokeBecomeCapabilityAsPrincipal, readBecomeLinkStates, ENTITY_UNBIND_OPERATION, allowedFor, unbindEntityHolderBounded, capabilityAttachmentWriteRefused, createCapabilityVerbs, createEntityEdgeVerbs, createEntityStateVerbs, createTrashedReads, CONTINUATION_POSITION_CAP, visibleContinuation, searchStateWhere, uncheckedView, addStatePlans, addUpdatedStampPlans, watchUpdatedStamps, assertNoCallerPurge, isUnreachableParent, PURGE_BATCH, heldPurgePass, lifecycleRefusal, purgeHeldBy, assertPlatformRequestRoom, purgeDueOf, purgeOnlyKeysOf, runPurgePass, refuseTrashedTarget, assertBoundOperations, checkHeldOperationsOf, countChecks, noteUncheckedCompletion, registerTrashTargets, withheldKeysFor, capCoverage, delegationCeilingOf, delegationStampOf, outsideCeiling, parseScopeDelegation, statefulTablesOf, afterMigration, afterRuntimeDdl, derivesAnything, repairDerivedObjects, StateColumnLost, exchangeCapability, exchangeBecomeLinkById, guardSecrets, mintBecomeCapability, redactSecrets, redactSecretText, moduleLog, asyncInvocationId, asyncLinePass, resolveCapabilitySession, revokeCapabilityAsPlatform, readCapabilityPage, domainEventOf, facetEvents, readDeadLetters, readLifecycleFlow, readOperationSeries, readHistory, readInvocation, readUndrainedOutbox, walkEventCause, walkEventEffects, } from '@substrat-run/kernel';
11
12
  import { COPY_RESTORE_FENCE_LAPSED, copyRestoreFenceLapsed, orphanSweepVersionRefusal } from '@substrat-run/kernel';
@@ -135,6 +136,10 @@ const KERNEL_DDL = `
135
136
  -- range, and the trailing id gives the ORDER BY for free. IF NOT EXISTS in the spine
136
137
  -- DDL, which every wake re-runs, so existing scopes get it too.
137
138
  CREATE INDEX IF NOT EXISTS _substrat_outbox_drained ON _substrat_outbox (drained_at, id);
139
+ -- D-74: subject access reads every event keyed to one person, and erasure redacts them, both by
140
+ -- subject_id. Partial, so the many events with no subject pay nothing; the trailing id gives the
141
+ -- access read its ORDER BY. IF NOT EXISTS in the spine DDL, so existing scopes get it on wake.
142
+ CREATE INDEX IF NOT EXISTS _substrat_outbox_subject ON _substrat_outbox (subject_id, id) WHERE subject_id IS NOT NULL;
138
143
  -- platform-intents.md: durable intents a vertical enqueues (ctx.requestPlatform) for the platform
139
144
  -- to drain and execute with HostAdmin authority -- the sandbox-clean way a vertical asks for a
140
145
  -- privileged action. Written by the kernel (spine), settled by the platform drain.
@@ -615,7 +620,6 @@ function decodeDumpCursor(cursor) {
615
620
  * and over-counting only refuses a restore that could have landed.
616
621
  */
617
622
  class WriteRevision {
618
- raw;
619
623
  storage;
620
624
  suspended;
621
625
  refusal;
@@ -640,16 +644,24 @@ class WriteRevision {
640
644
  /** Inside `untracked`: a capture's own bookkeeping, which nothing here counts. */
641
645
  bypass = false;
642
646
  sql;
643
- constructor(raw, storage, suspended,
647
+ /** The handle every statement runs on: the runtime's, under the scope-work meter when there is one (#3316). */
648
+ raw;
649
+ constructor(runtime, storage, suspended,
644
650
  /** Why this store takes no write at all right now, or null (a `carried_away` copy, #1722). */
645
651
  refusal,
646
652
  /** Run before every write statement (#2450: an idle capture's triggers go before the write). */
647
- beforeWrite = () => undefined) {
648
- this.raw = raw;
653
+ beforeWrite = () => undefined,
654
+ /**
655
+ * #3316: the scope-work meter's counting wrapper, put UNDER everything here, so the revision's
656
+ * own bump and the capture's bypass are counted with the statement that caused them.
657
+ */
658
+ counted) {
649
659
  this.storage = storage;
650
660
  this.suspended = suspended;
651
661
  this.refusal = refusal;
652
662
  this.beforeWrite = beforeWrite;
663
+ const raw = counted ? counted(runtime) : runtime;
664
+ this.raw = raw;
653
665
  const exec = (query, ...bindings) => {
654
666
  if (this.bypass) {
655
667
  // Enforced, not trusted, as `bookkeeping` is: a write here that is not the capture's own
@@ -907,7 +919,7 @@ options = {}) {
907
919
  noteReservedKeys(declaredReserved, m.manifest);
908
920
  noteDeclaredKeys(declaredListed, m.manifest);
909
921
  }
910
- return class ScopeDO extends DurableObject {
922
+ const ScopeDO = class ScopeDO extends DurableObject {
911
923
  /**
912
924
  * #2351: the migrations this class registers, read by the control plane, which evaluates the
913
925
  * bundle in an isolate with no bindings and calls this before it stores the version. The same
@@ -1062,6 +1074,26 @@ options = {}) {
1062
1074
  carriedAwayCopy = false;
1063
1075
  /** #1722: the write revision, and the one way this object opens a transaction. */
1064
1076
  revision;
1077
+ /** #3316: this object's rows by origin, or undefined when the upload bound no dataset. */
1078
+ scopeWork;
1079
+ /** #3316: the tenant each point names, once known. */
1080
+ scopeWorkTenantId = null;
1081
+ /**
1082
+ * #3316: the tenant this scope was provisioned for, for the scope-work points — read with the
1083
+ * meter paused, the one read it does not count: two indexed lookups per point until the scope is
1084
+ * provisioned, then none again in this wake.
1085
+ */
1086
+ scopeWorkTenant() {
1087
+ if (this.scopeWorkTenantId !== null || !this.scopeWork)
1088
+ return this.scopeWorkTenantId;
1089
+ try {
1090
+ this.scopeWorkTenantId = this.scopeWork.uncounted(() => this.provisionedFor());
1091
+ }
1092
+ catch {
1093
+ // A point with no tenant is still a count; the scope and object ids name it.
1094
+ }
1095
+ return this.scopeWorkTenantId;
1096
+ }
1065
1097
  constructor(ctx, env) {
1066
1098
  super(ctx, env);
1067
1099
  // #1860: the client's 45s keep-alive (demos/ticket0/app/src/feed.ts) answered at
@@ -1069,11 +1101,24 @@ options = {}) {
1069
1101
  // subscriber's ping still reaches `webSocketMessage` and pins the DO in memory —
1070
1102
  // exactly the hibernation cost `acceptWebSocket` (below) exists to avoid.
1071
1103
  ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair('ping', 'pong'));
1104
+ // #3316: the rows each invocation runs, by origin, into Analytics Engine — only when the
1105
+ // upload bound a dataset. Built first, so the wake's own statements below are counted (`wake`).
1106
+ const scopeWork = env.SUBSTRAT_SCOPE_WORK;
1107
+ this.scopeWork = scopeWork
1108
+ ? new ScopeWorkMeter(scopeWork, {
1109
+ tenant: () => this.scopeWorkTenant(),
1110
+ vertical: env.SUBSTRAT_VERTICAL ?? null,
1111
+ scopeId: ctx.id.name ?? null,
1112
+ objectId: ctx.id.toString(),
1113
+ versionId: env.SUBSTRAT_VERSION_ID ?? null,
1114
+ kind: env.SUBSTRAT_SCRIPT_KIND ?? null,
1115
+ })
1116
+ : undefined;
1072
1117
  // #1722: the ONE handle this object writes through and the one way it opens a transaction,
1073
1118
  // so every write advances the write revision a carry's restore is fenced on, inside the
1074
1119
  // transaction that commits it. Nothing else here may take the raw handle or open a
1075
1120
  // transaction on `ctx.storage` itself (`carried-copy.test.ts` in the kernel holds that).
1076
- this.revision = new WriteRevision(ctx.storage.sql, ctx.storage, () => this.revisionSuspended, () => (this.carriedAwayCopy ? CARRIED_AWAY_WRITE_REFUSAL : null), () => this.expireIdleCaptures());
1121
+ this.revision = new WriteRevision(ctx.storage.sql, ctx.storage, () => this.revisionSuspended, () => (this.carriedAwayCopy ? CARRIED_AWAY_WRITE_REFUSAL : null), () => this.expireIdleCaptures(), this.scopeWork ? (runtime) => this.scopeWork.counting(runtime) : undefined);
1077
1122
  this.sql = this.revision.sql;
1078
1123
  for (const stmt of executableSqlStatements(KERNEL_DDL)) {
1079
1124
  this.sql.exec(stmt);
@@ -5018,8 +5063,13 @@ options = {}) {
5018
5063
  }
5019
5064
  // -- migrations (port of applyPendingMigrations) --------------------------
5020
5065
  ensureMigrations() {
5021
- if (!this.migrationPromise)
5022
- this.migrationPromise = this.applyPendingMigrations();
5066
+ if (!this.migrationPromise) {
5067
+ // #3316: counted as the migration it is, not as whichever entry woke it — the first
5068
+ // operation after a promote runs the whole pass.
5069
+ this.migrationPromise = this.scopeWork
5070
+ ? this.scopeWork.apart('migration-pass', 'migration', () => this.applyPendingMigrations())
5071
+ : this.applyPendingMigrations();
5072
+ }
5023
5073
  return this.migrationPromise;
5024
5074
  }
5025
5075
  /** Every registered module's derivation plans — what `repairDerivedObjects` and its checks read. */
@@ -6046,7 +6096,9 @@ options = {}) {
6046
6096
  this.readCaptureClock();
6047
6097
  if (this.captureIdleAt === null || this.captureIdleAt === undefined || Date.now() < this.captureIdleAt)
6048
6098
  return;
6049
- this.revision.untracked(() => {
6099
+ // #3316: a copy's capture ending is the copy's work, not the write's that found it idle.
6100
+ const apart = (fn) => (this.scopeWork ? this.scopeWork.apart('capture-expiry', 'export', fn) : fn());
6101
+ apart(() => this.revision.untracked(() => {
6050
6102
  // A load took the capture's tables with it: there is nothing left to end.
6051
6103
  if (!this.hasTable('_substrat_capture'))
6052
6104
  return;
@@ -6055,7 +6107,7 @@ options = {}) {
6055
6107
  .toArray();
6056
6108
  for (const { copy_id } of idle)
6057
6109
  this.forgetCapture(copy_id);
6058
- });
6110
+ }));
6059
6111
  // Read again at the next write, not now: should the write's own transaction roll back, the
6060
6112
  // capture is back, and the next write ends it again.
6061
6113
  this.captureIdleAt = undefined;
@@ -6070,10 +6122,15 @@ options = {}) {
6070
6122
  dropIdleCaptureLater() {
6071
6123
  setTimeout(() => {
6072
6124
  try {
6073
- this.revision.untracked(() => {
6125
+ const drop = () => this.revision.untracked(() => {
6074
6126
  if (this.hasTable('_substrat_capture'))
6075
6127
  this.dropCaptureIfIdle();
6076
6128
  });
6129
+ // #3316: the copy's teardown, counted apart from the write whose turn scheduled it.
6130
+ if (this.scopeWork)
6131
+ this.scopeWork.apart('capture-drop', 'export', drop);
6132
+ else
6133
+ drop();
6077
6134
  }
6078
6135
  catch {
6079
6136
  // Left to the next capture call or wake, as above.
@@ -7172,6 +7229,23 @@ options = {}) {
7172
7229
  return { failure: toWireFailure(err) };
7173
7230
  }
7174
7231
  }
7232
+ /**
7233
+ * One page of what this scope holds about one data subject (GDPR Art. 15, D-74): the kernel's
7234
+ * `readSubjectPage` over the same erasure plans `redactSubject` runs, so access reads exactly
7235
+ * what erasure writes. Writes nothing and runs no module code; one synchronous body, so no
7236
+ * other request interleaves with the page. A refusal (a cursor this read never issued) is
7237
+ * answered as data, as `redactSubject` answers one, so its code survives the RPC.
7238
+ */
7239
+ async readSubject(subjectId, page) {
7240
+ try {
7241
+ // Inside the envelope: a migration refusal is an answer too, and keeps its code across the RPC.
7242
+ await this.ensureMigrations();
7243
+ return readSubjectPage({ sql: doSpineSql(this.sql), plans: this.erasurePlans, subjectId, ...(page ? { page } : {}) });
7244
+ }
7245
+ catch (err) {
7246
+ return { failure: toWireFailure(err) };
7247
+ }
7248
+ }
7175
7249
  /** The body of `redactSubject`, inside its transaction. */
7176
7250
  redactSubjectInTransaction(subjectId, at) {
7177
7251
  // The module half first (#2068): the declared entities, then each hook, with the search
@@ -8195,5 +8269,18 @@ options = {}) {
8195
8269
  return row?.effective === 1;
8196
8270
  }
8197
8271
  };
8272
+ // #3316: each RPC entry counts the rows it runs under its origin (`scope-work.ts`). `invoke` is
8273
+ // the vertical's own operation when a person or a connection calls it, and one of its declared
8274
+ // schedules when the platform's sweeper does (`systemModuleId`, its eighth argument) — a purge
8275
+ // schedule apart, since a binned row's purge is the platform's retention, not the vertical's work.
8276
+ meterScopeWorkEntries(ScopeDO.prototype, (self) => self.scopeWork, {
8277
+ invoke: (self, args) => {
8278
+ if (typeof args[7] !== 'string')
8279
+ return 'operation';
8280
+ const purges = self.purgeSchedules;
8281
+ return purges?.has(String(args[0])) ? 'purge' : 'schedule';
8282
+ },
8283
+ });
8284
+ return ScopeDO;
8198
8285
  }
8199
8286
  //# sourceMappingURL=scope-do.js.map