Skip to content

fix(proxy-extras): bound the lock waits of the partitioned SpendLogs index build - #44109

Merged
yassin-berriai merged 1 commit into
mainfrom
litellm_spend_logs_index_bounded_lock_waits
Oct 2, 2026
Merged

yassin-berriai merged 1 commit into
mainfrom
litellm_spend_logs_index_bounded_lock_waits

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • The background SpendLogs index build still stalls spend-log writes on a partitioned table
  • Creating the parent index waits up to 2s per try, 30 tries
  • Attaching a partition index waits with no limit at all

How it solves it:

  • Both statements now give up their lock wait after 200ms
  • Retries back off (up to 8s apart) and release the migration lock between tries
  • After 10 tries the build stops and leaves the index for the next build

User Flow

Before: while a long-running read touches a partition index, every spend log write queues behind the index build

  1. The admin boots the proxy against a partitioned spend-logs table whose partition index is not attached yet
  2. A client sends POST http://localhost:4000/v1/chat/completions and gets 200 with a real completion
  3. http://localhost:4000/ui/?page=logs spins on "Loading request logs" with no rows for as long as the read lasts (4m40s here)

After: the same requests are logged within seconds while the read is still open

  1. The admin boots the same proxy against the same table
  2. The same POST http://localhost:4000/v1/chat/completions returns 200 with a real completion
  3. http://localhost:4000/ui/?page=logs lists every request within a few seconds, with the read still open

Before, http://localhost:4000/ui/?page=logs during the open read (rows never load):

Logs page stuck loading on unfixed code

After, same page and same open read (all 5 requests listed):

Logs page listing all five requests on fixed code

Relevant issues

Follow-up to #43948, which moved this index build out of the migrations so it would not block writes

Linear ticket

Resolves LIT-9130

Files changed

File What changed and why
litellm-proxy-extras/litellm_proxy_extras/request_log_indexes.py New _with_bounded_lock runs one DDL step under the migration lock with lock_timeout = 200ms, retries LockNotAvailable with capped jittered backoff, holds the migration lock per attempt only, and returns False after 10 tries. Parent CREATE INDEX ... ON ONLY and ALTER INDEX ... ATTACH PARTITION both go through it, replacing the old 2s x 30 parent-only loop and the unbounded attach

How it runs

On a partitioned LiteLLM_SpendLogs, Postgres takes a SHARE lock on the parent for CREATE INDEX ON ONLY and an ACCESS EXCLUSIVE lock on the child index for ATTACH PARTITION. While either waits for an open transaction, every new INSERT (and every planner that opens the table's indexes, including the Logs page query) queues behind it. A short lock_timeout caps how long that queue can form.

flowchart LR
    A[ensure_request_log_indexes] --> B[_with_bounded_lock]
    B -->|SET lock_timeout 200ms| C[migration lock + DDL step]
    C -->|ok| D[done]
    C -->|LockNotAvailable| E[release migration lock, sleep 0.25s x 2^n, max 8s]
    E -->|tries left| B
    E -->|10 tries used| F[return False, next build retries]
Loading

The step is called from the migration job (run_migration_job, which reports False so the job is rerun) and from the serving proxy's daemon index thread (start_request_log_index_build, picked up by the next boot). The invalid parent index left by a step that never got its lock is kept, since the next build resumes from it.

Pre-Submission checklist

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review

Screenshots / Proof of Fix

Shared setup: Postgres 16 (pg16, the image pinned in .github/workflows/test-postgres.yml), database proxy9130 with a partitioned LiteLLM_SpendLogs. Before each arm the table is truncated and the call-id index is reset to an un-attached pair: an invalid parent LiteLLM_SpendLogs_litellm_call_id_idx (ON ONLY) and a valid partition index on LiteLLM_SpendLogs_pdefault. A reader session then runs SET enable_seqscan = off, selects through the partition index (holding its AccessShareLock), and sleeps 300s. The proxy is started with PYTHONPATH=<tree>:<tree>/litellm-proxy-extras and this config:

model_list:
  - model_name: nano
    litellm_params:
      model: openai/gpt-5-nano
      api_key: os.environ/OPENAI_API_KEY
general_settings:
  master_key: <local key>
  proxy_batch_write_at: 2

Each arm sends the same 5 requests, one at a time:

curl -s http://localhost:4000/v1/chat/completions \
  -H 'Authorization: Bearer <local key>' -H 'Content-Type: application/json' \
  -d '{"model":"nano","messages":[{"role":"user","content":"Reply with the single word ok"}]}'

The build is identified by hasattr(request_log_indexes, "_with_bounded_lock"), printed as MARKER_with_bounded_lock or MARKER_with_bounded_lock ABSENT.

Before (cc42a35)

Proxy writes while a reader holds the partition index

  1. Marker: MARKER_with_bounded_lock ABSENT .../litellm-base/litellm-proxy-extras/litellm_proxy_extras/request_log_indexes.py
  2. 5 curls: every one content=ok http=200 (1.0s to 1.6s each)
  3. pg_stat_activity about 2.5 minutes in:
     pid |  waited  | wait_event_type |                                 query
    -----+----------+-----------------+------------------------------------------------------------------------
     823 | 00:03:04 | Timeout         | SELECT pg_sleep(300);
     829 | 00:02:45 | Lock            | ALTER INDEX "public"."LiteLLM_SpendLogs_litellm_call_id_idx" ATTACH PA
     831 | 00:02:31 | Lock            | INSERT INTO "public"."LiteLLM_SpendLogs" ("session_id","status","compl
     840 | 00:02:27 | Lock            | SELECT count(*) FROM "LiteLLM_SpendLogs"
     832 | 00:01:28 | Lock            | INSERT INTO "public"."LiteLLM_SpendLogs" ("messages","billing_agent_id
     865 | 00:00:24 | Lock            | INSERT INTO "public"."LiteLLM_SpendLogs" ("billing_agent_id","cache_hi
     869 | 00:00:14 | Lock            |         SELECT COALESCE(NULLIF(session_id, ''), request_id) AS sessio
    
    The proxy's spend-log INSERTs and the Logs page query (pid 869) all wait behind the ATTACH
  4. Logs page: stuck on "Loading request logs" (first screenshot above)
  5. Proxy log: 00:34:24 Attached index ... Request-log indexes are all in place, only once the reader ended; the 5 rows land after that

Index build without the proxy (repro.py, same fixture both arms, 10s blocker)

  1. Parent CREATE ON ONLY behind an open write: max_insert_latency=1.999s inserts_over_0.5s=5 probe_inserts=61
  2. ATTACH PARTITION behind a child-index reader: max_insert_latency=9.946s inserts_over_0.5s=1 probe_inserts=2

After (7e68c8b)

Proxy writes while a reader holds the partition index

  1. Marker: MARKER_with_bounded_lock .../litellm/litellm-proxy-extras/litellm_proxy_extras/request_log_indexes.py
  2. 5 curls: every one content=ok http=200 (1.1s to 1.5s each)
  3. pg_stat_activity 53s into the reader: only SELECT pg_sleep(300);, no Lock waiters
  4. SpendLogs row count polled every 2s after the curls: 3, 3, 3, 5, 5, ... with blocked_waiters=0 throughout
  5. Logs page: all 5 requests listed while the reader is still open (second screenshot above)
  6. Proxy log: Waiting for open transactions before attaching LiteLLM_SpendLogs_pdefault_litellm_call_id_idx, then Could not get the lock for attaching ... leaving it for the next index build

Index build without the proxy (repro.py, same fixture both arms, 10s blocker)

  1. Parent CREATE ON ONLY behind an open write: build_result=[True] parent_valid=(True,) max_insert_latency=0.186s inserts_over_0.5s=0 probe_inserts=279
  2. ATTACH PARTITION behind a child-index reader: build_result=[True] parent_valid=(True,) max_insert_latency=0.197s inserts_over_0.5s=0 probe_inserts=282

The proxy arm ran at bbe32b45cc; request_log_indexes.py there is byte-identical to 7e68c8b8e5 (git diff --quiet bbe32b45cc 7e68c8b8e5 -- <file>), the tip only rebased onto newer main and added tests.

Tests

tests/proxy_migration_tests/test_request_log_indexes.py gets four Postgres tests. Two confirm the builder's DDL is actually lock-blocked (pg_stat_activity) and then probe inserts for 3s with a 1s lock_timeout: one with the parent index waiting on an open write, one with ATTACH waiting on a reader of the child index. Two exhaust the retries (_DDL_LOCK_ATTEMPTS = 2), one for the parent and one for the attach, assert the build returns False with the give-up warning, then release the blocker and assert the next build succeeds and covers every partition. The four lock tests passed 3 runs in a row on Postgres 16; the earlier full-file run was 35 passed and the partition/attach/parent tests pass on Postgres 14.

Mutation checks (each restored from a cp backup, verified with cmp -s):

Mutant Result
_DDL_LOCK_TIMEOUT = "2s" both insert-probe tests fail
attach calls _under_migration_lock directly (unbounded) attach probe test and attach give-up test fail
drop SET lock_timeout in the helper parent test fails; give-up test fails with QueryCanceled under statement_timeout=5s

Taxonomy audit

  • B2: migration lock is held per attempt and released before every sleep
  • C1-C7: no public symbol, default, or status code changed; only private constants renamed
  • T1-T5: all three tests fail on a mutant; no assertion removed (git diff origin/main -- tests/ | grep -E '^-.*assert' is empty)
  • T10: the thread tests join the builder in a nested finally, so a failing commit() cannot skip the join
  • H1-H10: no docs, source comments, UI, Prisma, or config changed; test-postgres.yml runs tests/proxy_migration_tests with no paths: filter
  • F3/O4: the only two lock-taking DDL statements on the parent are both covered; the per-partition CREATE INDEX CONCURRENTLY path takes no blocking lock and is unchanged

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • A blocker longer than about 25 to 50s of backoff makes the build give up
    • Serving proxy: picked up on the next boot
    • Migration job: returns False, so the job exits nonzero and is rerun
    • The parent path already behaved this way (30 x 2s); attach now does too
  • The helper resets lock_timeout to 0, not the prior value; the build owns and closes its connection

Low

  • Measured regime: Postgres 16 and 14, one partition, 10s and 300s blockers

Link to Devin session: https://app.devin.ai/sessions/c5d88ea32b4e4a018f64035903078e78
Open in Devin Desktop: https://app.devin.ai/desktop/session/c5d88ea32b4e4a018f64035903078e78?variant=devin
Requested by: @yassin-berriai

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

@greptile-apps

greptile-apps Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[High risk] Changes database lock handling for index builds.

The PR appears safe to merge based on the reviewed changes.

Summary

The PR bounds lock waits for parent-index creation and partition-index attachment, then retries with backoff. The latest changes synchronize the contention probes with observed DDL waits and add coverage for recovery after attach retries are exhausted.

Reviews (2) · Last reviewed commit: "fix(proxy-extras): bound the lock waits ..."

@codecov

codecov Bot commented Oct 2, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

…index build

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration
devin-ai-integration Bot force-pushed the litellm_spend_logs_index_bounded_lock_waits branch from ed3536f to 7e68c8b Compare October 2, 2026 00:55
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai please re-review at 7e68c8b (rebased onto current main and squashed; adds the two test fixes from the previous round)

@yassin-berriai
yassin-berriai merged commit 123237c into main Oct 2, 2026
107 of 108 checks passed
@yassin-berriai
yassin-berriai deleted the litellm_spend_logs_index_bounded_lock_waits branch October 2, 2026 01:28
yuneng-berri added a commit that referenced this pull request Oct 2, 2026
yuneng-berri added a commit that referenced this pull request Oct 2, 2026
…4212)

This reverts merge commit dea6fb9, reversing changes made to 61876f2
DeoLeung pushed a commit to aiyou178/litellm that referenced this pull request Oct 4, 2026
…index build (BerriAI#44109)

Co-authored-by: yassin <yassin@berri.ai>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 123237c)
yuneng-berri added a commit that referenced this pull request Nov 10, 2026
…1_103_x_devin

fix(proxy-extras): backport the automatic SpendLogs index build (#43948, #44109, #44203) to stable/1.103.x
yuneng-berri added a commit that referenced this pull request Nov 10, 2026
…1_104_x_devin

fix(proxy-extras): backport the automatic SpendLogs index build (#43948, #44109, #44203) to stable/1.104.x
Lineaje-DepFixer pushed a commit to lineaje-labs-gos/BerriAI-litellm that referenced this pull request Nov 18, 2026
…index build (BerriAI#44109)

Co-authored-by: yassin <yassin@berri.ai>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 123237c)
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