Skip to content

fix: preserve exact-decimal AI-credit accounting - #11157

Merged
lpcox merged 3 commits into
mainfrom
lpcox-exact-decimal-pricing-accounting
Nov 5, 2026
Merged

lpcox merged 3 commits into
mainfrom
lpcox-exact-decimal-pricing-accounting

Conversation

@lpcox

@lpcox lpcox commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator

Summary

Make exact arithmetic authoritative from pricing sources through token charges and budget enforcement. Preserve the shared resolver and canonical fallback foundations from #11113 and #11117; no rate authoring, scope expansion, new admission policy, or shadow rollout.

Relates to #10295 and #10290. Both remain open.

Arithmetic and compatibility

  • Preserve canonical decimal strings in maintained/generated and governed-import assets. Normalize operator/configured/default/central rates and Copilot AIU/nano-AIU/batch prices with bounded exact rational arithmetic; Number inputs retain only their available String(value) representation.
  • Carry private exact rates through the shared resolver, partial-provider merging, request/connection captures, token multiplication, reasoning/cache splits, per-model buckets, and process accumulation. Existing numeric rate views stay JSON-safe; no internal BigInt/rational objects escape.
  • Round only public credit outputs to six decimal places, nearest with exact ties upward. Reflection percentage remains ceiling-clamped and rounded to two places. Response/reflection/log/JSONL/telemetry/env field types and meanings remain compatible.
  • Compare unrounded totals against exact configured limits, the 10,000-credit hard cap, and 80/90/95/99% steering thresholds. Equality exhausts the budget. 0.9999996 no longer prematurely exhausts a one-credit budget just because it displays as one. One thousand one-token responses at USD 0.0001/million retain exactly 0.00001 credits despite each response displaying zero.
  • Preserve source order/provenance, backend/channel/deployment/BYOK exclusions, strict tiers, additive versus total-inclusive caches, null versus zero, refresh pins, missing/unpriced warn-and-proceed exclusion, recovery and opt-outs. Pricing remains separate from execution admission.
  • Bound decimal/exponent parsing and arithmetic. Unsupported supplied values, unsafe counts and nonrepresentable outputs produce sanitized pricing errors and subsequent dispatch blocking, never approximate/free/legacy fallback. Invalid provider observations survive discovery as explicit invalid facts instead of being swallowed into stale-price reuse.

Validation

  • npm run models:generate / npm run models:check
  • npm run build / npm run type-check; commit-hook ESLint passes with warning-only existing output
  • Full proxy suite: 142 suites passed; 3,316 tests passed, 2 skipped (npm test --prefix containers/api-proxy -- --maxWorkers=2)
  • Model-information/environment regression selection: 12 suites / 423 tests passed; final compiler/shared-resolver rerun: 2 suites / 46 tests passed
  • Documentation Markdown lint passes
  • Extended scripts/ci/smoke-pricing-resolution.cjs runs real HTTP/WebSocket accounting in off-tree Docker application files and extracted npm packages, with both shipped data and compiler-generated long-decimal maintained/import fixtures. Every run enforces zero network calls. Includes tiny-response accumulation, fractional rates/batches, cache/reasoning, below/equal/above budget/hard-cap/steering boundaries, rounding ties, pins/refresh, partial fallback, and accounting-failure dispatch blocking.

No live provider inference, manual workflow dispatch, container/guest/VM run, labels, or merge performed. Automatic PR CI is expected.

Concrete limits

Existing host numeric configuration schemas and upstream JSON Number parsing cannot recover original decimal spellings. Public numeric snapshots are output projections, not a restartable exact ledger. Supported decimal inputs are bounded to 420 characters, 400 mantissa digits, three exponent digits and absolute adjusted exponent 400; rational intermediates are bounded to 4,096 digits. Larger/unrepresentable values fail explicitly. Generalized tariffs/units/currencies, promotions/successors, non-token charges and broader export/reasoning migrations remain out of scope.

Keep decimal tariff precision through normalization, shared resolution, token charges
and accumulation. Round only public outputs; compare exact budgets and steering
thresholds. Add bounded arithmetic and provider-free distributed HTTP/WebSocket
regressions.

Co-authored-by: Copilot App <[email protected]>
Copilot AI adaptive review requested due to automatic review settings November 5, 2026 16:11
@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Documentation Preview

Documentation has been built for this PR.

Download preview artifact

To view locally:

  1. Download the docs-preview-pr-11157 artifact from the workflow run
  2. Unzip and open index.html in your browser

Built from commit 3f12406

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

⚠️ Coverage Regression Detected

This PR decreases test coverage. Please add tests to maintain coverage levels.

Overall Coverage

Metric Base PR Delta
Lines 93.78% 93.77% 📉 -0.01%
Statements 92.33% 92.33% ➡️ +0.00%
Functions 93.07% 93.07% ➡️ +0.00%
Branches 86.57% 86.56% ➡️ -0.01%
📁 Per-file Coverage Changes (1 files)
File Lines (Before → After) Statements (Before → After)
src/nvx/one-shot-process.ts 84.0% → 81.5% (-2.47%) 76.8% → 74.7% (-2.11%)

Coverage comparison generated by scripts/ci/compare-coverage.ts

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unhandled pricing errors can leave reflection responses unfinished or stop the proxy during model recovery despite valid alternative candidates.

3 open issues
What changed in this PR

Extends AWF’s shared pricing pipeline with exact-decimal accounting from source rates through token charges and budget enforcement, while keeping public numeric outputs compatible.

Changes:

  • Adds bounded rational arithmetic and preserves exact rates through resolution, request snapshots and accumulated usage.
  • Compares unrounded totals against budgets and steering thresholds, rounding only public outputs.
  • Preserves decimal strings in generated pricing assets and expands regression coverage, provider-free smoke checks and documentation.
File Description
src/​model-information-contract/​pricing-resolution.js Updates the host resolver copy to preserve exact rates.
src/​model-information-contract/​pricing-resolution.d.ts Allows decimal-string source rates in host contracts.
src/​model-information-contract/​exact-pricing.js Adds the host copy of bounded rational arithmetic.
shared/​model-information/​target.generated.json Updates the generated catalogue revision.
shared/​model-information/​pricing-resolution.js Preserves exact rates during selection and component merging.
shared/​model-information/​pricing-resolution.d.ts Defines decimal-string support for pricing facts.
shared/​model-information/​manifest.generated.json Updates compiler version and catalogue revision.
shared/​model-information/​exact-pricing.js Implements exact arithmetic, private rate companions and output rounding.
shared/​model-information/​catalog.generated.json Updates the generated catalogue revision.
shared/​model-information/​baseline-to-target.generated.json Aligns comparison metadata with the regenerated catalogue.
scripts/​model-information/​compile.test.ts Verifies compiler version and long-decimal preservation.
scripts/​model-information/​compile.cjs Preserves source decimals and distributes the arithmetic helper.
scripts/​ci/​smoke-pricing-resolution.cjs Expands HTTP/WebSocket accounting and boundary smoke checks.
docs/​model-catalogue-publication.md Documents exact accounting, compatibility and failure limits.
docs/​adr/​0004-model-information-management.md Records the exact-arithmetic implementation and scope.
containers/​api-proxy/​token-budget-log.test.js Updates expectations for invalid operator pricing.
containers/​api-proxy/​runtime-model-catalog.js Normalizes provider prices exactly and preserves captured rates.
containers/​api-proxy/​provider-pricing-overlays.js Uses exact arithmetic for operator pricing conversions.
containers/​api-proxy/​model-pricing-catalog.js Normalizes configured catalogue rates with exact companions.
containers/​api-proxy/​model-information.pricing.generated.json Stores maintained prices as decimal strings.
containers/​api-proxy/​model-information.fallback-pricing.generated.json Preserves decimal strings in native compatibility prices.
containers/​api-proxy/​guards/​exact-pricing.test.js Adds arithmetic, budget, snapshot and failure regressions.
containers/​api-proxy/​guards/​ai-credits-guard.js Uses exact charges, accumulation and enforcement comparisons.
containers/​api-proxy/​catalogue-proxy.test.js Adds long-decimal fixtures to packaged smoke coverage.
containers/​api-proxy/​catalogue-pricing.js Adapts maintained, imported and central pricing to exact arithmetic.
containers/​api-proxy/​catalogue-contract/​pricing-resolution.js Updates the proxy resolver distribution.
containers/​api-proxy/​catalogue-contract/​pricing-resolution.d.ts Adds decimal-string source types to proxy contracts.
containers/​api-proxy/​catalogue-contract/​exact-pricing.js Ships the arithmetic helper with the proxy.

Review effort: Max (auto)

Comment on lines +488 to +489
} catch (error) {
throwAccountingFailure(error);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6a89974: both /reflect routes now catch pricing-resolution failures before writing headers and return a sanitized 500 JSON response; dispatch blocking remains intact.


function getRuntimePricingFact(provider, model, catalog = runtimeCatalog) {
const record = findRuntimeModel(provider, model, catalog);
if (record?.pricingError) throw new Error('pricing_resolution_invalid_tariff');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6a89974: recovery skips candidates that raise pricing_resolution_error and continues evaluating other candidates.

Comment on lines +95 to +99
Object.entries(tariff.components).some(([field, item]) => {
if (typeof item.price === 'object') return field !== 'cacheWrite';
exact.decimal(item.price);
return false;
})) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6a89974: tariff validation now checks the unit-converted numeric projection and reports catalogue_tariff_unsupported; regression coverage confirms the loader retains the bundled fallback.

@lpcox

lpcox commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

@copilot merge main, resolve conflicts, and address review feedback

…ricing-accounting

# Conflicts:
#	containers/api-proxy/model-information.fallback-pricing.generated.json
#	shared/model-information/baseline-to-target.generated.json
#	shared/model-information/catalog.generated.json
#	shared/model-information/manifest.generated.json
#	shared/model-information/target.generated.json
@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

✅ Copilot review passed with no inline comments.

@lpcox Add the ready-for-aw label to this PR to trigger agentic CI smoke tests.

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

⚠️ Coverage Regression Detected

This PR decreases test coverage. Please add tests to maintain coverage levels.

Overall Coverage

Metric Base PR Delta
Lines 93.78% 93.77% 📉 -0.01%
Statements 92.33% 92.33% ➡️ +0.00%
Functions 93.07% 93.07% ➡️ +0.00%
Branches 86.57% 86.56% ➡️ -0.01%
📁 Per-file Coverage Changes (1 files)
File Lines (Before → After) Statements (Before → After)
src/nvx/one-shot-process.ts 84.0% → 81.5% (-2.47%) 76.8% → 74.7% (-2.11%)

Coverage comparison generated by scripts/ci/compare-coverage.ts

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

🔌 Smoke Services is testing service connectivity for this pull request...

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

🔑 Smoke Copilot BYOK AOAI (api-key) is testing Azure OpenAI BYOK (api-key) mode on this pull request...

@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

📰 VERDICT: Smoke Copilot has concluded. All systems operational. This is a developing story. 🎤

📰 BREAKING: Report filed by Smoke Copilot

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

💎 Smoke Gemini is crystallizing results on this pull request...

@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

✅ Smoke Copilot BYOK AOAI (Entra) completed. Copilot AOAI BYOK (Entra) mode operational. 🔓

🪪 BYOK (AOAI Entra) report filed by Smoke Copilot BYOK AOAI (Entra)

@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

✨ The prophecy is fulfilled... Smoke Codex has completed its mystical journey. The stars align. 🌟

🔮 The oracle has spoken through Smoke Codex

@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

✅ Smoke Copilot BYOK completed. Copilot BYOK mode operational. 🔓

🔑 BYOK report filed by Smoke Copilot BYOK

@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Smoke Cloud Hypervisor completed. Cloud Hypervisor + Copilot passed.

Cloud Hypervisor + Copilot smoke test by Smoke Cloud Hypervisor

@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

📡 Smoke OTel Tracing reports failed. OTel tracing regression detected. ⚠️

📡 OTel tracing validated by Smoke OTel Tracing

@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

🛡️ Smoke Copilot Network Isolation confirmed the egress allowlist is enforced. ✅

🛡️ Egress verdict from Smoke Copilot Network Isolation

@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

✅ Build Test Suite completed successfully!

Generated by Build Test Suite for #11157

@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Chroot tests passed! Smoke Chroot - All security and functionality tests succeeded.

Tested by Smoke Chroot

@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

✅ Security Guard completed successfully!

Security Guard

Outcome: reported_no_action

The agent completed and reported no action. A no-op output alone does not verify that all required work was completed or that publication was possible.

Agent messages are omitted from this comment. The category uses structured run status, not interpretation of agent prose.

Generated from Security Guard · sonnet55 · ~20 AIC · ⊞ 8.2K · ◷

Generated by Security Guard for #11157

@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

✅ Smoke Claude passed

Generated by Smoke Claude for #11157

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Smoke Copilot: PR "[WIP] Fix Copilot credential-placeholder assertions in daily runtime regression"

  • GitHub MCP ✅
  • GitHub.com connectivity ✅
  • File write/read ✅

Overall: PASS — @lpcox

📰 BREAKING: Report filed by Smoke Copilot
Add label ready-for-aw to run again

@github-actions github-actions Bot added smoke-copilot smoke-copilot-network-isolation Copilot network-isolation egress smoke test labels Nov 5, 2026
@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

EGRESS_RESULT allow=pass deny=pass

  • ✅ Allowed domain (api.github.com → 200)
  • ✅ Blocked domain (example.com blocked)

Overall: PASS — cc @lpcox

🛡️ Egress verdict from Smoke Copilot Network Isolation
Add label ready-for-aw to run again

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

@lpcox

fix: create issues for daily regression failures
[WIP] Fix shared enclave regression configuration and retain diagnostics

MCP connectivity ✅, GitHub.com ✅, File write/read ✅, BYOK ✅

Running in direct BYOK mode (AWF_AUTH_TYPE=github-oidc + AWF_AUTH_AZURE_* + COPILOT_PROVIDER_BASE_URL) via api-proxy → Azure OpenAI (Foundry, o4-mini-aw) authenticated via Microsoft Entra

Overall: PASS

🪪 BYOK (AOAI Entra) report filed by Smoke Copilot BYOK AOAI (Entra)
Add label ready-for-aw to run again

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

🏗️ Build Test Suite Results

Ecosystem Project Build/Install Tests Status
Bun elysia ✅ 1/1 passed ✅ PASS
Bun hono ✅ 1/1 passed ✅ PASS
C++ fmt ✅ N/A ✅ PASS
C++ json ✅ N/A ✅ PASS
Deno oak N/A 1/1 passed ✅ PASS
Deno std N/A 1/1 passed ✅ PASS
.NET hello-world ✅ N/A ✅ PASS
.NET json-parse ✅ N/A ✅ PASS
Go color ✅ all passed ✅ PASS
Go env ✅ all passed ✅ PASS
Go uuid ✅ all passed ✅ PASS
Java gson ❌ 0/0 (not run) ❌ FAIL
Java caffeine ❌ 0/0 (not run) ❌ FAIL
Node.js clsx ✅ passed ✅ PASS
Node.js execa ✅ passed ✅ PASS
Node.js p-limit ✅ passed ✅ PASS
Rust fd ✅ 1/1 passed ✅ PASS
Rust zoxide ✅ 1/1 passed ✅ PASS

Overall: 7/8 ecosystems passed — FAIL

Java failure details

  • mvn compile first failed with Could not create local repository at /home/runner/.m2/repository (~/.m2 is not writable as a repository location).
  • Retrying with -Dmaven.repo.local in a temp directory failed with: Could not transfer artifact org.apache.maven.plugins:maven-resources-plugin:pom:3.4.0 from central: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty (the JVM truststore is empty in this environment).

Note: .NET needed XDG_RUNTIME_DIR/DOTNET_CLI_HOME set to a writable temp dir (the default /run/user/1001 does not exist). The build-test label was not added because of the Java failure.

Generated by Build Test Suite for #11157 · copilot · auto · ~25 AIC · ⊞ 5.7K · ◷
Add label ready-for-aw to run again

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

OTEL smoke test

  • ✅ S1 Module loading: otel.js loads and exports startRequestSpan, setTokenAttributes, setBudgetAttributes, endSpan, endSpanError, routerCallTracing, shutdown, isEnabled (plus test internals).
  • ✅ S2 Tests: 3 suites, 75/75 passed.
  • ✅ S3 Env forwarding: GITHUB_AW_OTEL_TRACE_ID/PARENT_SPAN_ID in env-passthrough.ts; OTLP vars plus trace context in api-proxy-env-config.ts.
  • ✅ S4 Token tracker: onUsage callback present in token-tracker-http.js.
  • ✅ S5 Diagnostics: /tmp/gh-aw/otel.jsonl has 1 line. I did not check whether it was exported over OTLP.

📡 OTel tracing validated by Smoke OTel Tracing
Add label ready-for-aw to run again

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Smoke Test: Claude Engine

Check Result
API status ✅ PASS
GitHub check ✅ PASS
File status ✅ PASS

Overall result: PASS

Generated by Smoke Claude for #11157 · claude · haiku45 · ~35 AIC · ⊞ 6.1K · ◷
Add label ready-for-aw to run again

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Chroot version comparison

Runtime Host Version Chroot Version Match?
Python Python 3.12.16 Python 3.12.16 ✅ YES
Node.js v24.22.2 v2.98.0 ❌ NO
Go go1.22.12 go1.22.12 ✅ YES

Not all tests passed (Node.js mismatch), so the smoke-chroot label was not added.

Tested by Smoke Chroot
Add label ready-for-aw to run again

@lpcox
lpcox merged commit 4e759d1 into main Nov 5, 2026
148 of 157 checks passed
@lpcox
lpcox deleted the lpcox-exact-decimal-pricing-accounting branch November 5, 2026 18:19
rabeckett added a commit that referenced this pull request Nov 6, 2026
Before #11157, AWF parsed Copilot's batch_size 0, all-zero listing as no
runtime price: the model was unknown and its usage unpriced, never free.
Pricing it as a zero tariff would change that meaning, and Copilot's
premium-request billing still lists these models as premium with
multiplier 1. Keep the previous meaning; AWF's policy for unknown prices
then applies. A reviewed zero-cost catalog entry remains the way to
declare a model free.

This reverts commit 77fd6cc.

Co-authored-by: Copilot <[email protected]>
rabeckett added a commit that referenced this pull request Nov 6, 2026
State in the comment and the test name that a batch_size 0, all-zero
listing is no runtime price, as before #11157: the model is unknown, not
free and not an invalid tariff.

Co-authored-by: Copilot <[email protected]>
rabeckett added a commit that referenced this pull request Nov 6, 2026
buildCommonGuardChecks ran the pricing check before the model-specific
guards, so a model whose pricing can't be resolved got a 500
pricing_resolution_error even when model policy rejects it. Copilot lists
some models, such as gpt-4o, with batch_size 0, which pricing rejects
since #11157, so a disallowed gpt-4o got a 500 instead of a 403. This
broke the Model Routing End-to-End Smoke workflow on main.

Run the model-specific guards (multiplier cap, retired model and model
policy) before the pricing check, so a pricing failure never hides a
decision about the model. Pricing rules are unchanged: an allowed model
whose tariff is invalid still fails with pricing_resolution_error.

Refs #11211

Co-authored-by: Copilot <[email protected]>
lpcox pushed a commit that referenced this pull request Nov 6, 2026
buildCommonGuardChecks ran the pricing check before the model-specific
guards, so a model whose pricing can't be resolved got a 500
pricing_resolution_error even when model policy rejects it. Copilot lists
some models, such as gpt-4o, with batch_size 0, which pricing rejects
since #11157, so a disallowed gpt-4o got a 500 instead of a 403. This
broke the Model Routing End-to-End Smoke workflow on main.

Run the model-specific guards (multiplier cap, retired model and model
policy) before the pricing check, so a pricing failure never hides a
decision about the model. Pricing rules are unchanged: an allowed model
whose tariff is invalid still fails with pricing_resolution_error.

Refs #11211

Co-authored-by: Copilot <[email protected]>

This branch was previously deployed

1 inactive deployment
aoai-model — 6a89974e Deployed Nov 5, 2026 by lpcox via conclusion #2261
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants