Skip to content

C0-8: Make cost tracking region-aware #161

Closed

Description

@scttfrdmn

Summary

Storage pricing is hardcoded to us-east-1 rates in two separate places, and the config fields
that exist to make it region-aware are ignored. Cost estimates are wrong for every other
region.

Background

internal/cost/pricing.go carries literal us-east-1 rates (0.023, 0.0125, 0.004, 0.0036,
0.00099 $/GB/month). The same numbers are duplicated in StorageTierInfo.CostPerGBMonth in
internal/storage/s3/tiers.go:

TierStandard: {
    // ...
    CostPerGBMonth:     0.023, // Approximate USD
},

Two copies drift independently, and neither is correct outside us-east-1 — regional S3 pricing
varies materially (some regions are 20-30% higher). Cost-optimization decisions and tier
recommendations are made from these numbers.

Meanwhile s3.PricingConfig already declares the fields needed to fix this:

UsePricingAPI bool   `yaml:"use_pricing_api"`
Region        string `yaml:"region"`

Neither is honored anywhere. Region defaults to "us-east-1", which is at least an honest
description of current behavior.

Implementation

  1. Establish one source of truth for per-tier storage rates and have the other site reference
    it rather than restating the numbers. StorageTierInfo should keep tier characteristics
    (minimums, embargoes, latency); pricing belongs in the cost package.
  2. Make lookups region-aware, keyed on PricingConfig.Region, falling back to us-east-1 with a
    logged warning when a region has no table entry.
  3. Honor UsePricingAPI as opt-in: when true, fetch from the AWS Pricing API and cache;
    when false (default), use the static table. Keep the static path working with no
    credentials and no network — cost estimation must not become a hard dependency on another
    AWS service.
  4. Have CostOptimization and GetRecommendations read through the same accessor.

Document that static rates are approximate and dated, since they will drift regardless.

Acceptance Criteria

  • Per-tier storage rates are defined once; no duplicated literals
  • Cost calculations use PricingConfig.Region
  • An unknown region falls back to us-east-1 with a warning rather than returning zero
  • UsePricingAPI: false (default) needs no credentials and no network
  • UsePricingAPI: true fetches and caches live pricing
  • Tier recommendations reflect region-specific rates
  • go test -race ./internal/cost/... ./internal/storage/s3/... passes

Dependencies

None.

Activity

  1. added
    type: bug
    priority: medium
    area: cost
    on Jul 29, 2026
  2. scttfrdmn commented on Jul 30, 2026

    @scttfrdmn
    OwnerAuthor

    Correction: the framing is partly wrong — the config is honored, the extractors are stubs

    Two claims in this issue do not hold, and the real defect is elsewhere.

    UsePricingAPI and Region are both honored. PricingManager.getBasePricing (internal/storage/s3/pricing_manager.go:81) branches on the flag:

    if pm.config.UsePricingAPI {
    	if pricing, err := pm.fetchFromPricingAPI(tier); err == nil {

    and fetchFromPricingAPI interpolates the configured region into the endpoint (pricing_manager.go:100). So "nothing honors them" is incorrect — the plumbing is there.

    The actual defect is that the extractors are stubs. After fetching the AWS pricing index — a document on the order of 100 MB — the parse is discarded:

    func (pm *PricingManager) extractStorageCost(product AWSProduct, terms map[string]interface{}) float64 {
    	// Simplified extraction - real implementation would parse the complex terms structure
    	return 0.023 // Fallback
    }
    
    func (pm *PricingManager) extractRetrievalCost(product AWSProduct, terms map[string]interface{}) float64 {
    	// Simplified extraction
    	return 0.01 // Fallback for IA tiers
    }

    (pricing_manager.go:193-201)

    So enabling UsePricingAPI downloads ~100 MB over HTTP and returns two hardcoded us-east-1 constants — strictly worse than leaving it off, which returns the same numbers for free. Note also that 0.023 is returned for every tier, so with the API enabled all tiers price identically, which is worse than the StorageTiers defaults it bypasses.

    internal/cost is 100% dead code. Grep for objectfs/internal/cost across all Go files returns zero importers. The issue proposes consolidating it with pricing_manager.go, but there is nothing depending on it to preserve. That makes deletion the cheaper option and turns this into a decision rather than a refactor:

    • Delete internal/cost and keep pricing_manager.go as the single source. Least code, no migration.
    • Consolidate only if internal/cost contains logic worth keeping that pricing_manager.go lacks — needs a read-through to establish, not assumed.

    Suggested adjustment

    1. Retitle around the real defect: implement or remove the Pricing API path.
    2. Decide implement-vs-remove explicitly. Parsing the AWS pricing index properly is real work (nested terms.OnDemand -> priceDimensions traversal, ~100 MB fetch needing caching and a disk-backed TTL). Given UsePricingAPI defaults to false and the static StorageTiers numbers are adequate for cost estimation, removing the half-built API path and documenting the rates as approximations is the better trade unless accurate live pricing is a stated requirement.
    3. Resolve internal/cost delete-vs-consolidate as part of this.
    4. Keep the genuine finding: the same rates are duplicated between StorageTierInfo.CostPerGBMonth (tiers.go) and getDefaultPricing, and should have one home regardless of which route is taken.
  3. scttfrdmn commented on Jul 30, 2026

    @scttfrdmn
    OwnerAuthor

    Two amendments to this issue

    1. The Pricing API path is removed, not implemented — acceptance criteria 5 is withdrawn

    Criterion "UsePricingAPI: true fetches and caches live pricing" assumed the existing integration was a working foundation. It was not. Reading fetchFromPricingAPI and parsePricingData:

    • parsePricingData matched products on product.Attributes["storageClass"] == "General Purpose" / "Infrequent Access" — human-readable names produced by mapTierToStorageClass that do not appear in the Pricing API payload under that attribute. The loop never matched.
    • Both extractors ignored their arguments entirely:
    func (pm *PricingManager) extractStorageCost(product AWSProduct, terms map[string]interface{}) float64 {
    	// Simplified extraction - real implementation would parse the complex terms structure
    	return 0.023 // Fallback
    }

    So UsePricingAPI: true downloaded a multi-megabyte JSON index over HTTP, decoded it, and then returned 0.023/0.01 per GB — the same constants the static table already provides, minus the latency and the failure mode. The parsing work the comment defers to was never done.

    Removed rather than left in place, so nobody mistakes it for a partial implementation to finish: fetchFromPricingAPI, parsePricingData, mapTierToStorageClass, extractStorageCost, extractRetrievalCost, getBasePricing, and the AWSPricingResponse/AWSProduct types. GetTierPricing now calls getDefaultPricing directly. RefreshPricing is a documented no-op and use_pricing_api logs a deprecation warning at startup. Real Pricing API support, if wanted, should be filed fresh — it is a feature, not a bug fix, and it belongs behind pricingv2.GetProducts with a proper terms walk rather than the raw offer-file URL.

    The remaining scope of this issue — one source of truth for rates, region-aware lookups, us-east-1 fallback with a warning — is unchanged and still wanted.

    2. Correcting myself on internal/cost: it should be kept, not deleted

    I earlier recommended deleting internal/cost on the grounds that it has zero importers and duplicates the rate table in pricing_manager.go. That recommendation was wrong, and it was based on an incomplete reading of the package. The zero-importer finding is accurate; the conclusion I drew from it is not.

    The duplication is confined to the rate literals. Everything else in those ~1,200 lines has no counterpart anywhere in the repo:

    API What it does Equivalent in pricing_manager.go?
    Calculator.Calculate per-operation cost from request type + bytes + tier no — only returns rate tables
    Reporter.RecordOp / Report / ReportAll accumulates spend per tenant over time no
    TenantRecord per-tenant attribution no
    AlertManager + BudgetRule + Alert budget thresholds and alerting no
    CostReport ROI / spend reporting no

    pricing_manager.go answers "what does a GB cost in this tier"; internal/cost answers "what has this tenant spent, and are they over budget". Deleting it would delete the only implementation of #65 and leave the rate table with no consumer at all.

    It is unwired, not redundant — the fix is to wire it up, which is the deduplication half of this issue.

    In the meantime I added internal/cost/pricing_drift_test.go, a tripwire that fails when the rates in internal/cost/pricing.go diverge from StorageTierInfo.CostPerGBMonth, and that fails if a new tier is added to one table and not the other. It does not fix the duplication — it just stops the two copies drifting silently before this issue is worked, and it gives the consolidation a ready-made regression check.

  4. scttfrdmn commented on Aug 2, 2026

    @scttfrdmn
    OwnerAuthor

    Moved to v0.11.0. Re-verified against main at e969ff7 rather than assumed — still fully open:

    • internal/storage/s3/pricing_manager.go:39-40 defaults Region to us-east-1
    • :266 is the only read of pm.config.Region in the file, and it is a label on a summary struct

    So region remains decorative: region: us-west-2 yields us-east-1 numbers labelled us-west-2.

    One additional finding while checking, which belongs on this issue because it is the same table:

    pricing_manager.go:126 has Standard PUT at 0.0005 per 1000 requests. internal/cost/pricing.go:47 has PutRequest: 0.000005 with the comment // $0.005 / 1000. The real AWS rate is $0.005/1000, so pricing_manager.go is 10× low on Standard PUT.

    And internal/cost/pricing.go:48 carries this comment:

    // These match the values in internal/storage/s3/tiers.go and pricing_manager.go.

    They do not match. That comment is load-bearing — it is why nobody reconciled the two tables — and pricing_drift_test.go:34 cannot catch the disagreement because it compares only StoragePerGBMonth. Whatever fixes region-awareness should collapse these tables to one source and extend the drift test past the storage rate.

  5. added
    effort: small
    on Aug 3, 2026
  6. scttfrdmn commented on Aug 3, 2026

    @scttfrdmn
    OwnerAuthor

    Fixed in 7c70dc0 on v0.11.0-cli-subcommands.

    What was wrong. pricing_config.region was read at one line in the repository, and only to label a summary. Every rate came from a package-level table built at init, which cannot see a configuration, so every cost ObjectFS reported was us-east-1's no matter what the operator configured. region: sa-east-1 produced us-east-1 numbers labelled sa-east-1, and Standard storage in sa-east-1 is 76% above us-east-1.

    The acceptance criterion. An unknown region falls back to us-east-1 with a warning rather than returning zero — awsrates.ForRegion returns the fallback rate plus a bool, and both NewPricingManager and NewTierValidator warn once at construction naming the region asked for and the region used. Warning once rather than per lookup because GetTierPricing is reachable from GetObject via RecordAccess, so it is on the read path.

    Rates are now generated, not written. 36 regions × 8 storage classes × 6 rates in internal/awsrates/rates_generated.go, produced by the new internal/awsrates/offerfile package from AWS's public per-region price list offer files. Those need no credentials, so go generate ./internal/awsrates/... refreshes every number in one command anyone can run. Not the Pricing API: it needs credentials, and its Go client forces smithy-go ≥1.26.0 under the S3 client on the data path.

    A second defect this found. Glacier PUT was reading Requests-Tier3, which is the restore price — 67% too high. usagetype alone is not a key for a rate; Requests-GLACIER-Tier1 has 15 SKUs at 2 prices, separated by the operation attribute. The test that existed to catch exactly this agreed with it: it transcribed the queries a second time and named Requests-Tier3 for Glacier PUT itself. It also shelled out to aws pricing get-products, so it skipped without a configured profile — including in CI, and a drift check that skips is not a drift check. It now fetches the same offer files over plain HTTPS, drives its queries from offerfile.Queries() instead of a second copy, and compares the whole committed table across five regions spanning every band AWS publishes.

    StorageTierInfo.CostPerGBMonth is removed, not corrected. A rate on a package-level struct cannot know which region produced it, and that field was the mechanism by which the region became decorative. Filling it from the configured region would put a region-specific number on a value shared process-wide by every manager — the same defect with an extra step. The compiler found the callers.

    Verification. 12 mutations across lookup, the awsrates region accessors, PricingManager.StorageRate, and the generator's skip/refuse-to-write rules; all 12 caught. A 13th on the generated table itself (0.0405 → 0.0406) is caught by the live drift test, which passed against AWS with no credentials across 5 regions × 8 classes × 6 fields. internal/awsrates is at 100% coverage, the generator command at 74.4%, all three floors recorded in .coverage-floors. Full gate set green: build, gofmt, go test -race with zero failures, coverage gate 34/34, golangci-lint --new-from-merge-base=origin/main at 0 issues.

    Deliberately not in scope. internal/cost and internal/analytics stay region-blind, now stated in code rather than left silent: nothing imports either package, so a region argument there would have no caller to be wrong for, and the region belongs in a constructor that a package-level var cannot have.

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: costeffort: smallpriority: mediumtype: bug

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions