@substrat-run/adapter-cloudflare 0.205.0 → 0.207.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,EAiEL,KAAK,mBAAmB,EASxB,KAAK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AAE,CAAC;AA8lBjG,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,CA84R7E"}
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, 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';
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, countDumpRows, planDumpSample, sampleFilters, sampleGraph, 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';
@@ -561,6 +562,12 @@ const ROWID_NAMES = new Set(['rowid', '_rowid_', 'oid']);
561
562
  * the stamp over beside one); every load writes its own. #2350: the orphan sweep's licence is this
562
563
  * store's own, so its rows never leave either.
563
564
  */
565
+ /** `dumpRowFilter`, narrowed by a sample's filter for the table when it has one (#3232). */
566
+ function sampledRowFilter(name, filters) {
567
+ const base = dumpRowFilter(name);
568
+ const sampled = filters?.get(name);
569
+ return sampled ? { where: `(${base.where}) AND (${sampled})`, bindings: base.bindings } : base;
570
+ }
564
571
  function dumpRowFilter(name) {
565
572
  if (name === '_substrat_meta') {
566
573
  return { where: `key NOT IN (${STORE_LOCAL_META_KEYS.map(() => '?').join(', ')})`, bindings: [...STORE_LOCAL_META_KEYS] };
@@ -619,7 +626,6 @@ function decodeDumpCursor(cursor) {
619
626
  * and over-counting only refuses a restore that could have landed.
620
627
  */
621
628
  class WriteRevision {
622
- raw;
623
629
  storage;
624
630
  suspended;
625
631
  refusal;
@@ -644,16 +650,24 @@ class WriteRevision {
644
650
  /** Inside `untracked`: a capture's own bookkeeping, which nothing here counts. */
645
651
  bypass = false;
646
652
  sql;
647
- constructor(raw, storage, suspended,
653
+ /** The handle every statement runs on: the runtime's, under the scope-work meter when there is one (#3316). */
654
+ raw;
655
+ constructor(runtime, storage, suspended,
648
656
  /** Why this store takes no write at all right now, or null (a `carried_away` copy, #1722). */
649
657
  refusal,
650
658
  /** Run before every write statement (#2450: an idle capture's triggers go before the write). */
651
- beforeWrite = () => undefined) {
652
- this.raw = raw;
659
+ beforeWrite = () => undefined,
660
+ /**
661
+ * #3316: the scope-work meter's counting wrapper, put UNDER everything here, so the revision's
662
+ * own bump and the capture's bypass are counted with the statement that caused them.
663
+ */
664
+ counted) {
653
665
  this.storage = storage;
654
666
  this.suspended = suspended;
655
667
  this.refusal = refusal;
656
668
  this.beforeWrite = beforeWrite;
669
+ const raw = counted ? counted(runtime) : runtime;
670
+ this.raw = raw;
657
671
  const exec = (query, ...bindings) => {
658
672
  if (this.bypass) {
659
673
  // Enforced, not trusted, as `bookkeeping` is: a write here that is not the capture's own
@@ -911,7 +925,7 @@ options = {}) {
911
925
  noteReservedKeys(declaredReserved, m.manifest);
912
926
  noteDeclaredKeys(declaredListed, m.manifest);
913
927
  }
914
- return class ScopeDO extends DurableObject {
928
+ const ScopeDO = class ScopeDO extends DurableObject {
915
929
  /**
916
930
  * #2351: the migrations this class registers, read by the control plane, which evaluates the
917
931
  * bundle in an isolate with no bindings and calls this before it stores the version. The same
@@ -1066,6 +1080,26 @@ options = {}) {
1066
1080
  carriedAwayCopy = false;
1067
1081
  /** #1722: the write revision, and the one way this object opens a transaction. */
1068
1082
  revision;
1083
+ /** #3316: this object's rows by origin, or undefined when the upload bound no dataset. */
1084
+ scopeWork;
1085
+ /** #3316: the tenant each point names, once known. */
1086
+ scopeWorkTenantId = null;
1087
+ /**
1088
+ * #3316: the tenant this scope was provisioned for, for the scope-work points — read with the
1089
+ * meter paused, the one read it does not count: two indexed lookups per point until the scope is
1090
+ * provisioned, then none again in this wake.
1091
+ */
1092
+ scopeWorkTenant() {
1093
+ if (this.scopeWorkTenantId !== null || !this.scopeWork)
1094
+ return this.scopeWorkTenantId;
1095
+ try {
1096
+ this.scopeWorkTenantId = this.scopeWork.uncounted(() => this.provisionedFor());
1097
+ }
1098
+ catch {
1099
+ // A point with no tenant is still a count; the scope and object ids name it.
1100
+ }
1101
+ return this.scopeWorkTenantId;
1102
+ }
1069
1103
  constructor(ctx, env) {
1070
1104
  super(ctx, env);
1071
1105
  // #1860: the client's 45s keep-alive (demos/ticket0/app/src/feed.ts) answered at
@@ -1073,11 +1107,24 @@ options = {}) {
1073
1107
  // subscriber's ping still reaches `webSocketMessage` and pins the DO in memory —
1074
1108
  // exactly the hibernation cost `acceptWebSocket` (below) exists to avoid.
1075
1109
  ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair('ping', 'pong'));
1110
+ // #3316: the rows each invocation runs, by origin, into Analytics Engine — only when the
1111
+ // upload bound a dataset. Built first, so the wake's own statements below are counted (`wake`).
1112
+ const scopeWork = env.SUBSTRAT_SCOPE_WORK;
1113
+ this.scopeWork = scopeWork
1114
+ ? new ScopeWorkMeter(scopeWork, {
1115
+ tenant: () => this.scopeWorkTenant(),
1116
+ vertical: env.SUBSTRAT_VERTICAL ?? null,
1117
+ scopeId: ctx.id.name ?? null,
1118
+ objectId: ctx.id.toString(),
1119
+ versionId: env.SUBSTRAT_VERSION_ID ?? null,
1120
+ kind: env.SUBSTRAT_SCRIPT_KIND ?? null,
1121
+ })
1122
+ : undefined;
1076
1123
  // #1722: the ONE handle this object writes through and the one way it opens a transaction,
1077
1124
  // so every write advances the write revision a carry's restore is fenced on, inside the
1078
1125
  // transaction that commits it. Nothing else here may take the raw handle or open a
1079
1126
  // transaction on `ctx.storage` itself (`carried-copy.test.ts` in the kernel holds that).
1080
- this.revision = new WriteRevision(ctx.storage.sql, ctx.storage, () => this.revisionSuspended, () => (this.carriedAwayCopy ? CARRIED_AWAY_WRITE_REFUSAL : null), () => this.expireIdleCaptures());
1127
+ 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);
1081
1128
  this.sql = this.revision.sql;
1082
1129
  for (const stmt of executableSqlStatements(KERNEL_DDL)) {
1083
1130
  this.sql.exec(stmt);
@@ -5022,8 +5069,13 @@ options = {}) {
5022
5069
  }
5023
5070
  // -- migrations (port of applyPendingMigrations) --------------------------
5024
5071
  ensureMigrations() {
5025
- if (!this.migrationPromise)
5026
- this.migrationPromise = this.applyPendingMigrations();
5072
+ if (!this.migrationPromise) {
5073
+ // #3316: counted as the migration it is, not as whichever entry woke it — the first
5074
+ // operation after a promote runs the whole pass.
5075
+ this.migrationPromise = this.scopeWork
5076
+ ? this.scopeWork.apart('migration-pass', 'migration', () => this.applyPendingMigrations())
5077
+ : this.applyPendingMigrations();
5078
+ }
5027
5079
  return this.migrationPromise;
5028
5080
  }
5029
5081
  /** Every registered module's derivation plans — what `repairDerivedObjects` and its checks read. */
@@ -5721,7 +5773,7 @@ options = {}) {
5721
5773
  // Answered as data, so a refusal's code survives the hop (#113).
5722
5774
  return replyOf(() => this.dumpPage(cursor, opts));
5723
5775
  }
5724
- dumpPage(cursor, { stamp = false, maxBytes = SCOPE_DUMP_PAGE_MAX_BYTES, capture }) {
5776
+ dumpPage(cursor, { stamp = false, maxBytes = SCOPE_DUMP_PAGE_MAX_BYTES, capture, sample }) {
5725
5777
  let loadStamp = this.loadStamp();
5726
5778
  if (stamp && cursor === null && !loadStamp && !this.carriedAwayCopy) {
5727
5779
  loadStamp = ulid();
@@ -5736,6 +5788,8 @@ options = {}) {
5736
5788
  this.heldCapture(capture, defs);
5737
5789
  }
5738
5790
  const at = cursor === null ? null : decodeDumpCursor(cursor);
5791
+ // #3232: a sampled copy reads every page, and every change batch, under the plan its first page made.
5792
+ const sampling = sample ? this.samplingOf(defs, sample) : null;
5739
5793
  const tables = [];
5740
5794
  let bytes = 0;
5741
5795
  let next = null;
@@ -5745,7 +5799,7 @@ options = {}) {
5745
5799
  if (at && name < at.table)
5746
5800
  continue;
5747
5801
  const after = at && name === at.table ? at.after : null;
5748
- const { where, bindings } = dumpRowFilter(name);
5802
+ const { where, bindings } = sampledRowFilter(name, sampling?.filters);
5749
5803
  const { columns, byRowid } = this.tableShape(name, sql);
5750
5804
  // In batches, each read to its end: a cursor left part-read keeps its table locked, and
5751
5805
  // the next statement that drops or alters it fails with SQLITE_LOCKED.
@@ -5782,7 +5836,40 @@ options = {}) {
5782
5836
  break;
5783
5837
  }
5784
5838
  }
5785
- return { tables, next, loadStamp, revision: this.metaValue(WRITE_REVISION_KEY), ...(capture !== undefined ? { captured: true } : {}) };
5839
+ return {
5840
+ tables, next, loadStamp, revision: this.metaValue(WRITE_REVISION_KEY),
5841
+ ...(capture !== undefined ? { captured: true } : {}),
5842
+ ...(sampling ? { sample: sampling.plan } : {}),
5843
+ };
5844
+ }
5845
+ /**
5846
+ * #3232: the sample a copy reads under. Asked for by size alone (its first page), it is planned
5847
+ * here, reading each table's floor; asked for with its floors (every later page and change
5848
+ * batch), it is read as planned, so the whole copy reads one sample however the scope moved.
5849
+ */
5850
+ samplingOf(defs, sample) {
5851
+ const reader = { all: (sql, ...params) => this.sql.exec(sql, ...params).toArray() };
5852
+ const graph = sampleGraph(reader, defs.map(({ name, sql }) => ({ name, byRowid: this.tableShape(name, sql).byRowid })));
5853
+ const plan = sample.floors ? { rows: sample.rows, floors: sample.floors } : planDumpSample(reader, graph, sample.rows);
5854
+ return { plan, filters: sampleFilters(graph, plan) };
5855
+ }
5856
+ /**
5857
+ * How many rows a copy of this scope would move (#3232), whole or under a sample of `rows`, read
5858
+ * before the copy starts so a fork too costly to copy is refused before it writes anything.
5859
+ * Reads only, in one turn; a large table read under a sample's filter is counted on a probe.
5860
+ */
5861
+ estimateDump(opts = {}) {
5862
+ return replyOf(() => {
5863
+ const defs = this.dumpTableDefs();
5864
+ const reader = { all: (sql, ...params) => this.sql.exec(sql, ...params).toArray() };
5865
+ const tables = defs.map(({ name, sql }) => ({ name, byRowid: this.tableShape(name, sql).byRowid }));
5866
+ const sampling = opts.sample ? this.samplingOf(defs, { rows: opts.sample.rows }) : null;
5867
+ const counted = countDumpRows(reader, tables, {
5868
+ base: (name) => dumpRowFilter(name),
5869
+ ...(sampling ? { filters: sampling.filters, sample: sampling.plan } : {}),
5870
+ });
5871
+ return { ...counted, ...(sampling ? { sample: sampling.plan } : {}) };
5872
+ });
5786
5873
  }
5787
5874
  /** A dumped table's columns, and whether its rows are read, and named, by rowid. */
5788
5875
  tableShape(name, sql) {
@@ -5920,13 +6007,17 @@ options = {}) {
5920
6007
  * ends with it (its triggers too, when it was the last).
5921
6008
  */
5922
6009
  exportDumpChanges(copyId, seq, opts = {}) {
5923
- return replyOf(() => this.captureChanges(copyId, seq, opts.maxBytes ?? SCOPE_DUMP_PAGE_MAX_BYTES));
6010
+ return replyOf(() => this.captureChanges(copyId, seq, opts.maxBytes ?? SCOPE_DUMP_PAGE_MAX_BYTES, opts.sample));
5924
6011
  }
5925
- captureChanges(copyId, seq, maxBytes) {
6012
+ captureChanges(copyId, seq, maxBytes, sample) {
5926
6013
  if (!Number.isSafeInteger(seq) || seq < 0)
5927
6014
  throw substratError('validation_failed', 'a change batch is numbered from 0');
5928
6015
  const defs = this.dumpTableDefs();
5929
6016
  this.heldCapture(copyId, defs);
6017
+ // #3232: a row the sample does not keep reads as gone, so a row that left it is deleted there.
6018
+ if (sample && !sample.floors)
6019
+ throw substratError('validation_failed', 'a sampled copy catches up under the floors its first page answered');
6020
+ const filters = sample ? this.samplingOf(defs, sample).filters : undefined;
5930
6021
  const sqlOf = new Map(defs.map((d) => [d.name, d.sql]));
5931
6022
  return this.revision.untracked(() => {
5932
6023
  this.sql.exec(`DELETE FROM _substrat_capture_changes WHERE copy_id = ? AND batch < ?`, copyId, seq);
@@ -5947,7 +6038,7 @@ options = {}) {
5947
6038
  break;
5948
6039
  const ddl = sqlOf.get(name);
5949
6040
  const { columns, byRowid } = this.tableShape(name, ddl);
5950
- const { where, bindings } = dumpRowFilter(name);
6041
+ const { where, bindings } = sampledRowFilter(name, filters);
5951
6042
  const served = [];
5952
6043
  if (!byRowid) {
5953
6044
  const rows = Array.from(this.sql.exec(`SELECT * FROM ${quoteIdent(name)} WHERE ${where}`, ...bindings).raw(), (r) => r);
@@ -6050,7 +6141,9 @@ options = {}) {
6050
6141
  this.readCaptureClock();
6051
6142
  if (this.captureIdleAt === null || this.captureIdleAt === undefined || Date.now() < this.captureIdleAt)
6052
6143
  return;
6053
- this.revision.untracked(() => {
6144
+ // #3316: a copy's capture ending is the copy's work, not the write's that found it idle.
6145
+ const apart = (fn) => (this.scopeWork ? this.scopeWork.apart('capture-expiry', 'export', fn) : fn());
6146
+ apart(() => this.revision.untracked(() => {
6054
6147
  // A load took the capture's tables with it: there is nothing left to end.
6055
6148
  if (!this.hasTable('_substrat_capture'))
6056
6149
  return;
@@ -6059,7 +6152,7 @@ options = {}) {
6059
6152
  .toArray();
6060
6153
  for (const { copy_id } of idle)
6061
6154
  this.forgetCapture(copy_id);
6062
- });
6155
+ }));
6063
6156
  // Read again at the next write, not now: should the write's own transaction roll back, the
6064
6157
  // capture is back, and the next write ends it again.
6065
6158
  this.captureIdleAt = undefined;
@@ -6074,10 +6167,15 @@ options = {}) {
6074
6167
  dropIdleCaptureLater() {
6075
6168
  setTimeout(() => {
6076
6169
  try {
6077
- this.revision.untracked(() => {
6170
+ const drop = () => this.revision.untracked(() => {
6078
6171
  if (this.hasTable('_substrat_capture'))
6079
6172
  this.dropCaptureIfIdle();
6080
6173
  });
6174
+ // #3316: the copy's teardown, counted apart from the write whose turn scheduled it.
6175
+ if (this.scopeWork)
6176
+ this.scopeWork.apart('capture-drop', 'export', drop);
6177
+ else
6178
+ drop();
6081
6179
  }
6082
6180
  catch {
6083
6181
  // Left to the next capture call or wake, as above.
@@ -8216,5 +8314,18 @@ options = {}) {
8216
8314
  return row?.effective === 1;
8217
8315
  }
8218
8316
  };
8317
+ // #3316: each RPC entry counts the rows it runs under its origin (`scope-work.ts`). `invoke` is
8318
+ // the vertical's own operation when a person or a connection calls it, and one of its declared
8319
+ // schedules when the platform's sweeper does (`systemModuleId`, its eighth argument) — a purge
8320
+ // schedule apart, since a binned row's purge is the platform's retention, not the vertical's work.
8321
+ meterScopeWorkEntries(ScopeDO.prototype, (self) => self.scopeWork, {
8322
+ invoke: (self, args) => {
8323
+ if (typeof args[7] !== 'string')
8324
+ return 'operation';
8325
+ const purges = self.purgeSchedules;
8326
+ return purges?.has(String(args[0])) ? 'purge' : 'schedule';
8327
+ },
8328
+ });
8329
+ return ScopeDO;
8219
8330
  }
8220
8331
  //# sourceMappingURL=scope-do.js.map