Skip to content
Source
Sign inSign up
pingdotgg/t3code

perf(server): return freed database pages to the filesystem #29811

Closedjuliusmarmingewants to merge 5 commits intot3/prune-projected-events fromt3/reclaim-freed-pagesopened View on GitHub

juliusmarmingecommented

Stacked on https://git.cafe/pingdotgg/t3code/pulls/29806.

Problem

Pruning (#29806) frees about 5.7 GB of pages on cups (12.4 GB statev2.sqlite). That database has PRAGMA auto_vacuum = 0 (NONE) and already has a 0.44 GB freelist. With NONE, freed pages are reused but never returned to the filesystem. Today only t3 doctor changes that, by running VACUUM with the server stopped.

Options evaluated

What already works on main:

  • New databases are created INCREMENTAL (Sqlite.ts, empty schema).
  • DatabaseStorage.reclaim runs incremental_vacuum every minute, at most 1024 pages per pass, when the mode is INCREMENTAL.

So the remaining question is existing NONE databases. Switching them requires a full VACUUM, which rewrites every live page while it holds the write lock. Measured on cups (synthetic WAL database, half its rows deleted, then auto_vacuum=INCREMENTAL; VACUUM):

WrittenLiveVACUUM
64 MB32 MB0.33 s
256 MB128 MB1.8 s
1 GB512 MB5.9 s

That is roughly 11 ms per live MB on this VM's disk, and slower on laptop SSDs. After pruning, cups still has about 6 GB live, so the conversion would block for more than a minute here and several minutes on slower disks.

  • Startup VACUUM when cheap: works online for small databases. Chosen, with a 128 MiB live-data limit (about 2 s).
  • VACUUM INTO + swap at startup: it is still a full rewrite before serving (minutes for large databases) and needs 2× disk. Rejected.
  • Idle-window VACUUM: it blocks writers just as long. Agents and scheduled tasks run unattended, so "idle" is not reliable. Rejected.
  • Large existing databases: left to t3 doctor, which Settings → Maintenance already suggests once 1 GiB can be reclaimed.

Change

When the database opens (after migrations), a database with auto_vacuum = NONE and live data of 128 MiB or less runs PRAGMA auto_vacuum = INCREMENTAL; VACUUM. After that, the existing per-minute incremental_vacuum returns pruned pages to the filesystem. Failures, such as another process holding the file (CLI next to a running server), are logged and retried on the next open. The user storage note now says this.

Remaining trade-off (needs a call)

Large pre-existing databases like cups' still need one blocking step. Either keep t3 doctor (current; a minutes-long offline repair) or accept a startup VACUUM of several minutes on the next update. Even after conversion, reclaim returns 4 MiB per minute, so 5.7 GB would take about a day to drain. That is safe, but raising the per-pass budget would trade churn for speed.

Tests

  • Sqlite.test.ts: a small existing NONE database opens as INCREMENTAL with its data intact. This fails on main.
  • vp run check:changed passes.

Scope and approval

Maintainer-approved (Julius): projections are the source of truth once applied.

🤖 Generated with Claude Code

    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    2. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Needs Human Approval

      Macroscope's review found this PR requires human approval — Eligible existing databases will now be rewritten automatically at startup to enable space reclamation, rather than waiting for offline repair. Human review is required for this default change, including its startup locking and disk-work consequences.

      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    3. github-actions[bot](GitHub profile, opens in a new tab)commented

      Thread transfer impact

      ✅ Thread transfer remains within every enforced ceiling.

      ℹ️ No successful main baseline artifact is available yet. This run establishes the initial measurement.

      ProviderMetricMain baselineThis PRImpactPR ceiling
      CodexTotal thread wire—5.0 KiB—6.8 KiB✅
      CodexThread snapshot wire—3.8 KiB—4.9 KiB✅
      CodexLive turn WebSocket wire—1.2 KiB—2.0 KiB✅
      CodexLive turn WebSocket decoded—21.6 KiB—24.4 KiB✅
      CodexLive turn messages—2—8✅
      ClaudeTotal thread wire—5.1 KiB—6.8 KiB✅
      ClaudeThread snapshot wire—3.8 KiB—4.9 KiB✅
      ClaudeLive turn WebSocket wire—1.3 KiB—2.0 KiB✅
      ClaudeLive turn WebSocket decoded—21.9 KiB—24.4 KiB✅
      ClaudeLive turn messages—2—8✅

      Baseline: unavailable · PR result: e267404 · Source CI: success

      Scenario and decoded snapshot size

      10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.

      • Codex decoded thread snapshot: 108.5 KiB
      • Claude decoded thread snapshot: 108.8 KiB

      Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.

    4. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      Review in Change Stack →

      Note

      Reviews paused

      It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

      • Last reviewed commit: 504815f4b9ca50e37c9c9d3fd15ec559a0ce9890
      • Latest commit, not reviewed: e267404d353fe1f97bd238632f9f0a22ab4b4405

      Use the following commands to manage reviews:

      • @coderabbitai resume to resume automatic reviews.
      • @coderabbitai review to trigger a single review.

      Use the checkboxes below for quick actions:

      • Resume reviews
      • Trigger review
      Walkthrough

      SQLite setup now enables incremental vacuum for eligible existing databases and rebuilds message search when a pending rebuild is recorded. Tests cover search recovery, failure handling, and stored-data preservation. Documentation describes startup behavior for smaller databases and offline repair for larger databases.

      Changes: SQLite Persistence Setup

      Layer / File(s)Summary
      Vacuum setup and search recovery
      apps/server/src/persistence/Sqlite.ts
      After migrations, setup checks whether auto_vacuum is NONE and live data is at most 128 MiB. If so, it records a pending search rebuild, enables incremental vacuum, and runs VACUUM. Setup rebuilds message search when a pending marker exists and removes the marker after a successful rebuild. Errors are logged and do not fail setup.
      Persistence tests and database-space guidance
      apps/server/src/persistence/Sqlite.test.ts, docs/user/background-service.md
      Tests cover search-index recovery, failures during startup VACUUM and marker cleanup, and incremental-vacuum setup for a small existing database. They also verify stored data is preserved. The documentation describes startup behavior for smaller databases and offline repair for larger databases.

      Estimated code review effort: 3 (Moderate) | ~20 minutes

      Change: Feature · Severity of issue fixed: Medium

      Possibly related issues

      • pingdotgg/t3code#28903: The issue requests space reclamation after pruning, including incremental auto-vacuum. This change enables it for eligible existing databases.
      • pingdotgg/t3code#27598: The issue reports database growth and reliance on offline VACUUM. This change enables incremental vacuum for eligible existing databases; larger databases remain outside automatic conversion.

      Suggested reviewers: maria-rcks, only21mil, t3dotgg

      Merge Risk: Moderate · previous review 50481

      Searches may miss messages or associate results with the wrong messages until a later successful open. Prevent use of the pending index before merging.

      Pre-merge checks: Passed 4
      Check nameStatusExplanation
      Title checkPassedThe title clearly and concisely describes the main change: returning freed database pages to the filesystem through server-side database maintenance.
      Description checkPassedThe description includes the required Problem, Change, Scope and approval, and Verification sections. It explains the motivation, implementation, trade-offs, maintainer approval, and focused test resu…
      Linked Issues checkPassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes checkPassedCheck skipped because no linked issues were found for this pull request.
      Full details: Description check

      Explanation

      The description includes the required Problem, Change, Scope and approval, and Verification sections. It explains the motivation, implementation, trade-offs, maintainer approval, and focused test results.

      Finishing Touches
      Generate docstrings
      • Commit to this branch
      • Create a new PR
      Generate unit tests (beta)
      • Commit to this branch
      • Create a new PR
      • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

      CodeRabbit Verify

      • Run CodeRabbit Verify to test the changes in this pull request.
      Recent review info
      Run configuration
      Commits

      Reviewing files that changed from the base of the PR and between 09fbbab9e4bd3bead1790df56b084832f0272a76 and 504815f4b9ca50e37c9c9d3fd15ec559a0ce9890.

      Files selected for processing: 2
      • apps/server/src/persistence/Sqlite.test.ts
      • apps/server/src/persistence/Sqlite.ts

      Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.

      • Fix comments: Fix CodeRabbit comments on this PR
      • Fix comments: Fix CodeRabbit comments on this PR
      apps/server/src/persistence/Sqlite.ts lines 93 to 94Resolvedby juliusmarminge
      • Fix comments: Fix CodeRabbit comments on this PR
      apps/server/src/persistence/Sqlite.ts line 34Resolvedby juliusmarminge
    5. @coderabbitai The PR head is now e267404 (the GitHub mirror was lagging). It contains the search fallback from 766735f: ThreadSearch.ts uses the index only when no message-search-rebuild-pending marker exists, with the test "ThreadSearch scans instead of trusting the index while a rebuild is pending". Please re-verify.

    6. Tip

      For best results, initiate chat on the files or code changes.

      Analysis chain

      Script executed:

      #!/bin/bash
      git rev-parse HEAD
      git show -s --format='%h %s' HEAD
      fd -a '^(AGENTS\.md|ThreadSearch\.ts|ThreadSearch\.test\.ts)$'
      fd '^ThreadSearch(\.test)?\.ts$' --exec ast-grep outline {} --items all
      if [ -f AGENTS.md ]; then sed -n '1,200p' AGENTS.md; fi

      Length of output: 27305


      Script executed:

      #!/bin/bash
      git show --format=fuller --stat HEAD
      git show --format= -- apps/server/src/orchestration-v2/ThreadSearch.ts apps/server/src/orchestration-v2/ThreadSearch.test.ts
      nl -ba apps/server/src/orchestration-v2/ThreadSearch.ts | sed -n '100,128p;160,238p;300,465p'
      rg -n -C 6 'scans instead of trusting|MESSAGE_SEARCH_REBUILD_PENDING|message-search-rebuild-pending' apps/server/src/orchestration-v2/ThreadSearch.test.ts apps/server/src/persistence/Sqlite.ts
      fd '^messageSearchIndex\.ts$' --exec ast-grep outline {} --items all

      Length of output: 29028


      @juliusmarminge Re-verified the source at e267404d353fe1f97bd238632f9f0a22ab4b4405. The search fallback addresses the concern.

      • In apps/server/src/orchestration-v2/ThreadSearch.ts, Line 445 checks both index existence and the absence of message-search-rebuild-pending. When the marker exists, search scans projection messages instead of using the index.
      • In apps/server/src/orchestration-v2/ThreadSearch.test.ts, Line 221 adds the named regression test. It empties the index, inserts the pending marker, and asserts that search still returns the stored message.
      • In apps/server/src/persistence/Sqlite.ts, a failed rebuild retains the marker for retry on the next open.

      I found no remaining issue with this fallback. This was source verification only; I did not run the test.

      You are interacting with an AI system.
    7. Closing: t3 doctor on main already converts existing databases to incremental auto_vacuum and the server returns freed pages every minute after that. This PR only added a startup conversion for databases with at most 128 MiB live data, whose freed space is below the 1 GiB Maintenance threshold anyway; not worth a blocking startup VACUUM and the search-rebuild handling it needs. https://git.cafe/pingdotgg/t3code/pulls/29806 ships alone.

    8. juliusmarminge closed this

Sign in to join this conversation.