Skip to content

perf(agents): cut codex usage collector memory with SQL filter and cache - #6780

Merged
dhh merged 7 commits into
omacom:quattrofrom
markbus-ai:perf/codex-usage-fix
Aug 13, 2026
Merged

dhh merged 7 commits into
omacom:quattrofrom
markbus-ai:perf/codex-usage-fix

Conversation

@markbus-ai

Copy link
Copy Markdown
Contributor

Problem

The omarchy-agent-usage-codex collector scanned every row of opencode.db with Python-side json.loads — on a typical install that is a 1.7 GB DB with 55k+ rows, producing a ~716 MB RSS peak + 8 s CPU on every run. The omarchy.agents widget triggers it on shell start and every 15 minutes, and the panel's refreshLimits() call passes --limits-only — a flag the collector parsed and silently ignored, so opening the panel paid the full scan too.

Change

  1. SQL-level filtering in scan_opencode_sessions(): LIKE gates (acceleration) + json_valid + json_extract (authority) with the exact same semantics as the old Python filter (role == "assistant" and providerID == "openai"). Malformed rows are excluded via json_valid instead of aborting the scan.
  2. Local-stats cache following the existing omarchy-agent-usage-claude pattern: $XDG_CACHE_HOME/omarchy/agent-usage/codex-scan-<digest>.json with atomic writes, fcntl.flock double-checked locking, and a schemaVersion envelope validated on read.
  3. Flags honored: --force rescans and rewrites the cache; normal and --limits-only reuse a fresh (≤900 s) cache and fall back to a full scan when it is missing, stale, or corrupt. Cache-layer failures degrade to a direct scan and never drop the record.

Measured (this machine, real 1.7 GB opencode.db)

Scenario Wall Peak RSS
Before (baseline) 24.0 s 717.9 MB
Cold scan (after) 4.4 s 158.7 MB
--limits-only warm 1.4 s 85.1 MB

Parity

The output record schema and values are unchanged for the same data — verified against the old Python filter including malformed-row cases (valid rows still counted, bad rows skipped, no silent abort). --force produces byte-identical local stats to the pre-change full scan.

Tests

test/shell.d/agent-usage-codex-scanner-test.sh: 6 original + 9 new (cache write/perms/schema, --limits-only reuse, --force bypass, stale-cache rescan, corrupt/unwritable cache fallback, malformed-row parity, compact JSON). All 15 pass; claude collector suite (8) still passes.

The codex collector scanned every row of opencode.db (1.7 GB, 55k+ rows)
with Python-side json.loads, peaking around 716 MB of RSS on every run
-- including the panel's refreshLimits() call, which passed --limits-only
that the collector silently ignored.

Filter rows in SQL (LIKE gates + json_valid + json_extract authority,
mirroring the old Python filter semantics) so giant blobs are never
parsed, and cache the local stats scan in XDG_CACHE_HOME following the
claude collector's pattern (atomic writes, flock, schemaVersion).
--force rescans, --limits-only and normal mode reuse a fresh cache and
fall back to a full scan when it is missing, stale, or corrupt.

Measured: cold scan 716 MB -> 158 MB peak; warm --limits-only ~85 MB
and ~1.4 s. Output record schema and values are unchanged for the same
data (parity verified against the old filter, including malformed rows).
Copilot AI balanced review requested due to automatic review settings August 13, 2026 01:06

Copilot AI 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.

Pull request overview

Reduces Codex usage collector resource consumption through SQL filtering and cached local statistics.

Changes:

  • Filters OpenCode messages in SQLite.
  • Adds atomic, locked usage caching and flag handling.
  • Expands scanner cache and malformed-data tests.

Tip

If you aren't ready for review, convert to a draft PR.
Click "Convert to draft" or run gh pr ready --undo.
Click "Ready for review" or run gh pr ready to reengage.

Reviewed changes

Copilot reviewed 1 out of 2 changed files in this pull request and generated no comments.

File Description
bin/omarchy-agent-usage-codex Adds SQL filtering and local-stat caching.
test/shell.d/agent-usage-codex-scanner-test.sh Tests caching, flags, and failure recovery.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

dhh and others added 6 commits August 13, 2026 04:12
A no-flag run is the widget's periodic refresh, and refreshIntervalSec is
configurable down to 30 seconds; holding every mode to a 15-minute cache
meant stats could lag far behind the interval the user asked for. Mirror
the claude collector: normal runs reuse a scan for ~20 seconds purely to
dedup concurrent collectors, and only --limits-only, which promises just
fresh limits, may reuse a scan for up to 15 minutes.

Co-Authored-By: Claude Fable 5 <[email protected]>
The cached stats embed date-dependent fields (todayPrompts,
todayTotalTokens, recentDays), but only the file's age was checked, so a
cache written at 23:58 served yesterday's numbers as "today" for up to
15 minutes past midnight. Stamp the envelope with the scan's local date
and treat any other date as a miss.

Co-Authored-By: Claude Fable 5 <[email protected]>
A cache whose mtime is ahead of the clock has a negative age, which the
freshness check accepted forever: setting the clock backwards froze the
stats until real time caught up with the file. Require a non-negative
age before trusting the cache.

Co-Authored-By: Claude Fable 5 <[email protected]>
A transient lock, schema migration, or corrupted database aborts the
opencode scan mid-flight; the partial numbers still serve the current
run, but persisting them let a single bad read suppress opencode usage
for every cache reader until expiry. The claude collector already skips
its opencode cache write on a database error; do the same here.

Co-Authored-By: Claude Fable 5 <[email protected]>
The query relied on json_valid(data) evaluating before json_extract(),
but SQLite does not promise that AND terms run left to right; a
reordered plan would let json_extract raise on a malformed row and
silently truncate the scan. Wrap each json_extract in a CASE so the
guard is structural rather than positional.

Co-Authored-By: Claude Fable 5 <[email protected]>
"These caches were world-readable before" was copied from the claude
collector; codex had no caches before this one existed. Explain the
chmod on its own terms.

Co-Authored-By: Claude Fable 5 <[email protected]>
Copilot AI review requested due to automatic review settings August 13, 2026 11:17
@dhh

dhh commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

Reviewed. The SQL-side filtering and cache plumbing are well built — the filter agrees with the old Python filter on everything JS JSON.stringify can emit, the atomic write/flock pattern matches the claude collector exactly, and the memory win is real. I pushed six commits fixing freshness semantics that diverged from the claude collector this PR cites:

  1. The 900s reuse applied to every mode, including the widget's periodic no-flag refresh — stats could lag ~30 minutes and a lowered refreshIntervalSec was silently ignored. Normal mode now reuses a scan for only 20s (concurrent-run dedup), with the 15-minute reuse scoped to --limits-only, matching claude's split.
  2. The cache now records its scan date and treats any other day as a miss — a cache written at 23:58 no longer serves yesterday's "today" totals past midnight (the code claimed this guarantee without providing it).
  3. A cache with a future mtime (clock moved backwards) is no longer eternally fresh.
  4. An opencode scan interrupted by a database error is still served but never cached as a complete snapshot.
  5. The json_valid guard is now a CASE around each json_extract — SQLite doesn't promise AND evaluation order, and a reordered plan would have silently truncated the scan.

All pinned by new tests (20 assertions in the scanner test, full suites green).

— 🤖 Claude, posting on behalf of @dhh

Copilot AI 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.

Pull request overview

Copilot reviewed 1 out of 2 changed files in this pull request and generated no new comments.

@dhh
dhh merged commit 25c2b3a into omacom:quattro Aug 13, 2026
nick1udwig pushed a commit to nick1udwig/omarchy that referenced this pull request Sep 9, 2026
…che (omacom#6780)

* perf(agents): cut codex usage collector memory with SQL filter and cache

The codex collector scanned every row of opencode.db (1.7 GB, 55k+ rows)
with Python-side json.loads, peaking around 716 MB of RSS on every run
-- including the panel's refreshLimits() call, which passed --limits-only
that the collector silently ignored.

Filter rows in SQL (LIKE gates + json_valid + json_extract authority,
mirroring the old Python filter semantics) so giant blobs are never
parsed, and cache the local stats scan in XDG_CACHE_HOME following the
claude collector's pattern (atomic writes, flock, schemaVersion).
--force rescans, --limits-only and normal mode reuse a fresh cache and
fall back to a full scan when it is missing, stale, or corrupt.

Measured: cold scan 716 MB -> 158 MB peak; warm --limits-only ~85 MB
and ~1.4 s. Output record schema and values are unchanged for the same
data (parity verified against the old filter, including malformed rows).

* Scope the codex scan cache's 15-minute reuse to --limits-only

A no-flag run is the widget's periodic refresh, and refreshIntervalSec is
configurable down to 30 seconds; holding every mode to a 15-minute cache
meant stats could lag far behind the interval the user asked for. Mirror
the claude collector: normal runs reuse a scan for ~20 seconds purely to
dedup concurrent collectors, and only --limits-only, which promises just
fresh limits, may reuse a scan for up to 15 minutes.

Co-Authored-By: Claude Fable 5 <[email protected]>

* Invalidate the codex scan cache across day boundaries

The cached stats embed date-dependent fields (todayPrompts,
todayTotalTokens, recentDays), but only the file's age was checked, so a
cache written at 23:58 served yesterday's numbers as "today" for up to
15 minutes past midnight. Stamp the envelope with the scan's local date
and treat any other date as a miss.

Co-Authored-By: Claude Fable 5 <[email protected]>

* Reject codex scan caches with a future mtime

A cache whose mtime is ahead of the clock has a negative age, which the
freshness check accepted forever: setting the clock backwards froze the
stats until real time caught up with the file. Require a non-negative
age before trusting the cache.

Co-Authored-By: Claude Fable 5 <[email protected]>

* Never cache an interrupted opencode scan

A transient lock, schema migration, or corrupted database aborts the
opencode scan mid-flight; the partial numbers still serve the current
run, but persisting them let a single bad read suppress opencode usage
for every cache reader until expiry. The claude collector already skips
its opencode cache write on a database error; do the same here.

Co-Authored-By: Claude Fable 5 <[email protected]>

* Make the json_valid guard order explicit in the opencode query

The query relied on json_valid(data) evaluating before json_extract(),
but SQLite does not promise that AND terms run left to right; a
reordered plan would let json_extract raise on a malformed row and
silently truncate the scan. Wrap each json_extract in a CASE so the
guard is structural rather than positional.

Co-Authored-By: Claude Fable 5 <[email protected]>

* Drop a claude-collector comment that is false for codex

"These caches were world-readable before" was copied from the claude
collector; codex had no caches before this one existed. Explain the
chmod on its own terms.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: markbusking <[email protected]>
Co-authored-by: David Heinemeier Hansson <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
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