yams/tests/unit/daemon/db_salvage_catch2_test.cpp
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

405 lines
14 KiB
C++

#include <catch2/catch_test_macros.hpp>
#include <yams/daemon/components/db_salvage.h>
#include <yams/metadata/database.h>
#include <sqlite3.h>
#include <chrono>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <sstream>
namespace fs = std::filesystem;
namespace {
fs::path makeScratchDir(const std::string& prefix) {
auto base = fs::temp_directory_path() /
(prefix + "_" +
std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
fs::create_directories(base);
return base;
}
const char* kDocumentsTableDdl = R"(
CREATE TABLE documents (
id INTEGER PRIMARY KEY AUTOINCREMENT,
file_path TEXT NOT NULL,
file_name TEXT NOT NULL,
file_extension TEXT,
file_size INTEGER NOT NULL,
sha256_hash TEXT UNIQUE NOT NULL,
mime_type TEXT,
created_time INTEGER,
modified_time INTEGER,
indexed_time INTEGER,
content_extracted BOOLEAN DEFAULT 0,
extraction_status TEXT DEFAULT 'pending',
extraction_error TEXT,
path_prefix TEXT,
reverse_path TEXT,
path_hash TEXT,
parent_hash TEXT,
path_depth INTEGER DEFAULT 0,
repair_status TEXT DEFAULT 'pending',
repair_attempted_at INTEGER,
repair_attempts INTEGER DEFAULT 0
)
)";
const char* kDocumentsInsertSql = R"(
INSERT INTO documents (
file_path, file_name, file_extension, file_size, sha256_hash,
mime_type, created_time, modified_time, indexed_time, content_extracted,
extraction_status, extraction_error, path_prefix, reverse_path, path_hash,
parent_hash, path_depth, repair_status, repair_attempted_at, repair_attempts
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
)";
void createAndPopulateDb(const fs::path& dbPath, int docCount,
const std::vector<std::string>& hashes) {
yams::metadata::Database db;
auto open = db.open(dbPath.string(), yams::metadata::ConnectionMode::Create);
REQUIRE(open);
REQUIRE(db.execute(kDocumentsTableDdl));
for (int i = 0; i < docCount; ++i) {
const auto& hash = hashes[static_cast<size_t>(i)];
auto stmtResult = db.prepare(kDocumentsInsertSql);
REQUIRE(stmtResult);
auto stmt = std::move(stmtResult).value();
std::string filePath = "/test/file_" + std::to_string(i) + ".txt";
std::string fileName = "file_" + std::to_string(i) + ".txt";
std::string ext = "txt";
int64_t fileSize = static_cast<int64_t>(1024) * (i + 1);
REQUIRE(stmt.bind(1, filePath));
REQUIRE(stmt.bind(2, fileName));
REQUIRE(stmt.bind(3, ext));
REQUIRE(stmt.bind(4, fileSize));
REQUIRE(stmt.bind(5, hash));
REQUIRE(stmt.bind(6, "text/plain"));
REQUIRE(stmt.bind(7, static_cast<int64_t>(1000 + i)));
REQUIRE(stmt.bind(8, static_cast<int64_t>(2000 + i)));
REQUIRE(stmt.bind(9, static_cast<int64_t>(3000 + i)));
REQUIRE(stmt.bind(10, 0));
REQUIRE(stmt.bind(11, std::string("pending")));
REQUIRE(stmt.bind(12, std::string("")));
REQUIRE(stmt.bind(13, std::string("/test")));
REQUIRE(stmt.bind(14, std::string("txt.0_elif/tset/")));
REQUIRE(stmt.bind(15, std::string("path_hash_") + std::to_string(i)));
REQUIRE(stmt.bind(16, std::string("parent_hash_") + std::to_string(i)));
REQUIRE(stmt.bind(17, static_cast<int64_t>(1)));
REQUIRE(stmt.bind(18, std::string("pending")));
REQUIRE(stmt.bind(19, static_cast<int64_t>(0)));
REQUIRE(stmt.bind(20, static_cast<int64_t>(0)));
auto execResult = stmt.execute();
REQUIRE(execResult);
}
db.close();
}
std::string getJournalMode(const fs::path& dbPath) {
sqlite3* raw = nullptr;
int rc = sqlite3_open_v2(dbPath.string().c_str(), &raw, SQLITE_OPEN_READWRITE, nullptr);
REQUIRE((rc == SQLITE_OK));
sqlite3_stmt* stmt = nullptr;
rc = sqlite3_prepare_v2(raw, "PRAGMA journal_mode", -1, &stmt, nullptr);
REQUIRE((rc == SQLITE_OK));
std::string mode;
if (sqlite3_step(stmt) == SQLITE_ROW) {
const auto* text = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
if (text != nullptr) {
mode = text;
}
}
sqlite3_finalize(stmt);
sqlite3_close(raw);
return mode;
}
int countDocuments(const fs::path& dbPath) {
sqlite3* raw = nullptr;
int rc = sqlite3_open_v2(dbPath.string().c_str(), &raw, SQLITE_OPEN_READONLY, nullptr);
REQUIRE((rc == SQLITE_OK));
sqlite3_stmt* stmt = nullptr;
rc = sqlite3_prepare_v2(raw, "SELECT COUNT(*) FROM documents", -1, &stmt, nullptr);
REQUIRE((rc == SQLITE_OK));
int count = 0;
if (sqlite3_step(stmt) == SQLITE_ROW) {
count = sqlite3_column_int(stmt, 0);
}
sqlite3_finalize(stmt);
sqlite3_close(raw);
return count;
}
std::vector<std::string> makeTestHashes(int count) {
std::vector<std::string> hashes;
hashes.reserve(static_cast<size_t>(count));
for (int i = 0; i < count; ++i) {
std::ostringstream os;
os << std::hex << std::setfill('0') << std::setw(64) << (1000000 + i);
hashes.push_back(os.str());
}
return hashes;
}
} // namespace
TEST_CASE("salvageFromCorruptDb returns empty result when corrupt DB is missing",
"[unit][daemon][db_salvage]") {
auto dir = makeScratchDir("yams_salvage_missing");
auto freshPath = dir / "fresh.db";
{
yams::metadata::Database db;
REQUIRE(db.open(freshPath.string(), yams::metadata::ConnectionMode::Create));
REQUIRE(db.execute(kDocumentsTableDdl));
db.close();
}
auto corruptPath = dir / "nonexistent.db";
auto res = yams::daemon::salvageFromCorruptDb(corruptPath, freshPath);
REQUIRE(res);
REQUIRE((res.value().documentsSalvaged == 0));
REQUIRE_FALSE(res.value().diagnostics.empty());
std::error_code ec;
fs::remove_all(dir, ec);
}
TEST_CASE("salvageFromCorruptDb copies documents via ATTACH", "[unit][daemon][db_salvage]") {
auto dir = makeScratchDir("yams_salvage_attach");
auto corruptPath = dir / "corrupt.db";
auto freshPath = dir / "fresh.db";
auto hashes = makeTestHashes(5);
createAndPopulateDb(corruptPath, 5, hashes);
{
yams::metadata::Database db;
REQUIRE(db.open(freshPath.string(), yams::metadata::ConnectionMode::Create));
REQUIRE(db.execute(kDocumentsTableDdl));
db.close();
}
auto res = yams::daemon::salvageFromCorruptDb(corruptPath, freshPath);
REQUIRE(res);
REQUIRE((res.value().documentsSalvaged == 5));
REQUIRE((res.value().documentsFailed == 0));
REQUIRE((countDocuments(freshPath) == 5));
std::error_code ec;
fs::remove_all(dir, ec);
}
TEST_CASE("salvageFromCorruptDb preserves fresh DB journaling mode", "[unit][daemon][db_salvage]") {
auto dir = makeScratchDir("yams_salvage_journal");
auto corruptPath = dir / "corrupt.db";
auto freshPath = dir / "fresh.db";
auto hashes = makeTestHashes(2);
createAndPopulateDb(corruptPath, 2, hashes);
{
yams::metadata::Database db;
REQUIRE(db.open(freshPath.string(), yams::metadata::ConnectionMode::Create));
REQUIRE(db.execute(kDocumentsTableDdl));
REQUIRE(db.execute("PRAGMA journal_mode = WAL"));
db.close();
}
REQUIRE((getJournalMode(freshPath) == "wal"));
auto res = yams::daemon::salvageFromCorruptDb(corruptPath, freshPath);
REQUIRE(res);
CHECK((res.value().documentsSalvaged == 2));
CHECK((getJournalMode(freshPath) == "wal"));
std::error_code ec;
fs::remove_all(dir, ec);
}
TEST_CASE("salvageFromCorruptDb handles large document counts", "[unit][daemon][db_salvage]") {
auto dir = makeScratchDir("yams_salvage_large");
auto corruptPath = dir / "corrupt.db";
auto freshPath = dir / "fresh.db";
auto hashes = makeTestHashes(100);
createAndPopulateDb(corruptPath, 100, hashes);
{
yams::metadata::Database db;
REQUIRE(db.open(freshPath.string(), yams::metadata::ConnectionMode::Create));
REQUIRE(db.execute(kDocumentsTableDdl));
db.close();
}
auto res = yams::daemon::salvageFromCorruptDb(corruptPath, freshPath);
REQUIRE(res);
REQUIRE((res.value().documentsSalvaged == 100));
REQUIRE((res.value().documentsFailed == 0));
REQUIRE((countDocuments(freshPath) == 100));
std::error_code ec;
fs::remove_all(dir, ec);
}
TEST_CASE("salvageFromCorruptDb skips duplicate hashes", "[unit][daemon][db_salvage]") {
auto dir = makeScratchDir("yams_salvage_dupes");
auto corruptPath = dir / "corrupt.db";
auto freshPath = dir / "fresh.db";
auto hashes = makeTestHashes(3);
createAndPopulateDb(corruptPath, 3, hashes);
// Pre-populate fresh DB with one of the same hashes
{
yams::metadata::Database db;
REQUIRE(db.open(freshPath.string(), yams::metadata::ConnectionMode::Create));
REQUIRE(db.execute(kDocumentsTableDdl));
auto stmtResult = db.prepare(kDocumentsInsertSql);
REQUIRE(stmtResult);
auto stmt = std::move(stmtResult).value();
REQUIRE(stmt.bind(1, std::string("/test/dup.txt")));
REQUIRE(stmt.bind(2, std::string("dup.txt")));
REQUIRE(stmt.bind(3, std::string("txt")));
REQUIRE(stmt.bind(4, static_cast<int64_t>(100)));
REQUIRE(stmt.bind(5, hashes[0]));
REQUIRE(stmt.bind(6, std::string("text/plain")));
REQUIRE(stmt.bind(7, static_cast<int64_t>(1)));
REQUIRE(stmt.bind(8, static_cast<int64_t>(2)));
REQUIRE(stmt.bind(9, static_cast<int64_t>(3)));
REQUIRE(stmt.bind(10, 0));
REQUIRE(stmt.bind(11, std::string("pending")));
REQUIRE(stmt.bind(12, std::string("")));
REQUIRE(stmt.bind(13, std::string("/")));
REQUIRE(stmt.bind(14, std::string("")));
REQUIRE(stmt.bind(15, std::string("")));
REQUIRE(stmt.bind(16, std::string("")));
REQUIRE(stmt.bind(17, static_cast<int64_t>(0)));
REQUIRE(stmt.bind(18, std::string("pending")));
REQUIRE(stmt.bind(19, static_cast<int64_t>(0)));
REQUIRE(stmt.bind(20, static_cast<int64_t>(0)));
REQUIRE(stmt.execute());
db.close();
}
// The duplicate hash should be skipped (INSERT OR IGNORE)
// So 2 new docs + 1 existing = 3 total
auto res = yams::daemon::salvageFromCorruptDb(corruptPath, freshPath);
REQUIRE(res);
REQUIRE((countDocuments(freshPath) == 3));
std::error_code ec;
fs::remove_all(dir, ec);
}
TEST_CASE("salvageFromCorruptDb fails cleanly when fresh DB is missing",
"[unit][daemon][db_salvage]") {
auto dir = makeScratchDir("yams_salvage_fresh_missing");
auto corruptPath = dir / "corrupt.db";
auto freshPath = dir / "fresh.db";
auto hashes = makeTestHashes(1);
createAndPopulateDb(corruptPath, 1, hashes);
auto res = yams::daemon::salvageFromCorruptDb(corruptPath, freshPath);
REQUIRE_FALSE(res);
std::error_code ec;
fs::remove_all(dir, ec);
}
TEST_CASE("recovery sentinel cleanup is independent of salvage need",
"[unit][daemon][db_salvage][startup_refactor]") {
auto dir = makeScratchDir("yams_recovery_sentinel_cleanup");
auto dbPath = dir / "yams.db";
auto hashes = makeTestHashes(2);
createAndPopulateDb(dbPath, 2, hashes);
const auto sentinelA = dir / "yams.db.recovered-20260101T000000Z";
const auto sentinelB = dir / "yams.db.recovered-20260101T000001Z";
const auto unrelated = dir / "other.db.recovered-20260101T000000Z";
{
std::ofstream(sentinelA) << "recovered";
std::ofstream(sentinelB) << "recovered";
std::ofstream(unrelated) << "keep";
}
const auto qc = yams::daemon::quickCheckSalvageNeeded(dir, dbPath);
REQUIRE_FALSE(qc.needsSalvage);
REQUIRE((qc.corruptDbCount == 0));
const auto cleanup = yams::daemon::removeRecoverySentinels(dbPath);
REQUIRE(cleanup.errors.empty());
REQUIRE((cleanup.removed.size() == 2));
REQUIRE_FALSE(fs::exists(sentinelA));
REQUIRE_FALSE(fs::exists(sentinelB));
REQUIRE(fs::exists(unrelated));
std::error_code ec;
fs::remove_all(dir, ec);
}
TEST_CASE("quick salvage check tracks unreadable corrupt DBs without requesting cleanup",
"[unit][daemon][db_salvage][startup_refactor]") {
auto dir = makeScratchDir("yams_salvage_unreadable_corrupt");
auto dbPath = dir / "yams.db";
auto hashes = makeTestHashes(1);
createAndPopulateDb(dbPath, 1, hashes);
const auto unreadableCorrupt = dir / "yams.db.corrupt-bad";
{
std::ofstream(unreadableCorrupt, std::ios::binary) << "not a sqlite database";
}
const auto qc = yams::daemon::quickCheckSalvageNeeded(dir, dbPath);
REQUIRE((qc.corruptDbCount == 1));
REQUIRE((qc.unreadableCorruptDbCount == 1));
REQUIRE_FALSE(qc.needsSalvage);
REQUIRE((qc.maxCorruptCount == 0));
REQUIRE(fs::exists(unreadableCorrupt));
std::error_code ec;
fs::remove_all(dir, ec);
}
TEST_CASE("corrupt DB cleanup removes readable artifacts but keeps unreadable evidence",
"[unit][daemon][db_salvage][startup_refactor]") {
auto dir = makeScratchDir("yams_corrupt_cleanup_safe");
auto readableCorrupt = dir / "yams.db.corrupt-readable";
auto unreadableCorrupt = dir / "yams.db.corrupt-unreadable";
auto readableWal = fs::path(readableCorrupt.string() + "-wal");
auto readableShm = fs::path(readableCorrupt.string() + "-shm");
auto hashes = makeTestHashes(1);
createAndPopulateDb(readableCorrupt, 1, hashes);
{
std::ofstream(readableWal) << "wal";
std::ofstream(readableShm) << "shm";
std::ofstream(unreadableCorrupt, std::ios::binary) << "not sqlite";
}
const auto cleanup = yams::daemon::removeCorruptDbFiles(dir);
REQUIRE(cleanup.errors.empty());
REQUIRE((cleanup.removed.size() == 1));
REQUIRE((cleanup.removed.front().filename() == readableCorrupt.filename()));
REQUIRE_FALSE(fs::exists(readableCorrupt));
REQUIRE_FALSE(fs::exists(readableWal));
REQUIRE_FALSE(fs::exists(readableShm));
REQUIRE(fs::exists(unreadableCorrupt));
std::error_code ec;
fs::remove_all(dir, ec);
}