Skip to content

feat(spend-logs): rust spend log ledger writer - #52163

Merged
narmstrong-berri merged 1 commit into
nate_spend_logs_v2_row_builderfrom
nate_spend_logs_v2_writer
Nov 21, 2026
Merged

narmstrong-berri merged 1 commit into
nate_spend_logs_v2_row_builderfrom
nate_spend_logs_v2_writer

Conversation

@narmstrong-berri

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

Copy link
Copy Markdown
Contributor
  • Stacked on feat(spend-logs): rust spend log row builder #52161. PR 3 of the spend logs on CustomLoggerV2 in Rust stack: on the ledger-on path, SpendLogs rows queue and flush through Rust
  • New SpendLogRepository in litellm-repositories: one transaction with Python's SQL shape (delivery rows, settle-once cleanup, all SpendLogs columns via jsonb_populate_recordset, skip conflicts), four .sql queries run through Database::run; .sqlx regenerated; litellm-db keeps only the connection side
  • New crate litellm-spend-log-writer (no pyo3, own error type): Python's byte-budget queue (accounting-only overflow), metadata retention, 100 rows / 2 MB statements, poison-row bisection budget 256, 3 retries, pool outage gets 3 in-pass retries like a Prisma outage
  • JSON sanitizers (safe_json, jsonify_object) live in python-compat
  • python-bridge exports RustSpendLogWriter; Python glue litellm/proxy/db/rust_spend_log_writer.py
  • Python installs it only when a Rust pool exists, the ledger is on and SPEND_LOGS_URL is unset; enqueue_spend_logs, update_spend_logs and friends switch to it
  • Stays in Python: ledger-off path (frozen), SPEND_LOGS_URL mode, the monitor and update_spend jobs (they also drain rollups), Redis parking, the ledger worker
  • DB events are reported once per repository call
  • Not preserved from Python: huge integers become floats; rows with lone surrogates are dropped at enqueue with the charge kept
  • Tests: writer unit tests plus Postgres tests, repository tests on a Prisma-migrated PG16; existing queue and batching tests pass unchanged; Rust twins; Postgres parity test writes identical rows through both writers

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

⚠️ 2 benchmarks are 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_writer (6f573b5) with nate_spend_logs_v2_row_builder (80009ad)

Open in CodSpeed

@narmstrong-berri narmstrong-berri changed the title feat(spend-logs): native spend log ledger writer feat(spend-logs): rust spend log ledger writer Nov 17, 2026
@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_writer branch from 7501012 to e3b77d0 Compare November 18, 2026 05:05
@narmstrong-berri
narmstrong-berri changed the base branch from main to nate_spend_logs_v2_row_builder November 18, 2026 05:25
@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_writer branch from e3b77d0 to 6f573b5 Compare November 18, 2026 06:55
@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_writer branch 2 times, most recently from 6783b22 to 95102a7 Compare November 19, 2026 20:49
@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_writer branch from 95102a7 to f159a0a Compare November 19, 2026 22:40
@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_writer branch 2 times, most recently from adf92b8 to 400001c Compare November 20, 2026 00:58
@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_writer branch from 400001c to 74f9310 Compare November 20, 2026 01:31
@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_writer branch from 74f9310 to f1acf48 Compare November 20, 2026 02:21
@narmstrong-berri
narmstrong-berri marked this pull request as ready for review November 20, 2026 02:21
@narmstrong-berri
narmstrong-berri requested a review from a team November 20, 2026 02:21
@narmstrong-berri narmstrong-berri self-assigned this Nov 20, 2026
@veria-ai

veria-ai Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

The PR introduces a Rust-backed spend log ledger writer and routes eligible spend log writes through it instead of the Python path.

One issue has been addressed, but the Rust routing still bypasses the external export path when an export client and SPEND_LOGS_URL are configured. This causes logs intended for external-only storage—including retained prompts and responses—to be persisted locally in LiteLLM_SpendLogs, while the external sink receives nothing.

Open issues (1)

Fixed/addressed: 1 · PR risk: 4/10

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 2 potential issues.

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

Devin Review

Comment on lines +161 to +164
match tokio::spawn(pass).await {
Ok(result) => result.map_err(PassError::Database),
Err(error) => Err(PassError::Aborted(error.to_string())),
}

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.

🔴 Lost accounting deliveries during shutdown

When shutdown cancels flush, tokio::spawn keeps writing after the drain sees an empty queue. Failed rows can requeue after uninstallation and disappear.

Learn more

The Python shutdown drain cancels and awaits the queue monitor, then uses queued counts to decide whether another pass is necessary. The Rust flush removes its rows before writing, while the spawned task here survives cancellation of its Python waiter. Consequently, neither the queue count nor the Python write lock represents that in-flight work. Uninstallation only transfers currently queued rows and forgets the writer. A later failure requeues rows into that forgotten writer, bypassing the shutdown Redis parking path.

Example: A flush takes the final batch and encounters a connection outage. Shutdown cancels its monitor during the retry sleep. Both shutdown drain passes can observe an empty queue before retries finish, and uninstallation removes the writer. When retries fail, its accounting deliveries return to an unreachable queue instead of Redis.

Recommended fix: Track and await in-flight Rust passes before checking drain completion or uninstalling the writer. Preserve the completed result for guardrail processing, and ensure failed rows become visible to the shutdown parking path. Add a controlled cancellation test with a blocked store that fails after shutdown begins.

Devin Review


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

Comment on lines +36 to +42
fn guardrail_usage_rows(rows: &[QueuedSpendLog]) -> Vec<GuardrailUsageRow> {
rows.iter()
.filter_map(|entry| {
let row = entry.row()?;
row.metadata
.contains("guardrail_information")
.then(|| GuardrailUsageRow {

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.

🟡 Stranded guardrail metrics after write failures

After guardrail metric retries exhaust, guardrail_usage_rows drops later unguarded batches. The rollup returns early on empty input, leaving pending metrics unwritten.

Learn more

Guardrail usage processing returns immediately for an empty input. It only drains previously failed metrics after that check, through PendingRollups. The Python writer supplied every processed row, including ordinary requests without guardrail results. Filtering the Rust result removes the ordinary requests that previously triggered recovery of pending metrics.

Example: A guarded request's daily metric fails all database retries and enters PendingRollups. The database recovers, and subsequent requests use models without guardrails. Their spend logs persist successfully, but each bridge result is empty, so the pending metric never retries and can disappear when the worker exits.

Recommended fix: Separate draining pending guardrail rollups from processing new guardrail rows, and invoke the drain after successful ordinary spend-log batches too. Alternatively, preserve a nonempty batch signal without returning full ordinary log payloads. Add a regression that exhausts metric retries, recovers the database, and flushes an unguarded batch.

Devin Review


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

@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_writer branch from f1acf48 to dc07ef1 Compare November 20, 2026 04:20
@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_writer branch from dc07ef1 to df64c00 Compare November 20, 2026 04:51

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

lgtm seems need rebasing some code dupe with #52661

@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_writer branch from df64c00 to b9e72dc Compare November 20, 2026 18:45
Comment thread litellm/proxy/utils.py

MAX_LOGS_PER_INTERVAL: Final = 10000

if (rust_writer := rust_spend_log_writer(prisma_client)) is not None:

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.

Medium: External-only logs are persisted locally

With both SPEND_LOGS_URL and an export client, this branch skips the Python export path, which commits deliveries with write_spend_logs=False; the Rust store instead inserts full rows, including any retained prompts/responses, into local LiteLLM_SpendLogs and never calls the external sink. Callers supplying an export client need to retain the Python route to preserve the no-local-content storage boundary.

Suggested change
if (rust_writer := rust_spend_log_writer(prisma_client)) is not None:
if (rust_writer := rust_spend_log_writer(prisma_client)) is not None and not (
db_writer_client is not None and os.getenv("SPEND_LOGS_URL") is not None
):

@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_writer branch from b9e72dc to 5527410 Compare November 20, 2026 19:16
@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_writer branch from 5527410 to 04c334a Compare November 20, 2026 19:48
@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_writer branch 2 times, most recently from 0885d97 to 3295cee Compare November 20, 2026 20:47
@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_writer branch from 3295cee to 1b58336 Compare November 20, 2026 21:11
@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_writer branch from 1b58336 to dabe1c3 Compare November 20, 2026 21:21
@narmstrong-berri
narmstrong-berri force-pushed the nate_spend_logs_v2_writer branch from dabe1c3 to f7bca29 Compare November 21, 2026 00:18
@narmstrong-berri
narmstrong-berri merged commit e4d269a into main Nov 21, 2026
69 of 118 checks passed
@narmstrong-berri
narmstrong-berri deleted the nate_spend_logs_v2_writer branch November 21, 2026 00:31
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.

2 participants