mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-04 02:38:18 +00:00
feat(scan): an unwritable tree keeps a scan's learnings under the runs directory (item 5b)
The decision of the maintainer on the ninth session's menu, answer 9 (.kiro/handover.md,
untracked, 1340-1343 as it stood on 2026-11-27; the option as offered, 1451-1452):
> 9. The ledger in the image. Answer: "Decide the key now": a digest of the tree's files
> (the `fingerprint` of the `provenance` stage is no digest), one ledger per digest under
> the runs directory; a design note is shown to the maintainer before any code.
The design note (/tmp/opencode/s10_c10_design_note.md, 299 lines) was reviewed in five
rounds before it was shown, and shown to the maintainer whole on 2026-11-27 with its three
questions. The maintainer's answers came on 2026-11-28, through the question tool, each the
recommended option as offered: "Stand as written (Recommended)" on the note's rule of reading
and writing (its section 3.3), "With the runs, by last use (Recommended)" on how long a ledger
stays (section 3.5), and "Build it now (Recommended)". The dated note on task 3.1 of
.kiro/specs/contributor-scan/tasks.md (lines 459-502) carries the rule as approved.
The fault: the image mounts the target read-only, so the ledger a scan writes into the tree
(<target>/.openultrasast/calibration/false_positive_learnings.json) cannot be written there,
the scan records ledger_not_written, and the next scan in the image starts without the
learnings of the one before.
What changed
- src/openultrasast/tree_digest.py: tree_digest(target, runs_directory) (line 48), a sha256
over one entry per file in path order (the length of the path, a colon, the path, a tab,
the sha256 of the bytes), after a version line. Left out: links, the directories a scan
ignores (IGNORED_DIRS, so that the tree's ledger does not change its own key) and the runs
directory, whichever way it is reached (by device and inode). A file that cannot be read
and a directory that cannot be listed are named "unreadable"; a directory that can be
listed but not searched raises, as the scan's own reading of the tree does.
- src/openultrasast/digest_ledger.py: the ledger of a digest, calibration/<digest>.json under
the runs directory, in the JSON of the tree's ledger. read_digest_ledger (line 47) reads it
and marks it as used; settle_digest_ledger (line 65) applies the rule.
The tree took the write: the ledger is removed. The tree refused: the ledger is written
with its own entries and this scan's new ones, never one whose finding id the tree's
ledger has, only when that differs from its content, and removed when that would leave it
empty. No write: a ledger whose every entry the tree's ledger also has is removed. One that
could not be read (a file that is not a ledger, whatever its top level or its depth) is
taken for empty and goes, unless the tree refused and this scan wrote it. It is written
through a temporary file of the writer's own and a rename (line 112).
- src/openultrasast/cli.py: the stage tree_digest, before any stage reads the tree
(cli.py:603-605); _read_ledgers (cli.py:1085-1099), the tree's ledger and then the
digest's, the tree's entry winning by finding id; _persist_calibration_feedback
(cli.py:1101-1136), which writes the tree's ledger when its content would differ from what
it held, also when only the digest's entries are new to it; the manifest's ledger block
(cli.py:731-735); a notice when the digest's ledger could not be written or removed
(cli.py:755).
- src/openultrasast/run.py: prune_expired_ledgers (run.py:112), called by prune_scan_runs
(run.py:71-99). Under calibration/ of the same two locations as the runs, a ledger, or the
temporary file it was written through, last used OPENULTRASAST_RUNS_RETENTION_DAYS days
ago is removed; 0 keeps all. Files called something else, links and directories stay. A
removal that fails is said once and costs the scan nothing.
- src/openultrasast/reports.py: write_manifest takes ledger (reports.py:212, 254-255). The
ledger_not_written sentence names the digest's ledger when it holds the learnings
(reports.py:461-467, chosen at 479-483).
- README.md, docs/examples.md, docs/architecture.md and
.agents/skills/openultrasast-scan/SKILL.md say where the learnings of a read-only tree go,
and what removes them.
Two departures from recorded decisions, both put to the maintainer in the note and accepted
with it:
- The tree's ledger is written when a scan learns nothing new, because the digest's entries
are new to it. The decision of 2026-11-24 says it "is written only when a scan learns
something" (spec.json:68).
- A ledger of a digest is removed when it expires, and its time is changed when a scan reads
it. The decision of 2026-11-24 says "the scan's own run and anything not named like a run
are never touched" (spec.json:73), and dates a run by its id, where a ledger is dated by
its use.
Measured
- The built function gives the note's prototype's digest for the four-file subject
(915506a8...) and for libpng's copy (1dcd664f...): s10_c10_port.out.
- In the image, on the final code. A probe image of openultrasast:dev (3f959b31f2f2) with
the tree's package copied over it, built at 09:06:36Z and holding the tree's 297 .py files
(s10_c10_image_probe/03_probe_sources.out, s10_c10_sources_still_equal4.out). Standard
mode, no key, network none. The four C files of contrib/examples of libpng and their
README, copied fresh and mounted read-only at /target; a scratch runs directory mounted at
/reports with the wrapper's OPENULTRASAST_RUNS_DIR=/reports (s10_c10_image_probe.sh,
stamps 09:06:36Z to 09:09:14Z, 2026-11-28).
- The first scan learns four entries and keeps them in /reports/calibration/<digest>.json:
calibrations_applied=0, project_score 26, the manifest's ledger {digest_ledger: written,
learnings_read: {digest: 0, tree: 0}} (10_, 11_). The report names the file.
- The second scan of the same bytes reads them: calibrations_applied=2 on two files,
project_score 59, penalty_total 32.0, learnings_read 4 from the digest's ledger,
digest_ledger "left as it was" (20_, 21_). The file's time is that of the second scan's
read, 09:07:19Z (22_).
- The digest the scan took in the image equals the one taken on the host for the same
files (s10_c10_image_digest_host4.out). The target is unchanged
(s10_c10_image_target_same4.out).
- Three earlier runs of this probe and of the native run below, each on the code as it
stood before a later correction of the same rule (the value for a ledger that could not
be read; a ledger whose top level is not an object; one nested too deep), gave the same
numbers. Their stamps: 08:12:50Z to 08:17:31Z, 08:23:38Z to 08:27:42Z and 08:50:15Z to
08:54:17Z. They are kept as s10_c10_image_probe_run1, _run2, s10_c10_native_run1,
_run2 and _run3; of the third image run s10_c10_image_probe_run3.out and the host,
target and sources checks numbered 3 remain, since s10_c10_image_probe_run3 is empty.
Its files were read by the reviewer in round two.
- The shipped image, the control, on the same files: calibrations_applied=0 and
project_score 26 on both scans, no ledger block and no ledger (30_ to 42_).
- Natively, on a fresh copy of the same five files, the network off (s10_c10_native.sh,
09:09:14Z to 09:10:38Z): the first scan writes the tree's ledger (calibrations_applied=0,
project_score 26, digest_ledger none), the second reads it (calibrations_applied=2,
project_score 59, learnings_read 4 from the tree's ledger), and no ledger of a digest is
made (s10_c10_native/10_ to 22_).
- The probe left no container (2 before, 2 after: 00_, 91_) and its image is removed (90_,
92_).
Tests
- tests/test_tree_digest.py (7) and tests/test_digest_ledger.py (11, one over nine contents
a file may hold); seven tests in tests/test_scan_output_location.py, six through the scan
(three over two cases) and one on _read_ledgers; six in tests/test_run_pruning.py; one
sentence in tests/test_reports.py. The scan test of a refused write selects its run by
name now, since the runs directory holds calibration/ as well.
- RED on an archive of e231b78 with the final test files: the two unit files do not import
(s10_c10_red14.out); the scan, pruning and report files give 15 failed, 101 passed
(s10_c10_red13.out; the tree's tree_digest.py and digest_ledger.py were copied into that
archive, since the test file imports both, and cli.py, run.py and reports.py were HEAD's).
On the tree before each fix: the test of a ledger that is not a JSON object failed
(s10_c10_red8.out), and so did the content nested too deep and its scan test
(s10_c10_red12.out).
- GREEN on the final tree: 134 passed over the five files (s10_c10_green9.out); 873 passed
over the 60 files of the scan path (s10_c10_wide4_full.out; the list is
s10_c10_testfiles.txt); the docs and skills tests, with the strict site build, 11 passed
(s10_c10_docs_tests4.out; no page changed after it).
- Gates on the final tree: ten zeros (s10_c10e_exits.txt), the three gate outputs equal to
the baseline.
- Review: three rounds against e231b78, by one reviewer subagent, read-only; no
docker and no wrapper run, the probes read from their files. Round one blocked
on one finding and measured it end to end on a scratch tree: a ledger of a
digest whose top level is not a JSON object raised AttributeError in the tree's
loader and stopped the scan (exit 1), against the note's "a cache must not stop
a scan". Round two approved with remarks, which the code and the tests took:
RecursionError joined the tuple (digest_ledger.py:57), with a ninth content in
the unit test and a scan test of a ledger that is not a ledger, red before the
fix (s10_c10_red12.out). Round three approved the code, the tests and the dated
note, and blocked on one sentence of this message, which named
s10_c10_image_probe_run3 as kept: that directory is empty. On the final tree the
reviewer measured the scan past a digest's ledger nested 5000 deep (exit 0,
"unreadable", the file removed) and passed 30000 contents through
read_digest_ledger, with none let through; it re-ran the five files (134
passed), the docs and skills files with two scan files outside the sixty (20
passed), ruff, mypy (297 files) and the comparison of the three gate outputs
with the baseline, the gates themselves not run; it recomputed the three
digests, matched the tree's 297 .py files to the fourth probe image's list, and
read the fourth image and native runs. The third image run's files were read in
round two, before they were lost. The sentence was reworded as the reviewer
wrote it.
By reading, not measured
- A pre-push run does not go through _run_scan, and src/openultrasast/push names no ledger:
nothing changes there.
- ousast benchmark and the MCP server call _run_scan and get the rule as a scan does.
- mark_all of the hunt tooling lists the children of a runs root it is given; it has no
caller under src.
Found and not fixed, for the maintainer
- The note says the digest stage's seconds are in the manifest. No stage's are: a stage's
time is in trace/events.jsonl (stage_start and stage_end), and so is this one's. The pages
and the dated note do not repeat the sentence.
- The report's sentence (reports.py:461-467) says this scan's learnings are kept in the
ledger of the digest whenever that file holds some of them (cli.py:1131-1133). A new
learning whose finding id the tree's ledger already holds is left out by the rule; the
tree's version stands, and the new evidence text is in the run directory alone. The
sentence is the note's as approved.
- The tree's own ledger stops the scan when its top level is not a JSON object, or when it
is nested too deep (calibration.py:157-159, read at cli.py:610 outside any stage). That
is older than this commit; the ledger of a digest does not.
- read_digest_ledger raises when calibration/ cannot be searched, as the tree's ledger does
when .openultrasast/calibration cannot (digest_ledger.py:53).
- By reading: a tree whose runs directory is the target itself gets another digest at every
scan, since its run directory is made inside the target before the stage. Such a tree can
be written, so its own ledger takes the learnings and no ledger of a digest is made.
- docs/architecture.md draws no provenance stage, which cli.py runs between
entry_point_mapping and rank.
- The wrapper builds its image only when the image is missing: until a rebuild, a scan
through it runs the shipped code, which has none of this.
- The notice of a removed ledger names the runs directory as the scan sees it (/reports in
the image), not the host's path.
Not checked
- the whole test suite; Windows; ops/shell/ousast.ps1 (not read for this commit); two scans
of one tree at once; the wrapper and the compose route (the probe used docker run with the
wrapper's mount and override); a removal that fails on a real cache; Docker Desktop, where
a directory mounted twice may not keep one inode.
This commit is contained in:
@@ -35,6 +35,7 @@ from .calibration import (
|
||||
)
|
||||
from .complexity import map as complexity_map
|
||||
from .config import ModelLayerConfig, ObligationsConfig, ResolvedConfig, RetiredConfigError, load_config, load_dotenv
|
||||
from .digest_ledger import HOLDS_LEARNINGS, DigestLedger, digest_ledger_path, read_digest_ledger, settle_digest_ledger
|
||||
from .findings import StaticFinding, quick_scan_findings, uncovered_languages, write_findings
|
||||
from .fusion import FusionDecision, fuse_findings
|
||||
from .harness import HarnessRuntime, HarnessTraceWriter, write_harness_config
|
||||
@@ -82,6 +83,7 @@ from .semantic import (
|
||||
)
|
||||
from .semantic.facts import FactLoadError, SemanticFacts
|
||||
from .stages import Stage, plan_for_mode, record_completed, record_skip, skip_as_degradation, stages_payload
|
||||
from .tree_digest import tree_digest
|
||||
from .verification import VerificationResult, verify_findings, write_verification_results
|
||||
|
||||
CALIBRATION_DIR = ".openultrasast/calibration"
|
||||
@@ -598,11 +600,14 @@ def _run_scan(path: Path, config_path: Path, mode: str, fail_on: str) -> ScanOut
|
||||
)
|
||||
write_harness_config(config=config, path=run.root / "harness.json")
|
||||
runtime.start(mode=mode, target=run.target)
|
||||
# The key of the ledger kept under the runs directory for a tree that could not be written into. Taken before
|
||||
# any stage reads the tree.
|
||||
digest = runtime.run_stage("tree_digest", lambda: tree_digest(run.target, Path(config.runs_dir)))
|
||||
policy, ruleset, targets, entry_points, left_out = _map_scan_targets(runtime, run, config, mode)
|
||||
ledger_path = run.target / CALIBRATION_DIR / "false_positive_learnings.json"
|
||||
provenance = runtime.run_stage("provenance", lambda: fingerprint(run.target))
|
||||
rankings = runtime.run_stage("rank", lambda: rank_targets(targets))
|
||||
prior_learnings = load_false_positive_learnings(ledger_path)
|
||||
tree_learnings, ledger_of_digest, prior_learnings = _read_ledgers(ledger_path, Path(config.runs_dir), digest)
|
||||
rankings, calibrations = runtime.run_stage("calibrate", lambda: calibrate_rankings(rankings, prior_learnings))
|
||||
applied_calibrations = [calibration for calibration in calibrations if calibration.applied_learning_ids]
|
||||
write_rankings(rankings, run.root / "rank" / "ranking.json")
|
||||
@@ -617,7 +622,16 @@ def _run_scan(path: Path, config_path: Path, mode: str, fail_on: str) -> ScanOut
|
||||
write_hunter_trajectories(trajectories, files.trajectories)
|
||||
|
||||
verifications, fusion_decisions = _verify_and_fuse(
|
||||
runtime, run, config, mode, findings=findings, prior_learnings=prior_learnings, ledger_path=ledger_path, files=files
|
||||
runtime,
|
||||
run,
|
||||
config,
|
||||
mode,
|
||||
findings=findings,
|
||||
tree_learnings=tree_learnings,
|
||||
ledger_of_digest=ledger_of_digest,
|
||||
prior_learnings=prior_learnings,
|
||||
ledger_path=ledger_path,
|
||||
files=files,
|
||||
)
|
||||
cwe_by_rule = {rule.rule_id: rule.cwe for rule in ruleset}
|
||||
rule_cwe_by_id = {finding.finding_id: cwe_by_rule.get(finding.finding_id.split(":", 1)[0], "") for finding in findings}
|
||||
@@ -714,10 +728,16 @@ def _run_scan(path: Path, config_path: Path, mode: str, fail_on: str) -> ScanOut
|
||||
provenance=provenance.to_dict(),
|
||||
obligations=map_stage.obligations_summary,
|
||||
model=map_stage.model,
|
||||
ledger={
|
||||
"tree_digest": digest,
|
||||
"learnings_read": {"tree": len(tree_learnings), "digest": len(ledger_of_digest.learnings)},
|
||||
"digest_ledger": runtime.state["digest_ledger"][0],
|
||||
},
|
||||
),
|
||||
)
|
||||
runtime.finish(status="succeeded")
|
||||
prune_notices = prune_scan_runs(config, keep=run.root)
|
||||
ledger_error = runtime.state["digest_ledger"][1]
|
||||
return ScanOutcome(
|
||||
scan_id=run.scan_id,
|
||||
run_dir=run.root,
|
||||
@@ -732,6 +752,7 @@ def _run_scan(path: Path, config_path: Path, mode: str, fail_on: str) -> ScanOut
|
||||
if item.get("reason") == "language_not_covered"
|
||||
)
|
||||
+ prune_notices
|
||||
+ ((f"the ledger of this tree's digest could not be written or removed: {ledger_error}",) if ledger_error else ())
|
||||
+ _skipped_files_notices(Path(config.runs_dir), left_out),
|
||||
)
|
||||
|
||||
@@ -845,6 +866,8 @@ def _verify_and_fuse(
|
||||
mode: str,
|
||||
*,
|
||||
findings: list[StaticFinding],
|
||||
tree_learnings: list[FalsePositiveLearning],
|
||||
ledger_of_digest: DigestLedger,
|
||||
prior_learnings: list[FalsePositiveLearning],
|
||||
ledger_path: Path,
|
||||
files: _RunFiles,
|
||||
@@ -854,7 +877,9 @@ def _verify_and_fuse(
|
||||
write_verification_results(verifications, files.verification)
|
||||
runtime.run_stage(
|
||||
"record_calibration",
|
||||
lambda: _persist_calibration_feedback(run, ledger_path, prior_learnings, findings, verifications, runtime),
|
||||
lambda: _persist_calibration_feedback(
|
||||
run, ledger_path, tree_learnings, ledger_of_digest, prior_learnings, findings, verifications, runtime
|
||||
),
|
||||
)
|
||||
# Fusion: deterministic two-panel adjudication for triggered findings (standard mode).
|
||||
fusion_decisions: list[FusionDecision] = []
|
||||
@@ -1057,9 +1082,27 @@ def _attach_tool_hunter(
|
||||
return built_map, findings, verifications
|
||||
|
||||
|
||||
def _read_ledgers(
|
||||
ledger_path: Path, runs_directory: Path, digest: str
|
||||
) -> tuple[list[FalsePositiveLearning], DigestLedger, list[FalsePositiveLearning]]:
|
||||
"""What the tree's ledger holds, the ledger of the tree's digest (what scans learned while the tree could not be
|
||||
written into), and the learnings the scan is to apply.
|
||||
|
||||
An entry whose finding id is in both is taken from the tree's ledger: that is the file a user can read, edit
|
||||
and commit.
|
||||
"""
|
||||
tree_learnings = load_false_positive_learnings(ledger_path)
|
||||
ledger_of_digest = read_digest_ledger(digest_ledger_path(runs_directory, digest))
|
||||
tree_ids = {learning.finding_id for learning in tree_learnings}
|
||||
prior_learnings = tree_learnings + [learning for learning in ledger_of_digest.learnings if learning.finding_id not in tree_ids]
|
||||
return tree_learnings, ledger_of_digest, prior_learnings
|
||||
|
||||
|
||||
def _persist_calibration_feedback(
|
||||
run: ScanRun,
|
||||
ledger_path: Path,
|
||||
tree_learnings: list[FalsePositiveLearning],
|
||||
ledger_of_digest: DigestLedger,
|
||||
prior_learnings: list[FalsePositiveLearning],
|
||||
findings: list[StaticFinding],
|
||||
verifications: list[VerificationResult],
|
||||
@@ -1068,14 +1111,27 @@ def _persist_calibration_feedback(
|
||||
# Store rejected or held findings as scoped learnings for the next scan.
|
||||
new_learnings = learnings_from_verifications(findings, verifications)
|
||||
merged = merge_false_positive_learnings(prior_learnings, new_learnings)
|
||||
if merged != prior_learnings:
|
||||
# The ledger is the one thing a scan still writes into the analysed tree, so it is written only when its
|
||||
# content would change: a false positive already in the store is not a new learning. A tree that refuses
|
||||
# the write (mounted read-only) is recorded, not fatal.
|
||||
refused: OSError | None = None
|
||||
tree_takes_it = False
|
||||
if merged != tree_learnings:
|
||||
# The ledger is the one thing a scan still writes into the analysed tree. It is written when its content
|
||||
# would change, also when only the entries of the digest's ledger are new to it: the first scan that can
|
||||
# write the tree carries them into it. A tree that refuses the write (mounted read-only) is recorded, not
|
||||
# fatal: what was learned is kept in the ledger of the tree's digest under the runs directory instead.
|
||||
try:
|
||||
write_false_positive_learnings(merged, ledger_path)
|
||||
tree_takes_it = True
|
||||
except OSError as exc:
|
||||
runtime.state["degradations"].append({"stage": "record_calibration", "reason": "ledger_not_written", "detail": str(exc)})
|
||||
refused = exc
|
||||
outcome, error = settle_digest_ledger(
|
||||
ledger_of_digest, tree=tree_learnings, merged=merged, new=new_learnings, tree_takes_it=tree_takes_it
|
||||
)
|
||||
runtime.state["digest_ledger"] = (outcome, error)
|
||||
if refused is not None:
|
||||
degradation: dict[str, object] = {"stage": "record_calibration", "reason": "ledger_not_written", "detail": str(refused)}
|
||||
if outcome in HOLDS_LEARNINGS:
|
||||
degradation["kept_in"] = str(ledger_of_digest.path)
|
||||
runtime.state["degradations"].append(degradation)
|
||||
write_false_positive_learnings(new_learnings, run.root / "calibration" / "false_positive_learnings.json")
|
||||
return merged
|
||||
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
"""The ledger of a tree's digest: what scans learned while the tree could not be written into, kept under the runs
|
||||
directory and read by the next scan of the very same bytes (the decision of 2026-11-28)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from .calibration import (
|
||||
FalsePositiveLearning,
|
||||
load_false_positive_learnings,
|
||||
merge_false_positive_learnings,
|
||||
write_false_positive_learnings,
|
||||
)
|
||||
|
||||
LEDGERS_DIRNAME = "calibration"
|
||||
FOUND_NONE = "none"
|
||||
FOUND_READ = "read"
|
||||
FOUND_UNREADABLE = "unreadable"
|
||||
WRITTEN = "written"
|
||||
LEFT_AS_IT_WAS = "left as it was"
|
||||
REMOVED = "removed"
|
||||
FAILED = "failed"
|
||||
# What became of a ledger after which it holds what a refusing tree could not take.
|
||||
HOLDS_LEARNINGS = (WRITTEN, LEFT_AS_IT_WAS)
|
||||
# A ledger, and the temporary file it is written through before its rename.
|
||||
LEDGER_NAME = re.compile(r"[0-9a-f]{64}\.json(?:\.[0-9a-f]{32}\.tmp)?")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DigestLedger:
|
||||
"""The ledger of one tree digest: where it is, whether a scan could read it, and what it held."""
|
||||
|
||||
path: Path
|
||||
found: str
|
||||
learnings: list[FalsePositiveLearning] = field(default_factory=list)
|
||||
|
||||
|
||||
def digest_ledger_path(runs_directory: Path, digest: str) -> Path:
|
||||
return Path(runs_directory) / LEDGERS_DIRNAME / f"{digest}.json"
|
||||
|
||||
|
||||
def read_digest_ledger(path: Path) -> DigestLedger:
|
||||
"""The ledger at `path` and what it held: `FOUND_NONE` when there is no file, `FOUND_UNREADABLE` when there is one
|
||||
that is not a ledger (a cache must not stop a scan), `FOUND_READ` otherwise.
|
||||
|
||||
Reading one marks it as used, so that a ledger read every day stays while one left alone goes.
|
||||
"""
|
||||
if not path.is_file():
|
||||
return DigestLedger(path, FOUND_NONE)
|
||||
try:
|
||||
learnings = load_false_positive_learnings(path)
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError, RecursionError):
|
||||
# Whatever a hand or another tool left there: the reader of the tree's ledger stops on it, a cache must not.
|
||||
return DigestLedger(path, FOUND_UNREADABLE)
|
||||
with contextlib.suppress(OSError): # a mark that fails costs the scan nothing
|
||||
os.utime(path)
|
||||
return DigestLedger(path, FOUND_READ, learnings)
|
||||
|
||||
|
||||
def settle_digest_ledger(
|
||||
ledger: DigestLedger,
|
||||
*,
|
||||
tree: list[FalsePositiveLearning],
|
||||
merged: list[FalsePositiveLearning],
|
||||
new: list[FalsePositiveLearning],
|
||||
tree_takes_it: bool,
|
||||
) -> tuple[str, str]:
|
||||
"""Bring the ledger of the digest in line with what this scan did to the tree's ledger.
|
||||
|
||||
Returns what became of it and, when something failed, why. `tree` is what the tree's ledger held before this
|
||||
scan, `merged` what it is to hold now, `new` what this scan learned, and `tree_takes_it` whether the tree took
|
||||
that write, when there was one.
|
||||
|
||||
- The tree took the write: everything the ledger held is in the tree's ledger now, so the ledger is removed.
|
||||
- The tree refused the write: the ledger is written instead, with its own entries and this scan's new ones,
|
||||
never one whose finding id the tree's ledger has, and only when that differs from its content; when that
|
||||
would leave it empty, it is removed.
|
||||
- There was no write: a ledger whose every entry the tree's ledger also has is removed. It has nothing left
|
||||
to give. This is also what removes a ledger again when an earlier removal failed, and one that could not
|
||||
be read, which is taken for empty.
|
||||
|
||||
A ledger that could not be read is "unreadable" unless this scan wrote it or failed to: it is taken for
|
||||
empty and goes, since it has nothing left to give. A removal that finds the file already gone is nothing,
|
||||
and nothing here raises.
|
||||
"""
|
||||
outcome = FOUND_NONE if ledger.found == FOUND_NONE else LEFT_AS_IT_WAS
|
||||
error = ""
|
||||
tree_ids = {learning.finding_id for learning in tree}
|
||||
if merged != tree:
|
||||
if tree_takes_it:
|
||||
if ledger.found != FOUND_NONE:
|
||||
outcome, error = _remove(ledger.path)
|
||||
else:
|
||||
kept = [learning for learning in merge_false_positive_learnings(ledger.learnings, new) if learning.finding_id not in tree_ids]
|
||||
if not kept:
|
||||
if ledger.found != FOUND_NONE:
|
||||
outcome, error = _remove(ledger.path)
|
||||
elif kept != ledger.learnings:
|
||||
outcome, error = _write(ledger.path, kept)
|
||||
elif ledger.found != FOUND_NONE and all(learning.finding_id in tree_ids for learning in ledger.learnings):
|
||||
outcome, error = _remove(ledger.path)
|
||||
if ledger.found == FOUND_UNREADABLE and outcome not in (WRITTEN, FAILED):
|
||||
outcome = FOUND_UNREADABLE
|
||||
return outcome, error
|
||||
|
||||
|
||||
def _write(path: Path, learnings: list[FalsePositiveLearning]) -> tuple[str, str]:
|
||||
"""Through a temporary file of this writer's own and a rename: a scan stopped midway leaves the old ledger or the
|
||||
new one, and two scans of one tree never share a name."""
|
||||
temporary = path.with_name(f"{path.name}.{uuid.uuid4().hex}.tmp")
|
||||
try:
|
||||
write_false_positive_learnings(learnings, temporary)
|
||||
os.replace(temporary, path)
|
||||
except OSError as exc:
|
||||
with contextlib.suppress(OSError):
|
||||
temporary.unlink(missing_ok=True)
|
||||
return FAILED, str(exc)
|
||||
return WRITTEN, ""
|
||||
|
||||
|
||||
def _remove(path: Path) -> tuple[str, str]:
|
||||
try:
|
||||
path.unlink()
|
||||
except FileNotFoundError:
|
||||
pass # already gone: nothing to remove
|
||||
except OSError as exc:
|
||||
return FAILED, str(exc)
|
||||
return REMOVED, ""
|
||||
@@ -209,6 +209,7 @@ def write_manifest(
|
||||
variants: dict[str, object] | None = None,
|
||||
obligations: dict[str, object] | None = None,
|
||||
model: dict[str, object] | None = None,
|
||||
ledger: dict[str, object] | None = None,
|
||||
) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
verification_by_id = _verification_by_id(verifications)
|
||||
@@ -250,6 +251,8 @@ def write_manifest(
|
||||
payload["obligations"] = obligations
|
||||
if model is not None:
|
||||
payload["model"] = model
|
||||
if ledger is not None:
|
||||
payload["ledger"] = ledger
|
||||
path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")
|
||||
|
||||
|
||||
@@ -455,6 +458,13 @@ _COVERAGE_DEGRADATIONS: dict[str, str] = {
|
||||
"The false-positive ledger in the analysed tree could not be written, so this scan's learnings are kept "
|
||||
"only in this run directory and the next scan starts without them. {detail}"
|
||||
),
|
||||
# The same degradation when the ledger of the tree's digest holds the learnings (`kept_in`, written in this scan
|
||||
# or before): the next scan of the same bytes reads them there.
|
||||
"ledger_kept_by_digest": (
|
||||
"The false-positive ledger in the analysed tree could not be written, so this scan's learnings are kept in "
|
||||
"the ledger of this tree's digest under the runs directory, at `{kept_in}`, and the next scan of the same "
|
||||
"bytes reads them. {detail}"
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@@ -467,7 +477,10 @@ def _append_not_analysed(lines: list[str], degradations: Sequence[Mapping[str, o
|
||||
"""
|
||||
rendered: list[str] = []
|
||||
for item in degradations:
|
||||
template = _COVERAGE_DEGRADATIONS.get(str(item.get("reason") or ""))
|
||||
reason = str(item.get("reason") or "")
|
||||
if reason == "ledger_not_written" and item.get("kept_in"):
|
||||
reason = "ledger_kept_by_digest"
|
||||
template = _COVERAGE_DEGRADATIONS.get(reason)
|
||||
if template is None:
|
||||
# Never hide a recorded degradation because nobody wrote a sentence for it yet.
|
||||
rendered.append(f"`{item.get('reason')}` (stage `{item.get('stage', 'unknown')}`)")
|
||||
|
||||
@@ -8,6 +8,7 @@ from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from .config import ResolvedConfig, runs_dir_is_overridden, runs_dir_is_the_wrappers, write_resolved_config
|
||||
from .digest_ledger import LEDGER_NAME, LEDGERS_DIRNAME
|
||||
|
||||
_RUN_ID = re.compile(r"(\d{8}T\d{6}Z)-[0-9a-f]{8}")
|
||||
|
||||
@@ -68,12 +69,15 @@ def prune_old_runs(runs_root: Path, *, keep: Path | None = None, retention_days:
|
||||
|
||||
|
||||
def prune_scan_runs(config: ResolvedConfig, *, keep: Path) -> tuple[str, ...]:
|
||||
"""Remove the expired runs once a scan has written its own; returns what the scan is to say about it.
|
||||
"""Remove the expired runs and ledgers once a scan has written its own; returns what the scan is to say about it.
|
||||
|
||||
Two locations are pruned: the default one, and the shell wrapper's runs directory, which is the user's runs
|
||||
directory mounted in the image (`runs_dir_is_the_wrappers`). While `OPENULTRASAST_RUNS_DIR` points anywhere
|
||||
else, wherever it points, every run stays. Nothing is said when nothing was removed, and a removal that
|
||||
fails is said once and costs the scan nothing.
|
||||
|
||||
The ledgers of tree digests (`prune_expired_ledgers`) lie under the same two locations and go by the same
|
||||
number of days, dated by their last use.
|
||||
"""
|
||||
if runs_dir_is_overridden() and not runs_dir_is_the_wrappers():
|
||||
return ()
|
||||
@@ -82,7 +86,59 @@ def prune_scan_runs(config: ResolvedConfig, *, keep: Path) -> tuple[str, ...]:
|
||||
removed = prune_old_runs(root, keep=keep, retention_days=config.runs_retention_days)
|
||||
except (OSError, RecursionError) as exc:
|
||||
return (f"old runs could not be removed from {root}: {exc}",)
|
||||
if not removed:
|
||||
return ()
|
||||
runs = "run" if len(removed) == 1 else "runs"
|
||||
return (f"removed {len(removed)} {runs} older than {config.runs_retention_days} days from {root}",)
|
||||
notices = []
|
||||
if removed:
|
||||
runs = "run" if len(removed) == 1 else "runs"
|
||||
notices.append(f"removed {len(removed)} {runs} older than {config.runs_retention_days} days from {root}")
|
||||
ledgers = root / LEDGERS_DIRNAME
|
||||
gone, failed = prune_expired_ledgers(ledgers, retention_days=config.runs_retention_days)
|
||||
if gone:
|
||||
name = "ledger" if len(gone) == 1 else "ledgers"
|
||||
notices.append(f"removed {len(gone)} {name} of a tree digest unused for {config.runs_retention_days} days from {ledgers}")
|
||||
notices.extend(f"a ledger of a tree digest could not be removed from {ledgers}: {exc}" for _, exc in failed)
|
||||
return tuple(notices)
|
||||
|
||||
|
||||
def _is_expired_ledger(entry: Path, cutoff: datetime) -> bool:
|
||||
"""A ledger of a tree digest, or the temporary file it was written through, last used before `cutoff`."""
|
||||
if LEDGER_NAME.fullmatch(entry.name) is None or entry.is_symlink() or not entry.is_file():
|
||||
return False
|
||||
try:
|
||||
return datetime.fromtimestamp(entry.stat().st_mtime, UTC) < cutoff
|
||||
except (OSError, OverflowError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def prune_expired_ledgers(
|
||||
directory: Path, *, retention_days: int, now: datetime | None = None
|
||||
) -> tuple[list[Path], list[tuple[Path, OSError]]]:
|
||||
"""Remove the ledgers of tree digests under `directory` that were last used before `retention_days`; return them
|
||||
and the removals that failed.
|
||||
|
||||
A ledger is dated by its use, since a scan marks it when it reads it, where a run is dated by its id. Files
|
||||
called something else, links and directories stay. Nothing raises.
|
||||
"""
|
||||
if retention_days <= 0 or not directory.is_dir():
|
||||
return [], []
|
||||
try:
|
||||
cutoff = (now or datetime.now(UTC)) - timedelta(days=retention_days)
|
||||
except OverflowError:
|
||||
return [], [] # a retention longer than the calendar: no ledger is that old
|
||||
removed: list[Path] = []
|
||||
failed: list[tuple[Path, OSError]] = []
|
||||
try:
|
||||
entries = sorted(directory.iterdir())
|
||||
except OSError as exc:
|
||||
return [], [(directory, exc)]
|
||||
for entry in entries:
|
||||
if not _is_expired_ledger(entry, cutoff):
|
||||
continue
|
||||
try:
|
||||
entry.unlink()
|
||||
except FileNotFoundError:
|
||||
pass # already gone
|
||||
except OSError as exc:
|
||||
failed.append((entry, exc))
|
||||
else:
|
||||
removed.append(entry)
|
||||
return removed, failed
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
"""The key of the ledger a scan keeps for a tree it could not write into: a digest of the tree's files."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
from .preprocess import IGNORED_DIRS
|
||||
|
||||
# The hashed text starts with this, so that a later change of the definition cannot pass for the same key.
|
||||
_VERSION = b"openultrasast-tree-v1\n"
|
||||
|
||||
|
||||
def _identity(path: Path) -> tuple[int, int] | None:
|
||||
"""The device and the inode of `path`: the same under every path it is reached by."""
|
||||
try:
|
||||
status = os.stat(path)
|
||||
except OSError:
|
||||
return None
|
||||
return status.st_dev, status.st_ino
|
||||
|
||||
|
||||
def _files(root: Path, skipped: tuple[int, int] | None) -> Iterator[tuple[str, Path | None]]:
|
||||
"""Every file to hash and every directory that could not be listed: its path under `root`, and the file
|
||||
(None for a directory that could not be listed), in path order."""
|
||||
entries: list[tuple[str, Path | None]] = []
|
||||
|
||||
def unlisted(error: OSError) -> None:
|
||||
if error.filename is not None:
|
||||
entries.append((Path(os.path.relpath(error.filename, root)).as_posix(), None))
|
||||
|
||||
def kept(name: str, path: Path) -> bool:
|
||||
return name not in IGNORED_DIRS and (skipped is None or _identity(path) != skipped)
|
||||
|
||||
for parent, directories, names in os.walk(root, followlinks=False, onerror=unlisted):
|
||||
base = Path(parent)
|
||||
directories[:] = sorted(name for name in directories if kept(name, base / name))
|
||||
for name in names:
|
||||
path = base / name
|
||||
if path.is_symlink() or not path.is_file():
|
||||
continue
|
||||
entries.append((path.relative_to(root).as_posix(), path))
|
||||
yield from sorted(entries, key=lambda entry: entry[0])
|
||||
|
||||
|
||||
def tree_digest(target: Path, runs_directory: Path | None = None) -> str:
|
||||
"""A sha256 of the name and the bytes of every file under `target`, in path order.
|
||||
|
||||
Left out: links; the directories a scan ignores (`IGNORED_DIRS`), so that the ledger in the tree does not
|
||||
change its own key; and `runs_directory`, whichever way it is reached. A file that cannot be read and a
|
||||
directory that cannot be listed are named `unreadable` instead of a hash, so that neither is skipped in
|
||||
silence. Each entry is the length of the path, a colon, the path, a tab and the hash: one path is one entry.
|
||||
A directory that can be listed but not searched raises, as the scan's own reading of the tree does.
|
||||
"""
|
||||
digest = hashlib.sha256()
|
||||
digest.update(_VERSION)
|
||||
skipped = _identity(runs_directory) if runs_directory is not None else None
|
||||
for relative, path in _files(target, skipped):
|
||||
name = relative.encode("utf-8", "surrogatepass")
|
||||
digest.update(f"{len(name)}:".encode("ascii") + name + b"\t")
|
||||
digest.update(_hash(path) if path is not None else b"unreadable")
|
||||
digest.update(b"\n")
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _hash(path: Path) -> bytes:
|
||||
"""The sha256 of the file's bytes, read in chunks, or the word `unreadable`."""
|
||||
try:
|
||||
with path.open("rb") as handle:
|
||||
return hashlib.file_digest(handle, "sha256").hexdigest().encode("ascii")
|
||||
except OSError:
|
||||
return b"unreadable"
|
||||
Reference in New Issue
Block a user