Repository navigation
feat(spend-logs): rust spend log ledger writer - #52163
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Merging this PR will not alter performance1 warning
Comparing |
7501012 to
e3b77d0
Compare
e3b77d0 to
6f573b5
Compare
6783b22 to
95102a7
Compare
95102a7 to
f159a0a
Compare
adf92b8 to
400001c
Compare
400001c to
74f9310
Compare
74f9310 to
f1acf48
Compare
PR overviewThe 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 |
There was a problem hiding this comment.
Devin Review found 2 potential issues.
2 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)
| match tokio::spawn(pass).await { | ||
| Ok(result) => result.map_err(PassError::Database), | ||
| Err(error) => Err(PassError::Aborted(error.to_string())), | ||
| } |
There was a problem hiding this comment.
🔴 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.
Was this helpful? React with 👍 or 👎 to provide feedback.
| fn guardrail_usage_rows(rows: &[QueuedSpendLog]) -> Vec<GuardrailUsageRow> { | ||
| rows.iter() | ||
| .filter_map(|entry| { | ||
| let row = entry.row()?; | ||
| row.metadata | ||
| .contains("guardrail_information") | ||
| .then(|| GuardrailUsageRow { |
There was a problem hiding this comment.
🟡 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.
Was this helpful? React with 👍 or 👎 to provide feedback.
f1acf48 to
dc07ef1
Compare
dc07ef1 to
df64c00
Compare
yujonglee-berri
left a comment
There was a problem hiding this comment.
lgtm seems need rebasing some code dupe with #52661
df64c00 to
b9e72dc
Compare
|
|
||
| MAX_LOGS_PER_INTERVAL: Final = 10000 | ||
|
|
||
| if (rust_writer := rust_spend_log_writer(prisma_client)) is not None: |
There was a problem hiding this comment.
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.
| 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 | |
| ): |
b9e72dc to
5527410
Compare
5527410 to
04c334a
Compare
0885d97 to
3295cee
Compare
3295cee to
1b58336
Compare
1b58336 to
dabe1c3
Compare
dabe1c3 to
f7bca29
Compare
SpendLogRepositoryinlitellm-repositories: one transaction with Python's SQL shape (delivery rows, settle-once cleanup, all SpendLogs columns viajsonb_populate_recordset, skip conflicts), four.sqlqueries run throughDatabase::run;.sqlxregenerated;litellm-dbkeeps only the connection sidelitellm-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 outagesafe_json,jsonify_object) live inpython-compatRustSpendLogWriter; Python gluelitellm/proxy/db/rust_spend_log_writer.pySPEND_LOGS_URLis unset;enqueue_spend_logs,update_spend_logsand friends switch to itSPEND_LOGS_URLmode, the monitor andupdate_spendjobs (they also drain rollups), Redis parking, the ledger worker