Skip to content

Real AWS Pricing API integration — and the 10x-low Standard PUT rate the static tables disagree on #183

Closed

Description

@scttfrdmn

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,000

internal/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-124 divides by 1024³ where AWS bills decimal GB. byteToGB returns bytes / (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. Note MinObjectSize billing minimums are also decimal (128 KB = 128,000 bytes), so the same unit question recurs there.
  • Region is decorative. pm.config.Region is read at exactly one line (pricing_manager.go:266) to stamp a summary field. Every rate is us-east-1. So region: us-west-2 produces us-east-1 numbers labelled us-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:

  1. GetProducts via service/pricing, refreshed on a ticker (daily is ample — S3 list prices move rarely).
  2. 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: GetProducts needs pricing:GetProducts IAM permission, which a mount's credentials will usually not have. Without the fallback the feature is off for most users.
  3. 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:

  • PriceList as []string of raw JSON, not decoded objects
  • pricePerUnit values as strings
  • at least one SKU with multiple priceDimensions and endRange: "Inf"
  • productFamily omitted 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:

  1. 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.)
  2. Consolidate the six rate tables into one. Makes the drift test unnecessary rather than more thorough — a single table cannot drift from itself.
  3. Bump smithy-go, as its own commit.
  4. Bundled snapshot + //go:generate, with atomic.Pointer swap and background refresh — offline, no new IAM needs, and the safety property established before any network code exists.
  5. Offer-file fetcher.
  6. GetProducts with region validation and per-tier sanity bands.
  7. 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

  1. added this to the Future Work milestone on Aug 2, 2026
  2. added
    type: enhancement
    priority: medium
    area: cost
    on Aug 2, 2026
  3. scttfrdmn commented on Aug 2, 2026

    @scttfrdmn
    OwnerAuthor

    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:

    Hot-path constraint unchanged: GetTierPricing is reachable from GetObject → RecordAccess → calculateObjectCost. Use atomic.Pointer[RateTable], refresh from a background ticker only, and guarantee a pricing failure can never fail a filesystem operation.

  4. scttfrdmn commented on Aug 2, 2026

    @scttfrdmn
    OwnerAuthor

    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:

    rate was is
    Standard PUT 0.0000005 effective 0.000005 the 10× this issue names
    Glacier IR PUT 0.000005 0.00002 4× low
    Glacier IR GET 0.000002 0.00001 5× low
    Glacier retrieval 0.02/GB 0.01/GB Standard speed; the old comment said "Variable based on retrieval speed", which records that nobody had established which

    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. The atomic.Pointer[RateTable] hot-path constraint still applies to it unchanged — GetTierPricing is still reachable from GetObject → RecordAccess → calculateObjectCost.

    Trap 2 is load-bearing and now proven, not just observed. internal/awsrates/rates_aws_test.go queries 23 rates by usagetype alone, against location=US East (N. Virginia). It works for 23 and fails for a handful, which is worth knowing before writing the client:

    • TimedStorage-GDA-ByteHrs returns nothing under a bare usagetype filter
    • GDA retrieval usagetypes exist only in region-prefixed form

    Both are exempted explicitly in that test with the reason attached, and TestQueriesCoverEveryPricedField fails 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.023 only for the first 50 TB (beginRange 0–51200), then 0.022, then 0.021. The drift test selects beginRange == "0" explicitly. A client that takes the first priceDimension it 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.For is 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 with false is 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:

    service/pricing's transitive requirement moves smithy-go to ≥1.26.0, and smithy-go also sits under the S3 client that serves every read and write. Taking that bump for a drift check would put dependency risk on the data path to test a table.

    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. requireAWSCLI in that test pins --region us-east-1 on every call for exactly the reason this issue gives: a caller's AWS_REGION must not reach the pricing endpoint, because EndpointResolverV2 templates any well-formed region into an opaque DNS failure rather than validating it.

    Region-is-decorative is unchanged. awsrates.Region is a const us-east-1 and its package doc says plainly that these are us-east-1 rates and that PricingConfig.Region does not select them. That is honest rather than fixed — the fix is this issue.

  5. scttfrdmn commented on Aug 3, 2026

    @scttfrdmn
    OwnerAuthor

    Steps 1 and 2 are done, and step 0 is answered

    Landed in #220 and #225 (both merged):

    • The 10× Standard PUT rate is fixed. Verified against the live Pricing API, which turned up two the issue had not recorded: Glacier Instant Retrieval PUT was 4× low and its GET 5× low.
    • byteToGB now divides by 10⁹. It delegates to awsrates.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.
    • Five rate tables are one. internal/awsrates, read by internal/cost, internal/storage/s3/tiers.go, internal/storage/s3/pricing_manager.go, internal/storage/s3/doc.go, and internal/analytics/model.go. The drift test now compares both tables against it for every class the config loader accepts — including REDUCED_REDUNDANCY, which the old drift test had no entry for, so the tier it existed to check went unchecked.
    • A live-API integration test re-reads 23 rates and fails on any difference, so a price change is something the suite reports rather than something a report quietly gets wrong.

    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:

    internal/awsrates  (accurate, single-sourced, live-API checked)
        │
        ├─► s3.PricingManager.GetTierPricing ......... reachable from Backend ✓
        │        └─► CostOptimizer.calculateObjectCost
        │                 └─► RecordAccess ........... returns immediately.
        │                        MonitorAccessPatterns is false, and
        │                        buildS3Config deliberately does not map it
        │
        ├─► internal/cost (Calculator, Reporter, AlertManager)
        │        └─► ZERO importers outside itself
        │
        └─► internal/analytics/model.go ............... reached from internal/cache,
                 but the Predictor field is never set on the mount path
    

    Output surfaces, non-test callers:

    method callers
    GetTierPricingWithDiscounts 0
    GetAccessPatternCount 0
    GetCostOptimizationReport 1 — an example in doc.go
    metrics.RecordCost 0 anywhere; CostMetrics is never populated
    cmd/objectfs no cost output of any kind

    So the rates are now correct and single-sourced, and nothing a user can observe depends on them. RecordAccess is 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:

    1. Wire cost output to a surface a user can see. Map MonitorAccessPatterns — after fixing the unsynchronized accessPatterns map, which is why buildS3Config holds 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.
    2. Then GetProducts, judged on real output. Steps 3–7 as filed, with every verified trap carried over: productFamily absent from 315 of 381 products, usagetype as the only stable key, us-west-2 not being a pricing endpoint (and EndpointResolverV2 templating any well-formed region into an opaque DNS failure), the Glacier Deep Archive staging SKU at 21× the real rate, pricePerUnit as strings with endRange: "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.Region is read at exactly one line to stamp a summary field, so region: us-west-2 still 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.

  6. scttfrdmn commented on Aug 3, 2026

    @scttfrdmn
    OwnerAuthor

    Split filed:

    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.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: costpriority: mediumtype: enhancement

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions