Repository navigation
Description
The bug to fix first, independent of the API work
internal/storage/s3/pricing_manager.go:126 prices Standard PUT 10× too low.
// pricing_manager.go:122-127
func (pm *PricingManager) getDefaultRequestCost(requestType, tier string) float64 {
// Default request costs per 1000 requests
costs := map[string]map[string]float64{
"PUT": {
TierStandard: 0.0005, // ← AWS us-east-1 is $0.005 per 1,000internal/cost/pricing.go:48 has it right: PutRequest: 0.000005, // $0.005 / 1000. So the two tables in this repo disagree by 10× on the single most common billable write, and which number a caller gets depends on which package it reached for.
internal/cost/pricing_drift_test.go exists precisely to catch this and misses it: TestDefaultPricesMatchStorageTiers compares only StoragePerGBMonth. The comment at its head is candid about the risk — "The two tables are independent, so they can silently drift apart and report different costs for the same object depending on which package a caller reached for" — and then the assertion covers one of six fields. Extending it to GetRequest, PutRequest, ListRequest, RetrievalPerGB, and EgressPerGB fails immediately on this and is a ten-line change.
Two more arithmetic defects in the same neighbourhood:
internal/cost/calculator.go:119-124divides by 1024³ where AWS bills decimal GB.byteToGBreturnsbytes / (1024*1024*1024); S3 storage is billed per GB-month where GB = 10⁹ bytes. Every storage cost is ~7.4% low. The function's own comment states the binary choice explicitly — "(binary: 1 GB = 1 073 741 824 bytes)" — so this is a deliberate decision that happens to be wrong about how AWS invoices. NoteMinObjectSizebilling minimums are also decimal (128 KB = 128,000 bytes), so the same unit question recurs there.- Region is decorative.
pm.config.Regionis read at exactly one line (pricing_manager.go:266) to stamp a summary field. Every rate is us-east-1. Soregion: us-west-2produces us-east-1 numbers labelledus-west-2— worse than producing no number, because the label makes it look checked.
Storage rates are duplicated in six places, four of them live code: internal/cost/pricing.go:46,94, internal/storage/s3/tiers.go:63,133, internal/analytics/model.go:14, plus prose in internal/storage/s3/doc.go:60,96,287.
Context: what v0.10.1 removed and why this issue exists
#161 deleted the previous "Pricing API integration" (fetchFromPricingAPI, parsePricingData, mapTierToStorageClass, extractStorageCost, extractRetrievalCost). It was not a partial implementation — the parser matched products on human-readable storage-class names that do not appear in Pricing API payloads, and both cost extractors ignored their arguments and returned hardcoded constants. Enabling use_pricing_api fetched a multi-megabyte JSON document over HTTP and discarded it in favour of 0.023. The flag is now deprecated and warns at startup.
This issue is doing it for real. The traps below were verified against the live API during the audit; each one is why the previous attempt failed.
Verified traps to encode
1. productFamily is absent from 315 of 381 S3 products. Any filter or switch keyed on it silently drops 83% of the catalog. This is what broke the deleted parser.
2. usagetype is the only stable 1:1 key. USW2-Requests-Tier1, USW2-TimedStorage-ByteHrs, and so on. Match on it; do not match on storageClass or product descriptions.
3. us-west-2 is not a Pricing API endpoint. The API lives at api.pricing.us-east-1.amazonaws.com and api.pricing.ap-south-1.amazonaws.com. Worse, EndpointResolverV2 will template any well-formed region string into a hostname, so a wrong region produces an opaque DNS failure rather than a validation error. Validate the pricing region against the two known endpoints before constructing the client. (The region whose prices you want is a filter value, not the endpoint.)
4. productFamily=Storage + volumeType='Glacier Deep Archive' returns a staging SKU at 21× the real rate. This is the trap that makes a naive implementation worse than the static table it replaces — it looks like success, returns a plausible-shaped number, and is off by a factor that would dominate any report it appears in. Whatever filter is chosen needs a sanity band per tier, and a rate outside the band must be rejected and logged, not used.
5. pricePerUnit values are strings, and a SKU can carry multiple priceDimensions with endRange: "Inf". Tiered pricing is normal, not exceptional.
6. Adding service/pricing forces smithy-go ≥1.26.0. Its endpoints/private/bdd import is absent from the pinned v1.24.0 (go.mod:11), and the bump also moves under the S3 client (service/s3 v1.88.4, aws-sdk-go-v2 v1.41.0). That is a dependency change touching the data path, so it wants its own commit and a full -race run before the pricing code lands on top of it.
Hot-path constraint
GetTierPricing is reachable from a filesystem read: GetObject → CostOptimizer.RecordAccess (cost_optimizer.go:77) → calculateObjectCost (:327). So:
atomic.Pointer[RateTable], swapped whole. No lock on the read path.- Refresh from a background ticker only. Never fetch synchronously from a filesystem operation.
- A pricing failure must never fail a filesystem operation. Stale rates, or the bundled snapshot, or zero — never an error propagated to a read. This is the load-bearing requirement; the cost feature is advisory and the filesystem is not.
Proposed design
Three sources, in order:
GetProductsviaservice/pricing, refreshed on a ticker (daily is ample — S3 list prices move rarely).- The public offer file (
https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonS3/current/index.json) as an unauthenticated fallback. This matters more than it sounds:GetProductsneedspricing:GetProductsIAM permission, which a mount's credentials will usually not have. Without the fallback the feature is off for most users. - A bundled snapshot generated by
//go:generate, compiled in. Always available, never a network dependency, and the thing that makes "pricing failure cannot fail a read" trivially true.
Collapse the six duplicated rate tables into one, and make the bundled snapshot that one. internal/analytics/model.go:14 and internal/storage/s3/tiers.go should read from it rather than carry copies.
Testing
internal/testaws runs the real S3 backend against an in-process substrate endpoint. Substrate has no pricing plugin — GetProducts returns 501 today (63 plugins, none for pricing) — so this is filed upstream. The fidelity requirements are the traps above, and they are the point of asking for an emulator rather than a mock:
PriceListas[]stringof raw JSON, not decoded objectspricePerUnitvalues as strings- at least one SKU with multiple
priceDimensionsandendRange: "Inf" productFamilyomitted on some SKUs
Also filed upstream: extractRegionFromHost returns "pricing" instead of the region for api.pricing.<region>.amazonaws.com.
A hand-written mock cannot serve here for the reason CLAUDE.md gives: it agrees with the caller by construction. The deleted parser would have passed against any mock built from its own assumptions — that is exactly how it shipped.
Sequencing
Ship in this order; each step is independently valuable and the first two are cheap:
- Fix the 10× PUT rate and extend the drift test to all six fields. Do this now regardless of whether the API work ever happens. (Also decide the decimal-vs-binary GB question and fix
byteToGB.) - Consolidate the six rate tables into one. Makes the drift test unnecessary rather than more thorough — a single table cannot drift from itself.
- Bump smithy-go, as its own commit.
- Bundled snapshot +
//go:generate, withatomic.Pointerswap and background refresh — offline, no new IAM needs, and the safety property established before any network code exists. - Offer-file fetcher.
GetProductswith region validation and per-tier sanity bands.- Make region real: filter by the configured region, or refuse to label output with a region whose rates were not fetched.
One thing to decide first
internal/cost has no importers outside itself — the whole package, including Calculator, Reporter, and AlertManager, is unreachable from a mount. internal/analytics is reached (from internal/cache/multilevel.go), and PricingManager is reached from Backend, but the cost calculation layer is not wired to anything.
So step 0 is: is cost tracking a feature of this product? If yes, wiring it up belongs in this issue's scope and the accuracy work has a consumer. If it is speculative, then fixing a 10× error in a table nothing reads is still worth doing — a wrong number is a trap for the next reader — but the API integration is not, and this issue should be closed in favour of deleting the package. Getting real prices into a calculator no code calls is the most expensive way to change nothing.
Activity
scttfrdmn commentedon Aug 2, 2026
Scoped for v0.10.2. The rate defects this issue's title mentions are split out into #209 (Standard PUT 10× low, binary-vs-decimal GB, drift test covering one field of six, rates duplicated across five files) so they can land without the API dependency. Fix #209 first: it consolidates the rate tables to one site, which turns this issue from a five-place change into a one-place change, and it means the Pricing API replaces a correct static table rather than an incorrect one.
Two verified constraints re-confirmed against the current tree, both still true:
pm.config.Regionis read at exactly one line (internal/storage/s3/pricing_manager.go:266) for a summary string. Region is decorative —region: us-west-2yields us-east-1 numbers labelled us-west-2. C0-8: Make cost tracking region-aware #161 tracks the region-awareness half.service/pricingforces smithy-go ≥1.26.0. v0.10.1 moved smithy-go to v1.24.2 and the collision anticipated in Bump aws-sdk-go-v2 for GHSA-xmrv-pmrh-hhx2: EventStream decoder panic terminates the mount #195 did not occur, so the bump is still ahead of this work, not behind it.Hot-path constraint unchanged:
GetTierPricingis reachable fromGetObject→RecordAccess→calculateObjectCost. Useatomic.Pointer[RateTable], refresh from a background ticker only, and guarantee a pricing failure can never fail a filesystem operation.scttfrdmn commentedon Aug 2, 2026
The prerequisite half of this issue is done in #220, which also changes what the remaining half has to do. Recording it here so the next person to pick this up does not re-derive it.
What #220 settled
The 10× PUT rate is fixed, and so are two more the issue did not record — found by checking against the live Pricing API rather than against another table in this repo:
The decimal-GB error is fixed (7.4% understatement on every storage cost). The six copies of the rate card are now one,
internal/awsrates.What that means for the API work
"A single-site change" is now literally true. This issue's premise was that consolidating first would make the API integration one site instead of five; that site exists and is
internal/awsrates. Theatomic.Pointer[RateTable]hot-path constraint still applies to it unchanged —GetTierPricingis still reachable fromGetObject→RecordAccess→calculateObjectCost.Trap 2 is load-bearing and now proven, not just observed.
internal/awsrates/rates_aws_test.goqueries 23 rates byusagetypealone, againstlocation=US East (N. Virginia). It works for 23 and fails for a handful, which is worth knowing before writing the client:TimedStorage-GDA-ByteHrsreturns nothing under a bareusagetypefilterBoth are exempted explicitly in that test with the reason attached, and
TestQueriesCoverEveryPricedFieldfails if the exempt list grows without one. So the real client needs the region-prefixed form as a fallback, or a different filter for those SKUs — worth resolving before writing the parser, since it is the same class of thing that broke the deleted one.Trap 5 is now encoded, and it is not just Deep Archive. Storage pricing is volume-banded — Standard is
0.023only for the first 50 TB (beginRange0–51200), then0.022, then0.021. The drift test selectsbeginRange == "0"explicitly. A client that takes the firstpriceDimensionit finds gets whichever band the map iteration handed it, which is a non-deterministic rate.Trap 4's sanity band has a natural home now.
awsrates.Foris where a rejected out-of-band rate should fall back to, and it already returns(Rate, bool)so the caller can tell a fallback from a hit. A pricing failure returning the static rate withfalseis exactly the "can never fail a filesystem operation" guarantee this issue asks for.The one thing #220 deliberately did not do
The drift test shells out to the AWS CLI rather than importing
service/pricing, and the reason is a constraint on this issue rather than on that PR:So the SDK bump belongs to this issue, done deliberately, with the S3 client re-tested after it — not smuggled in as a side effect of a test. The subprocess version costs the module nothing in the meantime and is what verified every rate above.
Trap 3 is unchanged and still the sharpest one.
requireAWSCLIin that test pins--region us-east-1on every call for exactly the reason this issue gives: a caller'sAWS_REGIONmust not reach the pricing endpoint, becauseEndpointResolverV2templates any well-formed region into an opaque DNS failure rather than validating it.Region-is-decorative is unchanged.
awsrates.Regionis a constus-east-1and its package doc says plainly that these are us-east-1 rates and thatPricingConfig.Regiondoes not select them. That is honest rather than fixed — the fix is this issue.scttfrdmn commentedon Aug 3, 2026
Steps 1 and 2 are done, and step 0 is answered
Landed in #220 and #225 (both merged):
byteToGBnow divides by 10⁹. It delegates toawsrates.GBFromBytes, so the decimal-vs-binary question is settled in one place rather than at each call site. The old comment asserting the binary reading was correct is what let a 7.4% error look considered.internal/awsrates, read byinternal/cost,internal/storage/s3/tiers.go,internal/storage/s3/pricing_manager.go,internal/storage/s3/doc.go, andinternal/analytics/model.go. The drift test now compares both tables against it for every class the config loader accepts — includingREDUCED_REDUNDANCY, which the old drift test had no entry for, so the tier it existed to check went unchecked.Step 2 made step 1's drift test largely unnecessary, as this issue predicted: a single table cannot drift from itself. It is kept because two packages still hold derived structures.
Step 0: no cost figure reaches a user by any path
The issue says to decide this first, so I measured every path from a rate to an output:
Output surfaces, non-test callers:
GetTierPricingWithDiscountsGetAccessPatternCountGetCostOptimizationReportdoc.gometrics.RecordCostCostMetricsis never populatedcmd/objectfsSo the rates are now correct and single-sourced, and nothing a user can observe depends on them.
RecordAccessis on the hot read path and returns on its first line.Decision: wire up the output before fetching live prices
Per the issue's own framing — "Getting real prices into a calculator no code calls is the most expensive way to change nothing" — the API integration (steps 3–7) is deferred until the accurate rates have a consumer, and not closed, because the traps recorded here are the valuable part and they should not be re-derived.
Splitting into two issues:
MonitorAccessPatterns— after fixing the unsynchronizedaccessPatternsmap, which is whybuildS3Configholds it back today (M12) — and expose cost through the Prometheus surface the rest of the cache and operation telemetry already uses, rather than through a method nothing calls. That is the step that turns an accurate rate into an observable number.GetProducts, judged on real output. Steps 3–7 as filed, with every verified trap carried over:productFamilyabsent from 315 of 381 products,usagetypeas the only stable key,us-west-2not being a pricing endpoint (andEndpointResolverV2templating any well-formed region into an opaque DNS failure), the Glacier Deep Archive staging SKU at 21× the real rate,pricePerUnitas strings withendRange: "Inf", and the smithy-go ≥1.26.0 bump that also moves under the S3 client. Plus the hot-path constraint, which stands regardless:atomic.Pointer[RateTable], background ticker only, and a pricing failure that can never fail a filesystem operation.Filing both now and leaving this issue open as the parent until they are.
Region remains decorative, and that has not changed:
pm.config.Regionis read at exactly one line to stamp a summary field, soregion: us-west-2still yields us-east-1 numbers labelled us-west-2.internal/awsrates' package doc now states plainly that its rates are us-east-1, first volume band, Standard retrieval on the Glacier classes — which makes the label honest at the table but not at the summary. Fixing it properly belongs with (2), since it needs per-region rates to fix rather than to document. Step 7 covers it.scttfrdmn commentedon Aug 3, 2026
Split filed:
adapter.go:503records: M12's unsynchronized map is fixed, the lock landed, and that comment is stale. The real blocker is thatMonitorAccessPatternsdoes two unrelated things — one flag gates both access-pattern recording andHandleStandardTierOverhead, which silently rewrites the storage class of every object under 128 KiB to Standard, overriding what the user configured, with a Debug log line. Splitting that flag is a prerequisite to mapping it.GetProducts+ offer file + bundled snapshot (Future Work), carrying all six verified traps, the hot-path constraint, and the region work.Closing this as the parent: steps 0, 1, and 2 are done and merged, and steps 3–7 now live in #227 with the ordering dependency on #226 stated in both.
deps: bump five direct dependencies, clearing the smithy-go floor for #…