indexcache.py¶
clew/indexcache.py
Sidecar index cache store making rebuilds incremental.
_reclaim_free_pages
None clew.indexcache.IndexCache._reclaim_free_pages(self)
VACUUM the cache when more than VACUUM_FREE_RATIO of its pages are free.
Source · 34 lines
def _reclaim_free_pages(self) -> None:
"""ON THE SUCCESS PATH ONLY, under the build lock that already serialises builds of one
target. `flush` never vacuums: an aborted build that paid for a whole-file rewrite would
pay it again on every retry. The threshold keeps an ordinary warm build from rewriting a
multi-GB file to recover a few pages.
A failure is logged and swallowed: the cache is already committed and correct, and a
file that stays large is a disk cost, not a wrong answer.
@brief Reclaim free pages after a successful build.
@version 1
"""
pages = self.conn.execute("PRAGMA page_count").fetchone()[0]
free = self.conn.execute("PRAGMA freelist_count").fetchone()[0]
if not pages or free / pages <= VACUUM_FREE_RATIO:
return
try:
self.conn.execute("VACUUM")
except sqlite3.Error as exc:
logger.warning(
"index cache: VACUUM of %s failed (%s); %d of %d pages stay free",
self.cache_path,
exc,
free,
pages,
)
return
logger.info(
"index cache: vacuumed %s — %d of %d pages were free",
self.cache_path.name,
free,
pages,
)
Activity · 10 steps
Requirements
close
None clew.indexcache.IndexCache.close(self)
Close the sidecar connection without committing.
Source · 4 lines
def close(self) -> None:
self.conn.close()
Activity · 1 steps
Requirements
commit
None clew.indexcache.IndexCache.commit(self)
Version 3: a mostly-free cache is VACUUMed after the commit ( _reclaim_free_pages ).
Called by _align_doxygen_cache, _invalidate_on_build_version, flush, link
Calls _reclaim_free_pages
Source · 30 lines
def commit(self) -> None:
"""Replace `source_files` with this run's scan — rows for files that
disappeared are dropped, so a removed file stops hitting the cache.
THE SUCCESS CLAIM LIVES HERE AND ONLY HERE. `flush` persists payload rows during the
build; this is what additionally asserts the tree was indexed, so it must stay gated on
the atomic swap. Moving the `source_files` write into `flush` would let an aborted build
claim a tree it never finished — the failure this split exists to keep impossible.
@brief Flush the cache to disk.
@version 2
"""
self.conn.execute("DELETE FROM source_files")
self.conn.executemany(
"INSERT OR REPLACE INTO source_files(path, size_bytes, mtime_ns, content_sha) "
"VALUES (?, ?, ?, ?)",
[
(rel, ident.size_bytes, ident.mtime_ns, ident.content_sha)
for rel, ident in self._current.items()
],
)
self.conn.commit()
logger.info(
"index cache: %d per-file hits, %d misses (%s)",
self.hits,
self.misses,
self.cache_path.name,
)
self._reclaim_free_pages()
Activity · 5 steps
Requirements
config_sha
str clew.indexcache.IndexCache.config_sha(self, str doxyfile_content, list[str] extra)
Identify the build CONFIGURATION, independent of the file set.
Source · 19 lines
def config_sha(self, doxyfile_content: str, extra: list[str]) -> str:
"""WHAT THE INCREMENTAL SPLICE MAY SAFELY SPLICE INTO. `tree_sha` changes on any file
edit, which is exactly when a splice is wanted, so it cannot be the key for "is the
previous output compatible with this build". This one changes only when the
CONFIGURATION moves — Doxyfile bytes, forced flags, declared scope, PREDEFINED.
THIS EXISTS BECAUSE OMITTING IT RE-SHIPPED #399. The first version of `doxygen_any`
served the newest digest-verified output regardless of the key that produced it, which
is precisely the aliasing `doxygen_get` was hardened against: withdrawing an
`index_scope` statement served the NARROWER earlier output, so a widened scope got the
file inventory back while its functions stayed missing. An existing integration test
caught it at commit time, not this module's own tests.
@brief Compute the configuration hash.
@return Hex digest.
@version 1
"""
return self._config_digest(doxyfile_content, extra).hexdigest()
Activity · 1 steps
Requirements
doxygen_any
Path | None clew.indexcache.IndexCache.doxygen_any(self, str config_sha)
Serve the newest verified doxygen output built under THIS configuration.
Source · 30 lines
def doxygen_any(self, config_sha: str) -> Path | None:
"""The newest cached doxygen output that still holds the bytes it was recorded with,
WHATEVER key produced it. `doxygen_get` answers "is this exact configuration's output
still here", which is the right question for skipping the stage entirely. The
incremental splice asks a different one: "is there a previous whole-tree output I can
splice INTO", and the answer is useful even when the tree hash has moved — that is
precisely the case where a splice is wanted.
Verified by digest for the same reason `doxygen_get` is (#399): every key in this
table names the SAME `db_path`, so existence alone proves nothing about whose output
the file currently holds. A row whose digest no longer matches is skipped rather than
served, because splicing into an unrecognised database would silently mix two
configurations' rows and report success.
@brief Serve the newest verified doxygen output, any key.
@return Path to a usable previous output, or None.
@version 1
"""
if not self.read_enabled:
return None
for raw_path, recorded in self.conn.execute(
"SELECT db_path, output_sha FROM doxygen_cache WHERE config_sha = ? AND config_sha != '' "
"ORDER BY created_at DESC",
(config_sha,),
):
path = Path(str(raw_path))
if path.exists() and hash_file(path) == str(recorded):
return path
return None
Activity · 7 steps
Requirements
doxygen_get
Path | None clew.indexcache.IndexCache.doxygen_get(self, str tree_sha)
Look up a previously generated doxygen SQLite output.
Source · 52 lines
def doxygen_get(self, tree_sha: str) -> Path | None:
"""VERIFIED BY CONTENT, NOT BY EXISTENCE (#399). Every key in this table names the
SAME `db_path`: doxygen's output directory is derived from `--index-cache`/`--output`
alone (`cli._doxygen_out_dir`) and its filename is fixed
(`doxygen.doxygen_db_path`), so N configurations of one repo produce N rows all
pointing at one file that each build OVERWRITES. The old hit condition was "a row
exists AND the path exists", which is true of every key the moment ANY of them has
run — so a key was served whatever bytes happened to be there last.
Measured both directions, which is what pins it as aliasing rather than staleness:
withdrawing a `predefined` statement served the WIDER earlier output (the gated
function stayed indexed after the macro was withdrawn), and withdrawing an
`index_scope` statement served the NARROWER earlier output (`extra/` stayed missing
after the scope was widened). Not "the newer output wins" — "whichever output was
written last wins, whatever its key said".
Comparing the recorded digest against the file's current one makes the hit
conditional on the file BEING this key's output, whichever process last wrote it.
MEASURED COST, one sha256 of the doxygen database per build: on this repo's own index
that database is 6.9 MB and hashes in 6-10 ms, which is 0.33% of a 3.0 s warm build
and is dwarfed by the tree scan beside it — the same build already hashes every
source file, and the doxygen output is one file. A cold build it saves is 10.4 s here
and tens of seconds on a large C++ target (#363). The skip is kept; it is now only
taken when it is right.
@brief Serve a cached doxygen output only under the key that produced it.
@version 1
"""
if not self.read_enabled:
return None
row = self.conn.execute(
"SELECT db_path, output_sha FROM doxygen_cache WHERE tree_sha = ?",
(tree_sha,),
).fetchone()
if row is None:
return None
path, recorded = Path(row[0]), str(row[1])
if not path.exists():
return None
current = hash_file(path)
if current != recorded:
logger.info(
"index cache: %s no longer holds this configuration's doxygen output "
"(recorded %s, found %s) — another build overwrote it, so re-running doxygen",
path,
recorded[:12],
current[:12] or "unreadable",
)
return None
return path
Activity · 13 steps
Requirements
doxygen_put
None clew.indexcache.IndexCache.doxygen_put(self, str tree_sha, Path db_path, str config_sha="")
Record which doxygen SQLite output a tree hash produced.
Source · 26 lines
def doxygen_put(self, tree_sha: str, db_path: Path, config_sha: str = "") -> None:
"""Records the output's DIGEST alongside its path, which is what lets `doxygen_get`
tell this key's output from the next key's overwrite of the same file (#399).
A file that will not hash is NOT recorded at all. `hash_file` returns "" for an
unreadable file, so storing that would make a later unreadable read compare
`"" == ""` and HIT — the empty string as a wildcard, which is precisely the false
hit this column exists to close.
@brief Store a doxygen output path with the digest of what it held.
@version 1
"""
output_sha = hash_file(db_path)
if not output_sha:
logger.warning(
"index cache: could not hash the doxygen output at %s — not caching it, so "
"the next build re-runs doxygen rather than trusting an unverifiable file",
db_path,
)
return
self.conn.execute(
"INSERT OR REPLACE INTO doxygen_cache(tree_sha, db_path, output_sha, config_sha, "
"created_at) VALUES (?, ?, ?, ?, ?)",
(tree_sha, str(db_path), output_sha, config_sha, int(time.time())),
)
Activity · 5 steps
Requirements
extract_get
Any | None clew.indexcache.IndexCache.extract_get(self, str content_sha, str stage, int stage_version, str extra_key)
Fetch a cached per-file extraction payload.
Source · 16 lines
def extract_get(
self,
content_sha: str,
stage: str,
stage_version: int,
extra_key: str,
) -> Any | None:
if not self._readable((content_sha, stage, stage_version, extra_key)):
return None
row = self.conn.execute(
"SELECT payload FROM extract_cache WHERE content_sha = ? AND stage = ? "
"AND stage_version = ? AND extra_key = ?",
(content_sha, stage, stage_version, extra_key),
).fetchone()
return None if row is None else json.loads(row[0])
Activity · 4 steps
Requirements
extract_has
bool clew.indexcache.IndexCache.extract_has(self, str content_sha, str stage, int stage_version, str extra_key)
Whether a per-file extraction payload is present and readable.
Source · 23 lines
def extract_has(
self,
content_sha: str,
stage: str,
stage_version: int,
extra_key: str,
) -> bool:
"""Existence WITHOUT decoding the payload, for the shared parse pass —
which asks ten questions per file and wants none of the answers, only
which stages still need computing.
@brief Cheap presence check for one stage payload.
@version 1
"""
if not self._readable((content_sha, stage, stage_version, extra_key)):
return False
row = self.conn.execute(
"SELECT 1 FROM extract_cache WHERE content_sha = ? AND stage = ? "
"AND stage_version = ? AND extra_key = ?",
(content_sha, stage, stage_version, extra_key),
).fetchone()
return row is not None
Activity · 4 steps
Requirements
extract_put
None clew.indexcache.IndexCache.extract_put(self, str content_sha, str stage, int stage_version, str extra_key, Any payload)
Store a per-file extraction payload under its content identity.
Source · 21 lines
def extract_put(
self,
content_sha: str,
stage: str,
stage_version: int,
extra_key: str,
payload: Any,
) -> None:
self._fresh.add((content_sha, stage, stage_version, extra_key))
self.conn.execute(
"INSERT OR REPLACE INTO extract_cache"
"(content_sha, stage, stage_version, extra_key, payload) VALUES (?, ?, ?, ?, ?)",
(
content_sha,
stage,
stage_version,
extra_key,
json.dumps(payload, separators=(",", ":")),
),
)
Activity · 2 steps
Requirements
flush
None clew.indexcache.IndexCache.flush(self)
Durably persist payload rows without asserting the build succeeded.
Source · 38 lines
def flush(self) -> None:
"""THE HALF OF `commit` THAT AN ABORTED BUILD IS STILL ENTITLED TO, and the reason a
large target can now get warm at all.
Payload rows and the `source_files` claim used to share one transaction that was
committed only after the atomic swap, so a killed build discarded every parsed payload.
Measured in the field: a 103 MB sidecar whose mtime did not move across six build
attempts, several running twenty minutes. Attempt N+1 cost exactly what attempt 1 cost,
which is a trap a target cannot climb out of once its corpus outgrows one sitting.
THE TWO CLAIMS ARE NOT THE SAME CLAIM, which is what makes this safe:
* a `(file, stage)` payload is keyed by the file's `content_sha`, so it is TRUE
whether or not the build that computed it finished;
* `source_files` asserts "this tree was successfully indexed" — which an aborted
build has NOT earned, and which is written ONLY by `commit`.
WHAT ELSE RIDES ALONG, because a bare `commit()` flushes the whole connection and a
reviewer will ask. Each is safe for its own reason, not by a blanket argument:
* `doxygen_cache` — `doxygen_put` records output that EXISTS on disk, and
`doxygen_any` re-verifies before serving it, so a row describing output a later
failure removed is rejected rather than trusted.
* `splice_generation` — `record_splice` runs immediately after the doxygen pass it
describes, so a persisted value describes a pass that genuinely ran. Persisting it
early can only over-state drift by one, which biases the NEXT build toward a full
run: the fail-safe direction.
Called from `harvest.run_shared_parse` (periodically, so a kill part-way through a long
parse still banks most of it) and at the end of `harvest.run_harvest`. Deliberately NOT
scattered across `_build_stages`: one call per mechanism means a stage added later
inherits the durability instead of silently missing it.
@brief Commit payload rows, leaving the success claim ungranted.
@version 1
"""
self.conn.commit()
Activity · 1 steps
Requirements
memoized
Any clew.indexcache.memoized(IndexCache|None cache, str rel, Path abs_path, str stage, int version, str extra_key, Any compute)
A per-file result, from the cache when this content was seen before, else computed and stored.
Called by _collect_file_docs, _file_yields, _ingest_one_doc_file, _refresh_file_doc, _refresh_generated, _refresh_mentions, _scan, file_code_texts, file_scope_text, kerneldoc_of, license_of, record_self_declared
Calls none
Source · 35 lines
def memoized(
cache: IndexCache | None,
rel: str,
abs_path: Path,
stage: str,
version: int,
extra_key: str,
compute: Any,
) -> Any:
"""1.3.4, Track 2. The whole-tree text stages (file docs, requirement mentions, code text,
generated-file banners) re-scanned every indexed file on every build; a refresh after a
one-file edit paid for all of them. Keyed like every other extract payload — content sha,
stage, stage version, extra key — so an unchanged file is served and an edited one is not.
WRAPPED IN A ONE-KEY OBJECT, because `extract_get` answers None for a miss and a stage's
legitimate result is often None ("this file has no docstring"). Storing the bare value would
make every such file a permanent miss — correct, and never faster.
An unreadable file (no sha) is computed, not cached: there is no identity to key it by.
@brief Memoize one file's stage result on its content.
@return The result.
@version 1
"""
sha = cache.sha_for(rel, abs_path) if cache is not None else None
if cache is None or sha is None:
return compute()
hit = cache.extract_get(sha, stage, version, extra_key)
if hit is not None:
cache.record(True)
return hit["v"]
value = compute()
cache.extract_put(sha, stage, version, extra_key, {"v": value})
cache.record(False)
return value1 more lines, not shown
Activity · 11 steps
Requirements
previous_sha
str | None clew.indexcache.IndexCache.previous_sha(self, str rel)
The content sha the last committed build recorded for one path.
Source · 11 lines
def previous_sha(self, rel: str) -> str | None:
"""THE FAST TIER'S BASELINE (1.3.5): what the index describes, as distinct from what the
working tree now holds (`sha_for`).
@brief Read the recorded sha.
@return Sha or None.
@version 1
"""
known = self._previous.get(rel)
return None if known is None else known.content_sha
Activity · 2 steps
Requirements
record
None clew.indexcache.IndexCache.record(self, bool hit)
Count one cache hit or miss for the end-of-build summary.
Source · 6 lines
def record(self, hit: bool) -> None:
if hit:
self.hits += 1
else:
self.misses += 1
Activity · 4 steps
Requirements
record_pair
None clew.indexcache.IndexCache.record_pair(self, str content_sha, str stage, int stage_version, str extra_key, bool hit)
Count one (file, stage) payload once per build, however often it is served.
Source · 24 lines
def record_pair(
self,
content_sha: str,
stage: str,
stage_version: int,
extra_key: str,
hit: bool,
) -> None:
"""IDEMPOTENT, and that is the whole point. Since gh#358 a payload is
normally COMPUTED by the shared parse pass and then READ BACK by the stage
that needs it, so the naive count would report every cold build as both
fully missed and fully hit — and `misses` is published as the index's
`payloads_recomputed`, which `status` shows to an agent deciding whether to
trust the answer. First outcome for a pair wins; the pair is the unit.
@brief Record one per-file-per-stage outcome, at most once.
@version 2
"""
key = (content_sha, stage, stage_version, extra_key)
if key in self._accounted:
return
self._accounted.add(key)
self.record(hit)
Activity · 5 steps
Requirements
record_splice
None clew.indexcache.IndexCache.record_splice(self, bool reset=False)
Advance or clear the splice generation counter.
Source · 11 lines
def record_splice(self, reset: bool = False) -> None:
"""@brief Increment the splice generation, or zero it after a full build.
@version 1
"""
value = 0 if reset else self.splice_generation() + 1
self.conn.execute(
"INSERT INTO cache_meta(key, value) VALUES('splice_generation', ?) "
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
(str(value),),
)
Activity · 2 steps
Requirements
scan
ScanSummary clew.indexcache.IndexCache.scan(self, dict[str, Path] files)
Hash a whole tree and classify it against the previous scan.
Source · 28 lines
def scan(self, files: dict[str, Path]) -> ScanSummary:
"""Populate this run's identity map from `enumerate_tree` output and
bucket the result. Content sha decides; mtime+size only decide whether
re-hashing is needed.
@brief Scan + classify the indexed tree.
@version 2
"""
unchanged: list[str] = []
modified: list[str] = []
added: list[str] = []
for rel, abs_path in files.items():
identity = self._identity(rel, abs_path)
if identity is None:
continue
self._current[rel] = identity
prev = self._previous.get(rel)
if prev is None:
added.append(rel)
elif prev.content_sha == identity.content_sha:
unchanged.append(rel)
else:
modified.append(rel)
removed = sorted(set(self._previous) - set(files))
summary = ScanSummary(sorted(unchanged), sorted(modified), sorted(added), removed)
logger.info("index cache: %s", summary.describe())
return summary
Activity · 19 steps
Requirements
sha_for
str | None clew.indexcache.IndexCache.sha_for(self, str rel, Path abs_path)
Content sha for one indexed path, computing it on demand.
Source · 17 lines
def sha_for(self, rel: str, abs_path: Path) -> str | None:
"""Serve the sha recorded by `scan`, or stat+hash a path the scan never
saw (doxygen can index a file outside the enumerated INPUT roots — e.g.
a followed include) and remember it for the next run.
@brief Look up (or compute) one file's content sha.
@version 1
"""
known = self._current.get(rel)
if known is not None:
return known.content_sha
identity = self._identity(rel, abs_path)
if identity is None:
return None
self._current[rel] = identity
return identity.content_sha
Activity · 8 steps
Requirements
splice_generation
int clew.indexcache.IndexCache.splice_generation(self)
How many incremental splices have run since the last whole-tree doxygen build.
Source · 22 lines
def splice_generation(self) -> int:
"""MEASURED DRIFT IS WHY THIS EXISTS, not caution in the abstract. A spliced database
is not bit-identical to a full rebuild: on this repository a modification-only refresh
carried ONE call edge a full rebuild does not emit, out of 5168, with nothing missing.
The cause is doxygen resolving names against the files it can SEE, so a subset can
attribute an intra-file call to a different memberdef row than the whole tree does.
One stale edge in five thousand is a fair price for a 3.2x cheaper refresh. A hundred
splices' worth of accumulated stale edges is not, and nothing about a splice bounds
the accumulation on its own. Counting generations turns unbounded drift into a known
ceiling: the caller refuses to splice past the limit and pays for one full rebuild,
which resets the count.
@brief Read the splice generation counter.
@return Generations since the last full build.
@version 1
"""
row = self.conn.execute(
"SELECT value FROM cache_meta WHERE key = 'splice_generation'"
).fetchone()
return int(row[0]) if row and str(row[0]).isdigit() else 0
Activity · 2 steps
Requirements
tree_sha
str clew.indexcache.IndexCache.tree_sha(self, str doxyfile_content, list[str] extra)
Hash of everything that determines the doxygen run's output.
Source · 13 lines
def tree_sha(self, doxyfile_content: str, extra: list[str]) -> str:
"""Fold the sorted (path, content_sha) set together with the exact
Doxyfile content the pipeline pipes to doxygen (which already carries
the forced flags and any --extra-input/--extra-exclude lines).
@brief Compute the doxygen-cache tree hash.
@version 5
"""
digest = self._config_digest(doxyfile_content, extra)
for rel in sorted(self._current):
digest.update(f"\n{rel}\x00{self._current[rel].content_sha}".encode())
return digest.hexdigest()