yams/docs/design/daemon-startup-refactor.md
Trevon 5bda4d77a2
perf+assert(storage): eliminate zero-init, temp-path overhead, add DCHECK invariants (#42)
* fix(core): add assertions and harden daemon lifecycle

* fix(daemon): tighten shutdown lifecycle invariants

* fix(test): add PressureLimitedPoller capability-sleep shutdown test

* refactor(vector): harden backend contracts

Split the vector backend surface into narrower contracts and
move entity read paths to Result<> so callers can distinguish
backend errors from empty results.

Also fixes the TurboQuant lazy-init race, makes VectorDatabase
error state thread-safe, wires eager index preparation, and
adds regression plus memory-scaling benchmark coverage.

* fix(vector): address audit findings plus hardening

Fix the five confirmed bugs: coroutine lifetime hazard in
embedding_generator (await_with_timeout outliving captured state),
VectorSystemManager init retry latch poisoning, incremental HNSW
persistence race, vec0 registry key collisions, and simeon PMI
output_dim/config() drift.

Add invariant hardening: PostIngestQueue stage validation +
numChunks assertion, VectorSystemManager success postcondition,
VectorDatabase TurboQuant non-null assertions on all quantize/
dequantize paths, and sqlite_vec_backend Simeon PQ range and
divisibility preconditions.

Also adds regression coverage for init-retry and lock-busy paths
and a locked node snapshot helper for safe incremental HNSW
persistence.

* fix(test): add PressureLimitedPoller wake-timer shutdown tests

* chore(vector): resolve clang-tidy hygiene across queue, vdb, and sqlite-vec

Replace unprotected std::getenv calls with locked getenvCopy helpers,
add debug-level logging to previously-silent catch blocks in
PostIngestQueue, VectorDatabase, and SqliteVecBackend, wrap
PostIngestQueue timer-detach allocations in try-catch, and fix
unsigned-widening / optional-deref / unused-include hygiene.

Verified with LSP diagnostics and rebuilds of catch2_vector_submodule
and catch2_daemon_component_submodule.

* fix(daemon): harden PressureLimitedPoller inFlightCounter null check

* fix(daemon): harden PostIngestQueue wait_until deadline checks

* fix(daemon): clean up recovery sentinels regardless of salvage count

Previously the .recovered-* sentinel and .corrupt-* file cleanup
was gated on documentsSalvaged > 0, leaving quarantine
artifacts to accumulate on repeated crash/recovery cycles where
the corrupt DB had 0 salvageable docs.

Move cleanup outside the salvage-count guard so stale
quarantine artifacts are always removed after examination.

* feat(vec0): restore persisted ANN index on daemon restart

After vec0 rebuild, probe for vectors_<dim>_hnsw_meta shadow tables
and load a previously-persisted HNSW index.  When found, the ANN
index is set directly on the vec0 table, skipping the O(n log n)
rebuild that was previously paid on every daemon restart.

Removes the stub restoreVec0AnnIndexIfPresentUnlocked() in favor
of inline restoration in rebuildVec0DimUnlocked(), which has
the vec0 table already created and ready for ann_index assignment.

* fix: enable DCHECK by default and assert metadata counter consistency

* fix(services): assert document deletion ordering content-before-metadata

* fix(test): add fork-based assertion validation tests

* fix(test): expand assertion tests for POSTCONDITION, DCHECK, UNREACHABLE

* fix(ci): enable -Denable-dcheck=true in all test CI lanes

* fix(test): address assertion review findings

* refactor(daemon): isolate poller config assertion checks

* refactor(services): reduce deletion and poller complexity

* style(ci): normalize test workflow spacing

* refactor(services): extract list query helpers

* refactor(services): extract list hydration helpers

* refactor(daemon): extract metrics snapshot helpers

* refactor(daemon): extract metrics counter snapshot

* refactor(daemon): extract metrics resource snapshot

* feat(graph): add daemon-backed explore

Wire graph explore through daemon IPC, keep CLI rendering stable,
and fall back locally when daemon transport or protocol skew fails.

Also add graph context service/tests, improve graph follow-up hints,
and keep release builds working with the current JSON library.

* fix(services): prevent prune delete metadata orphans

* fix(cli): honor data-dir in graph explore

- bypass daemon explore when the CLI pins a data dir so\n  temp fixtures do not resolve against a long-lived global DB\n- guard snippet truncation and ratio math to remove Fold-\n  reported underflow and div-by-zero paths\n- clamp zero-based symbol lines before rendering graph\n  context

* fix(daemon): make lifecycle stop completion safe

* fix(daemon): gate db-open startup against shutdown

* fix(metadata): serialize FTS indexed counter updates

* test(daemon): simulate vector lock contention cross-process

* test(daemon): isolate post-ingest identity batch

* style(daemon): normalize test include order

* refactor(graph): split cli graph helpers

Keep graph command paths smaller and easier to evolve.

Lock graph explore/topology contracts into focused presenter,
dispatcher, and support tests so follow-up refactors keep the
current IPC and hot-path behavior intact.

* fix(config): harden expand_tilde and fix Windows XDG state path doubling

- expand_tilde: handle bare ~ and ~/ explicitly to avoid std::out_of_range
  on substr(2) for single-char input
- getXDGStateHome: on Windows, go up two levels from %LOCALAPPDATA%\yams\state
  to %LOCALAPPDATA% so callers' xdg/yams append doesn't double the yams segment

* fix(static-analysis): add logging to empty catch blocks and fix nosemgrep syntax

* fix(static-analysis): strip trailing text from nosemgrep comments

* fix(doctor): add logging to daemon_check empty catch blocks

* fix(db_repair): add logging to empty catch blocks

* fix(chunking): add precondition checks for rabin polynomial and windowSize

* fix(safety): add null precondition checks for Fold proved null-deref sites

* fix(daemon): widen init-failure dispatch, add null/dbz preconditions

InitializationFailedEvent races with shutdown — async init
fails after teardown begins. Widen canDispatch to accept
Ready/ShuttingDown. Add static_assert on SnapshotRing N>0.
Add YAMS_PRECONDITION null guards on hex/stages/data/bytes.

* ci(ubsan): use restricted build targets to avoid runner timeout

* fix(daemon): detach wake timers on Windows stop path to prevent SIGSEGV

* fix(config): cast parseTomlU32 to size_t for batch fields

* fix(ci): use static helper for Windows timer leak, restrict ubsan tests

* fix(storage): add MutexPool and hash-length precondition assertions

* fix(storage): add reference counter lifecycle assertions

- YAMS_PRECONDITION on increment size constraints
- YAMS_DCHECK on decrement zero-row detection
- YAMS_ASSERT on transaction AUTOINCREMENT ID
- YAMS_PRECONDITION on transaction active guard
- YAMS_POSTCONDITION on commit/rollback state

* fix(storage): add atomic-write and store postcondition assertions

* fix(ingestion): add batch concurrency and accounting assertions

* fix(storage): add remove counter and retrieve-read DCHECKs

* fix(daemon): add WorkCoordinator double-start precondition

* bench(storage): add store/retrieve throughput microbenchmark

* fix(daemon): replace WorkCoordinator double-start throw with precondition

* test(daemon): add fork-based double-start precondition test

* test(ingestion): add batch concurrency edge-case tests

* fix(storage): remove overly-aggressive decrement DCHECK, fix transaction test

* test(daemon): fork-based precondition test — known Catch2 SIGABRT artifact

Catch2 v3.12.0 signal handler catches child SIGABRT via abort(),
marking test as FAILED even though CHECK passes correctly.
Affects all fork-based assertion tests. Test logic is correct.

* refactor(test): remove duplicate fork test, defer to assert_catch2

* fix(review): downgrade transactionId to DCHECK, use unique benchmark hashes

* fix(review): document PRECONDITION+throw pattern, downgrade exists() to DCHECK

* test(ingestion): add maxConcurrent early-return branch coverage

* perf(storage): eliminate zero-init in retrieveRaw, fix benchmark build

retrieveRaw bottleneck: 73% of samples in vector<std::byte>(N) zero-init
that gets overwritten by file.read(). Use make_unique_for_overwrite (C++20)
to allocate uninitialized, then assign into vector.

Before/after (TSan, 1MB Retrieve): 41.7ms -> 9.0ms (4.6x faster)

Also fix Google Benchmark build: add benchmark_main_dep (provides main())
to all 7 benchmark targets. Fix storage benchmark to use valid hex hashes.

0 assertion violations across all benchmark runs.

* perf(storage): skip redundant temp-dir check, use hex table for names

Two micro-optimizations in getTempPath() hot path:
1. Drop ensureDirectories() call — temp dir already created at ctor,
   stat() on every store was wasted work.
2. Replace 16 fmt::format("{:x}") calls with pre-computed hex char
   table + push_back. Avoids format machinery per store.

0 opengrep findings.

* assert(storage): DCHECK temp dir, buffer, size invariants in hot paths

Coverage for the three changed functions:

getTempPath:
  - DCHECK temp dir still exists (catch external cleanup in dev/CI)
  - DCHECK temp name length matches TEMP_NAME_LENGTH

atomicWrite:
  - DCHECK temp file exists after successful ofstream write

retrieveRaw:
  - DCHECK buffer non-null for positive file sizes
  - DCHECK assigned vector size matches fileSize

All benchmarks pass with zero assertion violations (TSan + Release).

* style(storage): fmt wrap DCHECK lines

* fix(review): downgrade PRECONDITION→DCHECK for catchable throws, guard zero-size UB

getObjectPath: YAMS_PRECONDITION always aborts — throw below is dead code.
Use YAMS_DCHECK instead (aborts in dev/CI, compiles out in release so
throw fires for backward-compatible catchable std::invalid_argument).

retrieveRaw: fileSize==0 → make_unique_for_overwrite(0) may return null,
assign(null,null) is UB. Early-return empty RawObject for zero-size files.

meson.build: guard benchmark blocks with benchmark_main_dep.found() too.

* fix(review): drop PRECONDITION dead throw, fix test comments

reference_counter: downgrade YAMS_PRECONDITION→DCHECK for transaction
active_ guard (aborts dev/CI, throw fires in release). Add matching
DCHECKs to decrement() and pruneReference() for consistency.

Fix inaccurate test comments claiming fork-test coverage for
WorkCoordinator double-start invariant.

* fix(review): DCHECK store postcondition, cast fileSize, rm dup main

store: downgrade YAMS_POSTCONDITION→DCHECK for exists() check.
Always-on POSTCONDITION adds stat() syscall to hot store() path;
debug-only DCHECK is the correct tier.

retrieveRaw: explicit static_cast<size_t>(fileSize) in assign
to avoid signed/unsigned narrowing warnings.

meson.build: remove benchmark_main_dep from metadata_query_bench_deps.
metadata_path_query_bench.cpp and tree_list_filter_bench.cpp both
define BENCHMARK_MAIN() — linking benchmark_main would be duplicate.

WorkCoordinator.h: update @throws→@pre in doxygen comment to match
YAMS_PRECONDITION(!started_) behavior.

* fix(bench): move pre-store to SetUp, PauseTiming unreliable

PauseTiming before first benchmark iteration caused single-iteration
runs in some Google Benchmark versions. Move pre-store into Fixture::SetUp
where it runs outside the timing loop naturally.

* fix(bench): check store/retrieve results, fix comment copy-vs-move

SetUp: throw if pre-store fails instead of silently continuing.
Retrieve: SkipWithError if retrieveRaw returns error.
Comment: assign() copies, not moves — fix misleading wording.

* fix(bench): rm benchmark_main_dep from targets with own main

ingestion_e2e_bench, retrieval_quality_bench, fusion_strategy_experiment
all define their own main() — linking benchmark_main_dep would cause
duplicate symbol at link time.

* fix(test): rename work_coordinator section, no longer tests double-start

Section title "Rejects start when already running" implied
double-start coverage but only checked worker count after first
start. Renamed to "Starts with correct worker count".

* test(refcount): add closed-state throw coverage for increment/decrement

After commit, increment/decrement must fail:
- Dev/CI (DCHECK): YAMS_DCHECK aborts, covered by fork tests
- Release (NDEBUG): DCHECK compiles out, throw fires

Conditional REQUIRE_THROWS_AS for release path.

* fix(bench): split meson guard for own-main vs benchmark_main targets

Targets with BENCHMARK_MAIN (metadata_path_query, tree_list_filter,
retrieval_quality, fusion_experiment, ingestion_e2e) only need
benchmark_dep. Storage/retrieval benchmarks need benchmark_main_dep.

Split into two guarded blocks to avoid skipping own-main targets
when benchmark_main is unavailable.

* fix(refcount): downgrade increment size PRECONDITION to DCHECK+error return

compressedSize>0 and uncompressedSize>=compressedSize come from user
content (block sizes). PRECONDITION would abort the process on corrupted
or malicious blocks. Return ErrorCode::InvalidArgument instead so
callers can handle gracefully.

* fix(daemon): defer startup maintenance

Make metadata repository readiness the startup boundary while moving search build, recovery cleanup, salvage, and VACUUM into coordinated background or pre-publication paths.\n\nKeep status honest for operators by separating database readiness from maintenance phase and surfacing recovery artifacts.
2026-06-04 22:44:12 -04:00

13 KiB

Daemon Startup Refactor: Metadata-First Availability and Async Maintenance

Goal

Make the YAMS daemon searchable as soon as the content store and metadata repository are usable, while moving expensive recovery, cleanup, indexing, and maintenance work out of the critical startup path.

This plan addresses a concrete failure mode observed during startup: the daemon reported it was "still opening database" for many minutes, but live sampling showed the blocking worker inside ServiceManager::maybeAutoVacuumDatabase() executing SQLite VACUUM / WAL checkpoint work. Because that work ran before finalizeDatabaseStartup(), recovery sentinels and stale corrupt DB artifacts were not cleaned up and clients could not use metadata search.

Current Problem

ServiceManager currently mixes several different responsibilities into one sequential startup path:

  1. open/create the metadata DB
  2. recover stale WAL files
  3. run integrity checks and quarantine corrupt DBs
  4. run migrations
  5. initialize DB pools and the metadata repository
  6. quick-check corrupt DBs for salvage
  7. optionally run blocking salvage
  8. clean corrupt DBs and .recovered-* sentinels, but only when salvage is needed
  9. run auto-VACUUM
  10. initialize vector/search subsystems and build the initial search engine

This makes the daemon availability boundary too late. Work that is not required for basic metadata search can delay the entire daemon.

Observed failure mode

  • Logs repeatedly emitted:
    • [ServiceManager] still opening database '/Users/trevon/.local/share/yams/yams.db' (...)
  • A live process sample showed the worker in:
    • ServiceManager::openDatabaseBlocking
    • ServiceManager::maybeAutoVacuumDatabase
    • metadata::Database::execute("VACUUM")
    • SQLite WAL checkpoint / write calls
  • Recovery sentinel cleanup is only reached later in finalizeDatabaseStartup() and only under quickCheckSalvageNeeded(...).needsSalvage == true.

Design Principle

Split startup into two lanes:

critical startup lane
  -> content store
  -> metadata DB open/create
  -> migrations
  -> DB pools + MetadataRepository
  -> metadata search available

async maintenance lane
  -> stale artifact cleanup
  -> corrupt DB salvage
  -> orphan repair / metadata rebuild
  -> FTS/search engine rebuild
  -> vector/topology rebuild
  -> VACUUM / compaction

The daemon should consider metadata search availability a useful degraded-ready state. Full hybrid search, vector search, topology rebuilds, and maintenance can converge in the background.

Target Startup Boundary

The synchronous path should only include work needed to safely answer metadata-backed requests:

  • initialize content store
  • open or create yams.db
  • perform bounded integrity checks necessary to avoid opening an unsafe DB
  • migrate schema
  • initialize connection pools
  • construct MetadataRepository
  • set:
    • databaseReady = true
    • metadataRepoReady = true
    • database phase ready
  • write bootstrap/status state

After this point, SearchRequest can route to metadata search while searchEngineReady == false. This behavior already exists in the dispatcher: if the hybrid search engine is not ready, the search request is forced to metadata mode.

Proposed Component Split

StartupCoordinator

Owns the minimal synchronous boot sequence and readiness transitions.

Responsibilities:

  • order critical startup phases
  • call DB open/migrate helpers
  • initialize DatabaseManager
  • mark metadata availability
  • schedule post-startup jobs
  • avoid doing maintenance inline

Candidate methods:

Result<void> StartupCoordinator::runCriticalStartup();
void StartupCoordinator::publishMetadataReady();
void StartupCoordinator::schedulePostStartupMaintenance();

DatabaseStartup

Encapsulates the metadata DB open/migrate path.

Responsibilities:

  • stale WAL recovery, if kept on the critical path
  • open/create DB
  • bounded integrity check
  • quarantine/recreate on hard corruption
  • migration
  • no VACUUM
  • no salvage
  • no sentinel cleanup unrelated to opening the active DB

Candidate methods:

Result<void> DatabaseStartup::openActiveDatabase(const fs::path& dbPath);
Result<void> DatabaseStartup::ensureIntegrityOrRecover(const fs::path& dbPath);
Result<void> DatabaseStartup::migrate(metadata::Database& db);

RecoveryArtifactManager

Owns cleanup of quarantine artifacts and recovery sentinels.

Responsibilities:

  • list yams.db.corrupt-*
  • list yams.db.recovered-*
  • remove stale sentinels independently of whether salvage is needed
  • remove corrupt DB files only after policy says they are safe to discard
  • report errors without blocking daemon startup

Candidate methods:

RecoveryArtifactSnapshot RecoveryArtifactManager::scan(const fs::path& dataDir);
CleanupResult RecoveryArtifactManager::cleanupSentinels(const fs::path& dbPath);
CleanupResult RecoveryArtifactManager::cleanupSafeCorruptDbs(const fs::path& dbPath);

Important behavior change:

  • .recovered-* cleanup must not be gated by quickCheckSalvageNeeded().needsSalvage.

DatabaseMaintenanceScheduler

Schedules non-critical DB work after metadata availability.

Responsibilities:

  • run salvage if corrupt DBs contain more documents than the active DB
  • run orphan repair / CAS metadata rebuild where applicable
  • run VACUUM only as background maintenance
  • apply resource-governor/admission checks before heavy work
  • expose status as maintenance, not startup

Candidate methods:

void DatabaseMaintenanceScheduler::scheduleSalvageIfNeeded(const fs::path& dbPath);
void DatabaseMaintenanceScheduler::scheduleVacuumIfUseful(const fs::path& dbPath);
void DatabaseMaintenanceScheduler::scheduleArtifactCleanup(const fs::path& dbPath);

SearchBootstrapScheduler

Makes search progressively better after metadata search is already available.

Responsibilities:

  • publish metadata-only search availability immediately after MetadataRepository is ready
  • schedule initial FTS/hybrid engine build asynchronously
  • schedule vector/topology rebuilds after provider/vector readiness
  • keep dispatcher fallback behavior explicit and tested

Candidate methods:

void SearchBootstrapScheduler::markMetadataSearchAvailable();
void SearchBootstrapScheduler::scheduleInitialSearchBuild();
void SearchBootstrapScheduler::scheduleVectorTopologyBuildIfReady();

Startup State Model

Avoid a single boolean notion of ready for all clients. Report readiness by capability:

  • content_store_ready
  • database_ready
  • metadata_repo_ready
  • metadata_search_ready
  • search_engine_ready
  • vector_index_ready
  • maintenance_running
  • maintenance_phase
  • recovery_artifacts_pending

Recommended user-facing states:

  • starting: cannot serve requests yet
  • metadata_ready: content store + metadata repository usable; metadata search works
  • degraded: serving metadata search while search/vector/maintenance work continues
  • ready: full configured capabilities available
  • maintenance: ready or degraded, with background cleanup/repair running

Execution Model

Critical path

ServiceManager::startAll
  -> StartupCoordinator::runCriticalStartup
     -> initializeDataDirAndContentStore
     -> DatabaseStartup::openActiveDatabase
     -> DatabaseStartup::migrate
     -> DatabaseManager::initializePools
     -> publish metadata-ready state
  -> schedulePostStartupMaintenance

Background path

DatabaseMaintenanceScheduler
  -> RecoveryArtifactManager::cleanupSentinels
  -> quickCheckSalvageNeeded
  -> salvageFromAllCorruptDbs, if useful
  -> removeCorruptDbFiles, if safe
  -> scheduleVacuumIfUseful, if idle and enough disk space

SearchBootstrapScheduler
  -> build text/hybrid engine
  -> publish searchEngineReady
  -> schedule vector/topology rebuilds

Concrete Code Changes

1. Remove auto-VACUUM from openDatabaseBlocking

Current critical-path behavior should change from:

state_.readiness.databaseReady = true;
maybeAutoVacuumDatabase(dbPath);
setDatabasePhase(dbphase::kReady);

to:

state_.readiness.databaseReady = true;
setDatabasePhase(dbphase::kReady);

Then schedule maybeAutoVacuumDatabase through a background maintenance component.

2. Decouple sentinel cleanup from salvage-needed

Current cleanup lives inside:

if (qc.needsSalvage) {
    ...
    removeCorruptDbFiles(...);
    remove yams.db.recovered-*;
}

Move it into an independent helper and call it during async maintenance regardless of salvage result.

3. Convert blocking salvage into async repair

If the active DB is open and the repository is usable, startup should not block on corrupt DB salvage. Instead:

  • mark metadata search available
  • schedule salvage
  • surface maintenance status
  • rebuild derived indexes after salvage completes

4. Defer initial search engine build

Keep metadata search available even when searchEngineReady == false. Schedule full search engine build after metadata-ready publication.

5. Improve status/log names

The watchdog currently says "still opening database" even when the worker is in VACUUM or other post-open work. Split phases so logs say what is actually happening:

  • opening database
  • checking database integrity
  • migrating database
  • initializing metadata repository
  • running database maintenance: vacuum
  • running database maintenance: salvage
  • building search engine

Tests

Add focused tests before large refactors.

Unit tests

  • RecoveryArtifactManager removes .recovered-* sentinels even when salvage is not needed.
  • RecoveryArtifactManager does not delete corrupt DBs unless cleanup policy allows it.
  • DatabaseStartup::openActiveDatabase does not call VACUUM.
  • DatabaseMaintenanceScheduler schedules VACUUM only after metadata readiness.

Integration tests

  • A daemon with a large DB crosses metadataRepoReady before any VACUUM starts.
  • SearchRequest succeeds in metadata mode while searchEngineReady == false.
  • Corrupt DB salvage runs after the daemon can answer status/search requests.
  • Recovery sentinels are eventually cleaned after startup, even when corrupt DB document counts are less than or equal to active DB document counts.

Manual checks

  • Start daemon with stale yams.db.recovered-* files and no useful corrupt DBs; verify cleanup logs.
  • Start daemon with a large DB eligible for VACUUM; verify yams search --type keyword ... works before maintenance completes.
  • Sample the daemon during startup and confirm no critical worker is blocked in SQLite VACUUM.

Risks and Mitigations

Risk: serving from an incomplete DB after quarantine

Mitigation:

  • clearly report degraded/maintenance status
  • schedule orphan repair and salvage immediately
  • rebuild derived indexes after salvage/repair

Mitigation:

  • route through ResourceGovernor
  • use low-priority executor or maintenance lane
  • avoid VACUUM unless idle and disk space is sufficient

Risk: corrupt DB cleanup deletes recoverable data

Mitigation:

  • keep removal policy conservative
  • separate sentinel cleanup from corrupt DB deletion
  • only delete corrupt DBs after successful salvage or when quick-check proves active DB has equal or greater document coverage

Risk: status semantics become confusing

Mitigation:

  • expose capability-specific readiness
  • reserve ready for full configured capabilities
  • use metadata_ready / degraded for useful partial availability

Migration Plan

  1. Add tests for current failure modes.
  2. Move VACUUM out of openDatabaseBlocking into a background scheduler.
  3. Extract sentinel cleanup helper and run it asynchronously regardless of salvage-needed.
  4. Extract DB open/migrate logic into DatabaseStartup without behavior changes.
  5. Extract salvage/cleanup into DatabaseMaintenanceScheduler.
  6. Defer initial search engine build behind metadata-ready publication.
  7. Split status/log phases and update CLI/status rendering if needed.
  8. Remove obsolete inline startup branches from ServiceManager.

Non-Goals

  • Do not delete corrupt DBs aggressively without salvage/coverage checks.
  • Do not make vector search a startup requirement.
  • Do not add new env knobs for this behavior; use typed config if tuning is needed.
  • Do not block metadata search on FTS/vector/topology rebuilds.

Expected Outcome

  • Faster daemon availability for metadata and keyword search.
  • Recovery sentinels are cleaned eventually and independently of salvage-needed logic.
  • Large DB VACUUM cannot make the daemon look stuck in startup.
  • ServiceManager becomes a coordinator rather than a monolithic startup/repair/search maintenance implementation.