Repository navigation
fix(spored): charge --cost-limit on Spot instances at the Spot price (#1497) - #1555
Merged
Merged
Conversation
…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
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Contributor
Author
Live EC2 verification: PASS (spore-host-dev 435415984226, us-east-1, 2026-11-08)Build and method.
Launches.
Rates from
IAM, checked with real PutRolePolicy calls.
Fallback, partly exercised (no deny policy needed). Worth knowing before release.
Leak check (us-east-1 and us-west-2, after teardown).
Cost: c7g.medium Spot 67.6 min, c7g.medium on-demand 42.1 min, plus 2 short helpers. |
This was referenced Nov 8, 2026
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #1497 (the Spot-rate half). The other half of #1497, where the
--commandprocess gets no SIGTERM or grace period at the limit, is split out to #1554 and is not in this PR.Root cause
--cost-limitcharged 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 isspawn:price-per-hour, the on-demand rate truffle resolved at launch (pkg/aws/pricing.goresolvePricePerHour).accumulatedComputeCost(:991) feeds that intocostmodel.Accrue, andcheckAndAct(:795-807) terminates on the result.spawn:spot-price-per-hour,pkg/aws/spotprice.gorecordLaunchSpotPrice, 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.goFootprint.ComputePerHour).cmd/cost_accounting.goenforcedFootprint→costmodel.FromTagsreads onlyspawn:price-per-hour, andspawn statusprinted "counted at the on-demand rate".The fix
pkg/costmodel/accrual.go).ComputeAccrualis a running sum,cost(compute) = Dollars + PerHour × (compute − AtSeconds).Advancecharges 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 likespawn:cost-footprint).pkg/agent/spotaccrual.go):spawn:spot-accrual(an earlier run, for stop/start or upgrade), else fromspawn:spot-price-per-hour.DescribeSpotPriceHistory(newprovider.SpotPriceReader,EC2Provider.CurrentSpotPrice→ new exportedaws.SpotPriceForInstance) at once, then every 15 min. It runs off the monitor loop (CRITICAL: spored monitor loop never runs after startup — TTL/idle/on-complete/pre-stop all silently dead #65), and the monitor loop applies each read, since it owns the compute clock.spored status,spawn status/spawn costand the terminalcompletion.jsonall 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 assingleInstanceCostReport, spawn#1512). A later good read goes back to the Spot price.CostBasisJSON object to the task flush hook inSPAWN_COST_BASIS_JSON. Any inherited value is stripped, and it is set only forcost_limit_exceeded. The hook writes it as a new additivecost_basisfield (pkg/taskproto).costmodel.FromTagscharges compute fromspawn:spot-accrualwhen spored recorded one, sospawn status,spawn costandspawn extend --raise-cost-limitshow and size against the figure that terminates the instance. With onlyspawn:spot-price-per-hourthe CLI stays on on-demand, because that is what a spored older than this PR enforces.IAM change (verify with a real PutRolePolicy)
ec2:DescribeSpotPriceHistoryis added to the read statement in both policies a spored role carries:pkg/aws/iam.gosporedSelfManagementStatements→sporedReadPermissions: thespored-baseline-policyapplied to everyspawn-instance-*role on each launch (ensureSporedBaselinePolicy, so existing roles pick it up at their next launch).pkg/aws/iam.gosporedDCVRolePolicy:spored-instance-roleand the DCV role.It is an
AllowwithResource: "*"(the API supports no resource-level scoping) and noCondition. 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
spawn:spot-accrualis onpostLaunchInstanceTags(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.pkg/aws:SpotPriceAPI,SpotPriceForInstance.pkg/taskproto:CostBasis,CostBasisEnv,CompletionRecord.CostBasis.api/public-surface.txtis regenerated.--cost-limitflag help andspawn cost --helptext changed, anddocs-gen/is regenerated.Tests
pkg/agent/spotaccrual_test.go:pkg/costmodel/accrual_test.go: the accrual arithmetic, the max-price rule, encode/parse, and thatFromTagsprefers spored's accrual and ignores the launch spot tag alone.pkg/taskproto/flush_cost_basis_test.go: the real hook under bash. WithSPAWN_COST_BASIS_JSONset it writes a parsable record carryingcost_basis; with it unset there is no field.cmd/cost_limit_spot_test.go: CLIcostLimitSpendand labels (Spot, static fallback says static/date unknown/reason unknown, on-demand), plusspawn cost's compute line.pkg/aws/iam_spot_price_test.go,pkg/providertag parsing, andcmd/sporedstatus (the old test pinned the on-demand figure and now asserts the Spot figure and basis).make checkpasses locally except two checks that break only because my worktree path contains a space (/Volumes/External HD/...):lambda/dashboard-apiTestSetupAllRunsEveryStepFromAnyDirectory(passes in a checkout without a space; that module is untouched) andcheck-build-tags. CI will settle both.go test -race ./pkg/agent/...andsemgrep 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=arm64for Graviton), in us-east-1. Expected spend is under $0.10.spawn launch spot1497 --instance-type c7g.medium --spot --cost-limit 0.03 --ttl 3h.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).spawn statusshows.aws ec2 describe-tags --filters Name=resource-id,Values=<id> Name=key,Values=spawn:spot-accrualshowsv1:…/spot/…within a minute or two of spored starting, and its dollars andatmove every 15 min.spawn connectthensudo spored statusshowscounting compute at the Spot price, now $X/hr (DescribeSpotPriceHistory, as of …), and its "Cost limit … used" grows at the Spot running rate.spawn status spot1497shows a cost-limit line saying "compute at the Spot price spored samples".journalctl -u spored(or/var/log/spored.log) showsCost limit reached (… compute at the Spot price …).aws iam get-role-policy --role-name <spawn-instance-…> --policy-name spored-baseline-policylistsec2:DescribeSpotPriceHistory. The launch did a real PutRolePolicy, so a policy PutRolePolicy rejects would have failed the launch.--spot. It terminates at about 43 min (on-demand).spawn:spot-accrualis never written, andspored statussays "compute at the on-demand rate $0.0363/hr (spawn:price-per-hour, read live from the AWS Price List at launch, …)".ec2:DescribeSpotPriceHistoryto its role, then restart spored. Observe theWarning: could not read the Spot pricelines. After 1 h, check thatspawn:spot-accrualflips to/on-demand/and thatspored status/spawn statussay FALLBACK with the reason and the rate's launch collection date. Withspawn task run, a cost-limit kill'scompletion.jsoncarriescost_basis.fallback. Remove the deny policy afterwards.spawn listandaws ec2 describe-instances --filters Name=tag:Name,Values=spot1497*for no running or stopped instances, and no open Spot requests.