Repository navigation
feat(enrich): bound enrichment write pressure - #303
Conversation
📝 WalkthroughWalkthroughThis PR introduces batching controls for enrichment commit operations. A new ChangesEnrichment Write Batching
Sequence DiagramsequenceDiagram
participant EnrichRealtime as enrich_realtime
participant Batcher as _EnrichmentWriteBatcher
participant QueueIO as queue_io
participant Disk as Enrichment JSONL
EnrichRealtime->>Batcher: enqueue(update with content_hash)
EnrichRealtime->>Batcher: enqueue(update with content_hash)
alt Batch size reaches limit
Batcher->>Batcher: flush()
Batcher->>QueueIO: enqueue_enrichment_updates(batch)
else Max interval elapsed
Batcher->>Batcher: flush()
Batcher->>QueueIO: enqueue_enrichment_updates(batch)
end
QueueIO->>QueueIO: write to .tmp, atomic replace
QueueIO->>Disk: enrichment-{timestamp}.jsonl
Note over EnrichRealtime: finally: Batcher.flush()
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.
|
@coderabbitai review |
|
@codex review |
|
You need to increase your spend limit or enable usage-based billing to run background agents. Go to Cursor |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/brainlayer/enrichment_controller.py`:
- Around line 237-238: The interval-based flush guard in
enrichment_controller.py currently uses "len(self._pending) > 1" which prevents
single-item buffers from being flushed by time; change the condition in the
timer/check that now reads "if len(self._pending) >= self.max_batch or
(len(self._pending) > 1 and elapsed >= self.max_interval_seconds): self.flush()"
to remove the "> 1" check so interval-based flushing triggers for a single
pending item (i.e., use "elapsed >= self.max_interval_seconds" for that branch);
update the surrounding comment or add a TODO in the method that references
self._pending, max_batch, max_interval_seconds and flush() to explicitly
acknowledge and document any DB/concurrency risk and locking implications per
the coding guidelines.
- Line 48: MAX_COMMIT_INTERVAL_SECONDS is being computed directly from the env
var BRAINLAYER_MAX_COMMIT_INTERVAL_MS which will raise on import for non-numeric
values; change this to parse defensively using the same pattern as
_bounded_positive_int: read os.environ.get("BRAINLAYER_MAX_COMMIT_INTERVAL_MS"),
attempt to convert to float inside a try/except, fallback to the existing
default (250) on ValueError/TypeError, clamp the resulting milliseconds to >= 0,
and then divide by 1000.0 to set MAX_COMMIT_INTERVAL_SECONDS so invalid env
values do not crash startup.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Run ID: 66eae9bc-d61e-40b5-a390-6cc879d78527
📒 Files selected for processing (5)
scripts/launchd/com.brainlayer.enrichment.plistsrc/brainlayer/enrichment_controller.pysrc/brainlayer/queue_io.pytests/test_enrichment_bounded_commit.pytests/test_enrichment_controller.py
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
- GitHub Check: Cursor Bugbot
- GitHub Check: test (3.13)
- GitHub Check: test (3.11)
- GitHub Check: test (3.12)
- GitHub Check: Macroscope - Correctness Check
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py
📄 CodeRabbit inference engine (AGENTS.md)
**/*.py: Flag risky DB or concurrency changes explicitly and do not hand-wave lock behavior
Enforce one-write-at-a-time concurrency constraint; reads are safe but brain_digest is write-heavy and must not run in parallel with other MCP work
Run pytest before claiming behavior changed safely; current test suite has 929 tests
**/*.py: Usepaths.py:get_db_path()for all database path resolution; all scripts and CLI must use this function rather than hardcoding paths
When performing bulk database operations: stop enrichment workers first, checkpoint WAL before and after, drop FTS triggers before bulk deletes, batch deletes in 5-10K chunks, and checkpoint every 3 batches
Files:
tests/test_enrichment_bounded_commit.pysrc/brainlayer/queue_io.pytests/test_enrichment_controller.pysrc/brainlayer/enrichment_controller.py
src/brainlayer/**/*.py
📄 CodeRabbit inference engine (CLAUDE.md)
src/brainlayer/**/*.py: Use retry logic onSQLITE_BUSYerrors; each worker must use its own database connection to handle concurrency safely
Classification must preserveai_code,stack_trace, anduser_messageverbatim; skipnoiseentries entirely and summarizebuild_loganddir_listingentries (structure only)
Use AST-aware chunking via tree-sitter; never split stack traces; mask large tool output
For enrichment backend selection: use Groq as primary backend (cloud, configured in launchd plist), Gemini as fallback viaenrichment_controller.py, and Ollama as offline last-resort; allow override viaBRAINLAYER_ENRICH_BACKENDenv var
Configure enrichment rate viaBRAINLAYER_ENRICH_RATEenvironment variable (default 0.2 = 12 RPM)
Implement chunk lifecycle columns:superseded_by,aggregated_into,archived_aton chunks table; exclude lifecycle-managed chunks from default search; allowinclude_archived=Trueto show history
Implementbrain_supersedewith safety gate for personal data (journals, notes, health/finance); use soft-delete forbrain_archivewith timestamp
Addsupersedesparameter tobrain_storefor atomic store-and-replace operations
Run linting and formatting with:ruff check src/ && ruff format src/
Run tests withpytest
UsePRAGMA wal_checkpoint(FULL)before and after bulk database operations to prevent WAL bloat
Files:
src/brainlayer/queue_io.pysrc/brainlayer/enrichment_controller.py
🔇 Additional comments (4)
src/brainlayer/queue_io.py (1)
25-55: LGTM!Also applies to: 159-188
scripts/launchd/com.brainlayer.enrichment.plist (1)
44-46: LGTM!tests/test_enrichment_bounded_commit.py (1)
1-57: LGTM!tests/test_enrichment_controller.py (1)
1247-1248: LGTM!
|
Codex Review: Didn't find any major issues. Delightful! ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
There was a problem hiding this comment.
Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.
|
Review fixes pushed in bfda039: invalid |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bfda039ed4
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| "batch": float(os.environ.get("BRAINLAYER_BATCH_RATE", "0")), # no limit (async) | ||
| } | ||
| ENRICH_CONCURRENCY = int(os.environ.get("BRAINLAYER_ENRICH_CONCURRENCY", "10")) | ||
| MAX_COMMIT_BATCH = int(os.environ.get("BRAINLAYER_MAX_COMMIT_BATCH", "25")) |
There was a problem hiding this comment.
Guard MAX_COMMIT_BATCH env parsing at import time
BRAINLAYER_MAX_COMMIT_BATCH is parsed with a raw int(...) at module import, so any non-integer value (for example a launchd/env typo like "25ms") raises ValueError and prevents brainlayer.enrichment_controller from importing at all. This is a regression introduced with the new knob and it can take enrichment paths offline before runtime safeguards are reached; parse this variable with the same bounded fallback approach used for BRAINLAYER_MAX_COMMIT_INTERVAL_MS so misconfiguration degrades safely instead of crashing startup.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.
|
Cursor Bugbot issue fixed in e9cdf74: failed _EnrichmentWriteBatcher.flush() calls now retain _pending until the queue batch write succeeds, so final/retry flushes can still write the buffered updates. Added a regression covering failed flush retention and updated the PR evidence. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e9cdf74136
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| finally: | ||
| if write_batcher is not None: | ||
| write_batcher.flush() |
There was a problem hiding this comment.
Handle final flush errors inside batch processing loop
When arbitrated writes are enabled, enrich_batch defers queue writes and then unconditionally calls write_batcher.flush() in a finally block; if that final flush hits an I/O error (e.g., queue dir permission/disk issue) on a trailing partial batch, the exception escapes and aborts the whole run. This regresses prior behavior where enqueue failures were caught by the per-chunk except, recorded in result.failed, and processing continued; now a single final flush failure can crash the batch job and skip normal completion reporting.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.
|
Final Cursor Bugbot hardening pushed in ff7bfd2: invalid |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ff7bfd2dbd
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| finally: | ||
| if write_batcher is not None: | ||
| write_batcher.flush() |
There was a problem hiding this comment.
Catch flush errors before returning batch enrichment result
When arbitrated writes are enabled, write_batcher.flush() in the outer finally runs outside the per-chunk try/except, so any queue I/O failure during the trailing flush raises out of enrich_batch and skips the normal EnrichmentResult/completion path. This is a regression from the previous per-chunk enqueue behavior, where write failures were recorded as chunk-level failures and the run still returned a result. It becomes user-visible whenever the queue is temporarily unavailable at end-of-run (e.g., permission/disk/FS transient) and there are pending items below the batch cap.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.
|
Final review hardening pushed in 8994388: overdue flush failures now retain the current item in |
|
@codex review |
|
You need to increase your spend limit or enable usage-based billing to run background agents. Go to Cursor |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 8994388. Configure here.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8994388123
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| except Exception as exc: | ||
| result.failed += 1 | ||
| result.errors.append(f"{chunk['id']}: {exc}") | ||
| _emit_enrichment_error("batch", chunk["id"], str(exc)) |
There was a problem hiding this comment.
Defer failure accounting until batched write outcome is known
When write_batcher.enqueue(...) throws in enrich_batch, this block immediately increments result.failed and records an error for the current chunk, but the batcher keeps that chunk in _pending and can write it successfully on a later flush. With transient queue errors (e.g., first flush fails, next flush succeeds), chunks are persisted yet still reported as failed, which corrupts enrichment success/failure telemetry and any retry logic keyed off EnrichmentResult.
Useful? React with 👍 / 👎.
| "from brainlayer import enrichment_controller as c; print(c.MAX_COMMIT_INTERVAL_SECONDS)", | ||
| ], | ||
| check=False, | ||
| env=env, |
There was a problem hiding this comment.
Make subprocess import checks robust to src-layout test runs
This subprocess assertion assumes the child interpreter can import brainlayer, but the child only gets os.environ.copy() and no explicit PYTHONPATH/install context. In common src-layout test runs where the package is not installed, sys.executable -c "from brainlayer ..." fails with ModuleNotFoundError, so this test can fail for environment reasons instead of validating commit-interval parsing behavior.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.
|
Final accounting hardening pushed in 8c4e602: pending batched writes carry their credited result counter, transient enqueue-time flush failures retain writes without per-chunk double-counting, and persistent final flush failure reverses enriched/skipped credit before marking writes failed. Focused suite 7/7, relevant suite 118/118, local pre-push gate 2039 passed plus MCP/isolated/Bun/FTS gates. |
|
@codex review |
|
You need to increase your spend limit or enable usage-based billing to run background agents. Go to Cursor |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8c4e6021e9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| env = os.environ.copy() | ||
| env["BRAINLAYER_MAX_COMMIT_INTERVAL_MS"] = "not-a-number" |
There was a problem hiding this comment.
Propagate PYTHONPATH to subprocess import checks
These subprocess-based import assertions run with env = os.environ.copy() but never add the repo src/ path, so in environments where BrainLayer is tested from source (pytest pythonpath=src) without an editable install, the child process cannot import brainlayer and the test fails with ModuleNotFoundError. This makes the new regression tests brittle across common CI/local setups; set PYTHONPATH explicitly (or invoke with an import path that does not depend on installation state).
Useful? React with 👍 / 👎.

Summary
Implements Phase 2 candidate (4): reduce enrichment write pressure by bounding realtime enrichment concurrency and batching arbitrated enrichment-update queue writes.
BRAINLAYER_ENRICH_CONCURRENCY=4BRAINLAYER_MAX_COMMIT_BATCH=25as the bounded commit/queue batch knobImportant caveat: this candidate improved drain/queue movement modestly, but it did not meet the
<2sbrain_searchresponsiveness pass condition in the first live after-window. Candidate (2), signal-pause IPC, remains the documented fallback/follow-up.Before/After Evidence
All numbers below are from local artifacts captured during Phase 2. I am not extrapolating beyond observed output.
brain_recallp50brain_recallp95brain_tagsmedianbrain_searchmedian/tmp/brainbar_bench.pydid not emit p95 forbrain_tagsorbrain_search; it emitted min/median/max for those sections. The afterbrain_searchsection only had 2 completed calls, then timed out/errored.Source artifacts:
/tmp/brainlayer-phase2-before-20260520-231631/q-depth-before.log/tmp/brainlayer-phase2-before-20260520-231631/bench-before.log/tmp/brainlayer-phase2-before-20260520-231631/drain-before-wc.txt,drain-after-wc.txt,drain-before-tail-start.log,drain-before-tail-end.log/tmp/brainlayer-phase2-after-20260520-233053/q-depth-after.log/tmp/brainlayer-phase2-after-20260520-233053/bench-after.log/tmp/brainlayer-phase2-after-20260520-233053/drain-before-wc.txt,drain-after-wc.txt,drain-tail-start.log,drain-tail-end.logBench caveat:
/tmp/brainbar_bench.pyemitted valid latency sections in both runs, then exited nonzero at its stale final load footer because it still runsps -p 13093and that PID no longer exists.Live applied profile before after-window:
scripts/launchd/install.sh enrichmentBRAINLAYER_ENRICH_CONCURRENCY=4,BRAINLAYER_MAX_COMMIT_BATCH=25~/.brainlayer/queue/enrichment-*.jsonlfiles from the new code: max3JSONL lines/file, below configured cap25TDD / Review Evidence
RED:
.venv/bin/python -m pytest tests/test_enrichment_bounded_commit.py -v[2, 2, 1], actual[1, 1, 1, 1, 1]Focused final:
.venv/bin/python -m pytest tests/test_enrichment_bounded_commit.py -v7 passed in 6.71sRelevant suite final:
.venv/bin/python -m pytest tests/test_enrichment_bounded_commit.py tests/test_enrichment_controller.py tests/test_concurrent_enrichment.py tests/test_write_queue.py tests/test_arbitration.py -q118 passed in 16.06sLint/format final:
.venv/bin/python -m ruff check src/brainlayer/enrichment_controller.py tests/test_enrichment_bounded_commit.pyAll checks passed!.venv/bin/python -m ruff format --check src/brainlayer/enrichment_controller.py tests/test_enrichment_bounded_commit.py2 files already formattedFull local/pre-push gate after final review fix:
git pushpre-push hook ran the BrainLayer gate2039 passed, 9 skipped, 75 deselected, 1 xfailed, 102 warnings in 142.29s3 passed32 passed1 passPASSTest count note: this PR adds seven bounded-batch/review-hardening regressions; the observed full unit gate on this branch is
2039 passed.Review Fixes
BRAINLAYER_MAX_COMMIT_BATCHnow falls back to25instead of crashing import.EnrichmentResultinstead of escaping and skipping completion.Merge Policy
Per Etan's 2026-05-20 ban: NO SQUASH. Use
gh pr merge --rebaseonly.Note
Bound enrichment write pressure by batching commits in
enrich_realtimeandenrich_batch_EnrichmentWriteBatcherinenrichment_controller.pythat buffers enrichment writes and flushes when a batch reachesMAX_COMMIT_BATCHitems (default 25) orMAX_COMMIT_INTERVAL_SECONDSelapses (default 250ms).enqueue_enrichment_updatesandenqueue_jsonl_batchtoqueue_io.pyto write multiple enrichment events atomically in a single JSONL file.enrich_realtimeandenrich_batchuse the batcher when arbitrated writes are enabled; flush failures are reported per chunk without aborting the run.BRAINLAYER_MAX_COMMIT_BATCH=25in the process environment.Macroscope summarized 8c4e602.