Skip to content

feat(enrich): bound enrichment write pressure - #303

Merged
EtanHey merged 6 commits into
mainfrom
feat/phase-2-write-priority
May 20, 2026
Merged

EtanHey merged 6 commits into
mainfrom
feat/phase-2-write-priority

Conversation

@EtanHey

@EtanHey EtanHey commented May 20, 2026 •

Copy link
Copy Markdown
Owner

Summary

Implements Phase 2 candidate (4): reduce enrichment write pressure by bounding realtime enrichment concurrency and batching arbitrated enrichment-update queue writes.

  • sets the LaunchAgent enrichment profile to BRAINLAYER_ENRICH_CONCURRENCY=4
  • adds BRAINLAYER_MAX_COMMIT_BATCH=25 as the bounded commit/queue batch knob
  • batches arbitrated enrichment-update JSONL writes up to the configured cap, with a short flush interval so writes do not sit indefinitely
  • adds RED/GREEN regressions proving bounded queue batches, overdue single-item flush behavior, failed-flush retry retention, invalid env hardening, final flush failure reporting, and counter rollback on persistent flush failure

Important caveat: this candidate improved drain/queue movement modestly, but it did not meet the <2s brain_search responsiveness 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.

Metric Before After Delta
Queue depth avg over 10 min 18710.6 files 18378.5 files -332.1 files
Queue depth start -> end 18819 -> 18594 18500 -> 18226 net drain improved from -22.5/min to -27.4/min
Drain stdout throughput 0 new stdout lines 252 files / 10 min = 25.2/min +25.2/min by stdout
brain_recall p50 2.6ms 2.4ms -0.2ms
brain_recall p95 30.4ms 93.5ms +63.1ms
brain_tags median 1631.9ms 1649.0ms +17.1ms
brain_search median 16930.5ms (n=5) 16903.3ms (n=2 completed; 3 later iterations timed out/errored) -27.2ms on completed calls; pass condition not met

/tmp/brainbar_bench.py did not emit p95 for brain_tags or brain_search; it emitted min/median/max for those sections. The after brain_search section only had 2 completed calls, then timed out/errored.

Source artifacts:

  • before queue depth: /tmp/brainlayer-phase2-before-20260520-231631/q-depth-before.log
  • before bench: /tmp/brainlayer-phase2-before-20260520-231631/bench-before.log
  • before drain snapshots: /tmp/brainlayer-phase2-before-20260520-231631/drain-before-wc.txt, drain-after-wc.txt, drain-before-tail-start.log, drain-before-tail-end.log
  • after queue depth: /tmp/brainlayer-phase2-after-20260520-233053/q-depth-after.log
  • after bench: /tmp/brainlayer-phase2-after-20260520-233053/bench-after.log
  • after drain snapshots: /tmp/brainlayer-phase2-after-20260520-233053/drain-before-wc.txt, drain-after-wc.txt, drain-tail-start.log, drain-tail-end.log

Bench caveat: /tmp/brainbar_bench.py emitted valid latency sections in both runs, then exited nonzero at its stale final load footer because it still runs ps -p 13093 and that PID no longer exists.

Live applied profile before after-window:

  • ran scripts/launchd/install.sh enrichment
  • verified LaunchAgent env: BRAINLAYER_ENRICH_CONCURRENCY=4, BRAINLAYER_MAX_COMMIT_BATCH=25
  • sampled recent ~/.brainlayer/queue/enrichment-*.jsonl files from the new code: max 3 JSONL lines/file, below configured cap 25

TDD / Review Evidence

RED:

  • .venv/bin/python -m pytest tests/test_enrichment_bounded_commit.py -v
  • failed as intended before implementation: expected queue file line counts [2, 2, 1], actual [1, 1, 1, 1, 1]

Focused final:

  • .venv/bin/python -m pytest tests/test_enrichment_bounded_commit.py -v
  • 7 passed in 6.71s

Relevant 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 -q
  • 118 passed in 16.06s

Lint/format final:

  • .venv/bin/python -m ruff check src/brainlayer/enrichment_controller.py tests/test_enrichment_bounded_commit.py
  • All checks passed!
  • .venv/bin/python -m ruff format --check src/brainlayer/enrichment_controller.py tests/test_enrichment_bounded_commit.py
  • 2 files already formatted

Full local/pre-push gate after final review fix:

  • git push pre-push hook ran the BrainLayer gate
  • unit suite: 2039 passed, 9 skipped, 75 deselected, 1 xfailed, 102 warnings in 142.29s
  • MCP registration: 3 passed
  • isolated eval/hook routing: 32 passed
  • Bun stale index: 1 pass
  • FTS5 determinism shell regression: PASS

Test count note: this PR adds seven bounded-batch/review-hardening regressions; the observed full unit gate on this branch is 2039 passed.

Review Fixes

  • CodeRabbit: invalid commit-interval env no longer crashes import; single pending item can flush on elapsed interval.
  • Cursor Bugbot: failed flushes retain pending items until queue batch write succeeds.
  • Cursor Bugbot/Codex: invalid BRAINLAYER_MAX_COMMIT_BATCH now falls back to 25 instead of crashing import.
  • Cursor Bugbot/Codex: overdue pre-append flush failure retains pending writes; final batcher flush failure is reported on EnrichmentResult instead of escaping and skipping completion.
  • Cursor Bugbot/Macroscope: final persistent flush failure reverses pending enriched/skipped credit before marking those writes failed, avoiding over-counting.

Merge Policy

Per Etan's 2026-05-20 ban: NO SQUASH. Use gh pr merge --rebase only.

Note

Bound enrichment write pressure by batching commits in enrich_realtime and enrich_batch

  • Introduces _EnrichmentWriteBatcher in enrichment_controller.py that buffers enrichment writes and flushes when a batch reaches MAX_COMMIT_BATCH items (default 25) or MAX_COMMIT_INTERVAL_SECONDS elapses (default 250ms).
  • Adds enqueue_enrichment_updates and enqueue_jsonl_batch to queue_io.py to write multiple enrichment events atomically in a single JSONL file.
  • Both enrich_realtime and enrich_batch use the batcher when arbitrated writes are enabled; flush failures are reported per chunk without aborting the run.
  • Reduces enrichment concurrency from 18 to 4 in the launchd plist and sets BRAINLAYER_MAX_COMMIT_BATCH=25 in the process environment.
  • Behavioral Change: single enrichment writes now go through the batch API path; final flush errors adjust result counters and emit per-chunk errors rather than raising.

Macroscope summarized 8c4e602.

@coderabbitai

coderabbitai Bot commented May 20, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR introduces batching controls for enrichment commit operations. A new _EnrichmentWriteBatcher accumulates enrichment updates and flushes them in bounded batches or at configured intervals; queue I/O now supports atomic batch writes; both enrichment engines integrate the batcher when arbitrated writes are enabled; LaunchAgent config reduces concurrency and specifies batch limits.

Changes

Enrichment Write Batching

Layer / File(s) Summary
Queue I/O batch enqueue APIs
src/brainlayer/queue_io.py
enqueue_jsonl_batch writes multiple JSONL events atomically using temp-file + replace; enqueue_enrichment_updates maps update dicts to enrichment events and batches them; single-event paths refactored to delegate to batch helpers.
Enrichment write batcher class and constants
src/brainlayer/enrichment_controller.py (lines 47–48, 173–260)
MAX_COMMIT_BATCH and MAX_COMMIT_INTERVAL_SECONDS constants control batching thresholds; _EnrichmentWriteBatcher accumulates enrichment update payloads with computed hashes and flushes based on size or elapsed time via queue batch APIs.
Realtime enrichment with batching integration
src/brainlayer/enrichment_controller.py (lines 899–953)
enrich_realtime instantiates and uses batcher when arbitrated writes enabled; meta-research tags and enrichment updates enqueued to batcher; per-chunk result handling restructured for error emission and consistent accounting; batcher flushed in finally block.
Batch enrichment with batching integration
src/brainlayer/enrichment_controller.py (lines 1000–1056)
enrich_batch per-chunk loop uses batcher when enabled; meta-research handling, dedup, prompt build, Gemini call, and write submission inlined with batcher enqueuing; batcher flushed in finally block after candidates processed.
Configuration and test validation
scripts/launchd/com.brainlayer.enrichment.plist, tests/test_enrichment_bounded_commit.py, tests/test_enrichment_controller.py
LaunchAgent environment updated: BRAINLAYER_ENRICH_CONCURRENCY lowered to 4, BRAINLAYER_MAX_COMMIT_BATCH set to 25. New test validates enrich_batch batches writes (max size 2) across multiple enrichment files. Plist config assertions updated to match new env values.

Sequence Diagram

sequenceDiagram
  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()
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • EtanHey/brainlayer#234: Both PRs heavily modify src/brainlayer/enrichment_controller.py's arbitrated write path—PR #234 adds per-store single-writer queuing via _submit_write, while this PR layers an _EnrichmentWriteBatcher on top when arbitrated writes are enabled.
  • EtanHey/brainlayer#222: Both PRs refactor enrich_realtime internals: PR #222 adds ThreadPoolExecutor concurrency via _enrich_single_chunk, while this PR reworks write submission via _EnrichmentWriteBatcher with max-batch and interval commit controls.
  • EtanHey/brainlayer#225: Both PRs operate on the meta-research tagging → enrichment write path—this PR integrates meta-research tags through the bounded write-batching layer, while PR #225 changes the prompt/detection rules that determine which chunks receive the meta-research tag.

Poem

🐰 Batches batch in waves so grand,
Write them all at once, oh man!
When the timer ticks or limit's near,
Flush them down with batching cheer!
Queue and disk in sync, no fright—
Enrichment commits, done just right!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat(enrich): bound enrichment write pressure' accurately and concisely describes the main change—implementing batching and concurrency bounds to reduce enrichment write pressure.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/phase-2-write-priority

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

@EtanHey

EtanHey commented May 20, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@EtanHey

EtanHey commented May 20, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@EtanHey

EtanHey commented May 20, 2026

Copy link
Copy Markdown
Owner Author

@cursor @BugBot review

@cursor

cursor Bot commented May 20, 2026

Copy link
Copy Markdown

You need to increase your spend limit or enable usage-based billing to run background agents. Go to Cursor

@coderabbitai

coderabbitai Bot commented May 20, 2026

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7fbab10 and 0a89956.

📒 Files selected for processing (5)
  • scripts/launchd/com.brainlayer.enrichment.plist
  • src/brainlayer/enrichment_controller.py
  • src/brainlayer/queue_io.py
  • tests/test_enrichment_bounded_commit.py
  • tests/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: Use paths.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.py
  • src/brainlayer/queue_io.py
  • tests/test_enrichment_controller.py
  • src/brainlayer/enrichment_controller.py
src/brainlayer/**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

src/brainlayer/**/*.py: Use retry logic on SQLITE_BUSY errors; each worker must use its own database connection to handle concurrency safely
Classification must preserve ai_code, stack_trace, and user_message verbatim; skip noise entries entirely and summarize build_log and dir_listing entries (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 via enrichment_controller.py, and Ollama as offline last-resort; allow override via BRAINLAYER_ENRICH_BACKEND env var
Configure enrichment rate via BRAINLAYER_ENRICH_RATE environment variable (default 0.2 = 12 RPM)
Implement chunk lifecycle columns: superseded_by, aggregated_into, archived_at on chunks table; exclude lifecycle-managed chunks from default search; allow include_archived=True to show history
Implement brain_supersede with safety gate for personal data (journals, notes, health/finance); use soft-delete for brain_archive with timestamp
Add supersedes parameter to brain_store for atomic store-and-replace operations
Run linting and formatting with: ruff check src/ && ruff format src/
Run tests with pytest
Use PRAGMA wal_checkpoint(FULL) before and after bulk database operations to prevent WAL bloat

Files:

  • src/brainlayer/queue_io.py
  • src/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!

Comment thread src/brainlayer/enrichment_controller.py Resolved
Comment thread src/brainlayer/enrichment_controller.py Resolved
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

ℹ️ 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".

Comment thread src/brainlayer/enrichment_controller.py Resolved

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

@EtanHey

EtanHey commented May 20, 2026

Copy link
Copy Markdown
Owner Author

Review fixes pushed in bfda039: invalid BRAINLAYER_MAX_COMMIT_INTERVAL_MS now falls back to 250ms instead of crashing import; overdue pending enrichment batches flush before appending the next result so single-item buffers do not wait behind later writes. Added focused regressions and updated the PR body with current pre-push evidence.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/brainlayer/enrichment_controller.py Outdated
"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"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

@EtanHey

EtanHey commented May 20, 2026

Copy link
Copy Markdown
Owner Author

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/brainlayer/enrichment_controller.py Outdated
Comment on lines +1072 to +1074
finally:
if write_batcher is not None:
write_batcher.flush()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment thread src/brainlayer/enrichment_controller.py Resolved

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

@EtanHey

EtanHey commented May 20, 2026

Copy link
Copy Markdown
Owner Author

Final Cursor Bugbot hardening pushed in ff7bfd2: invalid BRAINLAYER_MAX_COMMIT_BATCH now falls back to 25 instead of crashing module import. Added test_invalid_commit_batch_env_does_not_crash_import; focused suite is 5/5, relevant suite is 116/116, and the final pre-push BrainLayer gate passed.

@EtanHey

EtanHey commented May 20, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/brainlayer/enrichment_controller.py Outdated
Comment on lines +1072 to +1074
finally:
if write_batcher is not None:
write_batcher.flush()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment thread src/brainlayer/enrichment_controller.py Resolved

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

@EtanHey

EtanHey commented May 20, 2026

Copy link
Copy Markdown
Owner Author

Final review hardening pushed in 8994388: overdue flush failures now retain the current item in _pending, and final batcher flush failures are reported on the EnrichmentResult instead of escaping and skipping completion. Added two regressions; focused suite is 7/7, relevant suite is 118/118, final local pre-push gate is 2039 passed plus MCP/isolated/Bun/FTS gates.

@EtanHey

EtanHey commented May 20, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@EtanHey

EtanHey commented May 20, 2026

Copy link
Copy Markdown
Owner Author

@cursor @BugBot review

@cursor

cursor Bot commented May 20, 2026

Copy link
Copy Markdown

You need to increase your spend limit or enable usage-based billing to run background agents. Go to Cursor

Comment thread src/brainlayer/enrichment_controller.py Resolved

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ 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.

Comment thread src/brainlayer/enrichment_controller.py Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +1093 to +1096
except Exception as exc:
result.failed += 1
result.errors.append(f"{chunk['id']}: {exc}")
_emit_enrichment_error("batch", chunk["id"], str(exc))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

@EtanHey

EtanHey commented May 20, 2026

Copy link
Copy Markdown
Owner Author

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.

@EtanHey

EtanHey commented May 20, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@EtanHey

EtanHey commented May 20, 2026

Copy link
Copy Markdown
Owner Author

@cursor @BugBot review

@cursor

cursor Bot commented May 20, 2026

Copy link
Copy Markdown

You need to increase your spend limit or enable usage-based billing to run background agents. Go to Cursor

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +174 to +175
env = os.environ.copy()
env["BRAINLAYER_MAX_COMMIT_INTERVAL_MS"] = "not-a-number"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@EtanHey
EtanHey merged commit 86b18b4 into main May 20, 2026
6 checks passed
@EtanHey
EtanHey deleted the feat/phase-2-write-priority branch May 20, 2026 22:02
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.

1 participant