Skip to content

Keep Tier-0 health checks bounded on large databases#593

Merged
EtanHey merged 3 commits into
mainfrom
fix/tier0-health-check-scale
Jul 13, 2026
Merged

Keep Tier-0 health checks bounded on large databases#593
EtanHey merged 3 commits into
mainfrom
fix/tier0-health-check-scale

Conversation

@EtanHey

@EtanHey EtanHey commented Jul 13, 2026

Copy link
Copy Markdown
Owner

Summary

  • replace the missing-embeddings full chunk scan with an exact indexed EXCEPT query that stays bounded on the 16 GB production database
  • enforce one 45-second internal health-check deadline across DB reads and source scans, persisting slow_check state before returning
  • detect launchd processes in uninterruptible U/D state, back off instead of repeatedly kickstarting, and escalate through the existing circuit breaker
  • make Tier-0 watchdog freshness and alert behavior explicit: 900-second stale threshold, immediate first alert, then 1800-second repeat cooldown, with cooldown reset after recovery
  • install the watchdog’s alert-state settings through the repository-owned plist and document the operator contract

Incident validation

All production-DB diagnostics were read-only. No VACUUM, schema change, deletion, or repair command was run.

  • old missing-vector query: interrupted by a read-only progress handler after 15.022s without completing
  • indexed replacement: exact count completed in 4.358s during profiling
  • complete changed health path against the live 16 GB DB (--json, no heal, isolated state file): 0.612s internal / 1.10s wall
  • query-plan test asserts indexed ID scans and rejects SCAN c

Verification

  • full suite: 3601 passed, 60 skipped, 5 xfailed (final branch tree, ulimit -n 4096)
  • mandatory pre-push gate: 3511 passed, 9 skipped, 61 deselected, 1 xfailed; MCP registration, isolated eval/hook routing, Bun regression, and shell FTS regression all passed
  • focused health/watchdog/install suite: 160 passed
  • Tier-0 drills: 10 passed; the unloaded-label drill also passed 20/20 isolated repetitions after one transient full-suite scheduling failure
  • ruff check . and ruff format --check .
  • sh -n scripts/tier0-watchdog.sh scripts/launchd/install.sh
  • plutil -lint scripts/launchd/com.brainlayer.tier0-watchdog.plist
  • git diff --check

The local CodeRabbit CLI produced only heartbeats and was stopped after roughly three minutes. PR-level CodeRabbit, Codex, Cursor, and Bugbot reviews are requested below.

Post-merge deploy checklist

  • update canonical main, reinstall the health-check and Tier-0 watchdog LaunchAgents from merged sources
  • explicitly bootstrap gui/501 watchdog and verify launchctl print
  • run the installed health check against the live DB and prove a fresh non-slow state under 60 seconds
  • prove one healthy watchdog tick emits no Tier-0 alert
  • signal and close monitor brainlayer-tier0-rearm-2026-07-13

Note

Medium Risk
Changes scheduled health-check, self-heal, and Tier-0 alerting on production launchd paths; mis-tuned deadlines or alert gating could miss real outages or delay repeat notifications.

Overview
Health checks now cap at 45 seconds end-to-end: DB counts use an indexed EXCEPT missing-vector query (replacing a full-chunk scan), SQLite progress handlers and a threaded source scan can abort under budget, and timeouts persist slow_check state (stage + duration) instead of leaving the tick hanging.

Self-heal skips launchctl kickstart when the target process is in uninterruptible U/D state, recording heal_backoff for the existing circuit breaker. ps/subprocess failures return None so doctor and health-check no longer treat a failed snapshot as hotlane_dead.

Tier-0 watchdog treats slow_check: true as unhealthy, lowers stale threshold to 900s, and adds 1800s repeat-alert suppression per failure class while kickstart recovery still runs; plist env documents alert state path and timings.

Reviewed by Cursor Bugbot for commit 126893a. Bugbot is set up for automated code reviews on this repo. Configure here.

Note

Bound Tier-0 health checks to a 45-second deadline on large databases

  • Adds a 45-second overall deadline to run_health_check in health_check.py; stages that exceed the budget write a slow_check state and return early instead of blocking indefinitely.
  • Interrupts long-running SQLite counts (count_missing_embeddings, _enrichment_backlog) via a progress handler that raises HealthCheckDeadlineExceeded when the budget is exhausted.
  • Runs the _source_recent filesystem scan in a daemon thread bounded by the remaining deadline, raising HealthCheckDeadlineExceeded if it does not finish in time.
  • Adds uninterruptible-process backoff in _apply_heals: if a launchd process is in state U/D, a heal_backoff action is recorded instead of kickstarting.
  • The Tier-0 watchdog in tier0-watchdog.sh now treats slow_check:true as unhealthy and suppresses repeat alerts for the same failure for 1,800 seconds via persisted alert state, while continuing recovery attempts. Stale threshold is reduced from 1,200 s to 900 s.
  • Behavioral Change: health checks that previously ran to completion on large databases will now time out and report slow_check rather than succeeding or hanging.

Macroscope summarized 126893a.

Summary by CodeRabbit

  • Improvements

    • Health checks now enforce a time limit and report slow or interrupted checks with additional status details.
    • Missing-vector checks use more efficient index-based counting.
    • Recovery avoids repeated restarts for unresponsive processes and applies backoff when appropriate.
    • Watchdog alerts for the same failure are suppressed during a configurable cooldown period.
    • Watchdog state now records alert history and resets after recovery.
  • Documentation

    • Updated operational guidance for health-check timeouts, recovery behavior, state updates, and watchdog alert timing.

@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 trial has ended. Reactivate Greptile to resume code reviews.

@cursor

cursor Bot commented Jul 13, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_40349fb7-e329-4a19-bdd0-213033ee6965)

@EtanHey

EtanHey commented Jul 13, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@EtanHey

EtanHey commented Jul 13, 2026

Copy link
Copy Markdown
Owner Author

@cursor @BugBot review

@EtanHey

EtanHey commented Jul 13, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@cursor

cursor Bot commented Jul 13, 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 Jul 13, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

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 commented Jul 13, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The health check now enforces a monotonic execution deadline, records slow-check state, and backs off for uninterruptible launchd processes. The Tier-0 watchdog persists alert state, suppresses repeated failure alerts, resets on recovery, and receives new launchd configuration and test coverage.

Changes

Health-check execution and recovery

Layer / File(s) Summary
Deadline-aware health-check execution
src/brainlayer/health_check.py, tests/test_stability_health_check.py, docs/operations/brainlayer-health-check.md
Missing-embedding and enrichment queries use deadline-aware SQLite reads; health-check results persist duration and slow-check stage information, with tests covering covering-index plans and interruptions.
Uninterruptible-process recovery
src/brainlayer/health_check.py, tests/test_stability_health_check.py, docs/operations/brainlayer-health-check.md
Launchd and process state checks select heal_backoff for uninterruptible processes instead of kickstarting them, with regression coverage and updated recovery documentation.
Persisted Tier-0 alert cooldown
scripts/tier0-watchdog.sh, scripts/launchd/com.brainlayer.tier0-watchdog.plist, tests/test_tier0_drills.py, tests/test_installable_build.py, docs/operations/brainlayer-health-check.md
The watchdog persists failure keys and alert epochs, suppresses repeated alerts within the configured interval, resets state after recovery, and exposes the new settings through launchd configuration and drills.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant run_health_check
  participant SQLite
  participant StateFile
  participant tier0-watchdog.sh
  participant AlertChannels
  run_health_check->>SQLite: run deadline-aware health query
  SQLite-->>run_health_check: result or interruption
  run_health_check->>StateFile: persist count and slow-check status
  tier0-watchdog.sh->>StateFile: read failure and alert state
  StateFile-->>tier0-watchdog.sh: failure key and last alert epoch
  tier0-watchdog.sh->>AlertChannels: send alert when cooldown permits
  tier0-watchdog.sh->>StateFile: record alert or reset recovery state
Loading

Poem

I’m a rabbit with a clock in my ear,
Counting vectors before time disappears.
Backoff for launchd, alerts softly spaced,
Fresh state means cooldowns erased.
Hop, hop—the watchdog knows what to do!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Title check ✅ Passed The title accurately summarizes the main change: bounding Tier-0 health checks for large databases.
✨ 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 fix/tier0-health-check-scale

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.

Comment thread src/brainlayer/health_check.py Outdated
Comment thread src/brainlayer/health_check.py Outdated

@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: 729b51f482

ℹ️ 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/health_check.py
@cursor

cursor Bot commented Jul 13, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_0ce95ccb-8803-48fe-b16a-1c44854ded05)

@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 trial has ended. Reactivate Greptile to resume code reviews.

@EtanHey

EtanHey commented Jul 13, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@EtanHey

EtanHey commented Jul 13, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

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.

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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: ecff1360de

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

@cursor

cursor Bot commented Jul 13, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_332be0f9-5f46-42c6-a688-b14dd7b5e27d)

@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 trial has ended. Reactivate Greptile to resume code reviews.

@EtanHey

EtanHey commented Jul 13, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@EtanHey

EtanHey commented Jul 13, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

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.

@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: 126893ab54

ℹ️ 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 +974 to +975
except HealthCheckDeadlineExceeded as exc:
return finish_slow("missing_embeddings", 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.

P2 Badge Preserve heal bookkeeping on slow exits

When the deadline fires here after an earlier healable issue was already collected (for example hotlane_dead or hotlane_backlog_disabled from the process snapshot), this returns before _apply_heals runs, so --heal neither increments heal_failures nor kickstarts the affected daemon even with heal_min_consecutive_failures=1. On a slow DB tick this can repeat every run and suppress the existing self-heal path for the real service outage; run the heal bookkeeping for already-collected labels before taking the slow exit or persist enough state for the next tick.

Useful? React with 👍 / 👎.

@EtanHey

EtanHey commented Jul 13, 2026

Copy link
Copy Markdown
Owner Author

Independent standing-reviewer verdict (s:399) — SHIP ✅

Reviewed from an isolated worktree at head 126893ab. All 5 mission-brief checks pass:

  1. Health-check scales — MEASURED on the live 16G DB. Ran run_health_check read-only (temp state, heal=False, no-op command_runner) against the real 16G brainlayer.db: 1.77s wall-clock, slow_check=False (was >15min pre-fix). Well under the <60s target and the 900s threshold.
  2. slow_check flag + internal deadline — a SQLite progress-handler deadline interrupts full-scan queries past budget → HealthCheckDeadlineExceeded; on timeout it still writes state with slow_check/slow_check_stage, so it can never silently blow the watchdog threshold.
  3. heal-kickstart UN-state backoff_state_is_uninterruptibleheal_backoff instead of hammering kickstart, with loud heal_escalation after N ineffective heals.
  4. Watchdog right-sized, no config drift — repo plist now carries TIER0_STALE_SECONDS=900 / REPEAT=1800 / ALERT_STATE (were absent = the drift); test_installable_build.py locks the packaged plist to those values.
  5. READ-ONLY honoredmode=ro + PRAGMA query_only=ON; no VACUUM/DDL/DML in the diff; my probe used a temp state path + no-op runner (zero side effects).

pytest on the 4 changed test files → 122 passed; CI green (3.11/3.12/3.13, lint, swift, CodeRabbit, Macroscope).

reviewDecision=REVIEW_REQUIRED and self-approval is unavailable on a same-account PR → proceeding with an admin merge (merge commit, no squash — R-010) per orc-driver's routed approval-block pattern; verification recorded in a .verified artifact. orc-driver re-arms the tier0 watchdog + closes the registry record post-merge.

@EtanHey EtanHey merged commit ff34c77 into main Jul 13, 2026
9 checks passed
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