[bug] Resume source matching accepts a replacement after duplicate basenames
What happened
reuse_is_safe() can accept a changed source collection when the recorded sources contain duplicate basenames and hashes. A new source can be present in the current inputs but never checked.
This reproduces with metadata produced by the unmodified CLI, not hand-written malformed metadata. Two files in different directories are both named book.txt and contain identical synthetic text. After their extraction completes, keep the output corpus and metadata intact and replace one input with a differently named file containing different text:
Recorded sources: a/book.txt (hash OLD), b/book.txt (hash OLD)
Current inputs: a/book.txt (hash OLD), replacement.txt (hash NEW)
reuse_is_safe(...): (True, 'workdir intact and all sources match the current inputs')
NEW_CONTENT is absent from the reused corpus.The unchanged duplicate-basename input collection is rejected instead. A negative control with unique recorded basenames correctly rejects the replacement.
I did not run a live agent conversion. The observed failure is the helper's incorrect source-matching verdict, which Step 0 names as the executable recovery check.
Expected behavior
Recorded and current sources must match one-to-one on filename and content fingerprint, including the multiplicity of each pair. Reusing the complete old extraction is unsafe when one source has been replaced by a new file with a different name and hash.
Environment
- Synthetic UTF-8 TXT; two original files in different directories with the same basename and bytes.
- Built-in text parser:
--mode text --install-missing no. masteratc108d25b0cb58e1bdc361f3de02ed9f37075152f; version 1.4.0.- Windows; initial reproduction on Python 3.14.0, independently repeated with fresh fixtures on supported Python 3.12.14.
- Original
metadata.jsonandfull_text.txtremain unchanged and readable in this reproduction.
Minimal reproduction
Run this from the repository root. It writes only its own new synthetic fixture and runs the real extractor. Set BOOK_SKILL_REPRO_DIR to an output directory if you want the fixture outside the checkout; otherwise it creates a uniquely named subdirectory of the current directory:
import hashlib, json, os, subprocess, sys, uuid
from pathlib import Path
from book_to_skill.utils import reuse_is_safe
root = Path(os.environ.get("BOOK_SKILL_REPRO_DIR", ".")) / f"bts-multiplicity-{uuid.uuid4().hex}"
root.mkdir(parents=True)
a, b, c = root / "a/book.txt", root / "b/book.txt", root / "replacement.txt"
for source in (a, b, c):
source.parent.mkdir(parents=True, exist_ok=True)
source.write_text("Chapter 1: Synthetic\n" + ("NEW_CONTENT" if source == c else "OLD_CONTENT") + "\n", encoding="utf-8")
def extract(name, inputs):
work = root / name
work.mkdir()
env = dict(os.environ, BOOK_SKILL_WORKDIR=str(work), PYTHONDONTWRITEBYTECODE="1", PYTHONIOENCODING="utf-8")
subprocess.run([sys.executable, "-B", "scripts/extract.py", *map(str, inputs), "--mode", "text", "--install-missing", "no"], env=env, check=True, capture_output=True)
return json.loads((work / "metadata.json").read_text(encoding="utf-8")), work
duplicate_meta, work = extract("duplicate", [a, b])
current = [(path, hashlib.sha256(path.read_bytes()).hexdigest()) for path in (a, c)]
print("recorded:", [(s["filename"], s["sha256"]) for s in duplicate_meta["sources"]])
print("current:", [(p.name, digest) for p, digest in current])
print("corpus intact:", (work / "full_text.txt").is_file())
print("new content in old corpus:", "NEW_CONTENT" in (work / "full_text.txt").read_text(encoding="utf-8"))
print("duplicate-source replacement:", reuse_is_safe(current, duplicate_meta, "text"))
print("unchanged duplicate-source control:", reuse_is_safe([(p, hashlib.sha256(p.read_bytes()).hexdigest()) for p in (a, b)], duplicate_meta, "text"))
single_meta, _ = extract("single", [a]); print("normal single-source control:", reuse_is_safe([current[0]], single_meta, "text"))
d = root / "unique.txt"
d.write_bytes(b.read_bytes())
unique_meta, _ = extract("unique", [a, d])
print("unique-source replacement control:", reuse_is_safe(current, unique_meta, "text"))Observed:
recorded: [('book.txt', '63e00c94e690c85f59b3885dd84d1fed75075375414455035752aff042991fef'),
('book.txt', '63e00c94e690c85f59b3885dd84d1fed75075375414455035752aff042991fef')]
current: [('book.txt', '63e00c94e690c85f59b3885dd84d1fed75075375414455035752aff042991fef'),
('replacement.txt', '494af4ff9f2c8d94f380315f77c6291e1751aba75c06404ea867805bba1b3e52')]
corpus intact: True
new content in old corpus: False
duplicate-source replacement: (True, 'workdir intact and all sources match the current inputs')
unchanged duplicate-source control: (False, 'sources changed')
normal single-source control: (True, 'workdir intact and all sources match the current inputs')
unique-source replacement control: (False, "sources changed (recorded 'unique.txt' is not in this run)")Cause
utils.py:969-991 first compares list lengths, then reduces current inputs to a dictionary keyed by basename. It checks that the current dictionary is not smaller than the recorded list, but it never checks the recorded collection's multiplicity.
Each recorded book.txt then looks up the same current dictionary entry. Both hashes match that one input, and the new replacement.txt is never visited. Equal cardinalities do not establish the promised one-to-one match.
The producer legitimately permits this input: resolve_input_files deduplicates resolved paths, so a/book.txt and b/book.txt remain separate files. metadata.sources records them separately. Step 0 explicitly requires sources to match one-to-one.
Impact
Folders of chapter exports, versioned documents, or repeated filenames across directories can produce valid duplicate-basename metadata. Changing that collection can yield a false “safe to resume” verdict even though the new document was never extracted. This can drop new material from a subsequent generation without an input-change warning. That downstream generation is a consequence of using the verdict, not a measured live-model result.
The opposite error also wastes work: the unchanged duplicate-basename collection is rejected because reducing the current inputs to a dictionary loses an entry.
Smallest correction
Compare multisets of (filename, sha256) pairs, for example with stdlib collections.Counter, rather than matching through a basename dictionary. Validate existing required fingerprints before building those counters and preserve the current legacy-fingerprint fallback.
This keeps the current documented identity policy: identical filename/content pairs can match after relocation; source paths do not silently become a new mandatory identity key. It also supports two same-basename files with different hashes and preserves their multiplicities.
Alternatives:
- Reject duplicate basenames on both sides. This is a smaller conservative patch, but it keeps needless re-extraction for valid collections that the CLI supports.
- Bind identity to canonical full paths. That is stricter and can distinguish otherwise identical sources, but changes the existing basename/content contract and prevents reuse after relocating a document. Treat that as a separate policy choice.
- Compare sets of pairs. Insufficient: sets discard multiplicity and can still accept collections with missing/repeated source occurrences.
Source order is another independent policy question; this fix need not change it or increase the always-loaded spec.
Acceptance criteria
- The real-CLI reproduction above rejects the changed collection, while the complete old corpus remains intact.
- The unchanged duplicate-basename collection is accepted when filenames, hashes and multiplicities match.
- Two same-basename sources with different hashes match only the same two pairs; replacing, removing or duplicating one is rejected.
- Unique-basename controls, changed bytes, renamed sources, missing legacy fingerprints and extraction-mode mismatch keep their intended behavior.
- Matching relocated basename/content pairs retain the existing policy unless a separate documented change explicitly binds identity to paths.
- Tests use synthetic files and exercise metadata emitted by the real extractor, not only hand-built dictionaries. Run focused fingerprint/recovery tests and repository checks before merging.
No new runtime dependency or normal extraction-format change is needed.
Relationship to existing reports
#224 introduced the source-fingerprint recovery contract. #259 checks whether the extracted output is missing or changed. This failure occurs with a complete, unchanged output; an output digest would still match the old corpus and does not establish that the current source collection matches the recorded one.
Fresh read-only issue/PR collection review covered 254 entries over three pages. The source-reuse matches were #224 and #259; no separate source-multiplicity report was found. Independent real-CLI checks on Python 3.12.14 also confirmed that unchanged single/unique-source collections are accepted, replaced single/unique-source collections are rejected, unchanged duplicate sources are rejected, and the duplicate-source replacement is incorrectly accepted.
Source: virgiliojr94/book-to-skill