Skip to content

Fix the oversized-source rename: poll until it takes, adopt strays instead of duplicating - #438

Merged
brettheap merged 2 commits into
mainfrom
change/fix-oversized-source-rename
Aug 27, 2026
Merged

brettheap merged 2 commits into
mainfrom
change/fix-oversized-source-rename

Conversation

@brettheap

Copy link
Copy Markdown
Contributor

Brett ruled the defect fixed. It had two halves, and so does the fix.

The defect, proven live 2026-08-27

add_text_source uploads an oversized document as a temp file and renames it afterwards (the CLI titles a --file source by filename). It waited a fixed time.sleep(2). For the 279KB ideation-dashboard spec — the retirement gate's own document — two seconds wasn't enough: the add succeeded, the rename silently didn't, and the source stranded under xf-sync-*.md where parity correctly read it MISSING.

The documented repair — re-running the book — added a second stray. Canon reached 120 sources with two temp-titled copies of one document and needed hand repair.

(a) Poll, don't sleep

_rename_source_when_ready retries until the rename takes, bounded by both a wall-clock deadline and an attempt count. The second bound matters: every test here patches time.sleep to a no-op, which turned the deadline into a 180-second busy-wait — the suite went 5s → 258s before I bounded it.

It confirms by reading the source list back, never by trusting the return. This CLI has been observed printing API error (code 7) while exiting 0, so the return value isn't evidence. Verify the state, not the return.

On timeout it raises, naming the source id, the hand-repair command, and do NOT re-run the sync to fix it. A silent failure stranded the source; a misleading remedy doubled it.

(b) Adopt strays

Before adding, the oversized path looks for an xf-sync-*.md source whose content matches the document (on the manifest's own digest) and renames it into place instead of adding a duplicate — converting the failure from compounding to self-healing.

Keyed on content, so it can only repair or do nothing: a stray whose content differs is left alone and the normal add proceeds, which is exactly today's behaviour.

Tests — hermetic, at the seam the suite already uses

Slow rename polled to success where sleep(2) would have failed · a rename that never takes failing loudly with the repair named · a re-run adopting the stray and issuing no add · a content-mismatched stray left alone.

Mutation-proved 4/4: restoring sleep(2), removing the repair, silencing the raise, and ignoring the content hash each fail tests.

I also fixed the fake. source rename returned "" without recording anything — so a seam that accepted writes it never modelled would have made every rename look like it never took. A test double that ignores the write cannot verify it.

Records corrected

The 2026-08-25 entry gets a dated forward note, and fairly: it called this "the known oversized-source readiness race" and repaired it by hand, which was accurate. What it did not do was file it — an accepted nuisance with a manual remedy, so nothing prevented the recurrence or the compounding re-run. The evidence doc and clearance record flip OPEN → FIXED.

No live re-verification was run, deliberately and on the record: the honest evidence path is the hermetic proof plus the next real apply exercising it naturally, rather than re-uploading a 279KB source to watch it work.

Gates

notebooklm 163 passed / 26 subtests (up 4, and back to 4.6s) · openspec 75/75 strict · hosting validator 0 errors · doc-health zero new (73/73 same-clock)

🤖 Generated with Claude Code

…s instead of duplicating

Brett ruled the defect fixed. It had two halves and so does the fix.

THE DEFECT, as proven live 2026-08-27. `add_text_source` uploads an oversized
document as a temp file and renames it afterwards, because the CLI titles a
--file source by filename. It waited a fixed `time.sleep(2)`. For the 279KB
`openspec/specs/ideation-dashboard/spec.md` — the retirement gate's own document
— two seconds was not enough: the add succeeded, the rename silently did not, and
the source stranded under `xf-sync-*.md` where parity correctly read it MISSING.
The documented repair, re-running the book, ADDED A SECOND STRAY. Canon reached
120 sources with two temp-titled copies of one document and needed a hand repair.

(a) POLL, DON'T SLEEP. `_rename_source_when_ready` retries until the rename
takes, bounded by BOTH a wall-clock deadline and an attempt count — the second
bound matters because every test here patches `time.sleep` to a no-op, which
would otherwise turn the deadline into a 180-second busy-wait (it did; the suite
went from 5s to 258s before I bounded it).

  IT CONFIRMS BY READING THE SOURCE LIST BACK, never by trusting the call's
  return. This CLI has been observed printing `API error (code 7)` while exiting
  0, so the return value is not evidence. Verify the state, not the return — the
  same rule the harness lessons keep arriving at from other directions.

  On timeout it RAISES, naming the source id, the hand-repair command, and
  "do NOT re-run the sync to fix it". A silent failure is what stranded the
  source; a misleading remedy is what doubled it.

(b) ADOPT STRAYS. Before adding, the oversized path looks for an `xf-sync-*.md`
source whose CONTENT matches the document, on the manifest's own digest, and
renames it into place instead of adding a duplicate. That converts the failure
mode from compounding to self-healing. Keyed on content so it can only repair or
do nothing — a stray whose content differs is left alone and the normal add
proceeds, which is exactly today's behaviour.

TESTS — hermetic, at the seam the suite already uses (`patch.object(sync,
"nlm", ...)`): a slow rename polled to success where sleep(2) would have failed;
a rename that never takes failing loudly with the repair named; a re-run adopting
the stray and issuing NO add; a content-mismatched stray left alone.
Mutation-proved 4/4 — restoring sleep(2), removing the repair, silencing the
raise, and ignoring the content hash each fail tests.

I ALSO FIXED THE FAKE. `source rename` returned "" without recording anything, so
a seam that accepted writes it never modelled would have made every rename look
like it never took. A test double that ignores the write cannot verify it.

RECORDS CORRECTED. The 2026-08-25 entry is annotated with a dated forward note,
and fairly: it called this "the known oversized-source readiness race" and
repaired it by hand, which was ACCURATE. What it did not do was FILE it — the
race was an accepted nuisance with a manual remedy, so nothing prevented the
recurrence or the compounding re-run. The evidence doc and the clearance record
flip from OPEN DEFECT to FIXED.

NO LIVE RE-VERIFICATION was run, deliberately and on the record: the honest
evidence path is the hermetic proof plus the next real apply exercising it
naturally, rather than re-uploading a 279KB source to watch it work.

Gates: notebooklm 163 passed / 26 subtests (up 4, and back to 4.6s from the
258s the unbounded poll caused), openspec 75/75 strict, hosting validator 0
errors, doc-health ZERO NEW (73/73 same-clock).

Co-Authored-By: Claude Fable 5 <[email protected]>
Copilot AI lite review requested due to automatic review settings August 27, 2026 22:28

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @brettheap! 👋

Your private repo does not have access to Sourcery.

Please upgrade to continue using Sourcery ✨

@brettheap

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 05bb787859

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread scripts/sync-notebooklm-books.py Outdated
Comment on lines +1026 to +1029
body = nlm("source", "content", source_id, parse=False) or ""
except RuntimeError:
continue
if hashlib.sha256(str(body).encode()).hexdigest()[:16] != want:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Unwrap source content before comparing hashes

When nlm source content returns the already-supported JSON form such as {"value":{"content":"..."}}, this hashes the entire serialized response rather than the source body. The digest can therefore never equal the digest of text, so a matching xf-sync-*.md source is not adopted and the rerun uploads another duplicate—the exact compounding failure this change is intended to fix. Pass the response through the existing source_content_text() helper before hashing it.

Useful? React with 👍 / 👎.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This pull request hardens scripts/sync-notebooklm-books.py against a live-proven race where oversized uploads sometimes fail to rename after add, leaving sources stranded under xf-sync-*.md and causing re-runs to duplicate sources instead of repairing them.

Changes:

  • Replace the fixed post-upload sleep(2) with a bounded polling rename that verifies provider state via re-listing sources and raises loudly on timeout.
  • Add “adopt strays” behavior: before adding an oversized source, detect a temp-titled xf-sync-*.md source with matching content digest and rename it into place instead of adding a duplicate.
  • Expand the hermetic NotebookLM sync tests and update related OpenSpec records/evidence to mark the defect FIXED.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
scripts/sync-notebooklm-books.py Adds rename polling + stray adoption logic for oversized-source uploads.
tests/notebooklm/test_sync_notebooklm_books.py Updates the nlm fake to model renames and adds targeted tests covering slow/failed renames and stray adoption behavior.
openspec/changes/archive/2026-08-25-add-projection-title-uniqueness/tasks.md Adds a forward note documenting the defect resolution and linking the fix change.
openspec/changes/add-notebook-projection-identity/review/retirement-gate-clearance-2026-08-26.md Updates the clearance record to mark the defect fixed and reference the change.
docs/notebook-projection-migration-evidence-2026-08-24.md Updates evidence doc from OPEN DEFECT to FIXED with a summary of the two-part fix and test proof.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread scripts/sync-notebooklm-books.py Outdated
last = str(exc)[:200]
# The read-back IS the check.
try:
if any(str(r.get("title") or "") == title for r in _source_rows(handle)):
Comment thread scripts/sync-notebooklm-books.py Outdated
Comment on lines +1026 to +1029
body = nlm("source", "content", source_id, parse=False) or ""
except RuntimeError:
continue
if hashlib.sha256(str(body).encode()).hexdigest()[:16] != want:
Both findings on #438 are fail-open shapes inside the code written to close a
fail-open. Both reproduced before fixing.

(1) THE VERIFIER KEYED ON THE TITLE ALONE (Copilot). It asked "does any source
carry this title?" — so when a PRE-EXISTING source already wore it, the check
returned success while the source just uploaded sat un-renamed. Reproduced: one
rename attempt, immediate success, and the new id still absent from the book.
It now asserts the PAIR — this id bears this title — which is what was meant all
along.

(2) ADOPTION HASHED RAW STDOUT (Codex P1 + Copilot). `nlm source content` may
return the body inside a JSON envelope, which `source_content_text()` already
exists to tolerate, and the digests could therefore never match on a wrapped
response. Reproduced: hash(wrapped) 0c0f9446 vs hash(text) 0d4e2ca9. Fail-safe —
it degraded to a plain add — but A REPAIR THAT CANNOT FIRE IS NOT A REPAIR, and
the stray-adoption half of the previous fix was silently inert against the very
response shape the normalizer was written for.

ONE MECHANISM, NOT TWO. `_content_digest()` unwraps with the existing
`source_content_text()` and then hashes in the manifest's own form, and it is
applied to BOTH sides of every comparison. Normalising only the fetched half is
what created the mismatch; one shared function is what stops a second call site
drifting the same way. On already-plain text the unwrap is a no-op, so the
symmetry costs nothing.

The one other `hashlib.sha256` in the module is left raw ON PURPOSE and now says
so: it hashes REPO text from disk against the manifest's stored value, where
there is no provider response to unwrap. The digest FORM matches, which is what
keeps the two comparable.

Tests: a duplicate title no longer satisfies the verifier; adoption fires on a
JSON-wrapped body and issues NO add; and the digest is proven identical across
the plain, `{"value":{"content":…}}` and `{"content":…}` forms while still
differing on different content. Mutation-proved 3/3 — reverting the verifier to
title-only, dropping the unwrap, and hashing raw again each fail tests.

Gates: notebooklm 166 passed / 26 subtests (up 3), openspec 75/75 strict, hosting
validator 0 errors.

Co-Authored-By: Claude Fable 5 <[email protected]>
Copilot AI review requested due to automatic review settings August 27, 2026 22:45
@brettheap

Copy link
Copy Markdown
Contributor Author

Both fixed in 739fd3df. Both reproduced first — and both are fail-open shapes inside the code written to close a fail-open, which is the part worth noting.

1. @copilot — the verifier keyed on the title alone

Reproduced: with a pre-existing source already wearing the title, _rename_source_when_ready returned success after one attempt while the newly uploaded id sat un-renamed and absent from the book.

returned SUCCESS after 1 rename attempt — but 'NEW' is still un-renamed
ids present: ['OLD']

It now asserts the pair — this id bears this title — which is what was meant all along. Pinned by test_a_DUPLICATE_TITLE_does_not_satisfy_the_rename_verifier.

2. @codex P1 (+ @copilot) — adoption hashed raw stdout

Reproduced numerically:

source_content_text unwraps correctly: True
hash(raw wrapped)=0c0f9446…  hash(text)=0d4e2ca9…  match=False

So against a JSON-wrapped response the digests could never match. Fail-safe — it degraded to a plain add — but a repair that cannot fire is not a repair, and the stray-adoption half of the previous fix was silently inert against the very response shape source_content_text() exists for.

One mechanism, not two

_content_digest() unwraps with the existing source_content_text() then hashes in the manifest's own form, and is applied to both sides of every comparison. Normalising only the fetched half is what created the mismatch; one shared function is what stops a second call site drifting the same way. On plain text the unwrap is a no-op, so the symmetry costs nothing.

I checked the module's only other hashlib.sha256: it hashes repo text from disk against the manifest's stored value — no provider response, nothing to unwrap. Left raw deliberately, and it now says so in a comment so it doesn't read as an oversight. The digest form matches, which is what keeps the two comparable.

Proof

Three tests added (duplicate-title rejected; adoption fires on a wrapped body and issues no add; digest identical across plain / {"value":{"content":…}} / {"content":…} while still differing on different content). Mutation-proved 3/3 — reverting the verifier to title-only, dropping the unwrap, and hashing raw again each fail tests.

Gates: notebooklm 166 passed / 26 subtests (up 3) · openspec 75/75 strict · hosting validator 0 errors.

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create an environment for this repo.

@brettheap
brettheap merged commit 4805137 into main Aug 27, 2026
3 checks passed

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

scripts/sync-notebooklm-books.py:991

  • max_attempts uses floor division, which can stop retries up to one poll interval before the configured timeout would be reached (e.g., timeout=10, interval=3 => 3 attempts and at most ~6s of sleeping). Consider adding 1 (or using a ceil) so the attempt bound doesn’t shorten the wall-clock budget.
    max_attempts = max(1, RENAME_READY_TIMEOUT_S // RENAME_POLL_INTERVAL_S)

Comment on lines +962 to +966
def _source_rows(handle: str) -> list[dict]:
rows = nlm("source", "list", handle, "--json")
if isinstance(rows, dict):
rows = rows.get("sources") or []
return [r for r in (rows or []) if isinstance(r, dict)]
@brettheap
brettheap deleted the change/fix-oversized-source-rename branch September 2, 2026 18:55
brettheap added a commit that referenced this pull request Sep 3, 2026
…, and stop instead of minting a fifth duplicate (#604)

#438's two halves both missed live on 2026-08-28 (issue #462), each doing
exactly what it was written to do.

(b) The rename's read-back proved a MOMENT. Both applies passed the poll on
attempt 1 and the title later regressed to the temp filename when ingestion of
the 279KB body completed — exit 0 over a stranded source. After the poll
confirms, the title is now re-read after RENAME_SETTLE_DELAY_S (45s, the middle
of the band the evidence gives: the re-stamp arrives on ingestion completion,
and a rename against a FULLY INGESTED stray held 2+ minutes). One re-rename is
attempted; a regression that survives it raises on the existing loud path.

(a) Adoption could never match this class. The provider returned 281,645 bytes
for the 279,235-byte document, so the strict digest differed every time and the
documented safe fall-through to a normal add minted a fresh duplicate on every
run (canon went 3 strays to 4, silently). The strict digest stays the FIRST
gate; when it fails, a bounded fallback considers only strays within
ADOPTION_LENGTH_TOLERANCE_BYTES (4,096, containing the observed +2,410) of the
projected body and adopts the one whose provider-normalized digest matches —
JSON unwrap, NFC, line endings, per-line trailing whitespace, trailing
newlines, each named in the docstring and applied to BOTH sides. Length never
adopts by itself and a title pattern never adopts at all.

And where the old code uploaded another copy, the run now STOPS: a
within-tolerance stray that does not match, or more than one match, raises with
every candidate named, both byte lengths, and the hand adoption that worked
live. Zero within-tolerance strays still falls through to a normal add.

The oversized path also narrates itself on success (uploaded as <id>, renamed
on attempt N, settle re-verify: title held, adopted stray <id> by
strict|normalized digest) — both stray-minting applies were indistinguishable
in the transcript from clean ones.

Tests: tests/notebooklm/test_sync_oversized_adoption.py, a new file (the
sibling suite is 3,000 lines several lanes edit at once). 11 tests, every
provider call stubbed and both sleeps monkeypatched — the settle sleep is where
the provider's re-stamp is injected. Mutation-proved 6/6: dropping the settle
re-verify, falling through instead of stopping, a zero tolerance, dropping NFC,
dropping the per-line rstrip, and raising without the one retry each fail
tests. notebooklm suite 190 passed / 26 subtests in 4s.

Closes #462

Lane: openxfactory-smalls

Claude-Session: https://claude.ai/code/session_012WEcJUPMqpciTRSbJZzkh2

Co-authored-by: Claude Fable 5.1 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants