@substrat-run/kernel 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.
Files changed (44) hide show
  1. package/dist/connection-landings.d.ts +52 -2
  2. package/dist/connection-landings.d.ts.map +1 -1
  3. package/dist/connection-landings.js +72 -6
  4. package/dist/connection-landings.js.map +1 -1
  5. package/dist/cost-rollup.d.ts +186 -0
  6. package/dist/cost-rollup.d.ts.map +1 -0
  7. package/dist/cost-rollup.js +475 -0
  8. package/dist/cost-rollup.js.map +1 -0
  9. package/dist/dump-sample.d.ts +113 -0
  10. package/dist/dump-sample.d.ts.map +1 -0
  11. package/dist/dump-sample.js +258 -0
  12. package/dist/dump-sample.js.map +1 -0
  13. package/dist/index.d.ts +11 -5
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +11 -3
  16. package/dist/index.js.map +1 -1
  17. package/dist/markup-schedule.d.ts +51 -0
  18. package/dist/markup-schedule.d.ts.map +1 -0
  19. package/dist/markup-schedule.js +70 -0
  20. package/dist/markup-schedule.js.map +1 -0
  21. package/dist/model-usage.d.ts +8 -1
  22. package/dist/model-usage.d.ts.map +1 -1
  23. package/dist/model-usage.js +38 -19
  24. package/dist/model-usage.js.map +1 -1
  25. package/dist/platform-sweep.d.ts +148 -6
  26. package/dist/platform-sweep.d.ts.map +1 -1
  27. package/dist/platform-sweep.js +472 -169
  28. package/dist/platform-sweep.js.map +1 -1
  29. package/dist/scope-host.d.ts +57 -4
  30. package/dist/scope-host.d.ts.map +1 -1
  31. package/dist/scope-host.js.map +1 -1
  32. package/dist/scope-work-bindings.d.ts +19 -0
  33. package/dist/scope-work-bindings.d.ts.map +1 -0
  34. package/dist/scope-work-bindings.js +17 -0
  35. package/dist/scope-work-bindings.js.map +1 -0
  36. package/dist/snapshot-retention.d.ts +19 -0
  37. package/dist/snapshot-retention.d.ts.map +1 -0
  38. package/dist/snapshot-retention.js +21 -0
  39. package/dist/snapshot-retention.js.map +1 -0
  40. package/dist/sweep-budget.d.ts +32 -0
  41. package/dist/sweep-budget.d.ts.map +1 -0
  42. package/dist/sweep-budget.js +177 -0
  43. package/dist/sweep-budget.js.map +1 -0
  44. package/package.json +2 -2
@@ -5,7 +5,9 @@ import { STORAGE_GAUGE_PRUNE_BATCH, STORED_SCOPE_STATUSES, holdsStore } from './
5
5
  import { BILLING_ROLLUP_RETENTION_MONTHS, billingRollupHorizon, utcDayOf } from './billing-retention.js';
6
6
  import { METER_DAYS_PRUNE_BATCH, METER_SNAPSHOT_TIMEOUT_MS } from './meter-days.js';
7
7
  import { REQUEST_ROLLUP_DAYS_PER_PASS, REQUEST_ROLLUP_LOOKBACK_DAYS, REQUEST_ROLLUP_MAX_LOOKBACK_DAYS, REQUEST_ROLLUP_PRUNE_BATCH, REQUEST_ROLLUP_READ_TIMEOUT_MS, REQUEST_ROLLUP_RETRY_MS, REQUEST_ROLLUP_SETTLE_MS, isRequestRollupSaturated, requestRollupDueDays, } from './request-rollup.js';
8
+ import { COST_ROLLUP_DAYS_PER_PASS, COST_ROLLUP_LOOKBACK_DAYS, COST_ROLLUP_MAX_LOOKBACK_DAYS, COST_ROLLUP_PRUNE_BATCH, COST_ROLLUP_READ_TIMEOUT_MS, COST_ROLLUP_RETRY_MS, COST_ROLLUP_SETTLE_MS, SCOPE_OBJECT_RETRY_MS, SCOPE_OBJECTS_PER_PASS, } from './cost-rollup.js';
8
9
  import { backoffAt, fetchLikeOf } from './connector-transport.js';
10
+ import { budgetedFetch, CONNECTOR_SWEEP_MAX_BYTES, CONNECTOR_SWEEP_MAX_MS } from './sweep-budget.js';
9
11
  import { assertRowLimit, TELEMETRY_PRUNE_BATCH } from './retention.js';
10
12
  import { MIGRATION_FLAG_THRESHOLD, migrationFleet, migrationProgress, scopeMigrationState } from './migration-progress.js';
11
13
  import { UNDRAINED_SKIPPED_IDS } from './outbox-event.js';
@@ -56,8 +58,15 @@ function tenantSentence(provider, f) {
56
58
  const counted = (n, noun) => `${n} ${noun}${n === 1 ? '' : 's'}`;
57
59
  /** The text a connection's sweep row carries when a poll found no binding to sweep. */
58
60
  export const NO_BINDING = 'connection has no binding: nothing was polled for any scope';
59
- /** How many access rows one pass ships, and one pass prunes, by default. */
61
+ /** How many access rows one access-log batch ships, and prunes, by default. */
60
62
  const ACCESS_LOG_BATCH = 500;
63
+ /**
64
+ * How many full access-log batches one pass may drain, by default (#3326). One batch a pass
65
+ * was outrun: the control plane's own sweep writes about 720 access rows a pass, so a drain of
66
+ * 500 fell further behind every tick (eight days behind and 944 K rows deep by 2026-11-18). Eight
67
+ * outruns that inflow several times over and still bounds the pass.
68
+ */
69
+ const ACCESS_LOG_BATCHES_PER_PASS = 8;
61
70
  /** How many events one pass drains PER SCOPE by default. */
62
71
  const EVENT_DRAIN_BATCH = 200;
63
72
  /** The #1172 phase's per-pass bound when `provisionReconcileBatch` is unset (#1653). */
@@ -221,6 +230,8 @@ function assertSweepBatches(options) {
221
230
  assertRowLimit('telemetryBatch', options.telemetryBatch);
222
231
  if (options.accessLogBatch !== undefined)
223
232
  assertRowLimit('accessLogBatch', options.accessLogBatch);
233
+ if (options.accessLogBatchesPerPass !== undefined)
234
+ assertRowLimit('accessLogBatchesPerPass', options.accessLogBatchesPerPass);
224
235
  const gauge = options.storageGauge;
225
236
  if (gauge?.pruneBatch !== undefined)
226
237
  assertRowLimit('storageGauge.pruneBatch', gauge.pruneBatch);
@@ -251,6 +262,29 @@ function assertSweepBatches(options) {
251
262
  }
252
263
  if (rollup?.readTimeoutMs !== undefined)
253
264
  assertPositiveMs('requestRollup.readTimeoutMs', rollup.readTimeoutMs);
265
+ const costs = options.cloudflareCosts;
266
+ if (costs?.pruneBatch !== undefined)
267
+ assertRowLimit('cloudflareCosts.pruneBatch', costs.pruneBatch);
268
+ if (costs?.batch !== undefined && !(Number.isInteger(costs.batch) && costs.batch >= 0)) {
269
+ throw substratError('validation_failed', `cloudflareCosts.batch must be a non-negative integer, got ${String(costs.batch)}`);
270
+ }
271
+ if (costs?.retentionMonths !== undefined)
272
+ assertBillingRetention('cloudflareCosts.retentionMonths', costs.retentionMonths);
273
+ const costLookback = costs?.lookbackDays;
274
+ if (costLookback !== undefined && !(Number.isInteger(costLookback) && costLookback >= 1 && costLookback <= COST_ROLLUP_MAX_LOOKBACK_DAYS)) {
275
+ throw substratError('validation_failed', `cloudflareCosts.lookbackDays must be a whole number of days from 1 to ${COST_ROLLUP_MAX_LOOKBACK_DAYS}, got ${String(costLookback)}`);
276
+ }
277
+ for (const name of ['settleMs', 'retryMs']) {
278
+ const ms = costs?.[name];
279
+ if (ms !== undefined && !(Number.isFinite(ms) && ms >= 0)) {
280
+ throw substratError('validation_failed', `cloudflareCosts.${name} must be a non-negative number of ms, got ${String(ms)}`);
281
+ }
282
+ }
283
+ if (costs?.readTimeoutMs !== undefined)
284
+ assertPositiveMs('cloudflareCosts.readTimeoutMs', costs.readTimeoutMs);
285
+ const objectsBatch = options.scopeObjects?.batch;
286
+ if (objectsBatch !== undefined)
287
+ assertRowLimit('scopeObjects.batch', objectsBatch);
254
288
  const snapshot = options.meterSnapshot;
255
289
  if (snapshot?.pruneBatch !== undefined)
256
290
  assertRowLimit('meterSnapshot.pruneBatch', snapshot.pruneBatch);
@@ -331,6 +365,7 @@ function scopeReaderFor(admin, actor, report) {
331
365
  }
332
366
  export async function runPlatformSweep(host, options) {
333
367
  assertSweepBatches(options);
368
+ assertConnectorSweepOptions(options);
334
369
  const concurrency = options.concurrency ?? 8;
335
370
  const report = {
336
371
  scopesDrained: 0,
@@ -338,6 +373,8 @@ export async function runPlatformSweep(host, options) {
338
373
  connectionsSwept: 0,
339
374
  connectionLandings: options.connectionLandings ? { granted: 0, bound: 0, failed: 0 } : null,
340
375
  connectionsSkipped: 0,
376
+ connectionsPaused: 0,
377
+ connectionsBackingOff: 0,
341
378
  snapshotsReaped: 0,
342
379
  archivedScopesReaped: 0,
343
380
  tenantsReaped: 0,
@@ -353,6 +390,8 @@ export async function runPlatformSweep(host, options) {
353
390
  storage: null,
354
391
  orphanAttachments: null,
355
392
  requestRollup: null,
393
+ scopeObjects: null,
394
+ cloudflareCosts: null,
356
395
  meterSnapshot: null,
357
396
  errors: [],
358
397
  };
@@ -751,13 +790,21 @@ export async function runPlatformSweep(host, options) {
751
790
  // (`kind === 'preview'` with no source — a source-less environment, #509 ask (b)).
752
791
  // Enumerate every scope regardless of status — a preview is `active` in the directory —
753
792
  // and compare ISO instants lexically, the same move the tuple checker's `live()` makes.
754
- // `deleteSnapshot` re-checks this same predicate, so a mislabeled row fails closed there,
755
- // never silently deletes.
793
+ // The listing is a candidate set, not a verdict: each predicate is judged again before
794
+ // the delete. `deleteSnapshot` refuses a row that is not a fork or a preview, so a
795
+ // mislabeled row fails closed there. The expiry is judged again by the reap claim
796
+ // (`beginScopeScriptReap` with `expiredBy`, #3314), in the same directory write that takes
797
+ // the claim and before anything is wiped: a fork pinned or renewed after this listing is
798
+ // refused, and once claimed, a pin is refused instead. A `deleteSnapshotFn` takes the same
799
+ // claim (the control plane's `reapExpiredSnapshot` does).
756
800
  const now = new Date().toISOString();
757
801
  const scopes = await listScopes();
758
802
  const expired = scopes.filter((s) => (s.forkedFrom !== null || s.kind === 'preview') && s.expiresAt !== null && s.expiresAt <= now);
759
803
  const reap = options.deleteSnapshotFn ??
760
- ((tenantId, scopeId) => host.deleteSnapshot(options.actor, tenantId, scopeId));
804
+ (async (tenantId, scopeId) => {
805
+ await host.admin.beginScopeScriptReap(options.actor, tenantId, scopeId, { expiredBy: now });
806
+ await host.deleteSnapshot(options.actor, tenantId, scopeId);
807
+ });
761
808
  await mapBounded(expired, concurrency, async (s) => {
762
809
  try {
763
810
  await reap(s.tenantId, s.id);
@@ -841,156 +888,12 @@ export async function runPlatformSweep(host, options) {
841
888
  }
842
889
  });
843
890
  }
844
- const connections = await host.admin.listConnections(options.actor, {});
845
- const landings = options.connectionLandings ? new LandingPass(host, options.actor, options.connectionLandings, concurrency, listScopes) : null;
846
- await mapBounded(connections, concurrency, async (c) => {
847
- // #1232: the connection's durable sweep record. A connection row carries no
848
- // scope (a connection spans scopes by construction) and no version.
849
- const record = (outcome, extra) => options.recordSweepRun?.({
850
- kind: 'connector',
851
- unit: c.id,
852
- outcome,
853
- tenantId: c.tenantId,
854
- vertical: c.vertical,
855
- operation: `sweep.connector:${c.provider}`,
856
- connectionId: c.id,
857
- ...extra,
858
- });
859
- if (c.revokedAt !== null) {
860
- // Terminal — nothing to reconcile through it, and deliberately unrecorded:
861
- // a revoked connection is not "waiting to be swept", and a skipped row per
862
- // pass forever would be noise every strip has to filter back out.
863
- report.connectionsSkipped += 1;
864
- return;
865
- }
866
- const sweeper = options.sweepers[c.provider] ?? options.sweeperFor?.(c);
867
- if (!sweeper) {
868
- report.connectionsSkipped += 1;
869
- // Recorded, unlike the revoked case: "bound but no sweeper registered" is a
870
- // live connection nothing will ever poll — exactly the declared-vs-observed
871
- // finding the signals views exist to surface.
872
- record('skipped');
873
- return;
874
- }
875
- const started = Date.now();
876
- // #2316: what the running versions declare, granted and bound before the poll reads bindings.
877
- // Never sinks the sweep: its failures join the poll's on the connection's row.
878
- const landed = landings ? await landings.apply(c).catch((err) => ({ granted: [], bound: [], failed: [{ scopeId: '*', error: message(err) }] })) : null;
879
- if (landed && report.connectionLandings) {
880
- report.connectionLandings.granted += landed.granted.length;
881
- report.connectionLandings.bound += landed.bound.length;
882
- report.connectionLandings.failed += landed.failed.length;
883
- }
884
- const landingFailed = landed?.failed ?? [];
885
- // #2316: the row is the connection's tenant's to read, so it says what became of the sweep, in
886
- // the platform's words with counts, under one reference; the text (a provider's answer, a landing
887
- // refusal) is staff's row under the same reference, or the report's when nothing files one.
888
- //
889
- // #3235: a failure that names the scope it belongs to is filed as a PAIR under that reference: a
890
- // row for the connection's tenant, carrying the scope, so that app's Failures view and fleet
891
- // health count it, saying in the platform's words what became of that binding (with the
892
- // connector's `said` when it gave one); and staff's row with the failure's own text. Only a
893
- // failure with no scope (a sweep that threw, a landing pass that could not start) stays staff's
894
- // alone, as before.
895
- const fail = (said, failures, neutralDetail) => {
896
- const reference = ulid();
897
- if (options.recordFailure) {
898
- const operation = `sweep.connector:${c.provider}`;
899
- const opening = `connection ${c.id} of tenant ${c.tenantId}: `;
900
- const unscoped = [];
901
- // One pair per scope: a scope can fail twice in one pass (a declared landing, then its
902
- // poll), and two pairs sharing the reference, the operation and the scope could not be told
903
- // apart by a reader that pairs them.
904
- const byScope = new Map();
905
- for (const f of failures) {
906
- const scope = f.scopeId === undefined ? undefined : scopeIdSchema.safeParse(f.scopeId);
907
- if (!scope?.success) {
908
- unscoped.push(f.scopeId === undefined ? f.error : `scope ${f.scopeId}: ${f.error}`);
909
- continue;
910
- }
911
- byScope.set(scope.data, [...(byScope.get(scope.data) ?? []), f]);
912
- }
913
- for (const [scope, fs] of byScope) {
914
- options.recordFailure(withheldOpsFailure({ operation, stage: 'sweep', tenantId: c.tenantId, scopeId: scope, vertical: c.vertical }, fs.map((f) => f.error).join('; '), (ref) => `${[...new Set(fs.map((f) => tenantSentence(c.provider, f)))].join('; ')} (reference ${ref})`, reference, `${opening}scope ${scope}: `));
915
- }
916
- if (unscoped.length > 0) {
917
- options.recordFailure(withheldStaffFailure({ operation, stage: 'sweep', vertical: c.vertical }, unscoped.join('; '), reference, opening));
918
- }
919
- }
920
- else {
921
- for (const f of failures)
922
- report.errors.push({ kind: 'sweep', id: c.id, error: f.scopeId === undefined ? f.error : `scope ${f.scopeId}: ${f.error}` });
923
- }
924
- const failureText = `${said.join('; ')} (reference ${reference})`;
925
- record('failed', { error: neutralDetail ? `Unsupported bindings: ${neutralDetail}\n${failureText}` : failureText, elapsedMs: Date.now() - started });
926
- };
927
- const landingSaid = landingFailed.length > 0 ? [`${counted(landingFailed.length, 'declared landing')} could not be granted or bound`] : [];
928
- const landingFailures = landingFailed.map((f) => ({ ...f, landing: true }));
929
- const everyMinutes = options.sweepEveryMinutes?.[c.provider];
930
- if (everyMinutes) {
931
- try {
932
- const [ok, failed, unsupported] = await Promise.all([
933
- host.admin.listSweepRuns(options.actor, { kind: 'connector', unit: c.id, outcome: 'ok', limit: 1 }),
934
- host.admin.listSweepRuns(options.actor, { kind: 'connector', unit: c.id, outcome: 'failed', limit: 1 }),
935
- host.admin.listSweepRuns(options.actor, { kind: 'connector', unit: c.id, outcome: 'unsupported', limit: 1 }),
936
- ]);
937
- // Ignore skipped rows and future-dated receipts: neither proves a poll inside this interval.
938
- const now = Date.now();
939
- const lastAttempt = Math.max(0, ...[ok[0], failed[0], unsupported[0]].filter((row) => row !== undefined).map((row) => Date.parse(row.at)).filter((at) => at <= now));
940
- if (now - lastAttempt < everyMinutes * 60_000) {
941
- if (landingFailed.length > 0)
942
- fail(landingSaid, landingFailures);
943
- report.connectionsSkipped += 1;
944
- return;
945
- }
946
- }
947
- catch (err) {
948
- // Without the ledger's clock, do not risk spending the provider's daily allowance.
949
- if (landingFailed.length > 0)
950
- fail(landingSaid, landingFailures);
951
- report.errors.push({ kind: 'sweep', id: c.id, error: `cannot read connector cadence: ${message(err)}` });
952
- report.connectionsSkipped += 1;
953
- return;
954
- }
955
- }
956
- let result;
957
- try {
958
- // #2498: a sized stream body the connector sends reaches the injected fetch converted.
959
- result = await sweeper(host, c.id, { fetch: fetchLikeOf(options.fetch) });
960
- }
961
- catch (err) {
962
- // The landing step's failures, if any, belong on the same row as the poll's throw.
963
- fail([...landingSaid, 'the sweep did not complete'], [...landingFailures, { error: message(err) }]);
964
- return;
965
- }
966
- const answer = options.connectionLandings && binderOf(options.connectionLandings, c) ? connectorSweepAnswerOf(result) : null;
967
- // Skipped only when the row below is `unsupported`: a failed landing makes it `failed`, and swept.
968
- if (answer && answer.found > 0 && answer.unsupported?.length === answer.found && answer.failed.length === 0 && landingFailed.length === 0) {
969
- report.connectionsSkipped += 1;
970
- }
971
- else {
972
- report.connectionsSwept += 1;
973
- }
974
- // #2316: a resolved sweep is not a landed one. A binding the connector could not land, or a
975
- // landing the platform could not seat, fails the row; a poll that found nothing to poll is
976
- // `skipped`, which a console reads as "nothing polls this connection". A mixed connection
977
- // records the result of its polled bindings and keeps unsupported bindings in the detail.
978
- const pollFailed = answer?.failed ?? [];
979
- const unsupported = answer?.unsupported ?? [];
980
- const unsupportedDetail = unsupported.map((u) => `scope ${u.scopeId}: ${u.reason}`).join('; ');
981
- if (landingFailed.length > 0 || pollFailed.length > 0) {
982
- fail([...landingSaid, ...(pollFailed.length > 0 ? [`${pollFailed.length} of ${counted(answer.found, 'binding')} did not land${saidOf(pollFailed)}`] : [])], [...landingFailures, ...pollFailed], unsupportedDetail || undefined);
983
- }
984
- else if (answer && answer.found === 0) {
985
- record('skipped', { error: NO_BINDING, elapsedMs: Date.now() - started });
986
- }
987
- else if (unsupported.length > 0 && answer?.found === unsupported.length) {
988
- record('unsupported', { error: unsupportedDetail, elapsedMs: Date.now() - started });
989
- }
990
- else {
991
- record('ok', { ...(unsupportedDetail ? { error: unsupportedDetail } : {}), elapsedMs: Date.now() - started });
992
- }
993
- });
891
+ // -- connector sweeps (#574, #3324) ------------------------------------------
892
+ // Skipped when the caller runs them itself, after everything else (`sweepConnectors: false`
893
+ // and `runConnectorSweep`): a connection's sweep reads a third party's data through this
894
+ // isolate, and a sweep that exhausts it takes every phase still to run with it.
895
+ if (options.sweepConnectors !== false)
896
+ await sweepConnections(host, options, report, listScopes, concurrency);
994
897
  // -- cross-vertical event delivery (#1705) ------------------------------------
995
898
  // After the provision reconcile, so a peer grant a new version declares is seated before
996
899
  // the edge that needs it is read. Before the Tier-2 drain, which only ships each scope's
@@ -1108,6 +1011,20 @@ export async function runPlatformSweep(host, options) {
1108
1011
  typeof host.admin.listRequestRollupDays === 'function') {
1109
1012
  report.requestRollup = await sweepRequestRollup(host.admin, options.actor, options.requestRollup, report);
1110
1013
  }
1014
+ // -- scope object ids, then the daily Cloudflare cost rollup (#3316) ------------
1015
+ // After the request rollup, for its reason: both wait on outside services and nothing in the
1016
+ // pass depends on them. Object ids first, so a scope provisioned since the last pass is already
1017
+ // mapped when a day that holds it is attributed.
1018
+ if (options.scopeObjects &&
1019
+ typeof host.admin.listScopeObjectsDue === 'function' &&
1020
+ typeof host.admin.recordScopeObject === 'function') {
1021
+ report.scopeObjects = await sweepScopeObjects(host.admin, options.actor, options.scopeObjects, report);
1022
+ }
1023
+ if (options.cloudflareCosts &&
1024
+ typeof host.admin.recordCostDay === 'function' &&
1025
+ typeof host.admin.listCostRollupDays === 'function') {
1026
+ report.cloudflareCosts = await sweepCostRollup(host.admin, options.actor, options.cloudflareCosts, report);
1027
+ }
1111
1028
  // -- drain the staff access log to Tier 2, then prune it (K-24, §4.4) --------
1112
1029
  // LAST, deliberately: every phase above reads the directory through the audited
1113
1030
  // seam, so each one writes access rows. Running the drain last means a pass ships
@@ -1803,22 +1720,30 @@ function skippedOf(read, refused) {
1803
1720
  */
1804
1721
  async function sweepAccessLog(host, options, sink, out) {
1805
1722
  const batch = options.accessLogBatch ?? ACCESS_LOG_BATCH;
1806
- const pending = await host.admin.accessLog(options.actor, {
1807
- drained: false,
1808
- order: 'asc', // oldest first — the window closes from the back
1809
- limit: batch,
1810
- });
1811
- if (pending.length > 0) {
1812
- const { ref } = await sink.ship(pending);
1813
- out.shipped = pending.length;
1814
- out.ref = ref;
1815
- // The batch's last id IS the watermark: ULID order is chronological and the log is
1816
- // append-only, so rows written during the shipment sort strictly after it and are
1817
- // left for the next tick rather than being stamped unshipped.
1818
- const upToId = pending[pending.length - 1].id;
1819
- out.marked = await host.admin.markAccessLogDrained(options.actor, upToId, instant.parse(new Date().toISOString()));
1723
+ const batches = options.accessLogBatchesPerPass ?? ACCESS_LOG_BATCHES_PER_PASS;
1724
+ // #3326: batch after batch while each comes back full, up to `batches`. Each one is a whole
1725
+ // ship→stamp→prune cycle, so a throw in the third leaves the first two shipped and pruned,
1726
+ // and the report counts what really happened.
1727
+ for (let i = 0; i < batches; i++) {
1728
+ const pending = await host.admin.accessLog(options.actor, {
1729
+ drained: false,
1730
+ order: 'asc', // oldest first — the window closes from the back
1731
+ limit: batch,
1732
+ });
1733
+ if (pending.length > 0) {
1734
+ const { ref } = await sink.ship(pending);
1735
+ out.shipped += pending.length;
1736
+ out.ref = ref;
1737
+ // The batch's last id IS the watermark: ULID order is chronological and the log is
1738
+ // append-only, so rows written during the shipment sort strictly after it and are
1739
+ // left for the next batch rather than being stamped unshipped.
1740
+ const upToId = pending[pending.length - 1].id;
1741
+ out.marked += await host.admin.markAccessLogDrained(options.actor, upToId, instant.parse(new Date().toISOString()));
1742
+ }
1743
+ out.pruned += await host.admin.pruneAccessLog(options.actor, batch);
1744
+ if (pending.length < batch)
1745
+ return;
1820
1746
  }
1821
- out.pruned = await host.admin.pruneAccessLog(options.actor, batch);
1822
1747
  }
1823
1748
  /**
1824
1749
  * Drive `runPlatformSweep` on a self-rescheduling timer — the node/long-lived
@@ -2108,6 +2033,102 @@ async function sweepRequestRollup(admin, actor, rollup, report) {
2108
2033
  }
2109
2034
  return out;
2110
2035
  }
2036
+ /**
2037
+ * One pass of the scope-object phase (#3316): ask each due scope's data script for its object id,
2038
+ * one at a time, and record the answer or the failure. Only a failure to read the due list itself
2039
+ * reaches `errors`; a scope that cannot answer waits `retryMs` and shows in the report.
2040
+ */
2041
+ async function sweepScopeObjects(admin, actor, options, report) {
2042
+ const out = { asked: 0, recorded: 0, failed: 0, failures: [] };
2043
+ try {
2044
+ const due = await admin.listScopeObjectsDue(actor, {
2045
+ limit: options.batch ?? SCOPE_OBJECTS_PER_PASS,
2046
+ retryMs: options.retryMs ?? SCOPE_OBJECT_RETRY_MS,
2047
+ });
2048
+ for (const target of due) {
2049
+ out.asked += 1;
2050
+ const attemptedAt = new Date().toISOString();
2051
+ try {
2052
+ const objectId = await options.read(target);
2053
+ await admin.recordScopeObject(actor, { ...target, attemptedAt, objectId });
2054
+ out.recorded += 1;
2055
+ }
2056
+ catch (err) {
2057
+ out.failed += 1;
2058
+ const error = message(err);
2059
+ if (out.failures.length < 3)
2060
+ out.failures.push(`${target.scopeId}: ${error}`);
2061
+ await admin.recordScopeObject(actor, { ...target, attemptedAt, error }).catch(() => undefined);
2062
+ }
2063
+ }
2064
+ }
2065
+ catch (err) {
2066
+ report.errors.push({ kind: 'scope-objects', id: 'directory', error: message(err) });
2067
+ }
2068
+ return out;
2069
+ }
2070
+ /**
2071
+ * One pass of the Cloudflare cost rollup (#3316): the request rollup's loop (`sweepRequestRollup`)
2072
+ * over Cloudflare's analytics, read one day at a time, oldest first. A standing failure is reported
2073
+ * when its run begins and kept on the ledger after that.
2074
+ */
2075
+ async function sweepCostRollup(admin, actor, rollup, report) {
2076
+ const out = { due: 0, deferred: 0, read: 0, failed: 0, repeated: 0, streak: null, recorded: 0, pruned: 0 };
2077
+ const batch = rollup.batch ?? COST_ROLLUP_DAYS_PER_PASS;
2078
+ const months = rollup.retentionMonths === undefined ? BILLING_ROLLUP_RETENTION_MONTHS : rollup.retentionMonths;
2079
+ const now = rollup.now ?? (() => new Date().toISOString());
2080
+ try {
2081
+ const nowMs = Date.parse(now());
2082
+ if (batch > 0) {
2083
+ const reads = await admin.listCostRollupDays(actor);
2084
+ let previous = previousAttempt(reads);
2085
+ const due = requestRollupDueDays({
2086
+ nowMs,
2087
+ reads,
2088
+ lookbackDays: rollup.lookbackDays ?? COST_ROLLUP_LOOKBACK_DAYS,
2089
+ settleMs: rollup.settleMs ?? COST_ROLLUP_SETTLE_MS,
2090
+ retryMs: rollup.retryMs ?? COST_ROLLUP_RETRY_MS,
2091
+ horizon: billingRollupHorizon(nowMs, months),
2092
+ });
2093
+ const take = due.slice(0, batch);
2094
+ out.due = due.length;
2095
+ out.deferred = due.length - take.length;
2096
+ for (const day of take) {
2097
+ try {
2098
+ const usage = await withinDeadline(rollup.read(day), rollup.readTimeoutMs ?? COST_ROLLUP_READ_TIMEOUT_MS, 'the cost rollup read');
2099
+ out.recorded += (await admin.recordCostDay(actor, { day, attemptedAt: now(), usage })).recorded;
2100
+ out.read += 1;
2101
+ previous = NO_ATTEMPT;
2102
+ }
2103
+ catch (err) {
2104
+ const error = message(err);
2105
+ const attemptedAt = now();
2106
+ out.failed += 1;
2107
+ const { run, repeated } = extendRun(previous, error, attemptedAt);
2108
+ out.streak = run;
2109
+ if (repeated)
2110
+ out.repeated += 1;
2111
+ else
2112
+ report.errors.push({ kind: 'cost-rollup', id: day, error });
2113
+ await admin
2114
+ .recordCostDay(actor, { day, attemptedAt, error, failingSince: run.since, failingCount: run.failures })
2115
+ .catch(() => undefined);
2116
+ break;
2117
+ }
2118
+ }
2119
+ if (out.streak === null && previous.error !== null && previous.since !== null) {
2120
+ out.streak = { error: previous.error, since: previous.since, failures: previous.failures };
2121
+ }
2122
+ }
2123
+ if (typeof admin.pruneCostDays === 'function') {
2124
+ out.pruned = await admin.pruneCostDays(actor, rollup.pruneBatch ?? COST_ROLLUP_PRUNE_BATCH, months);
2125
+ }
2126
+ }
2127
+ catch (err) {
2128
+ report.errors.push({ kind: 'cost-rollup', id: 'directory', error: message(err) });
2129
+ }
2130
+ return out;
2131
+ }
2111
2132
  const DAY_MS = 86_400_000;
2112
2133
  /**
2113
2134
  * One pass of the meter-snapshot phase (#2501): take the snapshot of the UTC day the pass runs in,
@@ -2280,4 +2301,286 @@ async function sweepOrphanAttachmentWindow(host, options, phase, scopes, report)
2280
2301
  });
2281
2302
  return out;
2282
2303
  }
2304
+ /** The `error` of a paused connection's `skipped` row (#3324). */
2305
+ export const CONNECTOR_SWEEP_PAUSED = 'paused by an operator: this connection is not swept until the pause is lifted';
2306
+ /**
2307
+ * How long a connection whose sweep the pass died in is waited out (#3324): `baseDelayMs` after the
2308
+ * first, doubling with each attempt in a row that did not finish, never more than `maxDelayMs`.
2309
+ * 30 minutes, then an hour, two, …, a day. Jittered by `backoffAt`.
2310
+ */
2311
+ export const CONNECTOR_CRASH_BACKOFF = { baseDelayMs: 30 * 60_000, maxDelayMs: 24 * 3_600_000 };
2312
+ /** Attempts read back to count a run of unfinished ones; past this many the delay is at its cap anyway. */
2313
+ const CRASH_STREAK_WINDOW = 8;
2314
+ /**
2315
+ * The connection's attempts newer than its newest `connector` row: each is a sweep that started and
2316
+ * recorded no outcome, so the pass running it ended inside it. Null when the newest attempt has an
2317
+ * outcome after it (or there is none).
2318
+ */
2319
+ async function crashedAttemptsOf(host, actor, unit) {
2320
+ const [attempts, outcomes] = await Promise.all([
2321
+ host.admin.listSweepRuns(actor, { kind: 'connector-attempt', unit, limit: CRASH_STREAK_WINDOW }),
2322
+ host.admin.listSweepRuns(actor, { kind: 'connector', unit, limit: 1 }),
2323
+ ]);
2324
+ const last = outcomes[0];
2325
+ let streak = 0;
2326
+ for (const a of attempts) {
2327
+ if (last !== undefined && (a.at < last.at || (a.at === last.at && a.id < last.id)))
2328
+ break;
2329
+ streak += 1;
2330
+ }
2331
+ return streak === 0 ? null : { streak, lastAt: attempts[0].at };
2332
+ }
2333
+ /**
2334
+ * The connector sweep alone (#3324), for a caller that runs it after every other phase of its pass
2335
+ * (`runPlatformSweep` with `sweepConnectors: false`). A connection's sweep reads a third party's
2336
+ * data through the calling isolate; run last, one that exhausts it ends a pass with nothing left
2337
+ * to lose but the connections still in flight.
2338
+ */
2339
+ export async function runConnectorSweep(host, options) {
2340
+ assertConnectorSweepOptions(options);
2341
+ const report = {
2342
+ connectionsSwept: 0,
2343
+ connectionsSkipped: 0,
2344
+ connectionsPaused: 0,
2345
+ connectionsBackingOff: 0,
2346
+ connectionLandings: options.connectionLandings ? { granted: 0, bound: 0, failed: 0 } : null,
2347
+ errors: [],
2348
+ };
2349
+ await sweepConnections(host, options, report, scopeReaderFor(host.admin, options.actor, report), options.concurrency ?? 8);
2350
+ return report;
2351
+ }
2352
+ /** The budget and backoff options, refused when they could not bound anything. */
2353
+ function assertConnectorSweepOptions(options) {
2354
+ const budget = options.connectorBudget;
2355
+ if (budget?.maxBytes !== undefined && !(Number.isInteger(budget.maxBytes) && budget.maxBytes > 0)) {
2356
+ throw substratError('validation_failed', `connectorBudget.maxBytes must be a positive whole number of bytes, got ${String(budget.maxBytes)}`);
2357
+ }
2358
+ if (budget?.maxMs !== undefined)
2359
+ assertPositiveMs('connectorBudget.maxMs', budget.maxMs);
2360
+ for (const name of ['baseDelayMs', 'maxDelayMs']) {
2361
+ const ms = options.connectorCrashBackoff?.[name];
2362
+ if (ms !== undefined)
2363
+ assertPositiveMs(`connectorCrashBackoff.${name}`, ms);
2364
+ }
2365
+ }
2366
+ async function sweepConnections(host, options, report, listScopes, concurrency) {
2367
+ const clock = options.clock ?? Date.now;
2368
+ const budget = {
2369
+ maxBytes: options.connectorBudget?.maxBytes ?? CONNECTOR_SWEEP_MAX_BYTES,
2370
+ maxMs: options.connectorBudget?.maxMs ?? CONNECTOR_SWEEP_MAX_MS,
2371
+ };
2372
+ const crashBackoff = {
2373
+ maxAttempts: Number.MAX_SAFE_INTEGER,
2374
+ baseDelayMs: options.connectorCrashBackoff?.baseDelayMs ?? CONNECTOR_CRASH_BACKOFF.baseDelayMs,
2375
+ maxDelayMs: options.connectorCrashBackoff?.maxDelayMs ?? CONNECTOR_CRASH_BACKOFF.maxDelayMs,
2376
+ };
2377
+ const connections = await host.admin.listConnections(options.actor, {});
2378
+ const landings = options.connectionLandings ? new LandingPass(host, options.actor, options.connectionLandings, concurrency, listScopes) : null;
2379
+ await mapBounded(connections, concurrency, async (c) => {
2380
+ // #1232: the connection's durable sweep record. A connection row carries no
2381
+ // scope (a connection spans scopes by construction) and no version.
2382
+ const record = (outcome, extra) => options.recordSweepRun?.({
2383
+ kind: 'connector',
2384
+ unit: c.id,
2385
+ outcome,
2386
+ tenantId: c.tenantId,
2387
+ vertical: c.vertical,
2388
+ operation: `sweep.connector:${c.provider}`,
2389
+ connectionId: c.id,
2390
+ ...extra,
2391
+ });
2392
+ if (c.revokedAt !== null) {
2393
+ // Terminal — nothing to reconcile through it, and deliberately unrecorded:
2394
+ // a revoked connection is not "waiting to be swept", and a skipped row per
2395
+ // pass forever would be noise every strip has to filter back out.
2396
+ report.connectionsSkipped += 1;
2397
+ return;
2398
+ }
2399
+ // #3324: an operator's pause. Recorded, unlike a revoke: the connection is live and nothing
2400
+ // polls it, which is what a reader of its row should see, pass after pass, until it is lifted.
2401
+ if (options.pausedConnections?.has(c.id)) {
2402
+ report.connectionsPaused += 1;
2403
+ report.connectionsSkipped += 1;
2404
+ record('skipped', { error: CONNECTOR_SWEEP_PAUSED });
2405
+ return;
2406
+ }
2407
+ const sweeper = options.sweepers[c.provider] ?? options.sweeperFor?.(c);
2408
+ if (!sweeper) {
2409
+ report.connectionsSkipped += 1;
2410
+ // Recorded, unlike the revoked case: "bound but no sweeper registered" is a
2411
+ // live connection nothing will ever poll — exactly the declared-vs-observed
2412
+ // finding the signals views exist to surface.
2413
+ record('skipped');
2414
+ return;
2415
+ }
2416
+ // #3324: a sweep the pass died in left its attempt and no outcome. Waited out, exponentially and
2417
+ // capped, rather than run again on the next pass: run on every pass, it was every pass that died.
2418
+ if (options.recordSweepAttempt) {
2419
+ let crashed;
2420
+ try {
2421
+ crashed = await crashedAttemptsOf(host, options.actor, c.id);
2422
+ }
2423
+ catch (err) {
2424
+ // Without the record, a sweep that kills its pass would be run again on every one.
2425
+ report.errors.push({ kind: 'sweep', id: c.id, error: `cannot read the connection's sweep attempts: ${message(err)}` });
2426
+ report.connectionsSkipped += 1;
2427
+ return;
2428
+ }
2429
+ if (crashed) {
2430
+ const retryAt = Date.parse(backoffAt(crashed.streak, crashBackoff, new Date(crashed.lastAt)));
2431
+ const said = `the last ${counted(crashed.streak, 'sweep')} of connection ${c.id} did not finish: the pass running ${crashed.streak === 1 ? 'it' : 'them'} ended first`;
2432
+ if (clock() < retryAt) {
2433
+ report.connectionsBackingOff += 1;
2434
+ report.connectionsSkipped += 1;
2435
+ report.errors.push({ kind: 'sweep', id: c.id, error: `${said}; next attempt after ${new Date(retryAt).toISOString()}` });
2436
+ return;
2437
+ }
2438
+ // Filed once per retry, so the failure digest names a connection whose sweeps keep dying.
2439
+ options.recordFailure?.(withheldStaffFailure({ operation: `sweep.connector:${c.provider}`, stage: 'sweep', vertical: c.vertical }, `${said}; trying again`, ulid(), `connection ${c.id} of tenant ${c.tenantId}: `));
2440
+ }
2441
+ }
2442
+ const started = Date.now();
2443
+ // #2316: what the running versions declare, granted and bound before the poll reads bindings.
2444
+ // Never sinks the sweep: its failures join the poll's on the connection's row.
2445
+ const landed = landings ? await landings.apply(c).catch((err) => ({ granted: [], bound: [], failed: [{ scopeId: '*', error: message(err) }] })) : null;
2446
+ if (landed && report.connectionLandings) {
2447
+ report.connectionLandings.granted += landed.granted.length;
2448
+ report.connectionLandings.bound += landed.bound.length;
2449
+ report.connectionLandings.failed += landed.failed.length;
2450
+ }
2451
+ const landingFailed = landed?.failed ?? [];
2452
+ // #2316: the row is the connection's tenant's to read, so it says what became of the sweep, in
2453
+ // the platform's words with counts, under one reference; the text (a provider's answer, a landing
2454
+ // refusal) is staff's row under the same reference, or the report's when nothing files one.
2455
+ //
2456
+ // #3235: a failure that names the scope it belongs to is filed as a PAIR under that reference: a
2457
+ // row for the connection's tenant, carrying the scope, so that app's Failures view and fleet
2458
+ // health count it, saying in the platform's words what became of that binding (with the
2459
+ // connector's `said` when it gave one); and staff's row with the failure's own text. Only a
2460
+ // failure with no scope (a sweep that threw, a landing pass that could not start) stays staff's
2461
+ // alone, as before.
2462
+ const fail = (said, failures, neutralDetail) => {
2463
+ const reference = ulid();
2464
+ if (options.recordFailure) {
2465
+ const operation = `sweep.connector:${c.provider}`;
2466
+ const opening = `connection ${c.id} of tenant ${c.tenantId}: `;
2467
+ const unscoped = [];
2468
+ // One pair per scope: a scope can fail twice in one pass (a declared landing, then its
2469
+ // poll), and two pairs sharing the reference, the operation and the scope could not be told
2470
+ // apart by a reader that pairs them.
2471
+ const byScope = new Map();
2472
+ for (const f of failures) {
2473
+ const scope = f.scopeId === undefined ? undefined : scopeIdSchema.safeParse(f.scopeId);
2474
+ if (!scope?.success) {
2475
+ unscoped.push(f.scopeId === undefined ? f.error : `scope ${f.scopeId}: ${f.error}`);
2476
+ continue;
2477
+ }
2478
+ byScope.set(scope.data, [...(byScope.get(scope.data) ?? []), f]);
2479
+ }
2480
+ for (const [scope, fs] of byScope) {
2481
+ options.recordFailure(withheldOpsFailure({ operation, stage: 'sweep', tenantId: c.tenantId, scopeId: scope, vertical: c.vertical }, fs.map((f) => f.error).join('; '), (ref) => `${[...new Set(fs.map((f) => tenantSentence(c.provider, f)))].join('; ')} (reference ${ref})`, reference, `${opening}scope ${scope}: `));
2482
+ }
2483
+ if (unscoped.length > 0) {
2484
+ options.recordFailure(withheldStaffFailure({ operation, stage: 'sweep', vertical: c.vertical }, unscoped.join('; '), reference, opening));
2485
+ }
2486
+ }
2487
+ else {
2488
+ for (const f of failures)
2489
+ report.errors.push({ kind: 'sweep', id: c.id, error: f.scopeId === undefined ? f.error : `scope ${f.scopeId}: ${f.error}` });
2490
+ }
2491
+ const failureText = `${said.join('; ')} (reference ${reference})`;
2492
+ record('failed', { error: neutralDetail ? `Unsupported bindings: ${neutralDetail}\n${failureText}` : failureText, elapsedMs: Date.now() - started });
2493
+ };
2494
+ const landingSaid = landingFailed.length > 0 ? [`${counted(landingFailed.length, 'declared landing')} could not be granted or bound`] : [];
2495
+ const landingFailures = landingFailed.map((f) => ({ ...f, landing: true }));
2496
+ const everyMinutes = options.sweepEveryMinutes?.[c.provider];
2497
+ if (everyMinutes) {
2498
+ try {
2499
+ const [ok, failed, unsupported] = await Promise.all([
2500
+ host.admin.listSweepRuns(options.actor, { kind: 'connector', unit: c.id, outcome: 'ok', limit: 1 }),
2501
+ host.admin.listSweepRuns(options.actor, { kind: 'connector', unit: c.id, outcome: 'failed', limit: 1 }),
2502
+ host.admin.listSweepRuns(options.actor, { kind: 'connector', unit: c.id, outcome: 'unsupported', limit: 1 }),
2503
+ ]);
2504
+ // Ignore skipped rows and future-dated receipts: neither proves a poll inside this interval.
2505
+ const now = Date.now();
2506
+ const lastAttempt = Math.max(0, ...[ok[0], failed[0], unsupported[0]].filter((row) => row !== undefined).map((row) => Date.parse(row.at)).filter((at) => at <= now));
2507
+ if (now - lastAttempt < everyMinutes * 60_000) {
2508
+ if (landingFailed.length > 0)
2509
+ fail(landingSaid, landingFailures);
2510
+ report.connectionsSkipped += 1;
2511
+ return;
2512
+ }
2513
+ }
2514
+ catch (err) {
2515
+ // Without the ledger's clock, do not risk spending the provider's daily allowance.
2516
+ if (landingFailed.length > 0)
2517
+ fail(landingSaid, landingFailures);
2518
+ report.errors.push({ kind: 'sweep', id: c.id, error: `cannot read connector cadence: ${message(err)}` });
2519
+ report.connectionsSkipped += 1;
2520
+ return;
2521
+ }
2522
+ }
2523
+ // #3324: the attempt, noted before the work and awaited, so a pass that dies inside the sweep
2524
+ // leaves it behind. A note that cannot be written holds the sweep back a pass: without it, a
2525
+ // sweep that kills its pass would be run again on every one.
2526
+ if (options.recordSweepAttempt) {
2527
+ try {
2528
+ await options.recordSweepAttempt({
2529
+ kind: 'connector-attempt',
2530
+ unit: c.id,
2531
+ outcome: 'started',
2532
+ tenantId: null,
2533
+ vertical: c.vertical,
2534
+ operation: `sweep.connector:${c.provider}`,
2535
+ connectionId: c.id,
2536
+ });
2537
+ }
2538
+ catch (err) {
2539
+ if (landingFailed.length > 0)
2540
+ fail(landingSaid, landingFailures);
2541
+ report.errors.push({ kind: 'sweep', id: c.id, error: `cannot note the sweep's attempt, so it waits for the next pass: ${message(err)}` });
2542
+ report.connectionsSkipped += 1;
2543
+ return;
2544
+ }
2545
+ }
2546
+ let result;
2547
+ try {
2548
+ // #2498: a sized stream body the connector sends reaches the injected fetch converted.
2549
+ // #3324: and the connection reads no more than its share of the pass (`budgetedFetch`).
2550
+ result = await sweeper(host, c.id, { fetch: budgetedFetch(fetchLikeOf(options.fetch), { ...budget, clock }) });
2551
+ }
2552
+ catch (err) {
2553
+ // The landing step's failures, if any, belong on the same row as the poll's throw.
2554
+ fail([...landingSaid, 'the sweep did not complete'], [...landingFailures, { error: message(err) }]);
2555
+ return;
2556
+ }
2557
+ const answer = options.connectionLandings && binderOf(options.connectionLandings, c) ? connectorSweepAnswerOf(result) : null;
2558
+ // Skipped only when the row below is `unsupported`: a failed landing makes it `failed`, and swept.
2559
+ if (answer && answer.found > 0 && answer.unsupported?.length === answer.found && answer.failed.length === 0 && landingFailed.length === 0) {
2560
+ report.connectionsSkipped += 1;
2561
+ }
2562
+ else {
2563
+ report.connectionsSwept += 1;
2564
+ }
2565
+ // #2316: a resolved sweep is not a landed one. A binding the connector could not land, or a
2566
+ // landing the platform could not seat, fails the row; a poll that found nothing to poll is
2567
+ // `skipped`, which a console reads as "nothing polls this connection". A mixed connection
2568
+ // records the result of its polled bindings and keeps unsupported bindings in the detail.
2569
+ const pollFailed = answer?.failed ?? [];
2570
+ const unsupported = answer?.unsupported ?? [];
2571
+ const unsupportedDetail = unsupported.map((u) => `scope ${u.scopeId}: ${u.reason}`).join('; ');
2572
+ if (landingFailed.length > 0 || pollFailed.length > 0) {
2573
+ fail([...landingSaid, ...(pollFailed.length > 0 ? [`${pollFailed.length} of ${counted(answer.found, 'binding')} did not land${saidOf(pollFailed)}`] : [])], [...landingFailures, ...pollFailed], unsupportedDetail || undefined);
2574
+ }
2575
+ else if (answer && answer.found === 0) {
2576
+ record('skipped', { error: NO_BINDING, elapsedMs: Date.now() - started });
2577
+ }
2578
+ else if (unsupported.length > 0 && answer?.found === unsupported.length) {
2579
+ record('unsupported', { error: unsupportedDetail, elapsedMs: Date.now() - started });
2580
+ }
2581
+ else {
2582
+ record('ok', { ...(unsupportedDetail ? { error: unsupportedDetail } : {}), elapsedMs: Date.now() - started });
2583
+ }
2584
+ });
2585
+ }
2283
2586
  //# sourceMappingURL=platform-sweep.js.map