Skip to content

feat(budgets): run the ledger's post-call spend counter step in rust - #52166

Merged
narmstrong-berri merged 1 commit into
nate_spend_logs_v2_contractfrom
nate_spend_logs_v2_counters
Nov 21, 2026
Merged

narmstrong-berri merged 1 commit into
nate_spend_logs_v2_contractfrom
nate_spend_logs_v2_counters

Conversation

@narmstrong-berri

@narmstrong-berri narmstrong-berri commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor
  • PR 0 of the spend logs on CustomLoggerV2 in Rust stack: with the ledger on, the whole post-call spend counter step runs in Rust
  • Entry point Budgets::charge_counters (callbacks-budgets/src/charge.rs), callable directly from the Rust spend log callback; Python's ledger-on increment_spend_counters reaches it through NativeBudgets.charge_counters
  • One call: customer hierarchy settlement, one MGET, reservation reconcile, warm checks and SET NX seeds (concurrent), committed twins, one pipeline with invalidation on failure, budget windows, applied_adjustment / finalized stamps
  • Counter key selection in counters.rs: key, team, member, user, end user, tags, access groups, org, project, customer windows, committed twins; raw sk- keys hashed; reserved counters skipped
  • Remaining host calls (one batched call per phase): budget windows from the auth cache or stored row, DB spend for reseeds, auth-cache spend, post-call settlement registration
  • Ledger off runs main's code unchanged (frozen legacy path)
  • Tests: existing ledger-off counter set 828 passed unchanged; ledger-on twins and test_customer_window_accounting.py ledger-on cases run on the Rust store (in-memory, or a scripted RESP server so "one MGET, one pipeline" is still asserted), 610 passed; litellm-callbacks-budgets 81 unit + 10 admission + 19 charge; wide run same 34 failures as main
  • Not preserved: seeding no longer shares Python's per-counter singleflight lock (SET NX keeps it safe); error text not matched to Python

Devin Review

@codecov

codecov Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 1 benchmark is dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 45 untouched benchmarks


Comparing nate_spend_logs_v2_counters (683026b) with nate_spend_logs_v2_contract (9ce9d12)

Open in CodSpeed

@narmstrong-berri narmstrong-berri changed the title feat(budgets): plan post-call spend counters in rust on the ledger path feat(budgets): run the ledger's post-call spend counter step in rust Nov 17, 2026
@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_counters branch from c00dc90 to a712582 Compare November 18, 2026 04:33
@narmstrong-berri
narmstrong-berri changed the base branch from main to nate_spend_logs_v2_contract November 18, 2026 05:25
@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_counters branch from a712582 to 683026b Compare November 18, 2026 06:52
@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_counters branch from 683026b to a86e617 Compare November 19, 2026 19:31
@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_counters branch 2 times, most recently from 84076ca to 8654578 Compare November 19, 2026 22:40
@narmstrong-berri
narmstrong-berri marked this pull request as ready for review November 19, 2026 22:40
@veria-ai

veria-ai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

@devin-ai-integration devin-ai-integration Bot 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.

Devin Review found 4 potential issues.

5 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

Comment on lines +243 to +246
SpendCounter::TeamMember {
user_id: user_id.clone(),
team_id: team_id.clone(),
},

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.

🟡 Double charges for composite team IDs

When a membership reservation uses a colon-containing team ID, plan charges it again. Parsed and constructed counters differ despite identical keys.

Learn more

Reservation counters and planned counters use different representations of the same Redis key. held_counters parses reservation keys, and SpendCounter::parse splits a membership key at its last colon. The plan instead preserves the original user and team IDs as separate fields. ensure_warmed_counters compares these enum values to decide whether reconciliation already owns the charge. Unequal values therefore bypass reservation skipping even when they serialize to the same key. The same representation problem affects team IDs containing :window:.

Example: A user alice belongs to team org:engineering. Both representations write spend:team_member:alice:org:engineering, but parsing produces user alice:org and team engineering. With a reservation of 5 and an actual cost of 2, reconciliation applies -3 and the direct charge adds another 2, leaving 4 instead of 2.

Recommended fix: Use canonical Redis-key identity for reservation skipping and affected-counter deduplication, or normalize all planned counters through the same parser as reservation counters. Add a regression covering a membership reservation with a colon-containing team ID.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +58 to +62
run_hosted(
move |host| async move {
budgets
.charge_counters(&host, request.as_ref(), &step, record.as_ref())
.await

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.

🟡 Missing request context for budget metrics

With ledger accounting enabled, charge_counters omits RedisCall scoping. Counter reads and seeds lose spend-counter labels and request spans.

Learn more

The Python-facing store wrapper captures the caller's context in call and runs each operation inside a RedisCall scope. The hosted counter step bypasses those wrappers and never installs that scope. ServiceLoggingEvents::call consequently selects its empty background context and raw Redis operation names. The Rust logger captured by Budgets does not install a Redis call tag. A request's separately scoped post-call flush can still retain its context, but direct reads and seeds do not.

Example: A ledger request that cold-seeds a team counter reports its MGET and SET without the request's parent span or spend-counter service target. The previous path reported those operations through the scoped store wrappers.

Recommended fix: Capture the caller's Redis reporting context at the bridge entrypoint and propagate it through the hosted execution. Preserve operation-specific labels for direct reads and seeds, while keeping request-pipeline flush attribution unchanged. Add a service-event regression that asserts the target and parent span.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +131 to +135
loop: Final = asyncio.new_event_loop()
thread: Final = threading.Thread(target=loop.run_forever, daemon=True)
thread.start()
server: Final = asyncio.run_coroutine_threadsafe(asyncio.start_server(redis.serve, "127.0.0.1", 0), loop).result(
timeout=5

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.

🟡 Network servers inside isolated unit tests

rust_redis_store opens TCP connections inside unit tests. The new redis_port fixture does likewise, violating the repository's explicit no-network unit-test rule.

Learn more

The repository assigns in-process tests to tests/unit and explicitly prohibits network access there. This helper starts a TCP Redis server on a background event loop, and redis_port starts another TCP server. The ledger tests that call these helpers therefore depend on sockets and background-server scheduling.

Example: Running a ledger counter test that uses rust_redis_store binds an ephemeral localhost port and connects NativeRedisClient to it, even though the test resides in the isolated unit-test suite.

Recommended fix: Move the TCP-backed scenarios and their server fixtures to the integration suite. Keep genuinely in-process Rust memory-store scenarios in the mapped unit-test files.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +1 to +2
"""The ledger's post-call counter step, which ``increment_spend_counters`` hands to Rust, run on the Rust spend
counter store: in memory, and over a Redis server."""

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.

🟡 Ledger tests bypass required path mapping

ledger_scenarios duplicates existing tests across new ledger files. Repository rules require extending mapped files, including test_rust_spend_counters.py for the new module.

Learn more

Repository rules require unit-test paths to mirror production paths and require additions for existing behavior to extend the existing mapped test file. The new production module is rust_spend_counters, but its dedicated scenarios live under a different name. The PR also creates parallel ledger files for existing counter, callback and reservation tests through ledger_scenarios. These are another execution mode of existing coverage rather than separately mapped production features.

Example: Selecting the mapped unit test for the new rust_spend_counters module does not select test_rust_counter_step.py. Existing callback coverage is also split between its original mapped file and a new ledger twin.

Recommended fix: Put the new module's dedicated tests in tests/unit/proxy/spend_tracking/test_rust_spend_counters.py. Parameterize the existing mapped callback, counter and reservation tests for ledger mode instead of generating parallel test modules.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_counters branch from 8654578 to fd968ae Compare November 20, 2026 00:55
@narmstrong-berri
narmstrong-berri requested a review from a team November 20, 2026 00:55

@yujonglee-berri yujonglee-berri 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.

Looks good, counter step reads cleanly

@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_counters branch 2 times, most recently from daa5d04 to 4086291 Compare November 20, 2026 19:48
@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_counters branch from 4086291 to f54bac8 Compare November 20, 2026 20:20
@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_counters branch from f54bac8 to a575627 Compare November 20, 2026 20:47
@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_counters branch 2 times, most recently from b172961 to eb66710 Compare November 21, 2026 00:18
@narmstrong-berri
narmstrong-berri merged commit 5eec273 into main Nov 21, 2026
69 of 118 checks passed
@narmstrong-berri
narmstrong-berri deleted the nate_spend_logs_v2_counters branch November 21, 2026 00:31
@mateo-berri

Copy link
Copy Markdown
Contributor

a_customer_counter_that_cannot_be_seeded_fails_the_step_with_the_rest from this PR fails on main. stamps is [Some(-3.0)] where the test expects [None]. Could you take a look?

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants