Skip to content

fix(spored): charge --cost-limit on Spot instances at the Spot price (#1497) - #1555

Merged
scttfrdmn merged 1 commit into
mainfrom
fix/1497-spot-cost-limit
Nov 8, 2026
Merged

scttfrdmn merged 1 commit into
mainfrom
fix/1497-spot-cost-limit

Conversation

@scttfrdmn

Copy link
Copy Markdown
Contributor

Fixes #1497 (the Spot-rate half). The other half of #1497, where the --command process gets no SIGTERM or grace period at the limit, is split out to #1554 and is not in this PR.

Root cause

--cost-limit charged every instance's compute at the on-demand rate. For a Spot instance that is about 3x what it pays, so spored terminated it after about a third of the user's budget.

  • pkg/agent/agent.go:997 (main, costFootprint): ComputePerHour: a.config.PricePerHour, which is spawn:price-per-hour, the on-demand rate truffle resolved at launch (pkg/aws/pricing.go resolvePricePerHour). accumulatedComputeCost (:991) feeds that into costmodel.Accrue, and checkAndAct (:795-807) terminates on the result.
  • The Spot price was already recorded at launch (spawn:spot-price-per-hour, pkg/aws/spotprice.go recordLaunchSpotPrice, spawn status: spot instances are costed at the on-demand rate; brand-new instances show $0.00 / '100% lower' effective rate #896), but it was deliberately display-only ("can only overstate a spot instance": pkg/provider/provider.go:103-107, pkg/costmodel/costmodel.go Footprint.ComputePerHour).
  • The CLI mirrored it: cmd/cost_accounting.go enforcedFootprint → costmodel.FromTags reads only spawn:price-per-hour, and spawn status printed "counted at the on-demand rate".

The fix

  • Spot accrual (pkg/costmodel/accrual.go). ComputeAccrual is a running sum, cost(compute) = Dollars + PerHour × (compute − AtSeconds). Advance charges each interval between samples at the higher of the two prices around it, so the cap fires early rather than late (the costmodel convention). spored saves it in a new tag, spawn:spot-accrual (v1:<dollars>/<at>/<rate>/<basis>/<sampled-unix>, append-only versioned like spawn:cost-footprint).
  • spored (pkg/agent/spotaccrual.go):
  • Fallback. If no read succeeds for 1 h (failing, or the sampler is stuck), compute is charged at the on-demand rate from then on. The log line, spored status, spawn status/spawn cost and the terminal completion.json all say it is a fallback, why, and where and when the rate was collected. A static rate says STATIC with its collection date and reason unknown, because the instance records neither (owner rule; same known gap as singleInstanceCostReport, spawn#1512). A later good read goes back to the Spot price.
  • Completion record. A cost-limit termination passes a CostBasis JSON object to the task flush hook in SPAWN_COST_BASIS_JSON. Any inherited value is stripped, and it is set only for cost_limit_exceeded. The hook writes it as a new additive cost_basis field (pkg/taskproto).
  • CLI. costmodel.FromTags charges compute from spawn:spot-accrual when spored recorded one, so spawn status, spawn cost and spawn extend --raise-cost-limit show and size against the figure that terminates the instance. With only spawn:spot-price-per-hour the CLI stays on on-demand, because that is what a spored older than this PR enforces.
  • On-demand instances are unchanged: no accrual, no tag, no reads.

IAM change (verify with a real PutRolePolicy)

ec2:DescribeSpotPriceHistory is added to the read statement in both policies a spored role carries:

  • pkg/aws/iam.go sporedSelfManagementStatements → sporedReadPermissions: the spored-baseline-policy applied to every spawn-instance-* role on each launch (ensureSporedBaselinePolicy, so existing roles pick it up at their next launch).
  • pkg/aws/iam.go sporedDCVRolePolicy: spored-instance-role and the DCV role.

It is an Allow with Resource: "*" (the API supports no resource-level scoping) and no Condition. There is no policy variable anywhere. Test: pkg/aws/iam_spot_price_test.go. Without the grant, spored falls back to the labelled on-demand rate rather than failing.

Other effects worth checking

  • One more tag slot on Spot launches. spawn:spot-accrual is on postLaunchInstanceTags (applies: isSpot), so the reserve grows by 1 for Spot launches. The pinned maximal-shape counts move: the maximal launch less a job array and a web app goes from 48 to 49 of 50, and the documented monitoring setup goes from 46 to 47. A Spot launch that was exactly at the 50-tag edge will now be refused, and the refusal names the slot.
  • Public surface (additive only):
    • pkg/aws: SpotPriceAPI, SpotPriceForInstance.
    • pkg/taskproto: CostBasis, CostBasisEnv, CompletionRecord.CostBasis.
    • api/public-surface.txt is regenerated.
  • The --cost-limit flag help and spawn cost --help text changed, and docs-gen/ is regenerated.

Tests

  • pkg/agent/spotaccrual_test.go:
    • The issue's numbers ($1.09 Spot / $3.418 on-demand / limit $7 / 2.05 h): a Spot instance accrues ~$2.23 and is not terminated. The on-demand twin accrues $7.01, is terminated, and writes no accrual tag.
    • A read is integrated and recorded.
    • A failure keeps the last price for under 1 h, then falls back with a labelled log line, and a good read recovers.
    • A stuck sampler falls back.
    • First-read activation, seeding from the tag, the cost-basis JSON for a static fallback, hook env scoping, and the sampler running off the loop and never reading on on-demand.
  • pkg/costmodel/accrual_test.go: the accrual arithmetic, the max-price rule, encode/parse, and that FromTags prefers spored's accrual and ignores the launch spot tag alone.
  • pkg/taskproto/flush_cost_basis_test.go: the real hook under bash. With SPAWN_COST_BASIS_JSON set it writes a parsable record carrying cost_basis; with it unset there is no field.
  • cmd/cost_limit_spot_test.go: CLI costLimitSpend and labels (Spot, static fallback says static/date unknown/reason unknown, on-demand), plus spawn cost's compute line.
  • pkg/aws/iam_spot_price_test.go, pkg/provider tag parsing, and cmd/spored status (the old test pinned the on-demand figure and now asserts the Spot figure and basis).
  • make check passes locally except two checks that break only because my worktree path contains a space (/Volumes/External HD/...): lambda/dashboard-api TestSetupAllRunsEveryStepFromAnyDirectory (passes in a checkout without a space; that module is untouched) and check-build-tags. CI will settle both. go test -race ./pkg/agent/... and semgrep scan --config=auto --error . are clean.

Live EC2 test plan (before merge)

This changes spored's behaviour, and nothing here has run on a real instance. Use spore-host-dev only, a branch-built CLI (make build; spored must be the branch build, GOOS=linux GOARCH=arm64 for Graviton), in us-east-1. Expected spend is under $0.10.

  1. Spot, the fix. Run spawn launch spot1497 --instance-type c7g.medium --spot --cost-limit 0.03 --ttl 3h.
    • Note the two rates at launch with spawn status spot1497. Roughly: on-demand $0.0363/h; Spot about $0.01–0.015/h; plus EBS (8 GiB gp3, about $0.0011/h) and IPv4 ($0.005/h).
    • At the on-demand rate $0.03 is reached after about 43 min; at Spot it takes about 1.5–2 h. Work out both exact times from the rates spawn status shows.
    • Observe:
      • (a) aws ec2 describe-tags --filters Name=resource-id,Values=<id> Name=key,Values=spawn:spot-accrual shows v1:…/spot/… within a minute or two of spored starting, and its dollars and at move every 15 min.
      • (b) spawn connect then sudo spored status shows counting compute at the Spot price, now $X/hr (DescribeSpotPriceHistory, as of …), and its "Cost limit … used" grows at the Spot running rate.
      • (c) spawn status spot1497 shows a cost-limit line saying "compute at the Spot price spored samples".
      • (d) The instance is still running past the on-demand-rate time (~45–50 min).
      • (e) It terminates when Spot spend reaches $0.03 (within one 15-min sample of the predicted time). journalctl -u spored (or /var/log/spored.log) shows Cost limit reached (… compute at the Spot price …).
    • Verify the IAM: aws iam get-role-policy --role-name <spawn-instance-…> --policy-name spored-baseline-policy lists ec2:DescribeSpotPriceHistory. The launch did a real PutRolePolicy, so a policy PutRolePolicy rejects would have failed the launch.
  2. On-demand control (unchanged). The same command without --spot. It terminates at about 43 min (on-demand). spawn:spot-accrual is never written, and spored status says "compute at the on-demand rate $0.0363/hr (spawn:price-per-hour, read live from the AWS Price List at launch, …)".
  3. Fallback (optional). On a third Spot instance, attach a temporary inline policy denying ec2:DescribeSpotPriceHistory to its role, then restart spored. Observe the Warning: could not read the Spot price lines. After 1 h, check that spawn:spot-accrual flips to /on-demand/ and that spored status / spawn status say FALLBACK with the reason and the rate's launch collection date. With spawn task run, a cost-limit kill's completion.json carries cost_basis.fallback. Remove the deny policy afterwards.
  4. Leave no trace. After each run, check spawn list and aws ec2 describe-instances --filters Name=tag:Name,Values=spot1497* for no running or stopped instances, and no open Spot requests.

…1497)

A Spot instance's compute was charged against --cost-limit at the on-demand
rate (spawn:price-per-hour), about 3x its Spot price, so spored terminated it
after about a third of the user's budget.

spored now reads the Spot price for its type, zone and platform
(DescribeSpotPriceHistory) every 15 minutes off the monitor loop and
integrates it over compute time (costmodel.ComputeAccrual, persisted in
spawn:spot-accrual). If the price cannot be read for an hour it falls back
to the on-demand rate, labelled with why, the rate's source and collection
date, in the log, spored status, the CLI displays and the terminal
completion record (new cost_basis field). The CLI reads the same accrual,
so spawn status/cost/extend show the figure that terminates the instance.

IAM: ec2:DescribeSpotPriceHistory added to the spored baseline policy and
spored-instance-role (Resource "*", no condition, no policy variable).

Fixes #1497
@scttfrdmn scttfrdmn added this to the Hardening milestone Nov 8, 2026
@scttfrdmn scttfrdmn added area:spored on-node agent: lifecycle, telemetry, readiness area:cost cost estimation, budgets, accounting type:bug spend-safety Bugs where a cost control does not do what it says — real-money risk labels Nov 8, 2026
@codecov

codecov Bot commented Nov 8, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.82879% with 21 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
pkg/agent/spotaccrual.go 92.14% 11 Missing ⚠️
pkg/provider/ec2.go 33.33% 6 Missing ⚠️
cmd/status_stopped.go 33.33% 2 Missing ⚠️
pkg/aws/spotprice.go 0.00% 1 Missing ⚠️
pkg/costmodel/accrual.go 97.61% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@scttfrdmn

Copy link
Copy Markdown
Contributor Author

Live EC2 verification: PASS (spore-host-dev 435415984226, us-east-1, 2026-11-08)

Build and method.

  • CLI built from this PR's head 3e4f36c (0.161.1-0.20261108201343-3e4f36c16470).
  • spored built from the same head with GOOS=linux GOARCH=arm64, sha256 29b462af…a56ebdef20ee7158e0901e823d77e.
  • A dev build's bootstrap installs the published spawn/current spored (v0.161.0). I did not write to the infra spawn-binaries buckets. Instead I swapped the branch spored in over SSM about 1.5 min after boot: presigned GET → sha256 check → atomic mv → systemctl restart spored. Both instances then tagged spawn:spored-version=0.161.1-0.20261108201343-3e4f36c16470.
  • The swap loses nothing. The seed is spawn:spot-price-per-hour at compute 0, so the minutes under the old spored are charged at the Spot price too.

Launches.

  • Spot: spawn launch spot1497 --instance-type c7g.medium --spot --cost-limit 0.03 --ttl 3h --region us-east-1 → i-04eca5bec181b8482, launched 21:12:25Z.
  • On-demand control: the same command without --spot → od1497 i-097ad6c9033924883, launched 21:12:58Z.

Rates from spawn status.

  • Spot: $0.0196/h Spot + $0.0022/h EBS + $0.005/h IPv4 = $0.0268/h, so $0.03 is reached after 67.2 min.
  • On-demand: $0.0363/h + the same = $0.0434/h, so after 41.5 min.
check result
(a) spawn:spot-accrual written and advancing v1:0.000806/148/0.019600/spot/… (21:15) → v1:0.010606/1948/… (21:45) → v1:0.015506/2848/… (22:00) → v1:0.020079/3688/… (22:14). One update per 15-min sample; 1800 s × $0.0196/h = $0.0098, which matches. On-demand: never written.
(b) spored status (over SSM) counting compute at the Spot price, now $0.0196/hr (DescribeSpotPriceHistory, as of 2026-11-08T19:00:00Z; re-read every 15m0s) and Compute cost: … × $0.0196/hr spot
(c) spawn status spot1497 Same line: counting compute at the Spot price, now $0.0196/hr (DescribeSpotPriceHistory, …). Note the wording differs from the plan's "compute at the Spot price spored samples". The on-demand control shows counting compute at the on-demand rate $0.0363/hr (spawn:price-per-hour, read live from the AWS Price List at launch, 2026-11-08T21:12:57Z)
(d) Spot outlives the on-demand point The on-demand control was terminated 21:55:03Z (42.1 min). The Spot instance was still running at 21:56:35Z with $0.02 used … 67%.
(e) Spot terminates at the Spot-rate time 22:12:57 Warning sent to users: ⚠️ COST LIMIT: $0.0270 of $0.03 spent (90%). Terminated 22:20:04Z (67.6 min; predicted 67.2). CloudTrail TerminateInstances was called by assumed-role/spored-instance-role/i-04eca5bec181b8482 at 22:20:05Z, and by …/i-097ad6c9033924883 at 21:55:03Z for the control: both self-terminated. I didn't capture the final Cost limit reached (…) line, because my log tail stopped at the first match, which was the 90% warning.

IAM, checked with real PutRolePolicy calls.

  • spored-instance-role / spored-policy: CloudTrail shows PutRolePolicy at 21:12:22Z and 21:12:56Z from the branch CLI, with no errorCode, and the document contains ec2:DescribeSpotPriceHistory. get-role-policy afterwards: ["ec2:DescribeTags","ec2:DescribeInstances","ec2:DescribeVolumes","ec2:DescribeSpotPriceHistory"]. Plain spawn launch uses this role, not a spawn-instance-* one.
  • spawn-instance-* / spored-baseline-policy: a branch-CLI launch with --s3-read created spawn-instance-4bc33c9a. Its baseline policy's first statement is ["ec2:DescribeTags","ec2:DescribeInstances","ec2:DescribeVolumes","ec2:DescribeSpotPriceHistory"]. That instance was terminated at once.

Fallback, partly exercised (no deny policy needed). Worth knowing before release.

  • At 21:17:33Z a released v0.161.0 spawn launch (an unrelated helper in this session) rewrote the shared spored-policy without the new action. The live Spot instance's next sample failed:
    21:29:57 Warning: could not read the Spot price (... UnauthorizedOperation ... spored-instance-role/i-04eca5bec181b8482 is not authorized to perform: ec2:DescribeSpotPriceHistory ...); still charging compute at the last one read, $0.0196/hr, until it is 1h0m0s old, then at the on-demand rate
    
  • A branch-CLI launch at 21:38 put the grant back, and the 21:45 sample succeeded and advanced the accrual. So the log line and the keep-last-price-under-1h path work live.
  • I did not observe the 1 h flip to /on-demand/ (the optional step 3). It would have needed the deny to persist and a third Spot instance, and I skipped it for time.
  • Implication: spored-instance-role is shared and rewritten by whichever CLI version launches last. Until every launcher is on a release with this change, Spot instances in a mixed-version account will keep losing the grant and falling back to on-demand after 1 h. The fallback is labelled, so this is not a blocker, but it is version skew users may notice.

Leak check (us-east-1 and us-west-2, after teardown).

  • No instances pending, running, stopping, stopped or shutting-down.
  • No open or active Spot requests: sir-qn5qqajg is closed / instance-terminated-by-user.
  • No unattached volumes, unassociated EIPs or new security groups, and no new key pairs.
  • The spawn-instance-4bc33c9a role remains. It is spawn-managed, and spawn cleanup --instance-roles or the reaper removes it after the 24 h guard.

Cost: c7g.medium Spot 67.6 min, c7g.medium on-demand 42.1 min, plus 2 short helpers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:cost cost estimation, budgets, accounting area:spored on-node agent: lifecycle, telemetry, readiness spend-safety Bugs where a cost control does not do what it says — real-money risk type:bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

--cost-limit on Spot instances is enforced at the on-demand rate, and terminates the job without a signal

1 participant