From b6250efd3e06330d378d789d8f97e610d0e727c9 Mon Sep 17 00:00:00 2001 From: marcoloco Date: Sat, 26 Sep 2026 22:16:23 +0200 Subject: [PATCH 1/9] =?UTF-8?q?site:=20'False=20alarms=20we=20caught'=20?= =?UTF-8?q?=E2=80=94=20the=20controls=20tripped=20the=20detector=20and=20w?= =?UTF-8?q?ere=20stopped=20before=20publication?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_017KN8pr3M1ayKPTNRcNSc2D --- src/watch/site-render.ts | 4 ++-- test/site-export.test.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/watch/site-render.ts b/src/watch/site-render.ts index e4d9ed9..1ed4aad 100644 --- a/src/watch/site-render.ts +++ b/src/watch/site-render.ts @@ -366,7 +366,7 @@ export function landingPage(c: Ctx, findings: Finding[]): { head: string; body: const fp = s.falsePositiveRate.overall; const num = (v: string, k: string, title = "") => `
${esc(k)}
${v}
`; - const wrongTitle = fp.decided ? `${fp.falsePositives} of the ${fp.decided} cases we could settle turned out wrong. We keep them on the site.` : "No case has been settled yet."; + const wrongTitle = fp.decided ? `${fp.falsePositives} of the ${fp.decided} cases we could settle were false alarms — caught by our own checks before anything was published. We keep them on the site.` : "No case has been settled yet."; const flow: [string, string][] = [ ["Spot", "satellites flag a change"], ["Double-check", "a second, separate source must agree"], @@ -390,7 +390,7 @@ export function landingPage(c: Ctx, findings: Finding[]): { head: string; body:
${num(String(s.cases.public), "Cases published")} - ${num(fp.decided ? `${fp.falsePositives} of ${fp.decided}` : "0", "Times we were wrong", wrongTitle)} + ${num(fp.decided ? `${fp.falsePositives} of ${fp.decided}` : "0", "False alarms we caught", wrongTitle)} ${num(s.lastSweep ? time(s.lastSweep.at, plainDate(s.lastSweep.at), "ago") : "—", "Last check", s.lastSweep ? `${s.lastSweep.at.replace("T", " ").slice(0, 16)} UTC` : "")}
diff --git a/test/site-export.test.ts b/test/site-export.test.ts index 383a748..42eb3f0 100644 --- a/test/site-export.test.ts +++ b/test/site-export.test.ts @@ -182,7 +182,7 @@ test("export writes a self-contained, relative, server-rendered site", async () assert.match(landing, new RegExp(`

${SITE.oneLine.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}

`)); assert.equal(landing.match(/class="pin pin--pub/g)?.length, 1); assert.equal(landing.match(/class="pin pin--open/g)?.length, 3, "two seeded candidates-in-progress + the hostile candidate"); - for (const k of ["Cases published", "Times we were wrong", "Last check", "Latest cases", "How the planet is doing", "Being checked", "34 hectares — about 48 football fields"]) { + for (const k of ["Cases published", "False alarms we caught", "Last check", "Latest cases", "How the planet is doing", "Being checked", "34 hectares — about 48 football fields"]) { assert.ok(landing.includes(k), `landing lacks ${k}`); } // …and nothing for developers: no commands, hashes, rule ids, tiers, feeds or JSON links. From 987719e059b57d42f1dc1204c8bb24a1f61be66a Mon Sep 17 00:00:00 2001 From: marcoloco Date: Sat, 26 Sep 2026 22:18:04 +0200 Subject: [PATCH 2/9] watch: sharded, time-budgeted, quota-governed sweeps for ~350 generated AOIs - kernel: --shard i/n (sha256(aoi.id, rule) mod n), least-recently-swept ordering, deadline-based budget stop ('budget exhausted: k of n pairs done', exit 0) - quota.ts: per-UTC-day caps (EARTHDECK_MAX_{CDSE,GFW,FIRMS}_CALLS, analyst cases/USD) persisted in watch/quota.json; skips as quota:; 429/403-quota marks provider exhausted for the run; ToolError carries upstream status/body - analyst: --max defaults from EARTHDECK_MAX_ANALYST_CASES (daily cap), analyst_spend journal records, stops at EARTHDECK_MAX_ANALYST_USD per day - runner: watchlist all-generated | all-handwritten | generated/, shard, timeBudgetSec; sweeps get --time-budget = remaining - 90 s, SIGTERM backstop at -60 s - infra: 8 shard schedules per 6 h window + analyst/export/hand-written; caps in env; README schedule + quota tables; run-job.sh --shard/--time-budget Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017KN8pr3M1ayKPTNRcNSc2D --- infra/README.md | 98 ++++++++++++++++-- infra/earthdeck.yaml | 110 ++++++++++++++++---- scripts/run-job.sh | 19 +++- src/analyst/analyst.ts | 15 ++- src/analyst/cli.ts | 11 +- src/cli.ts | 1 + src/runner/core.ts | 71 +++++++++++-- src/runner/lambda.ts | 4 +- src/watch/journal.ts | 2 +- src/watch/kernel.ts | 86 ++++++++++++++-- src/watch/quota.ts | 205 ++++++++++++++++++++++++++++++++++++ src/watch/rules/types.ts | 3 + src/watch/run.ts | 45 +++++--- test/analyst.test.ts | 32 ++++++ test/runner.test.ts | 72 +++++++++++++ test/scale.test.ts | 217 +++++++++++++++++++++++++++++++++++++++ 16 files changed, 928 insertions(+), 63 deletions(-) create mode 100644 src/watch/quota.ts create mode 100644 test/scale.test.ts diff --git a/infra/README.md b/infra/README.md index 330dcee..34280a8 100644 --- a/infra/README.md +++ b/infra/README.md @@ -5,8 +5,8 @@ runs the scheduled watch sweeps on Lambda, keeps the signed findings ledger in S serves the static Earth Watch site at `https://earthdeck.marcsperzel.com/`. ``` - EventBridge Scheduler (UTC, every 6 h, staggered) - :00 amazon :10 congo-borneo :20 controls :30 methane :40 flaring :50 analyst +1h export + EventBridge Scheduler (UTC, every 6 h from 00/06/12/18, staggered) + +0:00…+1:10 generated shards 0–7 +1:20 analyst +1:30 export +1:40 hand-written lists │ async invoke, JSON payload ▼ SSM /earthdeck/* ──► Lambda "earthdeck" (Node 22, arm64, 900 s, 1 GB, concurrency 1) @@ -73,9 +73,26 @@ touched. Pause/resume all schedules: `EARTHDECK_SCHEDULES=DISABLED|ENABLED scrip ## How a run works -Payload: `{ "job": "sweep"|"analyst"|"export"|"all", "watchlist"?: "amazon"|"congo-borneo"|"controls"|"methane"|"flaring", "dryRun"?: true }` -(`watchlist`/`dryRun` only with `sweep`; `all` = five sweeps + analyst + export, manual use — -it may not fit in 900 s). +Payload: `{ "job": "sweep"|"analyst"|"export"|"all", "watchlist"?: W, "shard"?: "i/n", "timeBudgetSec"?: N, "dryRun"?: true }` +where `W` is a hand-written list (`amazon`|`congo-borneo`|`controls`|`methane`|`flaring` → +`watchlists/.json`), `all-handwritten` (those five), `all-generated` (every file in +`watchlists/generated/`) or `generated/` (`watchlists/generated/.json`). +`watchlist`/`shard`/`timeBudgetSec`/`dryRun` only with `sweep`; no `watchlist` = every +top-level `watchlists/*.json`. `all` = five hand-written sweeps + analyst + export, manual use — +it may not fit in 900 s. + +- **Every sweep in Lambda is time-budgeted**: the runner passes + `--time-budget` = remaining invocation time − 90 s (or `timeBudgetSec`, whichever is smaller) + to `node dist/cli.js watch --once`. The kernel stops opening new pairs when one more pair (as + slow as the slowest so far) would overrun, finishes the current one, writes watermarks / + journal / ledger as usual and exits 0 with `budget exhausted: k of n pairs done`. As a + backstop the child is SIGTERMed at remaining − 60 s, leaving the rest for verify + upload. +- **Shards**: `--shard i/n` keeps only pairs with `sha256(aoi.id, rule) mod n == i` — disjoint, + deterministic, independent of file order. Within a sweep, pairs run **least-recently-swept + first** (never-swept first of all, by watermark), so a budget- or quota-cut sweep resumes + where the last one left off and nothing starves. +- **Quotas** (below): pairs whose provider's daily cap is spent are `skipped` with reason + `quota:` (journaled, watermark untouched). - The ledger working copy is `ledger/` in the state bucket minus `ledger/checkpoints/` (the archive) and `ledger.key` (never stored). It is downloaded fresh every run. @@ -99,18 +116,77 @@ The AWS SDK v3 is **not** in the zip: the Lambda Node.js 22 runtime ships it. Th `@aws-sdk/client-*` packages are exact-pinned devDependencies for typechecking only; the runner loads them lazily (`import()`, falling back to `require` via `NODE_PATH`). +## Schedule + +Every 6 hours, windows starting 00:00 / 06:00 / 12:00 / 18:00 UTC (11 schedules, all behind +`SchedulesState`): + +| Offset | Schedule | Payload | +| --- | --- | --- | +| +0:00 | `earthdeck-sweep-shard-0` | `{"job":"sweep","watchlist":"all-generated","shard":"0/8"}` | +| +0:10 … +1:10 | `earthdeck-sweep-shard-1` … `-7` (every 10 min) | same, `shard` `1/8` … `7/8` | +| +1:20 | `earthdeck-analyst` | `{"job":"analyst"}` | +| +1:30 | `earthdeck-export` | `{"job":"export"}` | +| +1:40 | `earthdeck-sweep-handwritten` | `{"job":"sweep","watchlist":"all-handwritten"}` | + +- ~350 generated AOIs / 8 shards ≈ 44 pairs per shard; at 1.5 s politeness delay + a few + seconds of API time per pair that is ~5–8 min, inside the ~13 min budget. A shard that runs + long is cut by its budget and resumes least-recently-swept first next window. +- Slots are 10 min apart but a run may take up to 15: with concurrency 1 an overlapping + invocation is throttled and Lambda's async queue retries it (event age ≤ 6 h), so the chain + drifts later instead of dropping a run. Only one writer ever touches the ledger. +- The hand-written lists run after the export, so their findings are narrated/published in + the next window (≤ 6 h later). +- 44 invocations/day; the 14 h no-success alarm is unchanged. + +## Quotas + +Per-UTC-day caps, counted in the ledger's `watch/quota.json` (synced with the ledger, so they +hold across invocations) and set as function env vars in the template: + +| Env var | Default | Counts | +| --- | --- | --- | +| `EARTHDECK_MAX_CDSE_CALLS` | 60 | `eo_compare`, `methane_plumes`, `eo_*` tool calls (1 each) | +| `EARTHDECK_MAX_GFW_CALLS` | 400 | `forest_alerts` calls (1 each) | +| `EARTHDECK_MAX_FIRMS_CALLS` | 300 | FIRMS transactions: `fires_in` 1; `flaring` ⌈days/5⌉ × sources (30 d × 2 = 12) | +| `EARTHDECK_MAX_ANALYST_CASES` | 10 | findings the analyst takes on per day (also the `--max` default) | +| `EARTHDECK_MAX_ANALYST_USD` | 3 | analyst API spend per day; journaled as `analyst_spend` | + +A pair is skipped `quota:` when any provider its rule needs (from the rule's +`requires`) is spent — note `forest_loss` needs CDSE (for its NDVI confirmation), so it stops +when CDSE does. A call that would cross a cap mid-pair is refused (skip, not gap). An HTTP 429, +a 403 whose body says quota/limit, or FIRMS's "transaction limit" text marks that provider +exhausted for the rest of the run. + +Expected demand for ~350 AOIs (assumed mix — one rule each: 170 `forest_loss`, 90 +`fires_in_protected`, 45 `flaring`, 45 `methane_anomaly`; recompute when the generated lists +land): + +| Provider | Per pair | Per full pass | Per day (4 passes) | Daily cap | Effective revisit under the cap | Provider's own limit | +| --- | --- | --- | --- | --- | --- | --- | +| GFW | forest 2 | 340 | 1,360 | 400 | forest pairs ~1.2×/day | rate-limited per key (UNCONFIRMED figure) | +| CDSE | forest 0–1 (confirm only; ~10% → 17), methane 1 | ~62 (45–215) | ~250 (180–860) | 60 | methane ~1×/day; forest capped with it | processing units / requests per month (UNCONFIRMED figure) | +| FIRMS | fires 2 (1 when quiet), flaring ~12 | 720 (180 + 540) | 2,880 | 300 | FIRMS pairs ~every 2.4 days | 5,000 transactions / 10 min per map key | +| Anthropic | ≈ $0.10 per case (narrate + review) | — | ≤ 10 cases | $3 | — | — | + +The caps, not Lambda time, set the revisit rate. FIRMS's own limit is per 10 minutes, so +`EARTHDECK_MAX_FIRMS_CALLS` can be raised (≈ 3,000 covers four full passes; one shard spends +~90) without risk; raising CDSE needs the account's monthly PU budget checked first. Caps +reset at 00:00 UTC, so the 00:00 window's shards spend them first; later windows sweep what +is left, least-recently-swept first within each shard. + ## Monthly cost (estimate) | Item | Usage | ≈ USD/month | | --- | --- | --- | -| Lambda (arm64, 1 GB) | 28 invocations/day ≈ 840/month; at ~3 min avg ≈ 150k GB-s (worst case 900 s each ≈ 760k GB-s) | 0 within the 400k GB-s free tier; ≤ 5 worst case | +| Lambda (arm64, 1 GB) | 44 invocations/day ≈ 1,320/month; shards ~8 min, others ~2 min ≈ 500k GB-s (worst case 900 s each ≈ 1.19M GB-s) | ~1.5 over the 400k GB-s free tier; ≤ 11 worst case | | S3 (3 buckets, versioned state) | tens of MB, a few thousand PUT/GET | < 0.20 | | CloudFront | low traffic; 1 TB + 10M requests/month always-free; ~120 `/*` invalidations (1,000 free) | ~0 | | Route 53 | existing zone (already paid); alias queries free | 0 extra | | SSM + KMS | standard parameters free; `aws/ssm` key free; ~5k decrypts | < 0.05 | | CloudWatch | 1 custom metric 0.30 + 1 alarm 0.10 + small log ingest (30-day retention) | ~0.50 | | EventBridge Scheduler, ACM, SNS email | well inside free tiers | 0 | -| **Total** | | **~1–3** (Anthropic API usage by the analyst is separate) | +| **Total** | | **~2–5** (analyst Anthropic spend is separate, capped at $3/day ≈ $90/month) | ## Key rotation @@ -160,5 +236,9 @@ CFN cannot create a bucket whose name already exists. and `s3://earthdeck-state-185692190330/state/heartbeat.json` for the last success. - **Site shows the placeholder** — the export job is `unavailable` in this build or hasn't run yet; `scripts/run-job.sh export`. -- **Sweeps time out at 900 s** — split a watchlist, or lower per-call delay (`--delay-ms`); - watermarks mean a killed sweep resumes next slot (its unverified writes are not uploaded). +- **Sweeps time out at 900 s** — should not happen (every Lambda sweep is time-budgeted); if + one does, a single call hung past the budget. Watermarks mean a killed sweep resumes next + slot. `budget exhausted: k of n pairs done` in the log is normal, not an error. +- **Many `quota:` skips** — the daily cap is spent (see Quotas); check + `ledger/watch/quota.json` in the state bucket, raise the env var in the template if the + provider allows it. diff --git a/infra/earthdeck.yaml b/infra/earthdeck.yaml index b7d67f2..41273c5 100644 --- a/infra/earthdeck.yaml +++ b/infra/earthdeck.yaml @@ -36,7 +36,8 @@ Conditions: WithFunction: !Equals [!Ref DeployFunction, "true"] Mappings: - # Schedules: 6-hour slots at 00/06/12/18 UTC — sweeps at :00 :10 :20 :30 :40, analyst :50, export +1 h. + # Schedules: 6-hour windows from 00/06/12/18 UTC — generated-list shards 0–7 at +0:00…+1:10 + # (every 10 min), analyst +1:20, export +1:30, hand-written lists +1:40. See infra/README.md. Const: CloudFront: HostedZoneId: Z2FDTNDATAQYW2 # fixed zone id for every CloudFront alias target @@ -386,6 +387,12 @@ Resources: EARTHDECK_SSM_PREFIX: /earthdeck EARTHDECK_SITE_URL: !Sub "https://${DomainName}" EARTHDECK_CONTACT: !Ref NotifyEmail + # Per-UTC-day caps (counted in ledger/watch/quota.json); see infra/README.md "Quotas". + EARTHDECK_MAX_CDSE_CALLS: "60" + EARTHDECK_MAX_GFW_CALLS: "400" + EARTHDECK_MAX_FIRMS_CALLS: "300" + EARTHDECK_MAX_ANALYST_CASES: "10" + EARTHDECK_MAX_ANALYST_USD: "3" NODE_OPTIONS: --enable-source-maps Tags: [{ Key: Project, Value: earthdeck }] @@ -431,11 +438,13 @@ Resources: Name: earthdeck Tags: [{ Key: Project, Value: earthdeck }] - SweepAmazon: + # Generated watchlists: 8 disjoint shards (hash(aoi.id, rule) mod 8), one every 10 min from +0:00. + # Each gets --time-budget = remaining Lambda time − 90 s; a cut shard resumes least-recently-swept first. + SweepShard0: Type: AWS::Scheduler::Schedule Condition: WithFunction Properties: - Name: earthdeck-sweep-amazon + Name: earthdeck-sweep-shard-0 GroupName: !Ref ScheduleGroup State: !Ref SchedulesState ScheduleExpression: cron(0 0/6 * * ? *) @@ -444,14 +453,14 @@ Resources: Target: Arn: !GetAtt RunnerFunction.Arn RoleArn: !GetAtt SchedulerRole.Arn - Input: '{"job":"sweep","watchlist":"amazon"}' + Input: '{"job":"sweep","watchlist":"all-generated","shard":"0/8"}' RetryPolicy: { MaximumRetryAttempts: 2, MaximumEventAgeInSeconds: 3600 } - SweepCongoBorneo: + SweepShard1: Type: AWS::Scheduler::Schedule Condition: WithFunction Properties: - Name: earthdeck-sweep-congo-borneo + Name: earthdeck-sweep-shard-1 GroupName: !Ref ScheduleGroup State: !Ref SchedulesState ScheduleExpression: cron(10 0/6 * * ? *) @@ -460,14 +469,14 @@ Resources: Target: Arn: !GetAtt RunnerFunction.Arn RoleArn: !GetAtt SchedulerRole.Arn - Input: '{"job":"sweep","watchlist":"congo-borneo"}' + Input: '{"job":"sweep","watchlist":"all-generated","shard":"1/8"}' RetryPolicy: { MaximumRetryAttempts: 2, MaximumEventAgeInSeconds: 3600 } - SweepControls: + SweepShard2: Type: AWS::Scheduler::Schedule Condition: WithFunction Properties: - Name: earthdeck-sweep-controls + Name: earthdeck-sweep-shard-2 GroupName: !Ref ScheduleGroup State: !Ref SchedulesState ScheduleExpression: cron(20 0/6 * * ? *) @@ -476,14 +485,14 @@ Resources: Target: Arn: !GetAtt RunnerFunction.Arn RoleArn: !GetAtt SchedulerRole.Arn - Input: '{"job":"sweep","watchlist":"controls"}' + Input: '{"job":"sweep","watchlist":"all-generated","shard":"2/8"}' RetryPolicy: { MaximumRetryAttempts: 2, MaximumEventAgeInSeconds: 3600 } - SweepMethane: + SweepShard3: Type: AWS::Scheduler::Schedule Condition: WithFunction Properties: - Name: earthdeck-sweep-methane + Name: earthdeck-sweep-shard-3 GroupName: !Ref ScheduleGroup State: !Ref SchedulesState ScheduleExpression: cron(30 0/6 * * ? *) @@ -492,14 +501,14 @@ Resources: Target: Arn: !GetAtt RunnerFunction.Arn RoleArn: !GetAtt SchedulerRole.Arn - Input: '{"job":"sweep","watchlist":"methane"}' + Input: '{"job":"sweep","watchlist":"all-generated","shard":"3/8"}' RetryPolicy: { MaximumRetryAttempts: 2, MaximumEventAgeInSeconds: 3600 } - SweepFlaring: + SweepShard4: Type: AWS::Scheduler::Schedule Condition: WithFunction Properties: - Name: earthdeck-sweep-flaring + Name: earthdeck-sweep-shard-4 GroupName: !Ref ScheduleGroup State: !Ref SchedulesState ScheduleExpression: cron(40 0/6 * * ? *) @@ -508,7 +517,55 @@ Resources: Target: Arn: !GetAtt RunnerFunction.Arn RoleArn: !GetAtt SchedulerRole.Arn - Input: '{"job":"sweep","watchlist":"flaring"}' + Input: '{"job":"sweep","watchlist":"all-generated","shard":"4/8"}' + RetryPolicy: { MaximumRetryAttempts: 2, MaximumEventAgeInSeconds: 3600 } + + SweepShard5: + Type: AWS::Scheduler::Schedule + Condition: WithFunction + Properties: + Name: earthdeck-sweep-shard-5 + GroupName: !Ref ScheduleGroup + State: !Ref SchedulesState + ScheduleExpression: cron(50 0/6 * * ? *) + ScheduleExpressionTimezone: UTC + FlexibleTimeWindow: { Mode: "OFF" } + Target: + Arn: !GetAtt RunnerFunction.Arn + RoleArn: !GetAtt SchedulerRole.Arn + Input: '{"job":"sweep","watchlist":"all-generated","shard":"5/8"}' + RetryPolicy: { MaximumRetryAttempts: 2, MaximumEventAgeInSeconds: 3600 } + + SweepShard6: + Type: AWS::Scheduler::Schedule + Condition: WithFunction + Properties: + Name: earthdeck-sweep-shard-6 + GroupName: !Ref ScheduleGroup + State: !Ref SchedulesState + ScheduleExpression: cron(0 1/6 * * ? *) + ScheduleExpressionTimezone: UTC + FlexibleTimeWindow: { Mode: "OFF" } + Target: + Arn: !GetAtt RunnerFunction.Arn + RoleArn: !GetAtt SchedulerRole.Arn + Input: '{"job":"sweep","watchlist":"all-generated","shard":"6/8"}' + RetryPolicy: { MaximumRetryAttempts: 2, MaximumEventAgeInSeconds: 3600 } + + SweepShard7: + Type: AWS::Scheduler::Schedule + Condition: WithFunction + Properties: + Name: earthdeck-sweep-shard-7 + GroupName: !Ref ScheduleGroup + State: !Ref SchedulesState + ScheduleExpression: cron(10 1/6 * * ? *) + ScheduleExpressionTimezone: UTC + FlexibleTimeWindow: { Mode: "OFF" } + Target: + Arn: !GetAtt RunnerFunction.Arn + RoleArn: !GetAtt SchedulerRole.Arn + Input: '{"job":"sweep","watchlist":"all-generated","shard":"7/8"}' RetryPolicy: { MaximumRetryAttempts: 2, MaximumEventAgeInSeconds: 3600 } Analyst: @@ -518,7 +575,7 @@ Resources: Name: earthdeck-analyst GroupName: !Ref ScheduleGroup State: !Ref SchedulesState - ScheduleExpression: cron(50 0/6 * * ? *) + ScheduleExpression: cron(20 1/6 * * ? *) ScheduleExpressionTimezone: UTC FlexibleTimeWindow: { Mode: "OFF" } Target: @@ -534,7 +591,7 @@ Resources: Name: earthdeck-export GroupName: !Ref ScheduleGroup State: !Ref SchedulesState - ScheduleExpression: cron(0 1/6 * * ? *) + ScheduleExpression: cron(30 1/6 * * ? *) ScheduleExpressionTimezone: UTC FlexibleTimeWindow: { Mode: "OFF" } Target: @@ -543,6 +600,23 @@ Resources: Input: '{"job":"export"}' RetryPolicy: { MaximumRetryAttempts: 2, MaximumEventAgeInSeconds: 3600 } + # The five hand-written watchlists in one invocation (after the export; published next window). + SweepHandwritten: + Type: AWS::Scheduler::Schedule + Condition: WithFunction + Properties: + Name: earthdeck-sweep-handwritten + GroupName: !Ref ScheduleGroup + State: !Ref SchedulesState + ScheduleExpression: cron(40 1/6 * * ? *) + ScheduleExpressionTimezone: UTC + FlexibleTimeWindow: { Mode: "OFF" } + Target: + Arn: !GetAtt RunnerFunction.Arn + RoleArn: !GetAtt SchedulerRole.Arn + Input: '{"job":"sweep","watchlist":"all-handwritten"}' + RetryPolicy: { MaximumRetryAttempts: 2, MaximumEventAgeInSeconds: 3600 } + # ── watchdog ────────────────────────────────────────────────────────────────────────── AlertTopic: Type: AWS::SNS::Topic diff --git a/scripts/run-job.sh b/scripts/run-job.sh index 1b5344c..fc0a9c9 100755 --- a/scripts/run-job.sh +++ b/scripts/run-job.sh @@ -3,6 +3,8 @@ # # scripts/run-job.sh sweep controls --dry-run # scripts/run-job.sh sweep amazon +# scripts/run-job.sh sweep all-generated --shard 3/8 +# scripts/run-job.sh sweep generated/forest-hotspots --time-budget 300 --dry-run # scripts/run-job.sh analyst # scripts/run-job.sh export # @@ -13,23 +15,32 @@ PROFILE=${AWS_PROFILE:-personal} REGION=us-east-1 FUNCTION=earthdeck -usage() { echo "usage: $0 [watchlist] [--dry-run]" >&2; exit 2; } +usage() { echo "usage: $0 [watchlist] [--shard i/n] [--time-budget SEC] [--dry-run]" >&2; exit 2; } [ $# -ge 1 ] || usage JOB=$1 shift WATCHLIST="" +SHARD="" +BUDGET="" DRY=false -for a in "$@"; do - case "$a" in +while [ $# -gt 0 ]; do + case "$1" in --dry-run) DRY=true ;; + --shard) [ $# -ge 2 ] || usage; SHARD=$2; shift ;; + --time-budget) [ $# -ge 2 ] || usage; BUDGET=$2; shift ;; -*) usage ;; - *) WATCHLIST=$a ;; + *) WATCHLIST=$1 ;; esac + shift done +case "$SHARD" in "" | [0-9]*/[0-9]*) ;; *) usage ;; esac +case "$BUDGET" in "" | *[!0-9]*) [ -z "$BUDGET" ] || usage ;; esac case "$JOB" in sweep | analyst | export | all) ;; *) usage ;; esac PAYLOAD="{\"job\":\"$JOB\"" [ -n "$WATCHLIST" ] && PAYLOAD="$PAYLOAD,\"watchlist\":\"$WATCHLIST\"" +[ -n "$SHARD" ] && PAYLOAD="$PAYLOAD,\"shard\":\"$SHARD\"" +[ -n "$BUDGET" ] && PAYLOAD="$PAYLOAD,\"timeBudgetSec\":$BUDGET" [ "$DRY" = true ] && PAYLOAD="$PAYLOAD,\"dryRun\":true" PAYLOAD="$PAYLOAD}" diff --git a/src/analyst/analyst.ts b/src/analyst/analyst.ts index f23ac7e..019520c 100644 --- a/src/analyst/analyst.ts +++ b/src/analyst/analyst.ts @@ -15,6 +15,7 @@ import type { Finding } from "../ledger/schema.js"; import type { EventInput, Ledger } from "../ledger/store.js"; import { uuidv7 } from "../util.js"; import type { Journal } from "../watch/journal.js"; +import type { QuotaGovernor } from "../watch/quota.js"; import { callJson, type JsonCallResult } from "./anthropic.js"; import { canPublish, @@ -45,6 +46,8 @@ export interface AnalystOptions { max?: number; dryRun?: boolean; log?: (line: string) => void; + /** Daily case count + USD spend cap (quota.json). Omitted = no daily limits. */ + quota?: QuotaGovernor; } export interface AnalystReport { @@ -103,8 +106,11 @@ export async function runAnalyst(o: AnalystOptions): Promise { const report: AnalystReport = { runId, dryRun, selected: 0, narrated: [], published: [], held: [], rejected: [], errors: [], calls: 0, costUsd: 0 }; const j = (kind: string, rec: Record = {}) => o.journal.append({ t: new Date().toISOString(), sweepId: runId, kind: `analyst_${kind}`, ...rec }); - const work = select(o.ledger, o.max ?? 5); + const q = o.quota; + const limit = Math.min(o.max ?? 5, q ? q.analystCasesLeft() : Infinity); + const work = limit > 0 ? select(o.ledger, limit) : []; report.selected = work.length; + if (q && q.analystCasesLeft() === 0) log(`daily analyst case cap reached (${q.caps.analystCases}) — nothing to do until tomorrow (UTC)`); j("start", { narrator, reviewer, dryRun, selected: work.length }); const call = async (purpose: "narrate" | "review", findingId: string, attempt: number, model: string, system: string, user: string, jsonSchema: Record): Promise => { @@ -113,6 +119,7 @@ export async function runAnalyst(o: AnalystOptions): Promise { report.calls++; report.costUsd += r.costUsd ?? 0; j("call", { findingId, purpose, attempt, model: r.model, usage: r.usage, costUsd: r.costUsd, ms: r.ms, requestSha256: r.requestSha256, responseSha256: r.responseSha256 }); + if (q) j("spend", { day: q.day, callUsd: r.costUsd, dayUsd: q.addAnalystUsd(r.costUsd ?? 0), limitUsd: q.caps.analystUsd }); log(` ↳ ${purpose}#${attempt} ${r.model} · ${r.usage.input_tokens} in / ${r.usage.output_tokens} out · ${r.costUsd == null ? "cost n/a" : `$${r.costUsd.toFixed(4)}`} · ${(r.ms / 1000).toFixed(1)}s`); return r; } catch (err) { @@ -123,6 +130,12 @@ export async function runAnalyst(o: AnalystOptions): Promise { }; for (const { finding: f, needs } of work) { + if (q?.analystBudgetSpent()) { + log(`daily analyst budget spent ($${q.analystUsd().toFixed(4)} ≥ $${q.caps.analystUsd}) — stopping until tomorrow (UTC)`); + j("budget_stop", { day: q.day, dayUsd: q.analystUsd(), limitUsd: q.caps.analystUsd }); + break; + } + q?.chargeAnalystCase(); log(`• ${f.title} [${f.findingId}] tier ${f.tier}${isControl(f) ? " CONTROL" : ""} — ${needs}`); const facts = JSON.stringify(dossier(f), null, 2); try { diff --git a/src/analyst/cli.ts b/src/analyst/cli.ts index 024f05b..e1bddf6 100644 --- a/src/analyst/cli.ts +++ b/src/analyst/cli.ts @@ -6,6 +6,7 @@ import { anthropicApiKey, ledgerDir } from "../config.js"; import { OverviewError } from "../errors.js"; import { Ledger } from "../ledger/store.js"; import { Journal } from "../watch/journal.js"; +import { capsFromEnv, QuotaGovernor } from "../watch/quota.js"; import { DEFAULT_NARRATOR, DEFAULT_REVIEWER, runAnalyst } from "./analyst.js"; const out = (s: string) => process.stdout.write(`${s}\n`); @@ -17,21 +18,25 @@ export async function runAnalystCli(args: string[]): Promise { }; if (!args.includes("--once")) { out("usage: earthdeck analyst --once [--max N] [--dry-run] [--model-narrator id] [--model-reviewer id]"); + out(" --max defaults to EARTHDECK_MAX_ANALYST_CASES (10), which is also the per-UTC-day case cap;"); + out(" the run stops once today's API spend reaches EARTHDECK_MAX_ANALYST_USD (3)."); out(` Narrates confirmed findings (${DEFAULT_NARRATOR}), has a different model review them (${DEFAULT_REVIEWER}),`); out(" and publishes those that pass the gates. Needs ANTHROPIC_API_KEY."); process.exitCode = 2; return; } - const max = opt("--max") ? Number(opt("--max")) : 5; + const caps = capsFromEnv(); + const max = opt("--max") ? Number(opt("--max")) : caps.analystCases; if (!Number.isInteger(max) || max < 1) throw new Error("--max must be a positive integer"); const dryRun = args.includes("--dry-run"); const dir = ledgerDir(); const ledger = Ledger.open(dir, { createKey: !dryRun }); const journal = new Journal(join(dir, "watch")); + const quota = new QuotaGovernor(journal.dir, caps); out(`earthdeck analyst — ledger ${dir}${dryRun ? " — DRY RUN (one narration call per finding, nothing appended)" : ""}`); let r: Awaited>; try { - r = await runAnalyst({ ledger, journal, apiKey: anthropicApiKey(), narrator: opt("--model-narrator"), reviewer: opt("--model-reviewer"), max, dryRun, log: out }); + r = await runAnalyst({ ledger, journal, apiKey: anthropicApiKey(), narrator: opt("--model-narrator"), reviewer: opt("--model-reviewer"), max, dryRun, quota, log: out }); } catch (err) { if (!(err instanceof OverviewError)) throw err; process.stderr.write(`earthdeck analyst: ${err.message}\n`); @@ -39,6 +44,6 @@ export async function runAnalystCli(args: string[]): Promise { return; } out(""); - out(`analyst ${r.runId}: ${r.selected} selected · ${r.narrated.length} narrated · ${r.published.length} published · ${r.held.length} held · ${r.rejected.length} rejected · ${r.errors.length} errors · ${r.calls} API calls ≈ $${r.costUsd.toFixed(4)}`); + out(`analyst ${r.runId}: ${r.selected} selected · ${r.narrated.length} narrated · ${r.published.length} published · ${r.held.length} held · ${r.rejected.length} rejected · ${r.errors.length} errors · ${r.calls} API calls ≈ $${r.costUsd.toFixed(4)} · today $${quota.analystUsd().toFixed(4)} of $${caps.analystUsd}`); if (r.errors.length) process.exitCode = 1; } diff --git a/src/cli.ts b/src/cli.ts index 1059cc5..6880c1b 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -63,6 +63,7 @@ function main(): void { " earthdeck dashboard ", " earthdeck watch --once sweep the watchlists once, write findings to the ledger", " earthdeck watch --once --dry-run [--watchlist ] [--max N] [--rules a,b]", + " earthdeck watch --once [--shard i/n] [--time-budget SEC] one shard, stop before the budget", " earthdeck analyst --once narrate + review (two models) + publish confirmed findings", " earthdeck analyst --once --dry-run [--max N] [--model-narrator id] [--model-reviewer id]", " earthdeck watch export --out [--base-url URL] write the public static site", diff --git a/src/runner/core.ts b/src/runner/core.ts index 93f6e3d..b94f933 100644 --- a/src/runner/core.ts +++ b/src/runner/core.ts @@ -14,18 +14,30 @@ import { z } from "zod"; // ── payload ────────────────────────────────────────────────────────────────────────────── +/** The hand-written watchlists (`watchlists/.json`). */ export const WATCHLISTS = ["amazon", "congo-borneo", "controls", "methane", "flaring"] as const; -export type WatchlistName = (typeof WATCHLISTS)[number]; +/** + * A sweep target: one hand-written list, `all-handwritten` (those five), `all-generated` + * (every file in `watchlists/generated/`), or one generated list `generated/`. + */ +export type WatchlistName = (typeof WATCHLISTS)[number] | "all-handwritten" | "all-generated" | `generated/${string}`; export type JobName = "sweep" | "analyst" | "export"; +const GENERATED = /^generated\/[a-z0-9][a-z0-9-]{0,63}$/; +const watchlistSchema = z.union([z.enum(WATCHLISTS), z.literal("all-handwritten"), z.literal("all-generated"), z.string().regex(GENERATED, "expected a hand-written name, all-handwritten, all-generated or generated/")]) as z.ZodType; + const payloadSchema = z .object({ job: z.enum(["sweep", "analyst", "export", "all"]), - watchlist: z.enum(WATCHLISTS).optional(), + watchlist: watchlistSchema.optional(), + shard: z.string().regex(/^\d{1,3}\/\d{1,3}$/, "expected i/n").refine((s) => { const [i, n] = s.split("/").map(Number); return n! >= 1 && i! < n!; }, "expected 0 ≤ i < n").optional(), + timeBudgetSec: z.number().int().positive().max(900).optional(), dryRun: z.boolean().optional(), }) .strict() .refine((p) => p.watchlist === undefined || p.job === "sweep", { message: "watchlist is only valid with job \"sweep\"" }) + .refine((p) => p.shard === undefined || p.job === "sweep", { message: "shard is only valid with job \"sweep\"" }) + .refine((p) => p.timeBudgetSec === undefined || p.job === "sweep", { message: "timeBudgetSec is only valid with job \"sweep\"" }) .refine((p) => !p.dryRun || p.job === "sweep", { message: "dryRun is only valid with job \"sweep\"" }); export type Payload = z.infer; @@ -48,6 +60,9 @@ export function parsePayload(raw: unknown): Payload { export interface Step { job: JobName; watchlist?: WatchlistName; + shard?: string; + /** Sweep time budget in seconds (`--time-budget`); set by the runner from the remaining Lambda time. */ + timeBudgetSec?: number; dryRun: boolean; } @@ -56,13 +71,43 @@ export function stepsFor(p: Payload): Step[] { if (p.job === "all") { return [...WATCHLISTS.map((w): Step => ({ job: "sweep", watchlist: w, dryRun: false })), { job: "analyst", dryRun: false }, { job: "export", dryRun: false }]; } - return [{ job: p.job, watchlist: p.watchlist, dryRun: p.dryRun ?? false }]; + return [{ job: p.job, watchlist: p.watchlist, ...(p.shard ? { shard: p.shard } : {}), ...(p.timeBudgetSec ? { timeBudgetSec: p.timeBudgetSec } : {}), dryRun: p.dryRun ?? false }]; +} + +/** `--watchlist` paths for a sweep target (repeatable flag; a directory loads its top-level *.json). */ +export function watchlistPaths(w: WatchlistName | undefined): string[] { + if (w === undefined) return ["watchlists"]; + if (w === "all-handwritten") return WATCHLISTS.map((n) => `watchlists/${n}.json`); + if (w === "all-generated") return ["watchlists/generated"]; + return [`watchlists/${w}.json`]; +} + +/** Soft reserve: the sweep's --time-budget ends this long before Lambda's deadline (verify + upload). */ +export const SWEEP_SOFT_RESERVE_MS = 90_000; +/** Hard reserve: a budgeted sweep that overruns is SIGTERMed this long before the deadline. */ +export const SWEEP_HARD_RESERVE_MS = 60_000; + +/** + * Budget math for a sweep given the Lambda time left: `--time-budget` = remaining − 90 s + * (capped by an explicit request), and the child is killed at remaining − 60 s as a backstop. + * `timeBudgetSec` ≤ 0 means there is no time to start. + */ +export function sweepTiming(remainingMs: number, requestedSec?: number): { timeBudgetSec: number; killAfterMs: number } { + const fromLambda = Math.floor((remainingMs - SWEEP_SOFT_RESERVE_MS) / 1000); + return { timeBudgetSec: requestedSec !== undefined ? Math.min(requestedSec, fromLambda) : fromLambda, killAfterMs: remainingMs - SWEEP_HARD_RESERVE_MS }; } /** argv for `node dist/cli.js …`. A sweep without a watchlist sweeps the whole directory. */ export function cliArgs(step: Step, siteDir: string): string[] { if (step.job === "sweep") { - return ["watch", "--once", ...(step.dryRun ? ["--dry-run"] : []), "--watchlist", step.watchlist ? `watchlists/${step.watchlist}.json` : "watchlists"]; + return [ + "watch", + "--once", + ...(step.dryRun ? ["--dry-run"] : []), + ...watchlistPaths(step.watchlist).flatMap((p) => ["--watchlist", p]), + ...(step.shard ? ["--shard", step.shard] : []), + ...(step.timeBudgetSec !== undefined ? ["--time-budget", String(step.timeBudgetSec)] : []), + ]; } if (step.job === "analyst") return ["analyst", "--once"]; // Public-site metadata comes from the function's environment (set by the stack). @@ -246,11 +291,15 @@ export interface RunnerConfig { env: NodeJS.ProcessEnv; /** Wall-clock budget left for this step, ms. */ budgetMs(): number; + /** Raw time left in the invocation, ms (Lambda `getRemainingTimeInMillis`); enables sweep time budgets. */ + remainingMs?(): number; } export interface StepResult { job: JobName; watchlist?: WatchlistName; + shard?: string; + timeBudgetSec?: number; dryRun: boolean; ok: boolean; status: "ok" | "failed" | "unavailable"; @@ -359,7 +408,7 @@ async function uploadDir(bucket: string, dir: string, keyOf: (rel: string) => st export async function runStep(step: Step, cfg: RunnerConfig, deps: RunnerDeps, avail: Record): Promise { const t0 = deps.now().getTime(); - const base = { job: step.job, ...(step.watchlist ? { watchlist: step.watchlist } : {}), dryRun: step.dryRun }; + const base: Pick = { job: step.job, ...(step.watchlist ? { watchlist: step.watchlist } : {}), ...(step.shard ? { shard: step.shard } : {}), dryRun: step.dryRun }; const done = (r: Omit): StepResult => ({ ...base, ...r, durationMs: deps.now().getTime() - t0 }); if (!avail[step.job]) { @@ -379,7 +428,17 @@ export async function runStep(step: Step, cfg: RunnerConfig, deps: RunnerDeps, a const env = { ...cfg.env, EARTHDECK_LEDGER_DIR: cfg.ledgerDir }; if (step.job === "export") rmSync(cfg.siteDir, { recursive: true, force: true }); - const run = await deps.exec(cliArgs(step, cfg.siteDir), { env, timeoutMs: cfg.budgetMs() }); + let runStepAs = step; + let timeoutMs = cfg.budgetMs(); + if (step.job === "sweep" && cfg.remainingMs) { + // Stop opening pairs 90 s before the deadline, leaving room for verify + upload. + const t = sweepTiming(cfg.remainingMs(), step.timeBudgetSec); + if (t.timeBudgetSec <= 0) return done({ ok: false, status: "failed", reason: `no time left to sweep (${Math.round(cfg.remainingMs() / 1000)} s remaining)` }); + runStepAs = { ...step, timeBudgetSec: t.timeBudgetSec }; + base.timeBudgetSec = t.timeBudgetSec; + timeoutMs = t.killAfterMs; + } + const run = await deps.exec(cliArgs(runStepAs, cfg.siteDir), { env, timeoutMs }); const outputTail = run.output.slice(-2_000); if (step.job === "export") { diff --git a/src/runner/lambda.ts b/src/runner/lambda.ts index d6f7706..9d61cf2 100644 --- a/src/runner/lambda.ts +++ b/src/runner/lambda.ts @@ -1,5 +1,5 @@ // AWS Lambda entry point (handler `dist/runner/lambda.handler`, Node.js 22). EventBridge -// Scheduler invokes it with `{ job, watchlist?, dryRun? }`; it loads secrets from SSM, pulls +// Scheduler invokes it with `{ job, watchlist?, shard?, timeBudgetSec?, dryRun? }`; it loads secrets from SSM, pulls // the ledger from the state bucket into /tmp, runs `node dist/cli.js …`, and — only when // `ledger verify` passes — pushes the ledger back. See infra/README.md. // @@ -43,6 +43,8 @@ export async function handler(event: unknown, context?: LambdaContext): Promise< siteDir: "/tmp/site", env: { ...process.env, ...secrets, HOME: "/tmp" }, budgetMs: () => (context ? context.getRemainingTimeInMillis() - RESERVE_MS : 780_000), + // Sweeps get `--time-budget` = remaining − 90 s from this (see sweepTiming in core.ts). + ...(context ? { remainingMs: () => context.getRemainingTimeInMillis() } : {}), }, { store: await s3Store(region), diff --git a/src/watch/journal.ts b/src/watch/journal.ts index 6043bfd..dad2133 100644 --- a/src/watch/journal.ts +++ b/src/watch/journal.ts @@ -9,7 +9,7 @@ import { createHash } from "node:crypto"; export interface JournalRecord { t: string; sweepId: string; - kind: "sweep_start" | "tool_call" | "candidate" | "created" | "evidence_added" | "confirmed" | "expired" | "gap" | "skip" | "sweep_end" | `analyst_${string}`; + kind: "sweep_start" | "tool_call" | "candidate" | "created" | "evidence_added" | "confirmed" | "expired" | "gap" | "skip" | "sweep_end" | "budget_exhausted" | `analyst_${string}`; aoi?: string; rule?: string; tool?: string; diff --git a/src/watch/kernel.ts b/src/watch/kernel.ts index d5cdd11..e9847b8 100644 --- a/src/watch/kernel.ts +++ b/src/watch/kernel.ts @@ -8,7 +8,9 @@ import { pushFindingCard } from "../dashboard/push.js"; import { CANDIDATE_TTL_DAYS, TERMINAL_STATUSES, eventPayload, type Context, type Finding } from "../ledger/schema.js"; import type { Ledger } from "../ledger/store.js"; import { uuidv7 } from "../util.js"; +import { createHash } from "node:crypto"; import { Journal } from "./journal.js"; +import { providersForRequires, QuotaExceeded, type QuotaGovernor } from "./quota.js"; import { bboxPolygon, ringBBox, ToolError, type Rule, type RuleContext, type ToolCall } from "./rules/types.js"; import type { WatchAoi, Watchlist } from "./watchlist.js"; @@ -29,6 +31,33 @@ export interface SweepOptions { /** Env presence check for rule.requires; default reads process.env. */ hasKey?: (name: string) => boolean; log?: (line: string) => void; + /** Only pairs in this shard: stable hash(aoi.id, rule) mod count === index. */ + shard?: Shard; + /** Wall-clock deadline (ms since epoch): stop opening new pairs when the next might not fit. */ + deadline?: number; + /** Clock for the deadline (default Date.now). */ + clock?: () => number; + /** Per-day provider caps; pairs needing an exhausted provider are skipped `quota:`. */ + quota?: QuotaGovernor; +} + +export interface Shard { + index: number; + count: number; +} + +/** `"3/8"` → { index: 3, count: 8 }. */ +export function parseShard(s: string): Shard { + const m = /^(\d+)\/(\d+)$/.exec(s.trim()); + const index = m ? Number(m[1]) : NaN; + const count = m ? Number(m[2]) : NaN; + if (!m || count < 1 || index >= count) throw new Error(`--shard must be i/n with 0 ≤ i < n (got "${s}")`); + return { index, count }; +} + +/** Deterministic shard of an AOI×rule pair (sha256, first 32 bits). */ +export function shardOf(aoiId: string, rule: string, count: number): number { + return createHash("sha256").update(`${aoiId}\n${rule}`).digest().readUInt32BE(0) % count; } export interface SweepReport { @@ -43,6 +72,8 @@ export interface SweepReport { gaps: { aoi: string; rule: string; message: string }[]; skipped: { aoi: string; rule: string; reason: string }[]; dryRun: boolean; + /** Set when the deadline stopped the sweep early: `done` of `total` pairs were visited. */ + budgetExhausted?: { done: number; total: number }; } export async function sweep(o: SweepOptions): Promise { @@ -77,23 +108,57 @@ export async function sweep(o: SweepOptions): Promise { } const pairs: { aoi: WatchAoi; ruleName: string; params: Record }[] = []; - for (const wl of o.watchlists) for (const aoi of wl.aois) for (const r of aoi.rules) if (!o.onlyRules || o.onlyRules.includes(r.name)) pairs.push({ aoi, ruleName: r.name, params: r.params }); + for (const wl of o.watchlists) + for (const aoi of wl.aois) + for (const r of aoi.rules) { + if (o.onlyRules && !o.onlyRules.includes(r.name)) continue; + if (o.shard && shardOf(aoi.id, r.name, o.shard.count) !== o.shard.index) continue; + pairs.push({ aoi, ruleName: r.name, params: r.params }); + } + // Least-recently-swept first (never-swept first of all), so a budget- or quota-cut sweep + // rotates through the list instead of starving its tail. Stable for equal watermarks. + const lastSwept = (p: (typeof pairs)[number]) => o.journal.watermark(p.aoi.id, p.ruleName) ?? ""; + pairs.sort((a, b) => (lastSwept(a) < lastSwept(b) ? -1 : lastSwept(a) > lastSwept(b) ? 1 : 0)); const capped = o.maxPairs ? pairs.slice(0, o.maxPairs) : pairs; report.pairs = capped.length; + const clock = o.clock ?? Date.now; + let longestPairMs = 0; for (const [i, { aoi, ruleName, params }] of capped.entries()) { if (i > 0 && o.delayMs) await new Promise((r) => setTimeout(r, o.delayMs)); + // Budget: open the next pair only if one more (as long as the slowest so far) still fits. + const pairStart = clock(); + if (o.deadline !== undefined && pairStart + longestPairMs > o.deadline) { + report.budgetExhausted = { done: i, total: capped.length }; + o.journal.append({ t: new Date().toISOString(), sweepId, kind: "budget_exhausted", done: i, total: capped.length }); + log(`budget exhausted: ${i} of ${capped.length} pairs done`); + break; + } + try { + await runPair(aoi, ruleName, params); + } finally { + longestPairMs = Math.max(longestPairMs, clock() - pairStart); + } + } + + async function runPair(aoi: WatchAoi, ruleName: string, params: Record): Promise { const rule = o.rules.get(ruleName); if (!rule) { report.gaps.push({ aoi: aoi.id, rule: ruleName, message: "unknown rule" }); o.journal.append({ t: now, sweepId, kind: "gap", aoi: aoi.id, rule: ruleName, message: "unknown rule" }); - continue; + return; } const missing = rule.requires.filter((k) => !hasKey(k)); if (missing.length) { report.skipped.push({ aoi: aoi.id, rule: ruleName, reason: `missing ${missing.join(", ")}` }); o.journal.append({ t: now, sweepId, kind: "skip", aoi: aoi.id, rule: ruleName, message: `missing ${missing.join(", ")}` }); - continue; + return; + } + const quotaBlock = o.quota ? providersForRequires(rule.requires).map((p) => o.quota!.blocked(p)).find(Boolean) : null; + if (quotaBlock) { + report.skipped.push({ aoi: aoi.id, rule: ruleName, reason: quotaBlock }); + o.journal.append({ t: now, sweepId, kind: "skip", aoi: aoi.id, rule: ruleName, message: quotaBlock }); + return; } const ctx: RuleContext = { aoi, params, now, since: o.journal.watermark(aoi.id, rule.name), call }; const key = Journal.findingKey(rule.name, rule.version, aoi.id); @@ -114,14 +179,14 @@ export async function sweep(o: SweepOptions): Promise { await card(open.findingId, o.ledger, report.dryRun); } else log(`· ${rule.name} @ ${aoi.id}: candidate, no independent signal yet`); o.journal.setWatermark(aoi.id, rule.name, now); - continue; + return; } const candidate = await rule.detect(ctx); if (!candidate) { log(`· ${rule.name} @ ${aoi.id}: quiet`); o.journal.setWatermark(aoi.id, rule.name, now); - continue; + return; } o.journal.append({ t: now, sweepId, kind: "candidate", aoi: aoi.id, rule: rule.name, values: candidate.values }); @@ -136,7 +201,7 @@ export async function sweep(o: SweepOptions): Promise { } log(`+ ${rule.name} @ ${aoi.id}: ${fresh.length} new evidence on open case`); o.journal.setWatermark(aoi.id, rule.name, now); - continue; + return; } // New finding: context first (best-effort), then the created event, then a confirmation attempt. @@ -201,6 +266,13 @@ export async function sweep(o: SweepOptions): Promise { await card(findingId, o.ledger, report.dryRun); o.journal.setWatermark(aoi.id, rule.name, now); } catch (err) { + if (err instanceof QuotaExceeded) { + // Cap reached mid-pair: a skip, not a gap — watermark untouched, retried on a later day. + report.skipped.push({ aoi: aoi.id, rule: rule.name, reason: `quota:${err.provider}` }); + o.journal.append({ t: now, sweepId, kind: "skip", aoi: aoi.id, rule: rule.name, message: `quota:${err.provider}` }); + log(`○ ${rule.name} @ ${aoi.id}: quota:${err.provider}`); + return; + } // A failed pair is a coverage gap: recorded, watermark untouched, sweep continues. const message = err instanceof Error ? err.message : String(err); report.gaps.push({ aoi: aoi.id, rule: rule.name, message }); @@ -216,7 +288,7 @@ export async function sweep(o: SweepOptions): Promise { } function summary(r: SweepReport): Record { - return { pairs: r.pairs, created: r.created.length, confirmed: r.confirmed.length, evidenceAdded: r.evidenceAdded.length, expired: r.expired.length, gaps: r.gaps.length, skipped: r.skipped.length, dryRun: r.dryRun }; + return { pairs: r.pairs, created: r.created.length, confirmed: r.confirmed.length, evidenceAdded: r.evidenceAdded.length, expired: r.expired.length, gaps: r.gaps.length, skipped: r.skipped.length, dryRun: r.dryRun, ...(r.budgetExhausted ? { budgetExhausted: r.budgetExhausted } : {}) }; } function valuesOf(f: Finding): Record { diff --git a/src/watch/quota.ts b/src/watch/quota.ts new file mode 100644 index 0000000..31135ca --- /dev/null +++ b/src/watch/quota.ts @@ -0,0 +1,205 @@ +// Quota governor: keeps the scheduled sweeps inside the free API tiers. Every tool call the +// watch makes goes through `wrap()`, which maps the tool to a provider, charges its cost +// against a per-UTC-day cap persisted in the journal dir (`quota.json`), and refuses the +// call (QuotaExceeded) once the cap would be crossed. A 429 — or a 403 that says quota — +// marks the provider exhausted for the rest of the run. The analyst's case count and USD +// spend ride in the same file. + +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { ToolError, type ToolCall } from "./rules/types.js"; + +export type Provider = "cdse" | "gfw" | "firms"; +export const PROVIDERS: readonly Provider[] = ["cdse", "gfw", "firms"]; + +export interface QuotaCaps { + cdse: number; + gfw: number; + firms: number; + analystCases: number; + analystUsd: number; +} + +const DEFAULT_CAPS: QuotaCaps = { cdse: 60, gfw: 400, firms: 300, analystCases: 10, analystUsd: 3 }; + +/** Caps from EARTHDECK_MAX_{CDSE,GFW,FIRMS}_CALLS, EARTHDECK_MAX_ANALYST_CASES, EARTHDECK_MAX_ANALYST_USD. */ +export function capsFromEnv(env: NodeJS.ProcessEnv = process.env): QuotaCaps { + const n = (name: string, dflt: number) => { + const raw = env[name]; + if (raw === undefined || raw.trim() === "") return dflt; + const v = Number(raw); + if (!Number.isFinite(v) || v < 0) throw new Error(`${name} must be a non-negative number (got "${raw}")`); + return v; + }; + return { + cdse: n("EARTHDECK_MAX_CDSE_CALLS", DEFAULT_CAPS.cdse), + gfw: n("EARTHDECK_MAX_GFW_CALLS", DEFAULT_CAPS.gfw), + firms: n("EARTHDECK_MAX_FIRMS_CALLS", DEFAULT_CAPS.firms), + analystCases: n("EARTHDECK_MAX_ANALYST_CASES", DEFAULT_CAPS.analystCases), + analystUsd: n("EARTHDECK_MAX_ANALYST_USD", DEFAULT_CAPS.analystUsd), + }; +} + +const TOOL_PROVIDER: Record = { + forest_alerts: "gfw", + eo_compare: "cdse", + eo_render: "cdse", + eo_index: "cdse", + eo_search: "cdse", + methane_plumes: "cdse", + fires_in: "firms", + flaring: "firms", +}; + +/** Provider + billable units for one tool call (null = not governed, e.g. EONET/ENSO). */ +export function costOf(tool: string, args: Record): { provider: Provider; units: number } | null { + const provider = TOOL_PROVIDER[tool]; + if (!provider) return null; + if (tool === "flaring") { + // FIRMS area API: one transaction per ≤5-day chunk per VIIRS source (default 30 d × 2 sources = 12). + const days = typeof args.days === "number" ? args.days : 30; + const sources = Array.isArray(args.sources) ? args.sources.length : 2; + return { provider, units: Math.max(1, Math.ceil(days / 5)) * sources }; + } + return { provider, units: 1 }; +} + +/** Env keys a rule requires → the providers it will spend. */ +export function providersForRequires(requires: readonly string[]): Provider[] { + const out = new Set(); + for (const k of requires) { + if (k === "GFW_API_KEY") out.add("gfw"); + else if (k.startsWith("CDSE_")) out.add("cdse"); + else if (k === "FIRMS_MAP_KEY") out.add("firms"); + } + return [...out]; +} + +/** Does this tool error mean "the provider's quota is spent"? 429 always; 403 only when it says so. */ +export function isQuotaError(message: string, status?: number, body?: unknown): boolean { + const text = `${message} ${typeof body === "string" ? body : JSON.stringify(body ?? "")}`; + if (status === 429 || /\(429\)|too many requests|rate limit/i.test(text)) return true; + const is403 = status === 403 || /\(403\)/.test(message); + if (is403 && /quota|limit|exceed|processing units/i.test(text)) return true; + return /transaction limit|exceed(?:ed|ing)? (?:the )?allowed/i.test(text); // FIRMS plain-text limit notice +} + +export class QuotaExceeded extends ToolError { + constructor( + tool: string, + readonly provider: Provider, + ) { + super(tool, `quota:${provider}`); + this.name = "QuotaExceeded"; + } +} + +interface DayRecord { + cdse?: number; + gfw?: number; + firms?: number; + analystCases?: number; + analystUsd?: number; +} + +const KEEP_DAYS = 14; + +export class QuotaGovernor { + private days: Record; + private readonly exhausted = new Map(); + private readonly file: string | null; + + /** `dir` = the journal dir (null = in-memory only); `day` = UTC YYYY-MM-DD the counters belong to. */ + constructor( + dir: string | null, + readonly caps: QuotaCaps, + readonly day: string = new Date().toISOString().slice(0, 10), + ) { + this.file = dir ? join(dir, "quota.json") : null; + this.days = this.file && existsSync(this.file) ? readDays(this.file) : {}; + } + + private get today(): DayRecord { + return (this.days[this.day] ??= {}); + } + + used(provider: Provider): number { + return this.today[provider] ?? 0; + } + + /** Why the provider can't be used now, or null. */ + blocked(provider: Provider, units = 1): string | null { + const hit = this.exhausted.get(provider); + if (hit) return hit; + return this.used(provider) + units > this.caps[provider] ? `quota:${provider}` : null; + } + + markExhausted(provider: Provider): void { + this.exhausted.set(provider, `quota:${provider}`); + } + + /** Charge units (also when the call later fails — the provider still counted the request). */ + charge(provider: Provider, units: number): void { + this.today[provider] = this.used(provider) + units; + this.save(); + } + + /** Wrap a ToolCall: refuse over-cap calls, charge the rest, learn from 429/403-quota errors. */ + wrap(call: ToolCall): ToolCall { + return async (tool, args) => { + const cost = costOf(tool, args); + if (!cost) return call(tool, args); + if (this.blocked(cost.provider, cost.units)) throw new QuotaExceeded(tool, cost.provider); + this.charge(cost.provider, cost.units); + try { + return await call(tool, args); + } catch (err) { + const e = err as { message?: string; status?: number; body?: unknown }; + if (isQuotaError(String(e.message ?? err), e.status, e.body)) this.markExhausted(cost.provider); + throw err; + } + }; + } + + // ── analyst ────────────────────────────────────────────────────────────────────────── + + analystCasesLeft(): number { + return Math.max(0, this.caps.analystCases - (this.today.analystCases ?? 0)); + } + chargeAnalystCase(): void { + this.today.analystCases = (this.today.analystCases ?? 0) + 1; + this.save(); + } + analystUsd(): number { + return this.today.analystUsd ?? 0; + } + /** Add spend; returns today's running total. */ + addAnalystUsd(usd: number): number { + this.today.analystUsd = Math.round((this.analystUsd() + usd) * 1e6) / 1e6; + this.save(); + return this.today.analystUsd; + } + analystBudgetSpent(): boolean { + return this.analystUsd() >= this.caps.analystUsd; + } + + snapshot(): DayRecord { + return { ...this.today }; + } + + private save(): void { + if (!this.file) return; + const keep = Object.keys(this.days).sort().slice(-KEEP_DAYS); + this.days = Object.fromEntries(keep.map((d) => [d, this.days[d]!])); + writeFileSync(this.file, JSON.stringify(this.days, null, 2)); + } +} + +function readDays(file: string): Record { + try { + const j = JSON.parse(readFileSync(file, "utf8")) as unknown; + return j && typeof j === "object" && !Array.isArray(j) ? (j as Record) : {}; + } catch { + return {}; + } +} diff --git a/src/watch/rules/types.ts b/src/watch/rules/types.ts index 624323f..2d4db6f 100644 --- a/src/watch/rules/types.ts +++ b/src/watch/rules/types.ts @@ -13,6 +13,9 @@ export class ToolError extends Error { constructor( readonly tool: string, message: string, + /** Upstream HTTP status / body when the tool reported one (quota detection). */ + readonly status?: number, + readonly body?: unknown, ) { super(`${tool}: ${message}`); this.name = "ToolError"; diff --git a/src/watch/run.ts b/src/watch/run.ts index bf0ee99..e41f9a1 100644 --- a/src/watch/run.ts +++ b/src/watch/run.ts @@ -12,60 +12,78 @@ import { ledgerDir } from "../config.js"; import { buildServer } from "../index.js"; import { Ledger } from "../ledger/store.js"; import { Journal } from "./journal.js"; -import { sweep } from "./kernel.js"; +import { parseShard, sweep } from "./kernel.js"; +import { capsFromEnv, QuotaGovernor } from "./quota.js"; import { RULES, ToolError, type ToolCall } from "./rules/index.js"; import { loadWatchlists } from "./watchlist.js"; const out = (s: string) => process.stdout.write(`${s}\n`); export async function runWatch(args: string[]): Promise { + const startedMs = Date.now(); const flag = (name: string) => args.includes(name); const opt = (name: string) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; }; if (!flag("--once")) { - out("usage: earthdeck watch --once [--watchlist ] [--dry-run] [--max N] [--rules a,b] [--delay-ms N]"); + out("usage: earthdeck watch --once [--watchlist ]... [--dry-run] [--max N] [--rules a,b] [--delay-ms N]"); + out(" [--shard i/n] [--time-budget ]"); out(" Runs one sweep. Schedule it (cron / GitHub Actions); watermarks handle late or missed runs."); process.exitCode = 2; return; } - const wlPath = opt("--watchlist") ?? (existsSync("watchlists") ? "watchlists" : undefined); - if (!wlPath) throw new Error("no watchlists: pass --watchlist or create ./watchlists/*.json"); - const watchlists = loadWatchlists(wlPath); + const wlPaths = args.flatMap((a, i) => (a === "--watchlist" && args[i + 1] ? [args[i + 1]!] : [])); + if (!wlPaths.length && existsSync("watchlists")) wlPaths.push("watchlists"); + if (!wlPaths.length) throw new Error("no watchlists: pass --watchlist or create ./watchlists/*.json"); + const watchlists = wlPaths.flatMap((p) => loadWatchlists(p)); const dryRun = flag("--dry-run"); const maxPairs = opt("--max") ? Number(opt("--max")) : undefined; const onlyRules = opt("--rules")?.split(",").map((s) => s.trim()); const delayMs = opt("--delay-ms") ? Number(opt("--delay-ms")) : 1500; + const shard = opt("--shard") ? parseShard(opt("--shard")!) : undefined; + const budgetSec = opt("--time-budget") ? Number(opt("--time-budget")) : undefined; + if (budgetSec !== undefined && !(budgetSec > 0)) throw new Error("--time-budget must be a positive number of seconds"); + const deadline = budgetSec !== undefined ? startedMs + budgetSec * 1000 : undefined; const dir = ledgerDir(); const ledger = Ledger.open(dir); const journal = new Journal(join(dir, "watch")); + const quota = new QuotaGovernor(journal.dir, capsFromEnv()); const server = buildServer(); const [st, ct] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "earthdeck-watch", version: "1.0.0" }); await Promise.all([server.connect(st), client.connect(ct)]); - const call: ToolCall = async (tool, a) => { + const rawCall: ToolCall = async (tool, a) => { const res = await client.callTool({ name: tool, arguments: a }, undefined, { timeout: 120_000 }); const texts = (res.content as { type: string; text?: string }[]).filter((c) => c.type === "text" && typeof c.text === "string"); const text = texts[texts.length - 1]?.text ?? ""; - if (res.isError) throw new ToolError(tool, firstLine(text)); + if (res.isError) { + const d = errorDetail(text); + throw new ToolError(tool, d.message, d.status, d.body); + } try { return JSON.parse(text); } catch { throw new ToolError(tool, "non-JSON result"); } }; + // Every governed tool call is counted against today's per-provider cap (quota.json). + const call = quota.wrap(rawCall); + const usage = () => `cdse ${quota.used("cdse")}/${quota.caps.cdse} · gfw ${quota.used("gfw")}/${quota.caps.gfw} · firms ${quota.used("firms")}/${quota.caps.firms}`; out(`earthdeck watch — ${watchlists.length} watchlist(s), ${watchlists.reduce((n, w) => n + w.aois.length, 0)} AOIs, rules: ${[...RULES.keys()].join(", ")}${dryRun ? " — DRY RUN" : ""}`); - out(`ledger: ${dir}`); - const report = await sweep({ watchlists, rules: RULES, ledger, journal, call, dryRun, maxPairs, onlyRules, delayMs, log: out }); + out(`ledger: ${dir}${shard ? ` · shard ${shard.index}/${shard.count}` : ""}${budgetSec !== undefined ? ` · time budget ${budgetSec}s` : ""}`); + out(`quota ${quota.day} before: ${usage()}`); + const report = await sweep({ watchlists, rules: RULES, ledger, journal, call, dryRun, maxPairs, onlyRules, delayMs, shard, deadline, quota, log: out }); out(""); out(`sweep ${report.sweepId}: ${report.pairs} pairs · ${report.created.length} opened · ${report.confirmed.length} confirmed · ${report.evidenceAdded.length} evidence added · ${report.expired.length} expired · ${report.gaps.length} gaps · ${report.skipped.length} skipped`); for (const s of report.skipped) out(` ○ ${s.rule} @ ${s.aoi}: ${s.reason}`); for (const g of report.gaps) out(` ✗ ${g.rule} @ ${g.aoi}: ${g.message}`); + if (report.budgetExhausted) out(`budget exhausted: ${report.budgetExhausted.done} of ${report.budgetExhausted.total} pairs done`); + out(`quota ${quota.day} after: ${usage()}`); if (!dryRun) { const v = ledger.verify(); out(v.ok ? `ledger verified ✓ (${v.size} entries, root ${v.root.slice(0, 16)}…)` : `ledger verify FAILED: ${v.problems.map((p) => p.message).join("; ")}`); @@ -74,12 +92,13 @@ export async function runWatch(args: string[]): Promise { await server.close(); } -function firstLine(text: string): string { +/** The tool's error message, plus the upstream status/body when `errorResult` reported them. */ +function errorDetail(text: string): { message: string; status?: number; body?: unknown } { try { - const j = JSON.parse(text) as { error?: string }; - if (j.error) return j.error; + const j = JSON.parse(text) as { error?: string; status?: number; body?: unknown }; + if (j.error) return { message: j.error, ...(typeof j.status === "number" ? { status: j.status } : {}), ...(j.body !== undefined ? { body: j.body } : {}) }; } catch { /* plain text */ } - return text.split("\n")[0]?.slice(0, 200) ?? "error"; + return { message: text.split("\n")[0]?.slice(0, 200) ?? "error" }; } diff --git a/test/analyst.test.ts b/test/analyst.test.ts index aeead24..4325109 100644 --- a/test/analyst.test.ts +++ b/test/analyst.test.ts @@ -17,6 +17,7 @@ import { applyEvent, PUBLISH_POLICY_VERSION, type Finding, type FindingEvent, ty import { Ledger } from "../src/ledger/store.js"; import { uuidv7 } from "../src/util.js"; import { Journal } from "../src/watch/journal.js"; +import { QuotaGovernor } from "../src/watch/quota.js"; import { jsonResponse, mockFetch, type CapturedCall } from "./helpers.js"; const NARRATION_FIXTURE = JSON.parse(readFileSync("test/fixtures/anthropic-narration.json", "utf8")) as { content: { type: string; text?: string }[]; model: string }; @@ -320,3 +321,34 @@ test("analyst vs the real Ledger: the narrated event satisfies today's contract" assert.ok(["confirmed", "published"].includes(f.status)); assert.ok(ledger.verify().ok); }); + +test("analyst: daily USD cap stops the run and journals analyst_spend; the daily case cap persists across runs", async (t) => { + const caps = { cdse: 60, gfw: 400, firms: 300, analystCases: 10, analystUsd: 0.15 }; + const l = new PolicyLedger(); + l.seed(); + l.seed(); + l.seed(); + const m = anthropicMock({ "claude-opus-5": [NARRATION_FIXTURE, NARRATION_FIXTURE], "claude-sonnet-5": [REVIEW_FIXTURE, REVIEW_FIXTURE] }); + t.after(m.restore); + const j = journal(); + const q = new QuotaGovernor(j.dir, caps, "2026-09-26"); + const lines: string[] = []; + const r = await runAnalyst({ ledger: l as unknown as AnalystLedger, journal: j, apiKey: "sk-test", max: 10, quota: q, log: (s) => lines.push(s) }); + // ≈ $0.099 per finding: after two the day's $0.15 is spent, the third is not started. + assert.equal(r.published.length, 2); + assert.equal(m.api.length, 4); + assert.ok(lines.some((s) => /daily analyst budget spent/.test(s))); + const recs = readFileSync(join(j.dir, "journal.jsonl"), "utf8").trim().split("\n").map((s) => JSON.parse(s) as { kind: string; dayUsd?: number; limitUsd?: number }); + const spend = recs.filter((x) => x.kind === "analyst_spend"); + assert.equal(spend.length, 4); + assert.ok(Math.abs(spend.at(-1)!.dayUsd! - r.costUsd) < 1e-6); + assert.equal(spend[0]!.limitUsd, 0.15); + assert.ok(recs.some((x) => x.kind === "analyst_budget_stop")); + + // Same day, new process: spend is remembered → nothing runs. Case cap: 2 used of 2 → nothing selected. + const again = await runAnalyst({ ledger: l as unknown as AnalystLedger, journal: j, apiKey: "sk-test", quota: new QuotaGovernor(j.dir, caps, "2026-09-26") }); + assert.equal(m.api.length, 4); + assert.equal(again.published.length, 0); + const cases = await runAnalyst({ ledger: l as unknown as AnalystLedger, journal: j, apiKey: "sk-test", quota: new QuotaGovernor(j.dir, { ...caps, analystUsd: 100, analystCases: 2 }, "2026-09-26") }); + assert.equal(cases.selected, 0); +}); diff --git a/test/runner.test.ts b/test/runner.test.ts index 895830a..558b4e3 100644 --- a/test/runner.test.ts +++ b/test/runner.test.ts @@ -19,6 +19,8 @@ import { parsePayload, runPayload, stepsFor, + sweepTiming, + watchlistPaths, syncPlan, uploadDecision, CACHE_DEFAULT, @@ -316,3 +318,73 @@ test("src/runner stays out of the MCP server / CLI import graph", () => { rec("src"); assert.deepEqual(offenders, []); }); + +// ── scale: generated watchlists, shards, time budgets ────────────────────────────────── + +test("parsePayload: generated lists, all-generated/all-handwritten, shard, timeBudgetSec", () => { + assert.deepEqual(parsePayload({ job: "sweep", watchlist: "all-generated", shard: "3/8" }), { job: "sweep", watchlist: "all-generated", shard: "3/8" }); + assert.deepEqual(parsePayload({ job: "sweep", watchlist: "generated/forest-hotspots", timeBudgetSec: 300 }), { job: "sweep", watchlist: "generated/forest-hotspots", timeBudgetSec: 300 }); + assert.deepEqual(parsePayload('{"job":"sweep","watchlist":"all-handwritten"}'), { job: "sweep", watchlist: "all-handwritten" }); + assert.throws(() => parsePayload({ job: "sweep", watchlist: "generated/../x" }), /payload: watchlist/); + assert.throws(() => parsePayload({ job: "sweep", watchlist: "generated/" }), /payload: watchlist/); + assert.throws(() => parsePayload({ job: "sweep", watchlist: "nope" }), /payload: watchlist/); + assert.throws(() => parsePayload({ job: "sweep", shard: "8/8" }), /payload: shard/); + assert.throws(() => parsePayload({ job: "sweep", shard: "a/b" }), /payload: shard/); + assert.throws(() => parsePayload({ job: "sweep", timeBudgetSec: 0 }), /payload: timeBudgetSec/); + assert.throws(() => parsePayload({ job: "sweep", timeBudgetSec: 12.5 }), /payload: timeBudgetSec/); + assert.throws(() => parsePayload({ job: "analyst", shard: "0/8" }), /shard is only valid/); + assert.throws(() => parsePayload({ job: "export", timeBudgetSec: 60 }), /timeBudgetSec is only valid/); +}); + +test("cliArgs: watchlist targets map to --watchlist paths; shard and budget pass through", () => { + assert.deepEqual(watchlistPaths("all-generated"), ["watchlists/generated"]); + assert.deepEqual(watchlistPaths("generated/methane-basins"), ["watchlists/generated/methane-basins.json"]); + assert.deepEqual(watchlistPaths("all-handwritten"), ["watchlists/amazon.json", "watchlists/congo-borneo.json", "watchlists/controls.json", "watchlists/methane.json", "watchlists/flaring.json"]); + assert.deepEqual(cliArgs({ job: "sweep", watchlist: "all-generated", shard: "2/8", timeBudgetSec: 681, dryRun: false }, "/s"), ["watch", "--once", "--watchlist", "watchlists/generated", "--shard", "2/8", "--time-budget", "681"]); + assert.equal(cliArgs({ job: "sweep", watchlist: "all-handwritten", dryRun: true }, "/s").filter((a) => a === "--watchlist").length, 5); + assert.deepEqual(stepsFor({ job: "sweep", watchlist: "all-generated", shard: "1/8", timeBudgetSec: 100 }), [{ job: "sweep", watchlist: "all-generated", shard: "1/8", timeBudgetSec: 100, dryRun: false }]); +}); + +test("sweepTiming: --time-budget = remaining − 90 s (capped by a request), kill at remaining − 60 s", () => { + assert.deepEqual(sweepTiming(895_000), { timeBudgetSec: 805, killAfterMs: 835_000 }); + assert.deepEqual(sweepTiming(895_000, 300), { timeBudgetSec: 300, killAfterMs: 835_000 }); + assert.deepEqual(sweepTiming(895_000, 900), { timeBudgetSec: 805, killAfterMs: 835_000 }); + assert.deepEqual(sweepTiming(90_500), { timeBudgetSec: 0, killAfterMs: 30_500 }); + assert.ok(sweepTiming(60_000).timeBudgetSec < 0); +}); + +test("runStep: in Lambda (remainingMs) a sweep gets --time-budget from the remaining time; too little time → failed, nothing run", async () => { + const h = harness({ job: () => 0 }); + let remaining = 880_400; + h.cfg.remainingMs = () => remaining; + const seen: number[] = []; + const exec = h.deps.exec; + h.deps.exec = async (args, opts) => { + if (args[0] === "watch") seen.push(opts.timeoutMs); + return exec(args, opts); + }; + const r = await runPayload({ job: "sweep", watchlist: "all-generated", shard: "0/8" }, h.cfg, h.deps); + assert.equal(r.ok, true); + assert.deepEqual(h.calls[1], ["watch", "--once", "--watchlist", "watchlists/generated", "--shard", "0/8", "--time-budget", "790"]); + assert.equal(r.steps[0]!.timeBudgetSec, 790); + assert.equal(r.steps[0]!.shard, "0/8"); + assert.deepEqual(seen, [820_400]); + + remaining = 80_000; + const r2 = await runPayload({ job: "sweep", watchlist: "all-generated" }, h.cfg, h.deps); + assert.equal(r2.ok, false); + assert.match(r2.steps[0]!.reason ?? "", /no time left to sweep/); + h.cleanup(); +}); + +test("infra: every schedule Input is a valid payload; 8 shards + hand-written + analyst + export", () => { + const yaml = readFileSync("infra/earthdeck.yaml", "utf8"); + const inputs = [...yaml.matchAll(/^\s+Input: '(.+)'$/gm)].map((m) => parsePayload(m[1]!)); + const shards = inputs.filter((p) => p.watchlist === "all-generated").map((p) => p.shard).sort(); + assert.deepEqual(shards, ["0/8", "1/8", "2/8", "3/8", "4/8", "5/8", "6/8", "7/8"]); + assert.equal(inputs.filter((p) => p.watchlist === "all-handwritten").length, 1); + assert.equal(inputs.filter((p) => p.job === "analyst").length, 1); + assert.equal(inputs.filter((p) => p.job === "export").length, 1); + assert.equal(inputs.length, 11); + assert.match(yaml, /EARTHDECK_MAX_ANALYST_CASES: "10"/); +}); diff --git a/test/scale.test.ts b/test/scale.test.ts new file mode 100644 index 0000000..56579ff --- /dev/null +++ b/test/scale.test.ts @@ -0,0 +1,217 @@ +// Sweeping ~350 AOIs inside Lambda's 15 minutes and the free API tiers: deterministic, +// disjoint shards; least-recently-swept ordering; the time budget; the per-day quota +// governor (persistence, skip reasons, 429 handling). + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdtempSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Ledger } from "../src/ledger/store.js"; +import { Journal } from "../src/watch/journal.js"; +import { parseShard, shardOf, sweep } from "../src/watch/kernel.js"; +import { capsFromEnv, costOf, isQuotaError, providersForRequires, QuotaExceeded, QuotaGovernor, type QuotaCaps } from "../src/watch/quota.js"; +import { RULES, ToolError, type ToolCall } from "../src/watch/rules/index.js"; +import { parseWatchlist, type Watchlist } from "../src/watch/watchlist.js"; +import { mockFetch } from "./helpers.js"; + +const NOW = "2026-09-26T12:00:00Z"; +const DAY = "2026-09-26"; +const CAPS: QuotaCaps = { cdse: 60, gfw: 400, firms: 300, analystCases: 10, analystUsd: 3 }; + +/** n quiet fire AOIs (one fires_in call each when quiet). */ +function fireList(n: number, prefix = "a"): Watchlist { + return parseWatchlist({ + version: 1, + name: "t", + aois: Array.from({ length: n }, (_, i) => ({ id: `${prefix}-${i}`, name: `AOI ${i}`, bbox: [10 + i * 0.01, 0, 10.5 + i * 0.01, 0.5], rules: [{ name: "fires_in_protected", params: {} }] })), + }); +} +const quiet = { count: 0, source: "VIIRS_NOAA20_NRT", fires: [] }; + +function setup() { + const dir = mkdtempSync(join(tmpdir(), "earthdeck-scale-")); + const fm = mockFetch(() => new Response("{}", { status: 200 })); + return { dir, ledger: Ledger.open(dir), journal: new Journal(join(dir, "watch")), restore: fm.restore }; +} + +function recorder(fn: (tool: string, args: Record) => unknown = () => quiet) { + const calls: { tool: string; aoi: string }[] = []; + const call: ToolCall = async (tool, args) => { + calls.push({ tool, aoi: String((args.bbox as number[])[0]) }); + return fn(tool, args); + }; + return { call, calls }; +} + +test("shards: deterministic, disjoint, covering; parseShard validates", () => { + const ids = Array.from({ length: 350 }, (_, i) => `aoi-${i}`); + const rules = ["forest_loss", "fires_in_protected"]; + const counts = new Array(8).fill(0); + for (const id of ids) + for (const r of rules) { + const s = shardOf(id, r, 8); + assert.equal(shardOf(id, r, 8), s, "stable"); + assert.ok(s >= 0 && s < 8); + counts[s]++; + } + assert.equal(counts.reduce((a, b) => a + b, 0), 700); + for (const c of counts) assert.ok(c > 50 && c < 125, `balanced-ish: ${counts.join(",")}`); + assert.equal(shardOf("br-sfx", "forest_loss", 8), shardOf("br-sfx", "forest_loss", 8)); + assert.deepEqual(parseShard("3/8"), { index: 3, count: 8 }); + assert.throws(() => parseShard("8/8"), /0 ≤ i < n/); + assert.throws(() => parseShard("1/0"), /shard/); + assert.throws(() => parseShard("x"), /shard/); +}); + +test("kernel: shard i/n sweeps exactly its pairs; the n shards together cover the list once", async (t) => { + const s = setup(); + t.after(s.restore); + const wl = fireList(40); + const seen = new Map(); + for (let i = 0; i < 4; i++) { + const { call } = recorder(); + const r = await sweep({ watchlists: [wl], rules: RULES, ledger: s.ledger, journal: s.journal, call, now: NOW, hasKey: () => true, shard: { index: i, count: 4 } }); + for (const a of wl.aois) if (shardOf(a.id, "fires_in_protected", 4) === i) seen.set(a.id, (seen.get(a.id) ?? 0) + 1); + assert.equal(r.pairs, wl.aois.filter((a) => shardOf(a.id, "fires_in_protected", 4) === i).length); + } + assert.equal(seen.size, 40); + assert.ok([...seen.values()].every((n) => n === 1)); + for (const a of wl.aois) assert.equal(s.journal.watermark(a.id, "fires_in_protected"), NOW); +}); + +test("kernel: least-recently-swept pairs go first (never-swept first of all)", async (t) => { + const s = setup(); + t.after(s.restore); + const wl = fireList(4); + s.journal.setWatermark("a-0", "fires_in_protected", "2026-09-26T06:00:00Z"); + s.journal.setWatermark("a-1", "fires_in_protected", "2026-09-25T06:00:00Z"); + s.journal.setWatermark("a-3", "fires_in_protected", "2026-09-26T00:00:00Z"); + const { call, calls } = recorder(); + await sweep({ watchlists: [wl], rules: RULES, ledger: s.ledger, journal: s.journal, call, now: NOW, hasKey: () => true }); + const order = calls.map((c) => wl.aois.find((a) => String(a.bbox[0]) === c.aoi)!.id); + assert.deepEqual(order, ["a-2", "a-1", "a-3", "a-0"]); + // With a cap, the stalest pair is what gets swept. + const { call: c2, calls: calls2 } = recorder(); + s.journal.setWatermark("a-3", "fires_in_protected", "2026-09-20T00:00:00Z"); // the one left behind + await sweep({ watchlists: [wl], rules: RULES, ledger: s.ledger, journal: s.journal, call: c2, now: "2026-09-27T12:00:00Z", hasKey: () => true, maxPairs: 1 }); + assert.equal(calls2.length, 1); + assert.equal(calls2[0]!.aoi, String(wl.aois[3]!.bbox[0])); +}); + +test("kernel: time budget stops opening pairs, keeps the ones done, reports k of n", async (t) => { + const s = setup(); + t.after(s.restore); + let clock = 1_000_000; + const { call } = recorder(() => { + clock += 10_000; // each pair takes 10 s + return quiet; + }); + const lines: string[] = []; + const r = await sweep({ watchlists: [fireList(5)], rules: RULES, ledger: s.ledger, journal: s.journal, call, now: NOW, hasKey: () => true, clock: () => clock, deadline: 1_000_000 + 25_000, log: (l) => lines.push(l) }); + // pair 1 at 0 s, pair 2 at 10 s (10+10 ≤ 25), pair 3 at 20 s would need until 30 s → stop. + assert.deepEqual(r.budgetExhausted, { done: 2, total: 5 }); + assert.ok(lines.includes("budget exhausted: 2 of 5 pairs done")); + assert.equal(s.journal.watermark("a-0", "fires_in_protected"), NOW); + assert.equal(s.journal.watermark("a-1", "fires_in_protected"), NOW); + assert.equal(s.journal.watermark("a-2", "fires_in_protected"), null); + const kinds = readFileSync(join(s.dir, "watch/journal.jsonl"), "utf8").trim().split("\n").map((l) => (JSON.parse(l) as { kind: string }).kind); + assert.ok(kinds.includes("budget_exhausted")); + assert.equal(kinds.at(-1), "sweep_end"); + + // Next run (resume): the untouched pairs go first. + const { call: c2, calls } = recorder(); + await sweep({ watchlists: [fireList(5)], rules: RULES, ledger: s.ledger, journal: s.journal, call: c2, now: "2026-09-26T18:00:00Z", hasKey: () => true, maxPairs: 3 }); + assert.deepEqual(calls.map((c) => c.aoi), ["10.02", "10.03", "10.04"]); + + // No deadline → no budget report. + const { call: c3 } = recorder(); + const r3 = await sweep({ watchlists: [fireList(2)], rules: RULES, ledger: s.ledger, journal: s.journal, call: c3, now: NOW, hasKey: () => true }); + assert.equal(r3.budgetExhausted, undefined); +}); + +test("quota: cost model, provider mapping, env caps, quota-error detection", () => { + assert.deepEqual(costOf("forest_alerts", {}), { provider: "gfw", units: 1 }); + assert.deepEqual(costOf("eo_compare", {}), { provider: "cdse", units: 1 }); + assert.deepEqual(costOf("methane_plumes", {}), { provider: "cdse", units: 1 }); + assert.deepEqual(costOf("fires_in", {}), { provider: "firms", units: 1 }); + assert.deepEqual(costOf("flaring", { days: 30 }), { provider: "firms", units: 12 }); + assert.deepEqual(costOf("flaring", { days: 2 }), { provider: "firms", units: 2 }); + assert.deepEqual(costOf("flaring", { days: 30, sources: ["VIIRS_NOAA20_NRT"] }), { provider: "firms", units: 6 }); + assert.equal(costOf("events", {}), null); + assert.equal(costOf("enso", {}), null); + assert.deepEqual(providersForRequires(RULES.get("forest_loss")!.requires).sort(), ["cdse", "gfw"]); + assert.deepEqual(providersForRequires(RULES.get("flaring")!.requires), ["firms"]); + assert.deepEqual(providersForRequires(RULES.get("methane_anomaly")!.requires), ["cdse"]); + + assert.deepEqual(capsFromEnv({}), CAPS); + assert.deepEqual(capsFromEnv({ EARTHDECK_MAX_CDSE_CALLS: "5", EARTHDECK_MAX_ANALYST_USD: "0.5" }), { ...CAPS, cdse: 5, analystUsd: 0.5 }); + assert.throws(() => capsFromEnv({ EARTHDECK_MAX_GFW_CALLS: "lots" }), /EARTHDECK_MAX_GFW_CALLS/); + + assert.equal(isQuotaError("GFW query failed (429)", 429), true); + assert.equal(isQuotaError("FIRMS request failed (429)"), true); + assert.equal(isQuotaError("Copernicus Process failed (403)", 403, '{"error":"processing units quota exceeded"}'), true); + assert.equal(isQuotaError("GFW API key was rejected", 403, "Forbidden"), false); // a bad key is not a quota + assert.equal(isQuotaError("Copernicus Process failed (500)", 500), false); +}); + +test("quota governor: per-day caps skip pairs as quota:, persist across runs, reset next day", async (t) => { + const s = setup(); + t.after(s.restore); + const caps = { ...CAPS, firms: 3 }; + const q1 = new QuotaGovernor(s.journal.dir, caps, DAY); + const { call: raw, calls } = recorder(); + const r1 = await sweep({ watchlists: [fireList(5)], rules: RULES, ledger: s.ledger, journal: s.journal, call: q1.wrap(raw), quota: q1, now: NOW, hasKey: () => true }); + assert.equal(calls.length, 3); + assert.deepEqual(r1.skipped.map((x) => x.reason), ["quota:firms", "quota:firms"]); + assert.equal(r1.gaps.length, 0); + assert.equal(s.journal.watermark("a-3", "fires_in_protected"), null, "watermark untouched on a quota skip"); + assert.equal(s.journal.watermark("a-4", "fires_in_protected"), null); + const journal = readFileSync(join(s.dir, "watch/journal.jsonl"), "utf8"); + assert.match(journal, /"kind":"skip","aoi":"a-3","rule":"fires_in_protected","message":"quota:firms"/); + assert.ok(existsSync(join(s.journal.dir, "quota.json"))); + assert.deepEqual(JSON.parse(readFileSync(join(s.journal.dir, "quota.json"), "utf8")), { [DAY]: { firms: 3 } }); + + // Same day, a later run (new process): the cap is already spent — nothing is called. + const q2 = new QuotaGovernor(s.journal.dir, caps, DAY); + assert.equal(q2.used("firms"), 3); + const { call: raw2, calls: calls2 } = recorder(); + const r2 = await sweep({ watchlists: [fireList(5)], rules: RULES, ledger: s.ledger, journal: s.journal, call: q2.wrap(raw2), quota: q2, now: "2026-09-26T18:00:00Z", hasKey: () => true }); + assert.equal(calls2.length, 0); + assert.equal(r2.skipped.length, 5); + + // Next UTC day: fresh counters, and the two starved pairs go first. + const q3 = new QuotaGovernor(s.journal.dir, caps, "2026-09-27"); + const { call: raw3, calls: calls3 } = recorder(); + await sweep({ watchlists: [fireList(5)], rules: RULES, ledger: s.ledger, journal: s.journal, call: q3.wrap(raw3), quota: q3, now: "2026-09-27T00:00:00Z", hasKey: () => true }); + assert.deepEqual(calls3.map((c) => c.aoi), ["10.03", "10.04", "10"]); + const file = JSON.parse(readFileSync(join(s.journal.dir, "quota.json"), "utf8")) as Record; + assert.deepEqual(Object.keys(file).sort(), ["2026-09-26", "2026-09-27"]); + assert.equal(file["2026-09-27"]!.firms, 3); +}); + +test("quota governor: a 429 marks the provider exhausted for the rest of the run; over-cap calls throw QuotaExceeded", async (t) => { + const s = setup(); + t.after(s.restore); + const q = new QuotaGovernor(null, CAPS, DAY); + let n = 0; + const { call: raw } = recorder(() => { + if (++n === 2) throw new ToolError("fires_in", "FIRMS request failed (429)", 429, "Too Many Requests"); + return quiet; + }); + const r = await sweep({ watchlists: [fireList(5)], rules: RULES, ledger: s.ledger, journal: s.journal, call: q.wrap(raw), quota: q, now: NOW, hasKey: () => true }); + assert.equal(n, 2); + assert.equal(r.gaps.length, 1); // the call that got the 429 is a real gap + assert.match(r.gaps[0]!.message, /429/); + assert.deepEqual(r.skipped.map((x) => x.reason), ["quota:firms", "quota:firms", "quota:firms"]); + assert.equal(q.blocked("gfw"), null, "other providers unaffected"); + + // Direct: a call that would cross the cap is refused before it reaches the provider. + const q2 = new QuotaGovernor(null, { ...CAPS, firms: 10 }, DAY); + let reached = 0; + const wrapped = q2.wrap(async () => (reached++, quiet)); + await assert.rejects(wrapped("flaring", { days: 30 }), (e: unknown) => e instanceof QuotaExceeded && e.provider === "firms" && e instanceof ToolError); + assert.equal(reached, 0); + await wrapped("events", {}); // ungoverned + assert.equal(q2.used("firms"), 0); +}); From d8e5e203b5a3a670eef27877c537cab7e94ed2bd Mon Sep 17 00:00:00 2001 From: marcoloco Date: Sat, 26 Sep 2026 22:19:16 +0200 Subject: [PATCH 3/9] CONTINUITY: rename checklist (one planned pass once the name is chosen) Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_017KN8pr3M1ayKPTNRcNSc2D --- CONTINUITY.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CONTINUITY.md b/CONTINUITY.md index 18c516d..d153a6b 100644 --- a/CONTINUITY.md +++ b/CONTINUITY.md @@ -44,6 +44,14 @@ reference is [CLAUDE.md](CLAUDE.md); the phase plan is [ROADMAP.md](ROADMAP.md). or buy anything without showing Marc the exact item + price first. IPv6 is disabled on CloudFront on purpose (AAAA-only resolver answers broke the fresh domain on IPv6-less networks); Tailscale MagicDNS on Marc's Mac negative-cached the name for an hour. +3b. **Rename — one planned pass once Marc picks a name** (2026-09-26: "naming is all over the + place: earthdeck / Earth Watch / vitalearth.io"). Checklist: npm package + bin + repo + name; `src/site.config.ts` (name, fullName, organization, baseUrl); ledger predicate + `https://earthdeck.dev/finding-event/v1` (keep v1 URL for old entries, add v2 or a + `$schema` alias — do NOT rewrite history); CloudFormation stack/bucket/function names + (new stack + migrate state, or keep internal names); domain (registration only after + trademark check + Marc's explicit OK on the exact name + price); README/CLAUDE/VISION; + `checkpoint` signer name stays "earthdeck" unless the key is rotated. Do it in one PR. 4. **Next build steps**: (a) attribution onto cases in `created.context` (`protected_areas` + `emitters`); (b) `emitters` as the methane confirmer while EMIT is stale; (c) `ledger verify --remote ` (the case pages already print it); (d) GEE: Marc creates the GCP From a8e1b434a2c7eaca6917d1de74398cdb1da86c58 Mon Sep 17 00:00:00 2001 From: marcoloco Date: Sat, 26 Sep 2026 22:25:36 +0200 Subject: [PATCH 4/9] =?UTF-8?q?site:=20TerraKeep=20=E2=80=94=20'Keeping=20?= =?UTF-8?q?Earth=20within=20its=20limits'=20(no=20domain=20purchase;=20ser?= =?UTF-8?q?ved=20at=20vitalearth.io=20for=20now)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_017KN8pr3M1ayKPTNRcNSc2D --- infra/placeholder/index.html | 4 ++-- src/site.config.ts | 10 +++++----- src/watch/site-render.ts | 6 +++--- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/infra/placeholder/index.html b/infra/placeholder/index.html index e9d9f5b..85c45ad 100644 --- a/infra/placeholder/index.html +++ b/infra/placeholder/index.html @@ -3,7 +3,7 @@ -Earth Watch +TerraKeep