codebase-memory-mcp icon indicating copy to clipboard operation
codebase-memory-mcp copied to clipboard

feat(config): add watcher_enabled config key to disable the background watcher (#335)

Open nguiaSoren opened this issue 4 months ago • 2 comments

Summary

Adds a persistent watcher_enabled config key (default true) that fully disables the background watcher when set to false. Closes #335.

Per the maintainer's contract on #335: watcher_enabled defaults to true, false prevents the watcher thread from starting and from registering projects, and manual index_repository continues to work normally. Scope is limited to this one switch — no other watcher policy changes.

Why (and how it differs from auto_watch)

auto_watch (default true) already gates per-session registration — but the watcher thread still runs idle even with auto_watch=false. #335 asks for a way to stop the watcher entirely (the doc-heavy-repo use case: every save churns the graph baseline). watcher_enabled is that master switch: when false, main() never creates the watcher, so the poll thread never starts and nothing is registered. auto_watch is left unchanged as the finer-grained per-session registration control. Both are now documented together.

(Note: the watcher polls for git changes now, not raw mtime as the original 0.6.0-era issue described; the user-visible concern — auto-reindex churn — is the same, and this switch addresses it.)

The change

  • src/cli/cli.h / src/cli/cli.c — CBM_CONFIG_WATCHER_ENABLED ("watcher_enabled") plus a small NULL-safe predicate cbm_config_watcher_enabled(cfg) (returns the persisted bool, default true). Listed in config usage help and config list output, alongside the sibling keys.
  • src/main.c — gate watcher creation + set_watcher on the predicate; the existing thread-create is already gated on g_watcher, so a disabled watcher means no thread and (via the existing NULL guard in register_watcher_if_enabled) no registration. cbm_mcp_server_set_config stays outside the gate so auto_index / auto_watch still read config when the watcher is off. Logs watcher.disabled reason=config when skipped.
  • tests/test_cli.c — cli_config_watcher_enabled_default_and_persist drives the predicate main() gates on: default on, false/0/off disable, true/1/on re-enable, persistence across reopen, and a NULL-config default (a config-store failure must never silently disable the watcher). The existing dump_verify-style tests feed synthetic values; this exercises the real seam.
  • docs/CONFIGURATION.md / README.md — document watcher_enabled, and add the previously-missing auto_watch row so the watcher knobs are described together.

Verification

  • Clean scripts/test.sh (ASan + UBSan) green: 6329 passed, 1 skipped, including the new test.
  • Behavioral proof on the built binary (isolated CBM_CACHE_DIR): config set watcher_enabled false → server logs watcher.disabled reason=config and no watcher thread starts; default/true → watcher starts normally (watcher.disabled count 0); manual index_repository unaffected.
  • No Makefile.cbm change (all touched files already compiled); no config set allowlist to update; no CHANGELOG in the repo.

All commits are DCO signed-off.

nguiaSoren avatar Jul 15 '26 21:07 nguiaSoren

Thanks for implementing the approved #335 contract and keeping the change focused. The exact head is security-clean, DCO-compliant, and CI is green. Before final review, two verification gaps need tightening:

  1. The current test proves config parsing and persistence, but it would still pass if the main() gate were removed. Please add a process-level regression using an isolated cache/config that proves watcher.disabled reason=config is emitted, watcher.start is absent, no project registration occurs, and manual index_repository remains available.
  2. Document that watcher_enabled is read at process startup, so changing it requires restarting or reconnecting the MCP server. Also clarify the auto_watch wording: it gates session registration, while the new key controls whether the watcher subsystem starts at all.

The separate key itself was explicitly approved in #335, so no redesign to overload auto_watch is requested. Review will resume against the updated exact head.

DeusData avatar Jul 16 '26 15:07 DeusData

Thanks for the careful review, @DeusData — both gaps are addressed in the updated head, and I kept it to the switch as you noted.

1. Process-level regression (tests/test_watcher_disabled.sh, wired into scripts/test.sh as Step 5c). It drives the real MCP server binary with an isolated CBM_CACHE_DIR and a tiny git fixture (CBM_INDEX_SUPERVISOR=0 so indexing/registration land in-process deterministically), across three runs:

  • disabled + manual index_repository — asserts watcher.disabled reason=config is emitted, watcher.start is absent, watcher.watch (registration) is absent, and the manual index_repository call is served and runs the pipeline (remains available with the watcher off);
  • disabled + auto_index=true — indexing still runs, but no watcher.start and no registration;
  • enabled positive control — watcher.start and watcher.watch both appear and watcher.disabled does not.

The positive control is what makes it bite: I verified it by neutering the main() gate (if (1 || cbm_config_watcher_enabled(...))), rebuilding, and confirming the test fails (watcher.start present, watcher.disabled not emitted) — then restored the gate and it passes. So it guards the wiring, not just the predicate, and would catch a removed gate.

2. Docs. docs/CONFIGURATION.md (and a companion note in README.md) now state that watcher_enabled — like auto_watch — is read once at process startup, so changing it takes effect on the next server start (restart or reconnect the MCP client), not on a running server. They also spell out the distinction: auto_watch gates whether a session registers its own project with an already-running watcher, while watcher_enabled controls whether the watcher subsystem starts at all.

No redesign — the separate key stays as approved in #335. Full scripts/test.sh is green including the new Step 5c. Ready for another look against the updated head.

nguiaSoren avatar Jul 16 '26 16:07 nguiaSoren

Reviewed in full. The config layer is clean and the contract is exactly right — what needs work is that the gate itself now targets code that no longer exists.

You implemented the agreed contract precisely. I checked it against issue #335, where the contract was written out verbatim: default true, false prevents the watcher thread from starting or registering projects, manual index_repository keeps working, plus config parsing/persistence coverage, a test proving no watcher initialisation when disabled, and user-facing docs. That is what this PR does, and nothing more. Worth saying explicitly: the new-config-key surface was opened by the maintainer, so this is not a direction question — it is agreed work.

Default preservation is exact, which is the thing that would matter most if it were wrong. cbm_config_get_bool(cfg, key, true) returns true when the key is absent and when the config store fails to open — so a config failure can never silently disable the watcher. Your test pins precisely that case. The accepted spellings (true/1/on, false/0/off) match cbm_config_get_bool on current main, and auto_watch is untouched. Behaviour with the key absent is bit-for-bit what it is today.

Coherence when disabled is clean too: the watcher object is simply never created, the thread-create is already gated on g_watcher, registration early-returns on a NULL watcher, and you deliberately kept cbm_mcp_server_set_config outside the gate so auto_index and auto_watch still read config. Read once at startup, so no live-reload race — and the docs say so.

The credit I most want to give: you noticed yourself that the unit test would still pass if the main() gate were deleted, and added a process-level test to close that hole. Catching your own vacuous-test gap is exactly the discipline this project asks for, and it is rarer than it should be.

What needs re-porting. The daemon rework moved watcher creation out of main.c entirely — on current main, main.c has zero watcher references and cbm_watcher_new is called only from src/daemon/host.c:578. So the gate has no home where you put it.

That makes this a re-port with genuine semantic decisions rather than a conflict resolution, and they are worth thinking about before you write code:

  • Where does the check belong now — at watcher construction in the daemon host, or earlier at daemon startup?
  • What should a daemon already running do if the key changes? Today the daemon is a long-lived process, so "read once at startup" means something different from when this was a per-invocation main().
  • Does a disabled watcher change anything about daemon lifecycle — should the daemon still start, and if so, what does it own?

The config layer, the tests, and the docs should all survive largely intact; it is the ~one gate that moves.

Two smaller notes:

  • scripts/test.sh gaining Step 5c is fine and clearly declared, but note that every step-zero contract runs on every CI leg, so a flaky process-level test there is expensive. Yours launches a real binary against a temp git fixture — worth making sure it waits on an asserted state rather than a sleep, since a timeout deciding a test is something we treat as a defect here.
  • Your branch is 367 commits behind, so please rebase before re-porting rather than after.

Nothing here is a design objection — the contract is agreed and your implementation of it is faithful. It is purely that the target moved.

DeusData avatar Jul 31 '26 05:07 DeusData

Thanks — and you were right on every point. Rebased first as you asked (394 behind by the time I started), then re-ported. src/main.c is now byte-identical to main; the gate lives in the daemon.

Where it went. host_state_prepare() in src/daemon/host.c, at watcher construction rather than earlier at daemon startup. runtime_config is opened three lines above cbm_watcher_new there, so the config handle is already in hand, and it keeps the property the original design leaned on: a NULL watcher makes every downstream path skip itself. That turned out to need almost nothing new — host_background_stop already NULL-checks, host_background_join gates on watcher_started, cbm_watcher_free is NULL-safe, register_watcher_if_enabled still early-returns on a NULL watcher, cbm_daemon_application_new copies the field plainly so NULL is fine, and the one http_server consumer is guarded. Two things did need changing: the !host->watcher clause in the startup check (a deliberately-unbuilt watcher must not fail daemon startup, while an allocation failure with the watcher enabled still must), and host_background_start, which creates the thread unconditionally — unlike the old main.c, it had no if (watcher) guard to inherit.

Key changes while a daemon is running. Read once, when the daemon builds its host state. I considered live re-reading for symmetry with auto_watch and decided against it: it adds a thread start/stop surface while serving, and the switch is defined in #335 as preventing the thread from starting. But your question exposed a real error in my round-2 docs — I had written that both keys are read at process startup. auto_watch is actually consulted per registration (application.c:440), and reconnecting a client no longer restarts a long-lived daemon, so "restart your MCP client" was wrong advice. The docs now state the asymmetry and give the actual procedure (daemon stop, then daemon status).

Daemon lifecycle. Unchanged — it still starts and still owns IPC, HTTP/UI, project locks and the application. Only the watcher and the watch_store that exists solely to back it go unbuilt. Worth recording explicitly: auto_index keeps working with the watcher off. I verified that rather than assumed it — the disabled run still logs index.supervisor.reap outcome=clean and writes the project DB.

The process test. Rewritten, and your note about the sleep was the more important of the two. No assertion is decided by a timeout now. The daemon logs to $CBM_CACHE_DIR/logs/cbm-daemon.log in a fixed order — watcher.disabled from host_state_prepare, then daemon.start, then the thread's own watcher.start, then the join, then daemon.stop — so each run retires its daemon and waits for that closed lifecycle before asserting. Absence over a closed lifecycle log is a fact rather than a race. Every wait is a bounded poll on an asserted state following wait_for_daemon_stop in scripts/soak-test.sh, and an exhausted budget fails loudly with the reason instead of passing quietly. Session stdin is held open through a FIFO until the last JSON-RPC response actually lands, not for an interval.

One gap that needed care: registration is asynchronous and unreachable until the project DB exists (application_refresh_watch_locked requires application_regular_db_exists), so a closed lifecycle alone would not have carried the negative — the session could just have ended first. The disabled+auto_index run now waits for the DB, i.e. registration's own precondition, before closing; and the enabled control waits for watcher.watch itself, so its absence in the disabled runs is evidence rather than noise.

It also honours CBM_TEST_BINARY like test_worker_watchdog.sh — the old hardcoded build/c path would have broken the BUILD_DIR= sanitizer and container legs.

Re-verified the gate-removal check at the new site, since that was the point of the test existing: neutering the host.c gate and rebuilding fails it immediately — watcher.disabled absent, watcher.start and watcher.watch both present. Restored byte-identical afterwards.

The config layer, the unit test and the docs survived the rebase intact; only comments moved from main() to the daemon host, and I corrected the unit-test comment, which still claimed it proved non-initialisation. It pins the config layer; the process test proves the gate.

nguiaSoren avatar Aug 01 '26 06:08 nguiaSoren

Three weeks late, and that's on us — you addressed both review rounds and then heard nothing. Re-reviewed now: the design is approved. It needs only a rebase.

What I checked, since you shouldn't have to take that on faith:

  • The default preserves today's behaviour exactly. cbm_config_get_bool(cfg, key, true) returns true both when the key is absent and when the config store fails to open, so an existing user who never sets it sees no change at all — including in the failure case, which is the one that usually gets missed.
  • auto_watch is untouched, and the distinction is the right one: auto_watch gates per-session registration on an already-running watcher, while watcher_enabled stops the thread being constructed at all. Two genuinely different questions that were previously answerable only by one switch.
  • The tests are binding, and you got there the hard way — you identified your own first-round unit test as vacuous and added a process-level shell test driving the real binary, asserting against daemon-log evidence rather than a timeout. That last part matters here more than usual: a watcher test that concludes from "nothing happened within N seconds" is exactly the kind of test this project treats as broken by construction.

The one wrinkle is that the gate had to move into src/daemon/host.c mid-review, because watcher construction relocated out of main.c during unrelated daemon work while your PR was open. You re-ported it correctly. That same drift is why the branch now conflicts — it's a long way behind main.

Please rebase onto current main and I'll merge once CI is green. If the rebase turns out to be painful given how far the daemon code has moved, say so and I'll take it from your commits with you credited as co-author — you've already done the design work and the test work, and I'd rather not have you fight a three-week-old conflict we caused.

One documentation point worth keeping when you rebase: the key is read once at daemon startup, so changing it requires daemon stop. You corrected that in the docs mid-review after the earlier claim about auto_watch turned out to be wrong — worth making sure it survives.

DeusData avatar Aug 20 '26 17:08 DeusData

Rebased onto current main — no help needed, the conflict was mechanical. Force-pushed; the two commits are unchanged in shape.

The gate itself didn't move. src/daemon/host.c had only 2 commits touching it since my base, and host_state_prepare / host_background_start / cbm_watcher_new are all still where I ported them — that file merged clean with no conflict. I re-verified each NULL-watcher assumption against current main rather than trusting the earlier port, since the surrounding daemon code did move:

  • registration: register_watcher_if_enabled no longer exists under that name, but application_refresh_watch_locked (application.c:435) still early-returns on !application->watcher, and it is the only path to cbm_watcher_watch. Registration remains unreachable with the watcher unbuilt.
  • teardown: host_background_stop still NULL-checks (host.c:510), host_background_join is still gated on watcher_started (host.c:522), cbm_watcher_free is still NULL-safe.
  • the UI consumer is still guarded (http_server.c:1233).
  • application_regular_db_exists still gates registration, so the process test's precondition-wait reasoning still holds.

One thing did change semantically, and it's worth flagging. My original PR notes said there was no config set allowlist to update. That's no longer true: #1522/#1558 turned CONFIG_KEYS into THE table, and config set/get/reset now reject any key absent from it. So the conflict in cli.c — where my two hand-rolled printf calls met your loop — could not be resolved by just taking the loop. watcher_enabled is now a CONFIG_KEYS row, next to auto_watch. Without that row config set watcher_enabled false exits with "unknown key" and the feature is unreachable from the CLI, which the process test would have caught at its first step. The default recorded there is true, matching the runtime reader's fallback as that table's comment asks.

scripts/test.sh: you took Step 5c for the worker error-response regression and 5d for the hook-conflict note, so mine is now Step 5e. Unchanged otherwise — still a bounded poll on an asserted state, no sleep deciding anything.

The docs point survived, and I checked it specifically: watcher_enabled is read once when the daemon starts, so daemon stop is what applies a change — reconnecting the client is not enough, because the daemon outlives the session. The auto_watch contrast (consulted per registration) is still there too.

Verified locally on the rebased head: prod build clean; tests/test_watcher_disabled.sh green on all three runs including the enabled positive control; the cli suite 282 passed / 0 failed (both cli_config_watcher_enabled_default_and_persist and your cli_ui_config_keys_are_discoverable_and_settable_issue1558, which the added table row had to not perturb); and the CLI surface by hand in an isolated CBM_CACHE_DIR.

Two caveats on my local run, neither branch-related. The same two pre-existing failures I flagged in round 2 still reproduce — test_index_supervisor.c:638 ASSERT(crash_terminal) and test_mcp.c:10420 code == 63 (was :9464; line drift, same assertion), both subprocess spawn/crash-containment tests. I can now name the mechanism: on this macOS box the probe worker wedges into uninterruptible state instead of dying by signal, so the supervisor reaps it outcome=killed exit_code=-1 signal=0 and the containment assert fails — other probes in the same suite reap correctly at signal=9/signal=15. The same wedge blocked four daemon_* suites from completing locally, since the runner blocks reaping the stuck child (daemon_runtime itself got 13 tests in clean, no failures, before that point). It is not new and not from this branch — I still have wedged workers from my round-2 session that came out of a clean origin/main worktree. Those suites should be judged on CI rather than on my machine.

nguiaSoren avatar Aug 23 '26 22:08 nguiaSoren

Merged in b0a3ca28. Thank you, @nguiaSoren — and sorry for the wait; after your 08-23 rebase the ball sat in our court, not yours.

You did two full rework rounds that were caused by our drift, not by anything wrong in your PR: the daemon rework moved the code your first gate targeted, and #1522/#1558 turned CONFIG_KEYS into the config set allowlist after you had already written the feature. Absorbing that twice without complaint, and picking up the new CONFIG_KEYS requirement yourself rather than waiting to be told, is why this needed so little from me at the end.

I verified the parts that decide whether this is safe rather than taking them on trust:

  • The default is bit-for-bit status quo. cbm_config_watcher_enabled() returns cbm_config_get_bool(cfg, CBM_CONFIG_WATCHER_ENABLED, true), and cbm_config_get_bool returns the default for an absent key, a NULL config, and an unrecognised value. So a user who never touches this key sees exactly today's behaviour, and a config-store failure cannot silently kill the watcher.
  • The relaxed startup check does not swallow real failures. Dropping watch_store/watcher from the main if was necessary for the disabled case, and the obvious risk is that a genuine allocation failure then goes unnoticed. You anticipated it: if (watcher_enabled && (!host->watch_store || !host->watcher)) still fails startup, with a comment stating exactly that distinction. That is the difference between a feature and a silent degradation, and it is the first thing I went looking for.
  • watcher_started is now scoped inside if (host->watcher), so teardown's join stays correctly gated.

Two other things worth calling out:

You self-identified a vacuous test. Rewriting the gate test to closed-lifecycle log assertions — asserting absence only after daemon.stop is already in the log, rather than letting a timeout stand in for proof — is exactly the standard we hold ourselves to, and you arrived at it on your own. The positive control in run 3 means gate removal fails runs 1–2 and gate inversion fails run 3; the test binds in both directions.

Your note about the wedged probe worker (outcome=killed exit_code=-1 signal=0, uninterruptible state) is the most useful attribution lead we have on a set of local-only failures we have been carrying unattributed for weeks. You were right that they are not yours. I have recorded it against that work — thank you for describing the mechanism instead of just reporting a red.

Closing #335 with this SHA.

DeusData avatar Aug 27 '26 17:08 DeusData