diff --git a/.github/ci/integration-paths.txt b/.github/ci/integration-paths.txt index 7880dfef0..0c82b7bd2 100644 --- a/.github/ci/integration-paths.txt +++ b/.github/ci/integration-paths.txt @@ -90,3 +90,5 @@ src/tests/workers/test_processing_layers_pg.py src/tests/workers/test_ingest_stored_pg.py src/tests/spine/test_d153_eligibility_pg.py src/tests/adapters/test_minio_object_operations.py +src/tests/adapters/test_minio_corpus_lock_loss.py +src/tests/adapters/test_minio_corpus_publication.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f7089a488..31dd3d1b9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -471,7 +471,7 @@ jobs: trap - EXIT test "$(docker compose --env-file .env exec -T postgres \ psql -U rememberstack -d rememberstack -Atc \ - 'SELECT version_num FROM alembic_version')" = 'p9_49_0070' + 'SELECT version_num FROM alembic_version')" = 'p9_51_0072' test "$(docker compose --env-file .env exec -T postgres \ psql -U rememberstack -d rememberstack -Atc \ 'SELECT count(*) FROM deployments')" = '1' diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f2bf9fcf9..fb9777099 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,6 +29,11 @@ Start a disposable MinIO container (Docker, curl and Python 3.11+ required): .github/ci/start-minio.sh REMEMBERSTACK_TEST_MINIO_ENDPOINT_URL=http://127.0.0.1:59000 \ uv run pytest src/tests/adapters/test_minio_object_operations.py -q +# Publication also needs the disposable PostgreSQL database configured as +# REMEMBERSTACK_DATABASE_URL. Run all database suites sequentially: +REMEMBERSTACK_TEST_MINIO_ENDPOINT_URL=http://127.0.0.1:59000 \ + uv run pytest src/tests/adapters/test_minio_corpus_publication.py \ + src/tests/adapters/test_minio_corpus_lock_loss.py -q # After testing: docker rm --force rememberstack-minio-test ``` diff --git a/decisions.md b/decisions.md index 861162c6c..12a2e068a 100644 --- a/decisions.md +++ b/decisions.md @@ -8076,6 +8076,11 @@ retains D54, D56, D67, D74, D140 and D152 correctness boundaries. **Status:** accepted design (owner direction and reviewer dispositions 2026-11-13); implementation is separate. **Date:** 2026-11-13. D154 is reserved for pagination PR #589. +**Scaling amendment (Claude, design owner, 2026-11-13):** the original ordinary +publication suffix scan and no-stored-path clause are superseded by the recorded +folder set below. Full scans remain for reconcile and forget/restore; the accepted +digest-verifying repair of late in-flight requests is unchanged. + **Context.** The customer mount must be a browsable corpus, with one real folder per document holding its original and every reader-useful derivative. Snapshot stubs and separate raw/artifact mounts cannot provide that interface. Originals @@ -8105,15 +8110,22 @@ There are no users requiring migration, aliases or a transition layout. processed version means no folder. D117 storage/parking is retained; its latest-stored-original P3 view is replaced. - **Idempotent publication through existing work.** `publish_corpus(doc_id)` reads - current DB authority for the desired folder/files, lists existing suffix-bearing - folders, writes desired files first, deletes other copies of this document, then - regenerates affected ancestor `_index.md` and root `llms.txt` **from the DB**. + current DB authority for the desired folder/files. Nullable + `documents.corpus_paths text[]` records the small set of possibly written folders; + commit the union with the desired path before any object write. List only these + prefixes, write desired files first, delete the other recorded folders, then + regenerate affected ancestor `_index.md` and root `llms.txt` **from the DB**. Never patch old index contents. One deployment advisory lock serializes these - operations; lost/reordered work self-heals on the next affected publish or - reconcile. Stale index-only remnants can be found by member `doc_id`/suffix and - regenerated without a historic path journal. Each committed trigger has a fresh - event target in existing `processing_state`, carrying only `doc_id`; retries - reuse the same row. No request table, lineage revision counter, pending-path + operations. Before every write/delete (including multipart requests), verify + ownership on that same session and the live claim; use bounded connect/read + timeouts without automatic write retries. Session loss can still let one issued + request land after a newer publisher: transient stale bytes are accepted and + repaired by digest-verifying reconcile, without coordination machinery. Keep + old paths recorded through ancestor-index repair, including after their last + object is gone, then reduce the set to `[desired]` (or null after removal). A + crash therefore leaves every possibly written path and affected ancestor known. + Each committed trigger has a fresh event target in existing `processing_state`, + carrying only `doc_id`; retries reuse the same row. No request table, lineage revision counter, pending-path journal, publication-receipt table or persistent directory-membership cache. Self-host classes and managed pushed `run_task` use the same engine handler, leases, retries and announcements. @@ -8123,9 +8135,20 @@ There are no users requiring migration, aliases or a transition layout. match. Clear it on relevant changes and before writes. MCP `p3_path` computes the current relative path only behind a matching marker for the served selected version; otherwise null. Readiness `p3` uses that same per-document guard, never - a global recent-build timestamp. There is no whole-tree snapshot guarantee. -- **Repair and navigation stay simple.** Full reconcile uses the same selectors/ - renderer, removes orphans and regenerates indexes. Deterministic bounded member + a global recent-build timestamp. It means the current inputs were published + once, not that a late request from a dead publisher cannot change the bytes. + There is no whole-tree snapshot guarantee. +- **Repair and navigation stay simple.** Full reconcile uses one full-store + listing with the same selectors/renderer, removes orphans, repairs `corpus_paths` + and regenerates all indexes. Ordinary publication renders/HEAD-checks only the + old/new ancestor chain and its radix pages plus root `llms.txt`, from current DB + membership. Reserved `~/` page subtrees make obsolete pages listable without + visiting unrelated document folders. A fresh tree initializes the fixed type + indexes once. Every corpus object carries + its expected SHA-256 in metadata; verify mode compares it with the desired digest + and rewrites mismatches/missing metadata even behind a matching marker. Periodic + verification repairs the bounded, rare DB-session-loss/in-flight-request race. + Deterministic bounded member tables, root `llms.txt` and navigation radix pages remain; page splits/merges never move document folders or recopy survivors. No Tier-1 `documents/`, facets, entities, K links or `_paths/` id index. Store `doc_id` and exact-version @@ -8148,17 +8171,19 @@ There are no users requiring migration, aliases or a transition layout. drain, verification and restore replay. Page through keys for the document's suffix, erase every matching folder/upload and controlled serving/cache copy, then regenerate/prune indexes from scrubbed DB authority, including index-only - remnants. Never wipe the corpus or recopy surviving originals/media. The existing + remnants, and clear `corpus_paths`. An empty set never skips the full scan. Never wipe the corpus or recopy surviving originals/media. The existing `doc_id` suffices in immutable intent; no historic friendly paths are needed. Re-honor even completed manifests on independent restores; object-version purge requirements are stated in [E0 §6.7](plan/designs/e0_files_design.md#67-hard-forget-and-restore-erase-the-document-regenerate-indexes). **Rationale and alternatives.** A copied original makes each folder self-contained; a single completed reading avoids pairing v2 bytes with v1 text. Recomputing from -authority plus suffix discovery replaces revision/journal/receipt coordination. +authority plus a small committed folder set replaces revision/journal/receipt +coordination. Per-document suffix scans would make N ingests quadratic in listed +objects; recorded paths bound ordinary object IO to that document and its ancestors. The 96-bit suffix makes accidental collision negligible without reservation state; -its unkeyed derivation survives restore without a secret. A paged key scan costs -listing work, while per-document erasure leaves other documents' bytes in place. +its unkeyed derivation survives restore without a secret. Rare repair/forget scans +recover unrecorded copies, while per-document erasure leaves other bytes in place. MCP and suffix search meet addressing needs without a second id index. Shared indexes always regenerate from DB authority, so neither event ordering nor old index contents determine truth. S3 interoperability uses the existing adapter. diff --git a/plan/analysis/corpus_document_folders.md b/plan/analysis/corpus_document_folders.md index 457e28956..d0dfee988 100644 --- a/plan/analysis/corpus_document_folders.md +++ b/plan/analysis/corpus_document_folders.md @@ -49,7 +49,7 @@ and D147 (`run_task`); D101 itself concerns ingest attribution. | What about parked uploads? | Retain D117 storage/parking and raw API access; no folder until a version completes | Losing early mount visibility is explicit, smaller than a mixed-version tree, and never promotes unfinished testimony | | Type/topic | Engine-derived small type enum; stored nullable topic from root placement | Asking the model for types or reconciling topics corpus-wide adds unstable choices and extra paid work | | Stable handle | Existing `doc_id`; a deterministic 96-bit SHA-256 suffix; MCP `p3_path` or mounted suffix search | A suffix reservation and radix id index add state without improving the required lookup or erasure contract | -| Maintenance | Idempotent `publish_corpus(doc_id)` recomputes paths/files and indexes from the DB; one deployment advisory lock serializes publication | Revision counters, path journals, publication receipts and membership tables duplicate authority and introduce recovery state | +| Maintenance | Idempotent `publish_corpus(doc_id)` recomputes desired files from the DB, lists only recorded possibly written folder paths, and regenerates their ancestor indexes; one deployment advisory lock serializes publication | Whole-store suffix discovery per document makes N ingests require quadratic object listing; revision counters, receipts and membership tables add unnecessary coordination | | Read consistency | Atomic objects, explicit folder-level in-progress marker, indexes written after files | S3 has no portable multi-object directory transaction; snapshot isolation would restore the recopy cost or add a pointer filesystem | | Hard forget | List by deterministic document suffix, erase that document's copies, then regenerate indexes from scrubbed DB authority under D74 | Resetting the store empties every customer's mount and recopies every survivor to forget one document; recording historic friendly paths in portable intent is unnecessary | | Provider API | S3 operations, streamed across stores when necessary | Native GCS and mandatory server-side copy add provider-specific behavior with no required benefit | @@ -96,35 +96,52 @@ retries deliver that same processing row. A→B→A commits get separate ordinar rows, but every handler reads current authority, so their delivery order cannot restore an obsolete reading. Existing attempts, leases and DLQ rules stay intact. -The sole new per-document state is nullable `corpus_published_revision`, a digest -of the current DB-selected export inputs, desired path and builder policy. Clear -it when those inputs change and before publication; set it only after files, -cleanup and index regeneration succeed and authority still matches. MCP computes -the current path only behind that match; readiness uses the same guard. No stored -published path, reader-inventory receipt or pending-path list is needed. Type/ -topic/title changes invalidate the digest by comparison; navigation pagination -changes indexes only, not physical document paths or other documents' markers. - -One deployment advisory lock keeps concurrent publishers from overwriting shared -indexes with competing snapshots and also serializes same-document copies. Each -publish lists existing suffix-bearing folders, streams the desired files, deletes -other copies, and renders affected ancestor indexes and root `llms.txt` afresh from -the DB. Never patch old index contents or replay queued paths. If a crash deletes -the last old-folder object before its parent index is repaired, a paged scan of -navigation indexes can still discover the stale member link by `doc_id`/suffix; -regenerate that entire index from the DB. Reconcile renders all current navigation -indexes and prunes obsolete ones. These are recomputable operations, not a journal. -The inventory's member links identify documents explicitly, so retry discovery -does not depend on titles. Empty obsolete topic/page indexes are pruned against -DB membership. Lost or reordered shared-index writes are corrected by the next -affected publish or reconcile. - -Suffix discovery requires a paged key scan because the navigation prefix can move; -it is O(corpus keys), not O(corpus bytes), and ordinary publication recopies only -the selected document. Navigation page splits/merges rewrite metadata only. -Measure listing cost, lock wait and large-media transfer cost. Full reconcile is -repair, not a prerequisite for every edit. There is no new scheduler or persistent -navigation-membership cache. +The publication marker, `corpus_published_revision`, is a nullable digest of +current DB-selected export inputs, desired path and builder policy. Clear it on +input changes and before publication; set it only after files, cleanup and index +regeneration succeed and authority still matches. MCP and readiness use that +match. The marker and the cleanup paths below do not enter paid-work identities. + +### Ordinary-publication scaling correction (Claude, design owner, 2026-11-13) + +The original no-path-state choice is superseded. Slice 3 listed every object to +find one document's suffix, then rendered and HEAD-checked every shared index. +At 100,000 documents with five reader objects each, a single publish lists about +500,000 keys. Repeating this for N ingests is quadratic listing work, despite +copying only each changed document. Avoiding a small DB field does not justify +that cost at the required millions-of-documents scale. + +Record one nullable `documents.corpus_paths text[]`: the small set of folder paths +this document may have written. Before any object write under a new path, commit +the union of the recorded paths and that path on the advisory-lock session. A move +from `pdf/finance/a--` to `pdf/legal/b--` therefore records both +before the first new object can exist. Write the new folder, remove the old ones, +and repair the ancestors of every recorded path before reducing the set to the +new path (or null after removal). Keeping old paths through index repair also +covers a crash just after deleting the last old object. A retry recomputes current +authority and can find every possibly written folder and stale ancestor without +looking through unrelated objects. No receipt table, path reservation or separate +membership cache is needed. + +Only affected ancestor indexes and root `llms.txt` are rendered from current DB +membership. Stream DB selections for membership/counts; retain document rows only +for affected indexes and their immediate topic rows. Never parse old Markdown as +authority. Put radix pages inside each index's reserved `~/` subtree, so paged +listing of that subtree finds obsolete pages without visiting sibling document +folders. Splits/merges change only navigation metadata. A fresh tree initializes +the fixed eleven type indexes once because root navigation links even empty types. +The builder-policy change rekeys P3 exports only, with no paid-work reuse change. + +Full-store scans remain the simple repair operation for reconcile and D74 +forget/restore replay: an independently restored bucket may contain paths that +PostgreSQL never recorded. Reconcile unions discovered and recorded paths, +rebuilds all navigation and repairs path state for served and unselected documents. +Portable forget intent still needs only `doc_id`, not friendly-path history. The +accepted digest-verifying repair of rare late writes after DB-session loss is +unchanged. Alternatives rejected: scanning suffixes per ordinary publish remains +quadratic; a directory-membership table or journal duplicates DB authority; using +recorded paths as navigation membership would confuse cleanup state with the +current served reading. Hard forget uses the same suffix scan after authority scrub. It also enumerates navigation-index keys and regenerates/prunes them against the scrubbed DB, covering @@ -138,6 +155,79 @@ mount/cache copies must acknowledge purge before serving reopens; external clien downloads are outside library-controlled active stores. An expired worker lease alone does not prove that an object request stopped. +## Slice 3 lock-loss counterexample (2026-11-13) + +**Historical stop, resolved by the reviewer disposition below.** Implementation +originally stopped under the owner's explicit instruction: if a single +idempotent recomputation is insufficient, report the concrete failure instead of +adding coordination machinery. The disposition below amends D155 and its binding +design to accept and repair this specific ordinary-publication race. + +[The executable reproducer](../../src/tests/adapters/test_minio_corpus_lock_loss.py) +uses the real PostgreSQL test database and real MinIO started with +`.github/ci/start-minio.sh`. A small HTTP relay delays delivery of one complete +signed PUT after boto3 has sent it. It forwards the request and MinIO's response +without mocking storage. The test controls ordering with thread events, not +timing sleeps: + +1. Writer A owns a deployment-scoped PostgreSQL advisory lock and sends the + ready document `_index.md` for the original export identity. The relay receives + its complete request and holds it in flight. +2. The test terminates A's PostgreSQL backend with `pg_terminate_backend`. Writer + B now successfully acquires the same advisory lock. The test also confirms + A's next DB operation fails: lock loss is observable, but the issued PUT + cannot be retracted by that observation. +3. A canonical title change from `Annual Report` to `ANNUAL REPORT` changes the + export identity while preserving its normalized physical path. B re-reads + authority, renders and writes every selected reader file and navigation index, + then locks the document row, confirms the desired digest and sets its marker. + The ready index contains B's identity and the old request is still in flight. +4. The relay releases A's old PUT. Real MinIO atomically replaces B's ready index + with A's old bytes. The document marker still equals the current DB-derived + digest, but the ready-folder identity is from the previous export. + +The original counterexample passed by asserting this **failure state**. It +characterized the proposed primitives; the current regression extends it with +the accepted repair and refusal of further writes described below. The upload +thread is joined before exit: it does not require a +detached upload, a new stale event, a lost announcement, or a stale final marker +write from A. B may finish while A's synchronous request remains outside its +control. A later recomputation could repair the index, but the last ordinary event +can already have succeeded; the marker cannot certify that its files survived. + +This violates E0 §6.5's requirement that claim/lock loss settle or fence in-flight +external IO **before another writer can proceed**. Renewing a lease, checking the +DB before/after each operation, or joining IO before a handler returns does not +keep the PostgreSQL lock held after its session is terminated. An HTTP timeout +also does not establish that a remote request cannot commit. The same ordering +can affect a file replacement or removal; delete/forget/restore have deliberately +not been wired or exercised by this change. + +**Accepted reviewer disposition (Claude, design owner, 2026-11-13).** Prevent +where cheap, repair by digest, and do not add coordination machinery. Check the +same lock session before every mutation, bound provider connect/read timeouts and +multipart units, and stop issuing requests on lock/claim loss. One already-issued +request can still land late; timeout alone cannot retract it. Accept that rare +transient staleness and define the marker as “current inputs were published once”. +Attach the expected SHA-256 to every corpus object and have verifying reconcile +rewrite mismatches, absent objects and missing metadata, including behind a matching +marker. This preserves the small protocol instead of introducing durable fences, +receipts or journals. Periodic verification is wired with activation in slice 4; +D74's erasure barrier/drain remains binding and separate. The reproducer becomes +an implementation regression: the late write really lands, further requests from +the dead publisher are refused, and verifying reconcile repairs the newer bytes. +The accepted contract is reconciled in D155 and E0 §§5–7. No ingestion identity or +paid-work reuse boundary changes (Rule 4). + +Reproduce with `REMEMBERSTACK_DATABASE_URL` pointing to a disposable PostgreSQL +test database (the imported fixture resets its schema): + +```bash +.github/ci/start-minio.sh +REMEMBERSTACK_TEST_MINIO_ENDPOINT_URL=http://127.0.0.1:59000 \ + uv run pytest src/tests/adapters/test_minio_corpus_lock_loss.py -q +``` + ## Provider facts checked on 2026-11-13 Google documents an S3 interoperability path using its XML endpoint and HMAC diff --git a/plan/designs/e0_files_design.md b/plan/designs/e0_files_design.md index ff927c76f..25fb5d834 100644 --- a/plan/designs/e0_files_design.md +++ b/plan/designs/e0_files_design.md @@ -676,7 +676,8 @@ mutable capability in `ports/object_store.py`, implemented by the same adapters: - `replace_stream(key, chunks, storage_class)`: create or atomically replace one complete object from bounded chunks; a small file supplies one chunk. - `iter_keys(prefix)`: bounded-memory, fully paginated key enumeration; empty - prefix means this deployment's whole corpus store. Error on incomplete/repeated + prefix means this deployment's whole corpus store, used only by reconcile and + forget/restore repair, never ordinary publication. Error on incomplete/repeated continuation tokens. Recursive deletion uses path boundaries (`path/`, never a sibling such as `path-other/`). - Idempotent exact `delete(key)`; missing keys succeed. Reuse this implementation @@ -695,8 +696,14 @@ published-object absence without claiming unfinished parts were checked or erase immediately. Mountable's gateway expires abandoned uploads after seven days; provider qualification records the deployed expiry/sweep guarantee. Other listing errors and all abort failures remain failures. No whole-video buffering or durable -worker-local state. A qualified adapter provides complete-object replacement and -read/write/delete/list consistency; mount caches have a separate lifetime. Existing raw create-only +worker-local state. Replacement accepts the expected SHA-256 for object metadata +and exposes a metadata read for digest verification. A caller-supplied guard runs immediately +before each provider mutation, including multipart create/part/complete requests; +cleanup may abort its own failed upload even after losing ownership. Every +provider request has bounded connect/read timeouts; one multipart part +is the largest upload unit. A qualified adapter provides complete-object +replacement and read/write/delete/list consistency; mount caches have a separate +lifetime. Existing raw create-only preconditions must also be qualified on each endpoint, not silently weakened. **Managed mount CLI contract.** `remember mount DIR` obtains a one-time mount @@ -875,8 +882,10 @@ of that document across title/topic/type moves. Navigation **index pages**, not document folders, split when a member table exceeds B entries (starting point B=150, a measured/versioned projection setting). Use deterministic radix pages over each child's key (`d:` for documents, -`t:` for topic branches), encoded into base32. Reserved `~` -page-directory prefixes distinguish index machinery from topics. Each split has +`t:` for topic branches), encoded into base32. Each index keeps +its pages under a reserved `~/` subtree (for example `pdf/~/mqq/_index.md`), +with recursive splits under the page's own `~/` subtree. This lets publication +list obsolete pages without enumerating sibling topic or document folders. Each split has at most 32 next-character branches; collapse single-child prefixes, recursively split overloaded pages and merge when membership falls to B or below. All rows, counts and page boundaries are computed from DB membership. @@ -958,53 +967,75 @@ cannot write; seed current-policy work instead. One deployment-scoped PostgreSQL advisory lock serializes publication, including index regeneration, normal removal, reconcile and forget's authorized internal calls. Reuse caller lock ownership for internal calls. Re-read authority after -taking the lock. Keep the claim alive while streaming; loss of claim/lock stops -writes and requires settling or fencing in-flight external IO before another -writer or forget can proceed. A lease expiry alone cannot prove IO stopped. -No detached uploads survive a handler. This small lock avoids competing writes to -the same folder and shared indexes without a durable coordination protocol. +taking the lock. Keep the claim alive while streaming. Before each object write +or delete, confirm ownership of that advisory lock on the same PostgreSQL session +and that the work claim is still live; abort further mutations on loss. Check +before each multipart request too, so one bounded part is the largest upload +unit. Configure bounded S3 connect/read timeouts and disable automatic write +retries that could issue a new request after lock loss. No detached uploads +survive a handler. + +A PostgreSQL session can die while its process still runs and an already-issued +object request can complete after a successor acquired the lock. The remaining +window is one in-flight request, not fenced external IO. This rare race can leave +stale complete bytes (or a missing object after a late delete) even after a newer +publication set its marker. This is accepted for ordinary publication: prevent +further requests cheaply and repair by digest, without a fence, journal or extra +coordination tables. It does not weaken D74's separate drain/barrier requirement +for erasure (§6.7). A lease expiry alone cannot prove IO stopped. For each publish: 1. Clear the publication marker before any store mutation. Compute the desired - path and inventory from the DB, then page through existing corpus keys to find - every document-folder component ending `--/`. Match the complete path - segment, not a substring; stop interpreting navigation components at the first - document folder, so reader-asset names cannot impersonate another document. - Topic normalization cannot produce the reserved double-hyphen leaf delimiter. - Collect existing old/new ancestors in memory; no historic paths are persisted. + path and inventory from DB authority. Read nullable + `documents.corpus_paths text[]`, the small set of folder paths this document + may currently have objects under. Before writing any object at a new path, add + that path to the set and **commit on the advisory-lock session**. Ordinary publication lists only these + document prefixes, never the entire store to find a suffix. For example, a + title/topic move records both the old and desired folders before the first new + object write. The field is cleanup state, not desired authority, a history or + a navigation-membership cache; a null value means no recorded paths. 2. If a served reading exists, write its desired folder **files first**. Mark an existing folder `_index.md` as `updating`, stream the selected original and allowlisted derivatives, confirm hashes/complete-object writes, and remove obsolete files at that path. A multipart ETag is not a SHA-256 checksum; use upload checksums or streamed read-back as required. Write `document.json`, then the ready folder `_index.md`, with the same deterministic export identity. -3. Delete every other folder carrying this document's suffix, including partial - unindexed copies; if no reading survives, delete every matching folder. Missing - objects succeed. Handle abandoned multipart uploads under §5's provider rule. -4. Regenerate affected old/new ancestors' `_index.md` bottom-up and root `llms.txt` - **from the DB**, never by editing previous index contents. Membership, paths, - counts and summaries come from current live served selections, not events or - a projection membership table. Prune navigation directories absent from DB - membership. If a crash already removed the last old-folder key, a paged scan of - navigation indexes can discover stale member links by `doc_id`/suffix and add - their ancestors to this regeneration; their old contents are discovery only. - Thus retries need neither a pending-path journal nor a stored publication path. - Index-page splits/merges rewrite only navigation metadata, leaving document - paths and unrelated originals/media unchanged. -5. After files, removal and indexes succeed, re-read the desired digest in a DB - transaction and set `corpus_published_revision` only if it still matches what - was published. Otherwise leave it null and retain/enqueue work for current - authority. Updating transactions and final marker writes serialize on the - document row; neither can erase the other's wake-up. Delayed/reordered work - always recomputes current state. No journal, publication-receipt table, path - reservation or directory-membership table is kept. - -Normal delete uses the same removal synchronously before D135 reports success; -an object/index failure reports failure and leaves ordinary durable work for -retry. Deletion and forget cannot be disabled with claims/facts switches. Removal -success is absence verified by suffix listing and index regeneration, with the -existing work row recording completion; it needs no separate empty receipt. +3. Delete every other recorded folder, including partial unindexed copies; if no + reading survives, delete all recorded folders. Missing objects succeed. Handle + abandoned multipart uploads under §5's provider rule. Keep old paths recorded + until their navigation has also been repaired: a crash after deleting the last + old-folder object must still leave its ancestors discoverable on retry. +4. Regenerate only the affected old/new ancestors' `_index.md` chain, including + their rendered radix pages, bottom-up, plus root `llms.txt`, **from the DB**. + Membership, paths, counts and summaries come from current live served + selections, not events, recorded cleanup paths or previous index contents. + Stream DB selections for counts and retain members only for affected indexes. + List each affected index's reserved `~/` subtree to remove obsolete pages; + prune topic indexes absent from DB membership. Never enumerate unrelated + object folders or render/HEAD-check the whole navigation tree. A fresh tree + creates the fixed eleven type indexes once, since root links include empty + types. Ordinary object work is proportional to this document's recorded + folders plus its ancestors' indexes. Page splits/merges never move document + paths or recopy unrelated originals/media. +5. After files, old-folder removal and navigation succeed, reduce `corpus_paths` + to exactly `[desired_path]`, or null after removal. A crash at any earlier + point leaves all possibly written paths recorded for the next publish or + forget. Then re-read the desired digest in a DB transaction and set + `corpus_published_revision` only if it still matches what was published. + Otherwise leave it null and retain/enqueue work for current authority. + Updating transactions and final marker writes serialize on the document row; + neither can erase the other's wake-up. Delayed/reordered work always recomputes + current state. No separate journal, publication-receipt table, path reservation + or directory-membership table is kept. + +Normal delete uses the same recorded-path removal synchronously before D135 +reports success; an object/index failure reports failure and leaves ordinary +durable work for retry. Deletion and forget cannot be disabled with claims/facts +switches. Removal success is absence under every recorded path plus repaired +indexes, with the existing work row recording completion; it needs no separate +empty receipt. Full suffix discovery remains mandatory for forget/restore (§6.7) +and available through reconcile to recover anything missing from the DB set. **What readers can observe.** Objects are replaced atomically, folders and trees are not. A new folder can be partly visible to direct `ls`; moves can briefly @@ -1015,8 +1046,11 @@ snapshot is promised. Check the ready folder identity before/after a read, or us immutable version-addressed source handles when exactness matters, including for cached/ranged media reads. The marker certifies a successful publication of this document's current inputs; it is not a whole-tree snapshot. Failed or interrupted -publication leaves it null, and the next affected publish or reconcile regenerates -shared indexes from authority. +publication normally leaves it null, and the next affected publish or reconcile +regenerates shared indexes from authority. The marker means “these current inputs +were published once”, not that no late request from a dead publisher can change +those bytes. Digest-verifying reconcile repairs that accepted transient staleness; +a matching marker never skips verification. ### 6.6 Repair, readiness and processing layers @@ -1024,9 +1058,18 @@ shared indexes from authority. selectors, renderer and publisher above. Stream DB lineages and paged key listings; delete unknown/orphan objects, render all current navigation indexes from the DB, and prune obsolete index keys even if no document folder remains there. Share -discovery/index work across the run rather than scanning the whole store anew -for every document. Existing originals/derivatives whose paths and hashes match -need not be recopied. A retry +one full-store discovery pass across the run; ordinary publication never does +this scan. Union discovered suffix folders with recorded `corpus_paths`, repair +each served document's set to its desired path after cleanup/navigation, and clear +sets for unselected/deleted documents after their objects are removed. This repairs +paths that an independently restored bucket or incomplete DB state missed. Match +the first complete `--` document-folder component, never a similarly named +asset below it. Reconcile has a verify mode: compare each desired object's stored +SHA-256 metadata with its desired digest, rewriting mismatches and missing metadata (or +missing objects), including files whose document has a matching marker. Delete +orphans through the same publication code path. Existing originals/derivatives +whose paths and digest metadata match need not be recopied. Periodic verifying +reconcile bounds how long rare late-request damage persists. A retry recomputes everything, with no progress reconstruction or snapshot registry. Without concurrent authority changes, incremental maintenance and reconcile converge to identical keys and bytes. Export identities are deterministic digests; @@ -1079,6 +1122,9 @@ paths, suffix reservations or a corpus-wide purge scope. it does not reset document folders or require a historic path list. Verify no matching folder, forgotten title/summary/member entry or controlled serving copy remains; report unfinished-upload coverage under §5's provider rule. + Clear `corpus_paths` after object cleanup and navigation repair; its friendly + paths must not survive a completed forget. Always do the full suffix scan even + when the recorded set is empty, including on restore replay. Reopen only after every D74 store acknowledges erasure within that scope. Any error leaves the barrier closed and retries the same idempotent procedure. 4. Before a restore serves traffic or controlled mounts, re-honor **every** portable @@ -1106,11 +1152,16 @@ Arbitrary downloaded client bytes remain outside the library-controlled boundary 3. Enabled E1/E2/E3 work completes. The transaction serving this version clears its publication marker and enqueues ordinary `publish_corpus` work. Sources-only deployments use their own completion boundary. -4. The self-host worker or managed pushed task recomputes DB inputs, lists suffix - matches and writes files to +4. The self-host worker or managed pushed task recomputes DB inputs, commits the + desired folder into `corpus_paths`, lists only recorded document folders and + writes files to `pdf/finance/annual-reports/acme-2023--9bf3e4c0c2d4861075a6ef82/`. It deletes other - folders of this document, regenerates ancestors/root from the DB and sets the - nullable marker after success. `p3` is ready; `p3_path` resolves that folder. + recorded folders of this document, regenerates their ancestors/root from the DB, + reduces the set to the desired folder and sets the nullable marker after success. Every object records its expected content digest; + requests are bounded and each mutation checks the same lock session. `p3` is + ready; `p3_path` resolves that folder. A late request after DB-session loss may + transiently replace newer bytes despite its matching marker; verifying + reconcile compares digest metadata and restores the newer reading. 5. A customer mounts read-only and opens Markdown, images or `original.pdf` in place. A newer stored upload leaves the completed folder intact until served and published. A type/topic/title change moves it; re-resolve `doc_id` via MCP diff --git a/plan/designs/postgres_schema_design.md b/plan/designs/postgres_schema_design.md index 9532e6668..2c43d79fd 100644 --- a/plan/designs/postgres_schema_design.md +++ b/plan/designs/postgres_schema_design.md @@ -1180,6 +1180,7 @@ CREATE TABLE documents ( current_version_id uuid, -- → document_versions; the SERVED version: newest non-deleted version whose representation completed processing (real FK added after that table) title text, -- best-effort current title; P3 friendly path can move corpus_published_revision text, -- nullable D155 digest of successfully published DB inputs/path/policy; no desired counter + corpus_paths text[], -- nullable D155 set of possibly written folders; commit before IO, reduce after cleanup/navigation first_seen_at timestamptz NOT NULL DEFAULT now(), last_observed_at timestamptz, -- last connector observation (watch loop heartbeat) deleted_at timestamptz, -- lineage tombstone for hard-delete/forget (§13) @@ -2265,9 +2266,9 @@ CREATE INDEX ix_obsadjud_live ON observation_adjudications (observation_i ## 10. Corpus publication progress and live graph catalog (D155, D98) P1 and the live graph are current PostgreSQL-derived state, without immutable -snapshot registries. D155 P3 is an idempotently maintained document tree; its only -new per-document state is nullable `documents.corpus_published_revision` (§3). -It records the deterministic digest of the successfully published DB-selected +snapshot registries. D155 P3 is an idempotently maintained document tree with +two nullable fields on `documents` (§3). `corpus_published_revision` records the +deterministic digest of the successfully published DB-selected version/representation/structure, reader inventory/hashes, title/type/topic, desired folder path and builder policy. The desired digest is computed, never a stored lineage counter. There are no corpus request, receipt, pending-path, @@ -2290,18 +2291,29 @@ A delayed handler always recomputes from the DB, including A→B→A and deletio No ingestion work identity or attempt semantics change. The [E0 procedure](e0_files_design.md#65-incremental-work-publication-order-and-reader-observations) -uses a deployment advisory lock, paged suffix discovery, files-first writes, -old-copy deletion and index regeneration from DB authority. Only after success -and a final input check does it set the nullable marker. `p3_path` and readiness -compare it with the computed current digest; no stored published path, inventory -receipt or publication timestamp is needed. Shared-index membership and counts +uses a deployment advisory lock and `corpus_paths text[]`, the small set of folder +paths this document may currently have objects under. Commit the desired path's +union with this set before any object write; ordinary publication lists only +recorded prefixes. Write files first, remove other recorded folders and repair +only affected ancestor indexes/root from DB membership. Keep old paths through +index repair, so a crash after their last object deletion cannot lose the stale +ancestors. Then reduce the set to `[desired]` (or null after removal). Full-store +suffix discovery remains for reconcile and forget/restore; reconcile repairs the +set and all navigation, including after independent restores. The set is cleanup +state, never navigation membership or desired authority. Only after success and +a final input check does publication set the nullable marker. `p3_path` and +readiness +compare it with the computed current digest; no inventory receipt or publication +timestamp is needed. Shared-index membership and counts are SQL results over live served selections, not another projection table. Successful null topic has a non-null placement generation and null root placement path; failure has no complete placement generation. D74 uses manifest `doc_id` to erase only that document's suffix-bearing folders, clear its marker and regenerate/prune navigation indexes from scrubbed authority. -It leaves surviving original/media objects in place. Retry and restore replay +Clear `corpus_paths` after cleanup/navigation; a null set never skips full suffix +discovery on forget or restore replay. It leaves surviving original/media objects +in place. Retry and restore replay need no historic path list; complete local markers never skip independently restored stores. Work-row scrub/retention follows existing D74 rules and cannot reintroduce scrubbed authority. @@ -3005,7 +3017,7 @@ Labs."* | D36/D37 E0 sub-workers (incl. crossref version), storage split | `documents` (URIs + all four sub-worker versions), `document_reference_generations.crossref_version` | | D140 effective periods, section keys, version-aware references | `document_effective_periods` (+ view `memory_v1.document_effective_periods_live`, function `memory_v1.versions_in_scope`); `document_effective_time_events`; `document_version_scope` (projection); `document_versions.version_key`; `document_sections.section_key`/`own_content_hash`/`subtree_content_hash`; `chunks.text_origin_at`/`reuse_identity_hash`; `document_crossrefs` (version-grain, generation, binding, origin, section keys) + `document_reference_generations` | | D39 PageIndex sections + placement | `document_sections` (path/role/span/summary/placement) | -| D40/D155 P3 corpus filesystem | `documents.corpus_published_revision` + nullable root placement generation/path; ordinary `publish_corpus` work; suffix/path/membership computed from authority | +| D40/D155 P3 corpus filesystem | `documents.corpus_published_revision`, small `corpus_paths text[]` cleanup set + nullable root placement generation/path; ordinary `publish_corpus` work; suffix/desired path/membership computed from authority | | D41 claim-grain source-asserted validity | `claims.claim_valid_from/until/precision/kind` (immutable); `claims_as_of` recipe (evidence-only); an ordinary SQL filter in `claims_as_of`, and a confirmation predicate in D142 ranked nomination | | D45 planned K compilation (planner/writer/driver; mechanical routing; manifest staleness) | `knowledge_page_rules`, `knowledge_rule_keys`, `knowledge_plan_decisions`, `knowledge_compilations`; `knowledge_artifacts.inputs_hash/page_summary/parent_artifact_id` | | D46 compiled vs authored pages; ownership + quarantine | `knowledge_artifacts.page_kind/curation_path/content_hash` (+ `status='quarantined'`); citations binding in `knowledge_artifact_evidence`; authored review flags via `knowledge_refresh_queue ('authored_review')` | diff --git a/plan/plans/corpus_document_folders.md b/plan/plans/corpus_document_folders.md index 426563a5e..98736f78f 100644 --- a/plan/plans/corpus_document_folders.md +++ b/plan/plans/corpus_document_folders.md @@ -1,7 +1,7 @@ # Corpus document folders — implementation order (D155) -Date: 2026-11-13. Design-only plan; none of these slices is implemented by the -amendment. Authority: [E0 §§5–7](../designs/e0_files_design.md#5-mounting--the-corpus-is-the-customer-filesystem), +Date: 2026-11-13. Implementation sequence for the accepted design; the design +amendment itself shipped no runtime changes. Authority: [E0 §§5–7](../designs/e0_files_design.md#5-mounting--the-corpus-is-the-customer-filesystem), [D155](../../decisions.md#d155-the-corpus-filesystem-is-a-mutable-tree-of-document-folders). [Analysis](../analysis/corpus_document_folders.md) records the tradeoffs. @@ -46,11 +46,22 @@ only navigation metadata, keeping physical document paths and bytes in place. ## 3. Idempotent publication, ordinary work and reconcile Implement `publish_corpus(doc_id)` with the deployment advisory lock: re-read DB, -clear the marker, page through suffix matches, stream desired files first, delete -other document folders, regenerate ancestors/root from DB, then set the marker -only if inputs still match. Scan stale navigation entries by doc id/suffix when -retry has lost an old folder, and prune empty branches from DB membership. -Reconcile uses the same code and enumerates all indexes/orphans. Bind the handler +clear the marker, and read nullable `documents.corpus_paths text[]`. Commit the +union with the desired path before any object write. List only recorded folder +prefixes, stream desired files first, delete other recorded folders, regenerate +only their ancestors/root from DB membership (including radix pages), then reduce +the set to exactly the desired path and set the marker only if inputs still match. +Retain old paths through index repair, even after the last old object is deleted. +Use reserved `~/` page subtrees to list/prune obsolete ancestor pages without +listing sibling documents. Reconcile keeps one full-store listing, unions +discovered and recorded paths, repairs path state and enumerates all navigation/ +orphans. Forget/restore retains full scans for independently restored objects. +Check the same lock session and live claim before each mutation, including multipart requests; +bound S3 connect/read timeouts. Store expected SHA-256 metadata on every object. +Verifying reconcile rewrites missing/mismatching digests even when the document's +marker matches: a late in-flight request after DB-session loss can transiently +leave stale bytes, and the marker means current inputs were published once. +This accepted rare race adds no coordination machinery. Bind the handler to tests, leaving profile activation to slice 4. In each relevant authoritative transaction enqueue a fresh event target in the @@ -65,21 +76,44 @@ last old-folder key before index regeneration; replay duplicate/reordered events A→B→A, changing authority mid-copy, two writers sharing ancestors, deletion during publish, and lease/lock loss with in-flight IO. Confirm stale shared indexes are regenerated from DB. Incremental edits and empty-store reconcile must converge to -the same keys/hashes. Ordinary edits never recopy unrelated originals/media. +the same keys/hashes. Assert that ordinary publication never lists the root, +never touches unrelated navigation indexes, and records paths in a committed +transaction before object writes. A crash after the new ready folder but before +old-folder cleanup leaves both paths recorded and the next publish cleans them. +Ordinary edits never recopy unrelated originals/media. Test transactional enqueue rollback, rejection of inactive-policy work, publish after an earlier succeeded event, parked uploads, every layer profile, current-policy seeding, announcements and lost delivery; no hosted models. Register/test the same pushed class map in the cloud repo as integration, without making engine tests depend on it. + +Implementation: [PR #607](https://github.com/writeitai/remember-stack/pull/607) +builds the slice-3 capability with the handler bound only in tests. The companion +[cloud PR #1017](https://github.com/writeitai/ultimate-memory-cloud/pull/1017) +checks the existing non-convert pushed class; engine tests do not depend on it. +The initial implementation's full-store discovery and all-navigation pass are +replaced by the design owner's scaling correction: recorded document paths and +affected-ancestor navigation only. The fixed eleven type indexes initialize once +on a fresh tree; DB selections stream for membership/counts without rendering +unrelated branches. Full reconcile repairs missing path state and all indexes. +The P3 builder policy advances for the reserved radix subtree layout, without +changing paid-work reuse identities. The real MinIO matrix lives in +[`test_minio_corpus_publication.py`](../../src/tests/adapters/test_minio_corpus_publication.py) +and the late-request repair regression in +[`test_minio_corpus_lock_loss.py`](../../src/tests/adapters/test_minio_corpus_lock_loss.py). +Profile activation and periodic verification remain slice 4. + ## 4. Activate with deletion, forget and restore together Switch both profiles to the new publisher/reconcile and marker-based readiness. +Schedule periodic digest-verifying reconcile to repair rare late-request damage. Normal delete completes per-document removal before success or leaves durable retry work and reports failure. Adapt D74's existing purge capability: keep intent, barrier, drain/fence and verification; compute the suffix from manifest `doc_id`, erase that document's copies/uploads/caches, then regenerate/prune navigation -indexes from scrubbed DB authority. Never reset the bucket or recopy survivors. +indexes from scrubbed DB authority and clear `corpus_paths`. An empty recorded +set never skips the full suffix scan for forget/restore. Never reset the bucket or recopy survivors. Use E0 §6.7's object-version erasure rule. Remove snapshots/pointers and obsolete mount composition. Replay all manifests before readiness, including complete ones. diff --git a/src/rememberstack/adapters/selfhost/minio.py b/src/rememberstack/adapters/selfhost/minio.py index 5a02738fb..5118d6dfb 100644 --- a/src/rememberstack/adapters/selfhost/minio.py +++ b/src/rememberstack/adapters/selfhost/minio.py @@ -5,6 +5,7 @@ """ from base64 import b64encode +from collections.abc import Callable from collections.abc import Iterable from collections.abc import Iterator from hashlib import md5 @@ -17,6 +18,7 @@ import boto3 from botocore.client import Config from botocore.exceptions import ClientError +from pydantic import Field from pydantic import SecretStr from pydantic_settings import BaseSettings from pydantic_settings import SettingsConfigDict @@ -46,6 +48,8 @@ class MinIOSettings(BaseSettings): access_key: SecretStr secret_key: SecretStr region: str = "us-east-1" + connect_timeout_s: float = Field(default=5, gt=0, allow_inf_nan=False) + read_timeout_s: float = Field(default=30, gt=0, allow_inf_nan=False) class _StreamingBody(Protocol): @@ -284,7 +288,13 @@ def storage_class_of(self, *, key: ObjectKey) -> str | None: return response.get("Metadata", {}).get("storage-class") def replace_stream( - self, *, key: ObjectKey, chunks: Iterable[bytes], storage_class: str + self, + *, + key: ObjectKey, + chunks: Iterable[bytes], + storage_class: str, + sha256: str | None = None, + before_write: Callable[[], None] | None = None, ) -> None: """Replace only after normal input exhaustion; abort any failed multipart. @@ -296,6 +306,9 @@ def replace_stream( raise ValueError("invalid storage class") name = _validated_key(key=key) metadata = {"storage-class": storage_class} + if sha256 is not None: + metadata["sha256"] = sha256 + guard = before_write or (lambda: None) upload_id: str | None = None parts: list[_CompletedPart] = [] buffer = bytearray() @@ -309,6 +322,7 @@ def replace_stream( view = view[count:] if len(buffer) == _PART_SIZE: if upload_id is None: + guard() upload_id = self._client.create_multipart_upload( Bucket=self._bucket, Key=name, Metadata=metadata )["UploadId"] @@ -317,10 +331,12 @@ def replace_stream( upload_id=upload_id, content=bytes(buffer), parts=parts, + before_write=guard, ) buffer.clear() if upload_id is None: content = bytes(buffer) + guard() record_object_transfer(bytes_written=len(buffer)) self._client.put_object( Bucket=self._bucket, @@ -332,8 +348,13 @@ def replace_stream( return if buffer: self._upload_part( - name=name, upload_id=upload_id, content=bytes(buffer), parts=parts + name=name, + upload_id=upload_id, + content=bytes(buffer), + parts=parts, + before_write=guard, ) + guard() self._client.complete_multipart_upload( Bucket=self._bucket, Key=name, @@ -350,11 +371,18 @@ def replace_stream( close() def _upload_part( - self, *, name: str, upload_id: str, content: bytes, parts: list[_CompletedPart] + self, + *, + name: str, + upload_id: str, + content: bytes, + parts: list[_CompletedPart], + before_write: Callable[[], None], ) -> None: """Send one bounded part, counting attempted network bytes as for E0.""" if len(parts) == 10_000: raise ValueError("object exceeds the multipart part limit") + before_write() record_object_transfer(bytes_written=len(content)) result = self._client.upload_part( Bucket=self._bucket, @@ -366,6 +394,32 @@ def _upload_part( ) parts.append({"PartNumber": len(parts) + 1, "ETag": result["ETag"]}) + def abort_uploads( + self, *, prefix: str, before_write: Callable[[], None] + ) -> ObjectPurgeEvidence: + """Clean unfinished uploads under the caller's publication lock.""" + boundary = validate_object_path(prefix, prefix=True) + try: + for name, upload_id in self._iter_uploads(prefix=boundary): + if matches_object_prefix(name, prefix=boundary): + before_write() + self._abort_upload(name=name, upload_id=upload_id) + except _UploadListingNotImplemented: + return ObjectPurgeEvidence(multipart_uploads="provider_managed") + return ObjectPurgeEvidence(multipart_uploads="checked") + + def sha256_of(self, *, key: ObjectKey) -> str | None: + """Read the publisher's expected digest; multipart ETags are not hashes.""" + try: + response = self._client.head_object( + Bucket=self._bucket, Key=_validated_key(key=key) + ) + except ClientError as error: + if _error_code(error=error) in {"404", "NoSuchKey", "NotFound"}: + return None + raise + return response.get("Metadata", {}).get("sha256") + def delete(self, *, key: ObjectKey) -> None: """Idempotently remove one exact key, never its descendants.""" try: @@ -581,6 +635,9 @@ def _client(*, settings: MinIOSettings) -> _S3Client: region_name=settings.region, config=Config( signature_version="s3v4", + connect_timeout=settings.connect_timeout_s, + read_timeout=settings.read_timeout_s, + retries={"total_max_attempts": 1}, s3={"addressing_style": "path"}, max_pool_connections=_MAX_POOL_CONNECTIONS, request_checksum_calculation="when_required", diff --git a/src/rememberstack/adapters/selfhost/object_store.py b/src/rememberstack/adapters/selfhost/object_store.py index 6772f15fe..47c634eed 100644 --- a/src/rememberstack/adapters/selfhost/object_store.py +++ b/src/rememberstack/adapters/selfhost/object_store.py @@ -1,5 +1,6 @@ """Local object storage: immutable E0 creation and atomic corpus replacement.""" +from collections.abc import Callable from collections.abc import Iterable from collections.abc import Iterator import os @@ -13,6 +14,7 @@ from rememberstack.model import ObjectAlreadyExistsError from rememberstack.model import ObjectKey from rememberstack.model import ObjectKeyEscapesRootError +from rememberstack.model import ObjectPurgeEvidence class LocalFSObjectStore: @@ -49,10 +51,23 @@ def write_bytes( ) def replace_stream( - self, *, key: ObjectKey, chunks: Iterable[bytes], storage_class: str + self, + *, + key: ObjectKey, + chunks: Iterable[bytes], + storage_class: str, + sha256: str | None = None, + before_write: Callable[[], None] | None = None, ) -> None: """Publish a complete temporary file only after normal input exhaustion.""" - self._write(key=key, chunks=chunks, storage_class=storage_class, replace=True) + self._write( + key=key, + chunks=chunks, + storage_class=storage_class, + replace=True, + sha256=sha256, + before_write=before_write, + ) def _write( self, @@ -61,6 +76,8 @@ def _write( chunks: Iterable[bytes], storage_class: str, replace: bool, + sha256: str | None = None, + before_write: Callable[[], None] | None = None, ) -> None: if storage_class not in {HOT, COLD}: raise ValueError("invalid storage class") @@ -77,6 +94,8 @@ def _write( handle.write(chunk) handle.flush() os.fsync(handle.fileno()) + if before_write: + before_write() if replace: temporary.replace(path) else: @@ -87,6 +106,12 @@ def _write( f"object key {key.root!r} is already occupied; objects are immutable" ) from error marker.write_text(storage_class, encoding="utf-8") + digest = self._digest_path(key=key) + if sha256 is not None: + digest.parent.mkdir(parents=True, exist_ok=True) + digest.write_text(sha256, encoding="ascii") + else: + digest.unlink(missing_ok=True) finally: try: if temporary is not None: @@ -101,6 +126,22 @@ def storage_class_of(self, *, key: ObjectKey) -> str | None: marker = self._class_path(key=key) return marker.read_text(encoding="utf-8") if marker.exists() else None + def abort_uploads( + self, *, prefix: str, before_write: Callable[[], None] + ) -> ObjectPurgeEvidence: + """Local temporary files are private and removed by their owning writer.""" + validate_object_path(prefix, prefix=True) + return ObjectPurgeEvidence(multipart_uploads="checked") + + def sha256_of(self, *, key: ObjectKey) -> str | None: + """Read private digest metadata without putting sidecars in reader paths.""" + digest = self._digest_path(key=key) + return ( + digest.read_text(encoding="ascii") + if self._path_for(key=key).is_file() and digest.is_file() + else None + ) + def iter_keys(self, *, prefix: str) -> Iterator[ObjectKey]: """Stream files at or beneath a safe prefix, including the empty prefix.""" boundary = validate_object_path(prefix, prefix=True) @@ -122,6 +163,10 @@ def delete(self, *, key: ObjectKey) -> None: marker = self._class_path(key=key) if not marker.is_dir(): marker.unlink(missing_ok=True) + digest = self._digest_path(key=key) + if not digest.is_dir(): + digest.unlink(missing_ok=True) + self._prune_parents(digest.parent, root=self._metadata_root) self._prune_parents(path.parent, root=self._root) self._prune_parents(self._class_path(key=key).parent, root=self._metadata_root) @@ -137,26 +182,28 @@ def purge_objects( for boundary in boundaries: for key in self.iter_keys(prefix=boundary): self.delete(key=key) - # Include orphaned class records when object bytes are already absent. - for key in self._iter_class_keys(): + # Include orphaned metadata records when object bytes are already absent. + for key in self._iter_metadata_keys(): if any(matches_object_prefix(key.root, prefix=p) for p in boundaries): self.delete(key=key) def verify_objects_purged( self, *, keys: tuple[ObjectKey, ...], prefixes: tuple[ObjectKey, ...] ) -> None: - """Verify both reader bytes and private class records are absent.""" + """Verify reader bytes and private class/digest records are absent.""" remaining = [ key.root for key in keys - if self._path_for(key=key).is_file() or self._class_path(key=key).exists() + if self._path_for(key=key).is_file() + or self._class_path(key=key).exists() + or self._digest_path(key=key).exists() ] boundaries = tuple(validate_object_path(p.root, prefix=True) for p in prefixes) for boundary in boundaries: remaining.extend(key.root for key in self.iter_keys(prefix=boundary)) remaining.extend( key.root - for key in self._iter_class_keys() + for key in self._iter_metadata_keys() if any(matches_object_prefix(key.root, prefix=p) for p in boundaries) ) if remaining: @@ -177,11 +224,16 @@ def _path_for(self, *, key: ObjectKey) -> Path: def _class_path(self, *, key: ObjectKey) -> Path: return self._metadata_root / "classes" / validate_object_path(key.root) - def _iter_class_keys(self) -> Iterator[ObjectKey]: - root = self._metadata_root / "classes" - for path in root.rglob("*"): - if path.is_file(): - yield ObjectKey(path.relative_to(root).as_posix()) + def _digest_path(self, *, key: ObjectKey) -> Path: + return self._metadata_root / "digests" / validate_object_path(key.root) + + def _iter_metadata_keys(self) -> Iterator[ObjectKey]: + """Include orphaned class or digest records after interrupted cleanup.""" + for kind in ("classes", "digests"): + root = self._metadata_root / kind + for path in root.rglob("*"): + if path.is_file(): + yield ObjectKey(path.relative_to(root).as_posix()) @staticmethod def _prune_parents(path: Path, *, root: Path) -> None: diff --git a/src/rememberstack/adapters/selfhost/queue.py b/src/rememberstack/adapters/selfhost/queue.py index 121186528..d336b0007 100644 --- a/src/rememberstack/adapters/selfhost/queue.py +++ b/src/rememberstack/adapters/selfhost/queue.py @@ -20,6 +20,7 @@ from rememberstack.model import QueueRoute from rememberstack.model import RunResultOutcome from rememberstack.model import UTCDateTime +from rememberstack.spine.catalog_contract import lane_is_valid from rememberstack.spine.work_ledger import WorkLedger from rememberstack.workers import RunResult from rememberstack.workers import Worker @@ -120,8 +121,9 @@ def __init__( self._deployment_id = deployment_id self._routes = tuple( (stage, lane) - for lane in (ProcessingLane.STEADY, ProcessingLane.BACKFILL) + for lane in (ProcessingLane.STEADY, ProcessingLane.BACKFILL, None) for stage in stages + if lane_is_valid(stage=stage, lane=lane) ) self._bucket = bucket self._database_url = database_url diff --git a/src/rememberstack/core/corpus_export.py b/src/rememberstack/core/corpus_export.py index 9c9da9738..46506379a 100644 --- a/src/rememberstack/core/corpus_export.py +++ b/src/rememberstack/core/corpus_export.py @@ -26,7 +26,7 @@ from rememberstack.core.format_registry import family_for_mime from rememberstack.core.format_registry import FORMAT_MIMES -CORPUS_BUILDER_VERSION: Final = "p3-reader-2026.11b:d155" +CORPUS_BUILDER_VERSION: Final = "p3-reader-2026.11c:d155" CORPUS_TYPES: Final = ( "email", "chat", @@ -333,6 +333,15 @@ def encode(item: object) -> str: ).encode("utf-8") +def corpus_policy_version(policy: CorpusPolicy = DEFAULT_CORPUS_POLICY) -> str: + """One component identity per builder policy, never per publication event.""" + return ( + policy.builder_version + + ":" + + hashlib.sha256(json_bytes(asdict(policy))).hexdigest() + ) + + def desired_export_revision( document: CorpusDocument, *, policy: CorpusPolicy = DEFAULT_CORPUS_POLICY ) -> str: @@ -504,7 +513,9 @@ def render(path: str, entries: list[_Member], lead: list[str]) -> None: groups[key[:depth]].append(member) rows = [] for prefix, group in sorted(groups.items()): - child = posixpath.join(path, "~" + prefix) + # One reserved subtree makes obsolete pages listable without + # enumerating any physical document/topic folders beside it. + child = posixpath.join(path, "~", prefix) count = sum(member.count for member in group) rows.append( _Member( @@ -530,7 +541,7 @@ def render(path: str, entries: list[_Member], lead: list[str]) -> None: "", f"{count} member(s) in this subtree.", "", - "[Parent](../_index.md)", + f"[Parent]({_link(child, posixpath.join(path, '_index.md'))})", "", ], ) @@ -556,9 +567,16 @@ def _date(document: CorpusDocument) -> str: def render_navigation( - documents: Iterable[CorpusDocument], *, policy: CorpusPolicy = DEFAULT_CORPUS_POLICY + documents: Iterable[CorpusDocument], + *, + policy: CorpusPolicy = DEFAULT_CORPUS_POLICY, + ancestors: set[str] | None = None, ) -> dict[str, bytes]: - """DB membership only: fixed types, optional topics and bounded indexes.""" + """Render DB membership, optionally only a complete affected ancestor chain. + + Stream selections for counts, retaining members only for requested indexes + and their immediate topic rows. Unrelated navigation is never rendered. + """ directories: dict[str, list[_Member]] = { "": [], **{kind: [] for kind in CORPUS_TYPES}, @@ -566,26 +584,32 @@ def render_navigation( counts: dict[str, int] = defaultdict(int) for document in documents: parent = posixpath.dirname(document.path) - directories.setdefault(parent, []).append( - _Member( - "d:" + corpus_suffix(document.doc_id), - document.display_title, - document.path + "/_index.md", - 1, - ( - "document", - "1", - str(document.doc_id), - document.source_kind, - _date(document), - str(document.version_id), - document.root_summary or "no summary", - ), + if ancestors is None or parent in ancestors: + directories.setdefault(parent, []).append( + _Member( + "d:" + corpus_suffix(document.doc_id), + document.display_title, + document.path + "/_index.md", + 1, + ( + "document", + "1", + str(document.doc_id), + document.source_kind, + _date(document), + str(document.version_id), + document.root_summary or "no summary", + ), + ) ) - ) while parent: - directories.setdefault(parent, []) - counts[parent] += 1 + if ( + ancestors is None + or parent in ancestors + or posixpath.dirname(parent) in ancestors + ): + directories.setdefault(parent, []) + counts[parent] += 1 parent = posixpath.dirname(parent) counts[""] += 1 for directory in sorted(directories): @@ -593,6 +617,8 @@ def render_navigation( continue parent = posixpath.dirname(directory) name = posixpath.basename(directory) + if ancestors is not None and parent not in ancestors: + continue directories[parent].append( _Member( "t:" + name, @@ -622,6 +648,8 @@ def render_navigation( "Summary", ) for directory, members in sorted(directories.items()): + if ancestors is not None and directory not in ancestors: + continue intro = [ f"# {directory or 'Corpus'}", "", diff --git a/src/rememberstack/model/processing.py b/src/rememberstack/model/processing.py index 8e2515bb0..7daa760da 100644 --- a/src/rememberstack/model/processing.py +++ b/src/rememberstack/model/processing.py @@ -28,6 +28,7 @@ class ProcessingTarget(StrEnum): SNAPSHOT = "snapshot" KNOWLEDGE_ARTIFACT = "knowledge_artifact" KNOWLEDGE_DISPATCH = "knowledge_dispatch" + CORPUS_PUBLICATION = "corpus_publication" class ProcessingStatus(StrEnum): diff --git a/src/rememberstack/model/queue.py b/src/rememberstack/model/queue.py index 3494bd51a..8a834c2e2 100644 --- a/src/rememberstack/model/queue.py +++ b/src/rememberstack/model/queue.py @@ -41,6 +41,7 @@ class PipelineStage(StrEnum): DISPATCH_KNOWLEDGE = "dispatch_knowledge" # appended by WP-6.6 HARD_FORGET = "hard_forget" REVIEW_FACT_WINDOWS = "review_fact_windows" # appended by D140 WP-ET.7 + PUBLISH_CORPUS = "publish_corpus" class ProcessingLane(StrEnum): diff --git a/src/rememberstack/ports/object_store.py b/src/rememberstack/ports/object_store.py index c0acb60f4..4d4164e2f 100644 --- a/src/rememberstack/ports/object_store.py +++ b/src/rememberstack/ports/object_store.py @@ -1,11 +1,13 @@ """D61 immutable E0 creation and the separate D155 mutable object capability.""" +from collections.abc import Callable from collections.abc import Iterable from collections.abc import Iterator from typing import Protocol from typing import runtime_checkable from rememberstack.model import ObjectKey +from rememberstack.model import ObjectPurgeEvidence @runtime_checkable @@ -34,16 +36,38 @@ class MutableObjectStorePort(Protocol): """D155 complete-object operations, separate from immutable E0 creation.""" def replace_stream( - self, *, key: ObjectKey, chunks: Iterable[bytes], storage_class: str + self, + *, + key: ObjectKey, + chunks: Iterable[bytes], + storage_class: str, + sha256: str | None = None, + before_write: Callable[[], None] | None = None, ) -> None: """Create or atomically replace an object after exhausting bounded chunks. The producer validates its expected size/hash before returning normally; raising leaves the previous object intact. No whole-object buffering. A closeable source iterator is closed on success or failure. + Persist a supplied expected SHA-256 as metadata. Call ``before_write`` + immediately before each provider mutation (each multipart request too). + Aborting one's failed unfinished upload is cleanup, not publication. """ ... + def abort_uploads( + self, *, prefix: str, before_write: Callable[[], None] + ) -> ObjectPurgeEvidence: + """Abort abandoned uploads in this boundary; report provider-managed cleanup. + + The caller owns publication exclusion. Check its guard before each abort. + """ + ... + + def sha256_of(self, *, key: ObjectKey) -> str | None: + """Read digest metadata; None means missing object or missing metadata.""" + ... + def iter_keys(self, *, prefix: str) -> Iterator[ObjectKey]: """Page through exact prefix and descendants, excluding sibling prefixes. diff --git a/src/rememberstack/spine/catalog_contract.py b/src/rememberstack/spine/catalog_contract.py index 5c18c2131..8e59128a6 100644 --- a/src/rememberstack/spine/catalog_contract.py +++ b/src/rememberstack/spine/catalog_contract.py @@ -333,6 +333,7 @@ "lint_knowledge", "dispatch_knowledge", "hard_forget", + "publish_corpus", } ) """Scheduled aggregate and deployment-orchestration stages whose route is unlaned. diff --git a/src/rememberstack/spine/corpus_publication.py b/src/rememberstack/spine/corpus_publication.py new file mode 100644 index 000000000..93cccd834 --- /dev/null +++ b/src/rememberstack/spine/corpus_publication.py @@ -0,0 +1,321 @@ +"""D155 publication transactions and the deployment's session advisory lock. + +The existing work ledger, nullable marker and possibly written folder paths are +durable. Events carry a document id, never a desired revision/path. +Profile activation, lifecycle removal and scheduling are composed separately. +""" + +from collections.abc import Iterator +from contextlib import contextmanager +from dataclasses import dataclass +from uuid import UUID +from uuid import uuid4 + +from sqlalchemy import text +from sqlalchemy.engine import Connection +from sqlalchemy.engine import Engine +from sqlalchemy.exc import DBAPIError + +from rememberstack.core.corpus_export import corpus_policy_version +from rememberstack.core.corpus_export import CorpusDocument +from rememberstack.core.corpus_export import CorpusPolicy +from rememberstack.core.corpus_export import DEFAULT_CORPUS_POLICY +from rememberstack.core.corpus_export import desired_export_revision +from rememberstack.model import ClaimedWork +from rememberstack.model import EnqueueOutcome +from rememberstack.model import EnqueueWork +from rememberstack.model import PipelineStage +from rememberstack.model import ProcessingTarget +from rememberstack.spine.corpus_export import _DOCUMENTS +from rememberstack.spine.work_ledger import enqueue_on + + +class CorpusLockLostError(RuntimeError): + """The original lock session or this work's live claim no longer owns IO.""" + + +def corpus_changed_on( + *, + connection: Connection, + deployment_id: UUID, + doc_id: UUID, + policy: CorpusPolicy = DEFAULT_CORPUS_POLICY, +) -> EnqueueOutcome: + """Invalidate and enqueue a fresh event in the authoritative transaction. + + The row update serializes with the final marker transaction. A later commit + always gets a fresh target, including a return to earlier inputs (A→B→A). + """ + connection.execute( + text("""UPDATE documents SET corpus_published_revision = NULL + WHERE deployment_id = :d AND doc_id = :doc"""), + {"d": deployment_id, "doc": doc_id}, + ) + return enqueue_on( + connection=connection, + work=EnqueueWork( + deployment_id=deployment_id, + target_kind=ProcessingTarget.CORPUS_PUBLICATION, + target_id=uuid4(), + stage=PipelineStage.PUBLISH_CORPUS, + component_version=corpus_policy_version(policy), + content_hash=str(doc_id), + lane=None, + payload={"doc_id": str(doc_id)}, + ), + ) + + +def corpus_version_changed_on( + *, connection: Connection, deployment_id: UUID, version_id: UUID +) -> None: + """A canonical metadata change affects only a served version, not parked input.""" + doc_id = connection.execute( + text("""SELECT doc_id FROM documents + WHERE deployment_id = :d AND current_version_id = :v AND deleted_at IS NULL"""), + {"d": deployment_id, "v": version_id}, + ).scalar_one_or_none() + if doc_id is not None: + corpus_changed_on( + connection=connection, deployment_id=deployment_id, doc_id=doc_id + ) + + +def document_on( + *, connection: Connection, deployment_id: UUID, doc_id: UUID +) -> CorpusDocument | None: + """Read current served inputs in the caller's transaction.""" + row = ( + connection.execute( + text(_DOCUMENTS + " AND d.doc_id = :doc_id"), + {"deployment_id": deployment_id, "doc_id": doc_id}, + ) + .mappings() + .one_or_none() + ) + return CorpusDocument(**dict(row)) if row is not None else None + + +@dataclass +class CorpusPublicationLock: + """One checked-out connection; it must never reconnect and reacquire silently.""" + + connection: Connection + deployment_id: UUID + backend_pid: int + work: ClaimedWork | None = None + + def check(self) -> None: + """Confirm actual lock ownership and live claim before a provider mutation.""" + if self.connection.closed or self.connection.invalidated: + raise CorpusLockLostError("corpus publication lock session was lost") + try: + held = self.connection.execute( + text("""SELECT pg_backend_pid() = :pid AND EXISTS ( + SELECT 1 FROM pg_locks WHERE locktype = 'advisory' + AND pid = pg_backend_pid() AND granted AND mode = 'ExclusiveLock' + AND classid = ((hashtextextended(:key, 0) >> 32) & 4294967295)::oid + AND objid = (hashtextextended(:key, 0) & 4294967295)::oid + AND objsubid = 1)"""), + { + "key": f"corpus-publication:{self.deployment_id}", + "pid": self.backend_pid, + }, + ).scalar_one() + if held and self.work is not None: + held = self.connection.execute( + text("""SELECT EXISTS ( + SELECT 1 FROM processing_state WHERE processing_id = :p + AND deployment_id = :d AND status = 'running' AND attempts = :a + AND lease_until > clock_timestamp())"""), + { + "p": self.work.processing_id, + "d": self.deployment_id, + "a": self.work.attempt, + }, + ).scalar_one() + except DBAPIError as error: + raise CorpusLockLostError( + "corpus publication lock session failed" + ) from error + if not held: + raise CorpusLockLostError("corpus publication lost its lock or work claim") + + +class CorpusPublicationCatalog: + """Own lock lifetime, folder/marker commits and current-policy seeding.""" + + def __init__(self, *, engine: Engine) -> None: + self._engine = engine + + @contextmanager + def locked( + self, *, deployment_id: UUID, work: ClaimedWork | None = None + ) -> Iterator[CorpusPublicationLock]: + """Serialize publishers on a dedicated session, including all streamed IO.""" + with self._engine.connect().execution_options( + isolation_level="AUTOCOMMIT" + ) as connection: + params = {"key": f"corpus-publication:{deployment_id}"} + connection.execute( + text("SELECT pg_advisory_lock(hashtextextended(:key, 0))"), params + ) + lock = CorpusPublicationLock( + connection=connection, + deployment_id=deployment_id, + backend_pid=connection.execute( + text("SELECT pg_backend_pid()") + ).scalar_one(), + work=work, + ) + try: + lock.check() + yield lock + finally: + if not connection.invalidated and not connection.closed: + try: + connection.execute( + text( + "SELECT pg_advisory_unlock(hashtextextended(:key, 0))" + ), + params, + ) + except DBAPIError: + # A dead backend already released its session locks. + connection.invalidate() + + def clear( + self, *, lock: CorpusPublicationLock, doc_id: UUID + ) -> CorpusDocument | None: + """Clear before store mutation, then read authority after acquiring the lock.""" + lock.check() + with self._engine.begin() as connection: + document = document_on( + connection=connection, deployment_id=lock.deployment_id, doc_id=doc_id + ) + connection.execute( + text("""UPDATE documents SET corpus_published_revision = NULL + WHERE deployment_id = :d AND doc_id = :doc"""), + {"d": lock.deployment_id, "doc": doc_id}, + ) + return document + + def paths(self, *, lock: CorpusPublicationLock, doc_id: UUID) -> set[str]: + """Read cleanup state even for a deleted or no-longer-served document.""" + lock.check() + paths = lock.connection.execute( + text("""SELECT corpus_paths FROM documents + WHERE deployment_id = :d AND doc_id = :doc"""), + {"d": lock.deployment_id, "doc": doc_id}, + ).scalar_one_or_none() + return set(paths or ()) + + def set_paths( + self, *, lock: CorpusPublicationLock, doc_id: UUID, paths: set[str] + ) -> None: + """Commit on the lock session before IO; never reconnect after lock loss. + + Keep old paths until their navigation is repaired too, so a crash after + the last old object deletion still leaves its ancestors discoverable. + """ + lock.check() + row = lock.connection.execute( + text("""UPDATE documents SET corpus_paths = :paths + WHERE deployment_id = :d AND doc_id = :doc RETURNING doc_id"""), + {"d": lock.deployment_id, "doc": doc_id, "paths": sorted(paths) or None}, + ).scalar_one_or_none() + if paths and row is None: + raise RuntimeError("document disappeared before corpus path recording") + + def clear_unselected_paths( + self, *, lock: CorpusPublicationLock, doc_ids: list[UUID] + ) -> None: + """Full reconcile removed all folders outside the served DB selection.""" + lock.check() + lock.connection.execute( + text("""UPDATE documents SET corpus_paths = NULL + WHERE deployment_id = :d AND NOT (doc_id = ANY(CAST(:ids AS uuid[]))) + AND corpus_paths IS NOT NULL"""), + {"d": lock.deployment_id, "ids": doc_ids}, + ) + + def finish( + self, + *, + lock: CorpusPublicationLock, + doc_id: UUID, + revision: str | None, + policy: CorpusPolicy, + ) -> bool: + """Set success only against matching inputs; retain a durable newer wake-up.""" + with self._engine.begin() as connection: + connection.execute( + text("""SELECT doc_id FROM documents + WHERE deployment_id = :d AND doc_id = :doc FOR UPDATE"""), + {"d": lock.deployment_id, "doc": doc_id}, + ) + lock.check() + current = document_on( + connection=connection, deployment_id=lock.deployment_id, doc_id=doc_id + ) + desired = ( + desired_export_revision(current, policy=policy) if current else None + ) + if desired != revision: + corpus_changed_on( + connection=connection, + deployment_id=lock.deployment_id, + doc_id=doc_id, + policy=policy, + ) + return False + if current: + connection.execute( + text("""UPDATE documents SET corpus_published_revision = :r + WHERE deployment_id = :d AND doc_id = :doc"""), + {"d": lock.deployment_id, "doc": doc_id, "r": revision}, + ) + return True + + def seed_current_policy( + self, + *, + deployment_id: UUID, + policy: CorpusPolicy = DEFAULT_CORPUS_POLICY, + batch_size: int = 500, + ) -> int: + """Seed each lineage lacking work for this policy, in bounded transactions. + + Existing succeeded/dead-letter work stays intact; seeding never resets + attempts or silently retries a DLQ. Each policy cut uses ordinary events. + """ + if batch_size <= 0: + raise ValueError("batch_size must be positive") + total = 0 + while True: + with self._engine.begin() as connection: + ids = list( + connection.execute( + text("""SELECT d.doc_id FROM documents d + WHERE d.deployment_id = :d AND NOT EXISTS ( + SELECT 1 FROM processing_state p WHERE p.deployment_id = d.deployment_id + AND p.stage = 'publish_corpus' AND p.component_version = :policy + AND p.payload->>'doc_id' = d.doc_id::text) + ORDER BY d.doc_id LIMIT :batch FOR UPDATE OF d SKIP LOCKED"""), + { + "d": deployment_id, + "policy": corpus_policy_version(policy), + "batch": batch_size, + }, + ).scalars() + ) + for doc_id in ids: + corpus_changed_on( + connection=connection, + deployment_id=deployment_id, + doc_id=doc_id, + policy=policy, + ) + total += len(ids) + if len(ids) < batch_size: + return total diff --git a/src/rememberstack/spine/document_catalog.py b/src/rememberstack/spine/document_catalog.py index 95e8a082f..5933eec3c 100644 --- a/src/rememberstack/spine/document_catalog.py +++ b/src/rememberstack/spine/document_catalog.py @@ -676,7 +676,16 @@ def record_section_tree(self, *, record: SectionTreeRecord) -> PersistedSectionT earlier attempt, that is the earlier attempt's tree, and derived artifacts (the sidecar) must be built from it, not from the input. """ + from rememberstack.core.corpus_export import desired_export_revision + from rememberstack.spine.corpus_publication import corpus_changed_on + from rememberstack.spine.corpus_publication import document_on + with self._engine.begin() as connection: + previous = document_on( + connection=connection, + deployment_id=record.deployment_id, + doc_id=record.doc_id, + ) generation_payload = record.model_dump(mode="json") generation_payload["stats"] = json.dumps( generation_payload["stats"], @@ -788,6 +797,19 @@ def record_section_tree(self, *, record: SectionTreeRecord) -> PersistedSectionT deployment_id=record.deployment_id, version_id=record.version_id, ) + current = document_on( + connection=connection, + deployment_id=record.deployment_id, + doc_id=record.doc_id, + ) + if (desired_export_revision(previous) if previous else None) != ( + desired_export_revision(current) if current else None + ): + corpus_changed_on( + connection=connection, + deployment_id=record.deployment_id, + doc_id=record.doc_id, + ) return _persisted_tree(generation=generation, sections=persisted) diff --git a/src/rememberstack/spine/document_metadata.py b/src/rememberstack/spine/document_metadata.py index f43309df5..b2375d316 100644 --- a/src/rememberstack/spine/document_metadata.py +++ b/src/rememberstack/spine/document_metadata.py @@ -150,6 +150,11 @@ def merge_converter_metadata_on( connection=connection, deployment_id=deployment_id, version_id=version_id ): return + previous_title = connection.execute( + text("""SELECT title FROM document_metadata + WHERE deployment_id = :d AND version_id = :v"""), + {"d": deployment_id, "v": version_id}, + ).scalar_one() source_fields = { field: "source" for field, value in ( @@ -175,6 +180,17 @@ def merge_converter_metadata_on( "mapping_version": mapping_version, }, ) + current_title = connection.execute( + text("""SELECT title FROM document_metadata + WHERE deployment_id = :d AND version_id = :v"""), + {"d": deployment_id, "v": version_id}, + ).scalar_one() + if previous_title != current_title: + from rememberstack.spine.corpus_publication import corpus_version_changed_on + + corpus_version_changed_on( + connection=connection, deployment_id=deployment_id, version_id=version_id + ) connection.execute( _DELETE_SOURCE_PEOPLE, {"deployment_id": deployment_id, "version_id": version_id}, @@ -238,6 +254,26 @@ def refresh_family_on( "family": family_for_mime(mime=mime), }, ) + # A MIME repair changes the original extension/type even when its broad + # family stays the same (for example audio → video, both "media"). + from rememberstack.spine.corpus_publication import corpus_changed_on + + docs = ( + connection.execute( + text("""SELECT d.doc_id FROM documents d + JOIN document_versions v ON v.version_id = d.current_version_id + AND v.deployment_id = d.deployment_id + WHERE d.deployment_id = :d AND v.content_hash = :hash + AND d.deleted_at IS NULL ORDER BY d.doc_id"""), + {"d": deployment_id, "hash": content_hash}, + ) + .scalars() + .all() + ) + for doc_id in docs: + corpus_changed_on( + connection=connection, deployment_id=deployment_id, doc_id=doc_id + ) def _lock_metadata( diff --git a/src/rememberstack/spine/migrations/env.py b/src/rememberstack/spine/migrations/env.py index e223b31c2..c4770c650 100644 --- a/src/rememberstack/spine/migrations/env.py +++ b/src/rememberstack/spine/migrations/env.py @@ -13,7 +13,7 @@ config = context.config if config.config_file_name is not None: - fileConfig(config.config_file_name) + fileConfig(config.config_file_name, disable_existing_loggers=False) target_metadata = None diff --git a/src/rememberstack/spine/migrations/versions/p9_50_0071_corpus_publication_work.py b/src/rememberstack/spine/migrations/versions/p9_50_0071_corpus_publication_work.py new file mode 100644 index 000000000..874eef1a3 --- /dev/null +++ b/src/rememberstack/spine/migrations/versions/p9_50_0071_corpus_publication_work.py @@ -0,0 +1,22 @@ +"""D155: ordinary unlaned publication work, without a new coordination table.""" + +from collections.abc import Sequence + +from alembic import op + +revision: str = "p9_50_0071" +down_revision: str | None = "p9_49_0070" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + """Add the stage and fresh-event target to the existing ledger vocabulary.""" + op.execute("ALTER TYPE pipeline_stage ADD VALUE IF NOT EXISTS 'publish_corpus'") + op.execute( + "ALTER TYPE processing_target ADD VALUE IF NOT EXISTS 'corpus_publication'" + ) + + +def downgrade() -> None: + """PostgreSQL cannot remove enum values in place; additive no-op.""" diff --git a/src/rememberstack/spine/migrations/versions/p9_51_0072_corpus_paths.py b/src/rememberstack/spine/migrations/versions/p9_51_0072_corpus_paths.py new file mode 100644 index 000000000..9601b614f --- /dev/null +++ b/src/rememberstack/spine/migrations/versions/p9_51_0072_corpus_paths.py @@ -0,0 +1,20 @@ +"""D155: record every possibly written document folder before object IO.""" + +from collections.abc import Sequence + +from alembic import op + +revision: str = "p9_51_0072" +down_revision: str | None = "p9_50_0071" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + op.execute("ALTER TABLE documents ADD COLUMN corpus_paths text[]") + op.execute("""COMMENT ON COLUMN documents.corpus_paths IS + 'D155 possibly written corpus folder paths, committed before object IO and reduced after cleanup/navigation. NULL means none recorded; reconcile repairs missing state. Not a paid-work identity.'""") + + +def downgrade() -> None: + op.execute("ALTER TABLE documents DROP COLUMN corpus_paths") diff --git a/src/rememberstack/spine/work_ledger.py b/src/rememberstack/spine/work_ledger.py index 41d8a63ef..751f6b102 100644 --- a/src/rememberstack/spine/work_ledger.py +++ b/src/rememberstack/spine/work_ledger.py @@ -814,9 +814,9 @@ def due_routes( self, *, deployment_id: UUID, - routes: Sequence[tuple[PipelineStage, ProcessingLane]], - ) -> tuple[tuple[PipelineStage, ProcessingLane], ...]: - """Return, in the given order, the laned routes that have claimable work now. + routes: Sequence[tuple[PipelineStage, ProcessingLane | None]], + ) -> tuple[tuple[PipelineStage, ProcessingLane | None], ...]: + """Return, in the given order, the routes that have claimable work now. One round trip probes every route with the claim's own due predicate, so a worker serving many routes does not open a claim transaction per @@ -832,7 +832,10 @@ def due_routes( { "deployment_id": deployment_id, "stages": [stage.value for stage, _ in routes], - "lanes": [lane.value for _, lane in routes], + "lanes": [ + lane.value if lane is not None else None + for _, lane in routes + ], }, ).scalars() ) @@ -2158,7 +2161,7 @@ def _claimed_work(*, row: RowMapping) -> ClaimedWork: FROM processing_state WHERE deployment_id = :deployment_id AND stage = r.stage - AND lane = r.lane + AND lane IS NOT DISTINCT FROM r.lane AND {_CLAIMABLE} ) """ diff --git a/src/rememberstack/workers/corpus_publication.py b/src/rememberstack/workers/corpus_publication.py new file mode 100644 index 000000000..a60be574f --- /dev/null +++ b/src/rememberstack/workers/corpus_publication.py @@ -0,0 +1,325 @@ +"""D155 idempotent publication and verifying reconcile over the same live tree. + +This capability is deliberately unbound from serving profiles until lifecycle +removal, restore and readiness switch together. It performs no paid model work. +""" + +from collections import defaultdict +from collections.abc import Iterator +from contextlib import nullcontext +import hashlib +import posixpath +import re +from typing import Protocol +from uuid import UUID + +from rememberstack.core.corpus_export import CopyFile +from rememberstack.core.corpus_export import corpus_policy_version +from rememberstack.core.corpus_export import corpus_suffix +from rememberstack.core.corpus_export import CORPUS_TYPES +from rememberstack.core.corpus_export import CorpusPolicy +from rememberstack.core.corpus_export import DEFAULT_CORPUS_POLICY +from rememberstack.core.corpus_export import GeneratedFile +from rememberstack.core.corpus_export import render_navigation +from rememberstack.model import ClaimedWork +from rememberstack.model import NonRetryableHandlerError +from rememberstack.model import ObjectKey +from rememberstack.ports.cost_meter import CostMeterPort +from rememberstack.ports.object_store import MutableObjectStorePort +from rememberstack.ports.object_store import ObjectStorePort +from rememberstack.ports.object_store import StreamingReadPort +from rememberstack.spine.corpus_export import CorpusReaderCatalog +from rememberstack.spine.corpus_publication import CorpusPublicationCatalog +from rememberstack.spine.corpus_publication import CorpusPublicationLock +from rememberstack.workers.base import HandlerOutcome +from rememberstack.workers.corpus_export import load_document_export + +_FOLDER = re.compile(r".+--([0-9a-f]{24})\Z") +_CHUNK_SIZE = 1024 * 1024 + + +class CorpusSourceStore(ObjectStorePort, StreamingReadPort, Protocol): + """Immutable inventory reads and bounded original/media streams.""" + + +def document_folder(key: str) -> tuple[str, str] | None: + """Find the first document component, never an impersonating asset below it.""" + parts = key.split("/") + for index, part in enumerate(parts[:-1]): + if match := _FOLDER.fullmatch(part): + return "/".join(parts[: index + 1]), match[1] + return None + + +class CorpusPublisher: + """Stream desired files, remove stale copies and regenerate DB navigation.""" + + def __init__( + self, + *, + catalog: CorpusPublicationCatalog, + readers: CorpusReaderCatalog, + raw_store: CorpusSourceStore, + artifact_store: CorpusSourceStore, + corpus_store: MutableObjectStorePort, + policy: CorpusPolicy = DEFAULT_CORPUS_POLICY, + ) -> None: + self._catalog = catalog + self._readers = readers + self._raw = raw_store + self._artifacts = artifact_store + self._store = corpus_store + self.policy = policy + + def seed_current_policy(self, *, deployment_id: UUID) -> int: + """Use ordinary events for a policy cut or obsolete-policy delivery.""" + return self._catalog.seed_current_policy( + deployment_id=deployment_id, policy=self.policy + ) + + def publish_corpus( + self, + *, + deployment_id: UUID, + doc_id: UUID, + work: ClaimedWork | None = None, + lock: CorpusPublicationLock | None = None, + verify: bool = False, + ) -> bool: + """Re-read authority; return False only when newer inputs need another event. + + Internal callers can reuse a held lock. No event's former desired path, + revision or processing order can override the current database selection. + """ + with ( + nullcontext(lock) + if lock + else self._catalog.locked(deployment_id=deployment_id, work=work) + ) as held: + if held.deployment_id != deployment_id: + raise ValueError("corpus lock belongs to another deployment") + folders = self._catalog.paths(lock=held, doc_id=doc_id) + revision, path = self._publish_document( + lock=held, doc_id=doc_id, folders=folders, verify=verify + ) + ancestors = {""} + for folder in folders: + parent = posixpath.dirname(folder) + while parent: + ancestors.add(parent) + parent = posixpath.dirname(parent) + self._navigation(lock=held, ancestors=ancestors) + self._catalog.set_paths( + lock=held, doc_id=doc_id, paths={path} if path else set() + ) + return self._catalog.finish( + lock=held, doc_id=doc_id, revision=revision, policy=self.policy + ) + + def reconcile(self, *, deployment_id: UUID, verify: bool = True) -> int: + """Share one discovery pass; verify digests even behind matching markers.""" + with self._catalog.locked(deployment_id=deployment_id) as lock: + folders, navigation = self._discover(lock=lock) + self._store.abort_uploads(prefix="", before_write=lock.check) + published: list[tuple[UUID, str | None, str | None]] = [] + # Keep only one document inventory at a time. Discovery stores + # folder paths, not asset keys, and is shared across this run. + with self._readers.documents(deployment_id=deployment_id) as documents: + for document in documents: + paths = folders.pop(corpus_suffix(document.doc_id), set()) + paths.update(self._catalog.paths(lock=lock, doc_id=document.doc_id)) + revision, path = self._publish_document( + lock=lock, doc_id=document.doc_id, folders=paths, verify=verify + ) + published.append((document.doc_id, revision, path)) + for paths in folders.values(): + for path in paths: + self._remove_folder(lock=lock, path=path) + self._navigation(lock=lock, existing=navigation) + # Only small input identities survive the metadata pass; no stored + # receipts or export inventories. Concurrent changes get fresh work. + self._catalog.clear_unselected_paths( + lock=lock, doc_ids=[doc_id for doc_id, _, _ in published] + ) + for doc_id, revision, path in published: + self._catalog.set_paths( + lock=lock, doc_id=doc_id, paths={path} if path else set() + ) + self._catalog.finish( + lock=lock, doc_id=doc_id, revision=revision, policy=self.policy + ) + return len(published) + + def _discover( + self, *, lock: CorpusPublicationLock + ) -> tuple[dict[str, set[str]], set[str]]: + """Full-store repair only: recover paths/navigation missed by DB state.""" + folders: dict[str, set[str]] = defaultdict(set) + navigation: set[str] = set() + for key in self._store.iter_keys(prefix=""): + if found := document_folder(key.root): + path, suffix = found + folders[suffix].add(path) + elif posixpath.basename(key.root) == "_index.md" or key.root == "llms.txt": + navigation.add(key.root) + else: + self._delete(lock=lock, key=key) + return folders, navigation + + def _publish_document( + self, + *, + lock: CorpusPublicationLock, + doc_id: UUID, + folders: set[str], + verify: bool, + ) -> tuple[str | None, str | None]: + document = self._catalog.clear(lock=lock, doc_id=doc_id) + if document is None: + for path in folders: + self._remove_folder(lock=lock, path=path) + return None, None + folders.add(document.path) + self._catalog.set_paths(lock=lock, doc_id=doc_id, paths=folders) + export = load_document_export( + document, artifact_store=self._artifacts, policy=self.policy + ) + existing = {key.root for key in self._store.iter_keys(prefix=export.path)} + desired = {export.path + "/" + file.path for file in export.files} + unchanged = not verify and document.corpus_published_revision == export.revision + changed = [ + file + for file in export.files + if not (unchanged and export.path + "/" + file.path in existing) + and self._store.sha256_of(key=ObjectKey(export.path + "/" + file.path)) + != file.sha256 + ] + index = next(file for file in export.files if file.path == "_index.md") + assert isinstance(index, GeneratedFile) + if changed or existing - desired: + self._store.abort_uploads(prefix=export.path, before_write=lock.check) + if existing: + updating = index.content.replace(b"State: ready", b"State: updating", 1) + self._put( + lock=lock, + path=export.path + "/_index.md", + file=GeneratedFile("_index.md", updating), + ) + for file in changed: + if isinstance(file, CopyFile): + self._put(lock=lock, path=export.path + "/" + file.path, file=file) + for key in sorted(existing - desired): + self._delete(lock=lock, key=ObjectKey(key)) + for file in changed: + if isinstance(file, GeneratedFile) and file.path not in { + "document.json", + "_index.md", + }: + self._put(lock=lock, path=export.path + "/" + file.path, file=file) + metadata = next( + file for file in export.files if file.path == "document.json" + ) + self._put(lock=lock, path=export.path + "/document.json", file=metadata) + self._put(lock=lock, path=export.path + "/_index.md", file=index) + for old in folders - {export.path}: + self._remove_folder(lock=lock, path=old) + return export.revision, export.path + + def _put( + self, *, lock: CorpusPublicationLock, path: str, file: CopyFile | GeneratedFile + ) -> None: + chunks = ( + self._stream(file=file) + if isinstance(file, CopyFile) + else iter((file.content,)) + ) + self._store.replace_stream( + key=ObjectKey(path), + chunks=chunks, + storage_class="hot", + sha256=file.sha256, + before_write=lock.check, + ) + + def _stream(self, *, file: CopyFile) -> Iterator[bytes]: + """Validate source integrity at EOF, before the adapter completes a PUT.""" + store = self._raw if file.store == "raw" else self._artifacts + source = store.iter_bytes(key=ObjectKey(file.uri), chunk_size=_CHUNK_SIZE) + digest = hashlib.sha256() + try: + for chunk in source: + digest.update(chunk) + yield chunk + if digest.hexdigest() != file.sha256: + raise ValueError(f"immutable corpus input hash mismatch: {file.uri}") + finally: + close = getattr(source, "close", None) + if close is not None: + close() + + def _delete(self, *, lock: CorpusPublicationLock, key: ObjectKey) -> None: + lock.check() + self._store.delete(key=key) + + def _remove_folder(self, *, lock: CorpusPublicationLock, path: str) -> None: + self._store.abort_uploads(prefix=path, before_write=lock.check) + for key in self._store.iter_keys(prefix=path): + self._delete(lock=lock, key=key) + + def _navigation( + self, + *, + lock: CorpusPublicationLock, + existing: set[str] | None = None, + ancestors: set[str] | None = None, + ) -> None: + """List only affected radix subtrees; full discovery belongs to reconcile.""" + if ancestors is not None: + # Root links include all fixed types, even empty ones. Bootstrap + # that constant-size scaffold once, without inspecting other topics. + if self._store.sha256_of(key=ObjectKey("llms.txt")) is None: + ancestors.update(CORPUS_TYPES) + existing = {posixpath.join(parent, "_index.md") for parent in ancestors} + for parent in ancestors: + existing.update( + key.root + for key in self._store.iter_keys(prefix=posixpath.join(parent, "~")) + ) + assert existing is not None + with self._readers.documents(deployment_id=lock.deployment_id) as documents: + desired = render_navigation( + documents, policy=self.policy, ancestors=ancestors + ) + for path in sorted(desired, key=lambda name: (-name.count("/"), name)): + file = GeneratedFile(path, desired[path]) + if self._store.sha256_of(key=ObjectKey(path)) != file.sha256: + self._put(lock=lock, path=path, file=file) + for path in sorted(existing - desired.keys()): + self._delete(lock=lock, key=ObjectKey(path)) + + +class PublishCorpusHandler: + """One ordinary event, executed by the existing class or pushed task runner.""" + + def __init__(self, *, publisher: CorpusPublisher) -> None: + self._publisher = publisher + + def handle(self, *, work: ClaimedWork, meter: CostMeterPort) -> HandlerOutcome: + payload = work.payload or {} + try: + if set(payload) != {"doc_id"}: + raise ValueError("publication payload must contain only doc_id") + doc_id = UUID(str(payload["doc_id"])) + except (ValueError, KeyError) as error: + raise NonRetryableHandlerError( + "invalid corpus publication event" + ) from error + if work.component_version != corpus_policy_version(self._publisher.policy): + # Stale policy delivery must not write; seed the current policy through + # ordinary work instead of changing this event or resetting attempts. + self._publisher.seed_current_policy(deployment_id=work.deployment_id) + return HandlerOutcome() + self._publisher.publish_corpus( + deployment_id=work.deployment_id, doc_id=doc_id, work=work + ) + return HandlerOutcome() diff --git a/src/tests/adapters/test_minio_corpus_lock_loss.py b/src/tests/adapters/test_minio_corpus_lock_loss.py new file mode 100644 index 000000000..e90679983 --- /dev/null +++ b/src/tests/adapters/test_minio_corpus_lock_loss.py @@ -0,0 +1,213 @@ +"""D155: a real late MinIO PUT is accepted, detected and repaired by reconcile. + +The relay holds the complete signed request after boto3 sends it. Responses and +storage are real; the actual publisher must refuse further IO after lock loss. +""" + +from collections.abc import Iterator +from concurrent.futures import ThreadPoolExecutor +from contextlib import contextmanager +from dataclasses import dataclass +from http.client import HTTPConnection +from http.server import BaseHTTPRequestHandler +from http.server import ThreadingHTTPServer +import threading +from typing import Any +from urllib.parse import urlsplit + +import boto3 +from botocore.config import Config +import pytest +from sqlalchemy import text + +from rememberstack.adapters.selfhost import MinIOObjectStore +from rememberstack.core.corpus_export import GeneratedFile +from rememberstack.model import ObjectKey +from rememberstack.spine.corpus_export import CorpusReaderCatalog +from rememberstack.spine.corpus_publication import CorpusLockLostError +from rememberstack.workers.corpus_export import load_document_export +from rememberstack.workers.corpus_publication import CorpusPublisher +from tests.adapters.test_minio_corpus_publication import Publication +from tests.adapters.test_minio_corpus_publication import publication as publication +from tests.adapters.test_minio_object_operations import bucket as bucket +from tests.adapters.test_minio_object_operations import minio_settings as minio_settings +from tests.workers.test_corpus_reader_export_pg import corpus as corpus +from tests.workers.test_corpus_reader_export_pg import engine as engine + + +def test_late_put_after_lock_loss_is_repaired_by_verifying_reconcile( + publication: Publication, +) -> None: + state = publication + source = state.source + original = load_document_export(state.selected()[0], artifact_store=state.artifacts) + old_index = next( + file + for file in original.files + if isinstance(file, GeneratedFile) and file.path == "_index.md" + ) + key = ObjectKey(original.path + "/_index.md") + with _delayed_put( + endpoint_url=state.bucket.settings.endpoint_url, + delay_path=f"/{state.bucket.name}/{key.root}", + ) as relay: + client: Any = boto3.client( + "s3", + endpoint_url=relay.endpoint_url, + aws_access_key_id=state.bucket.settings.access_key.get_secret_value(), + aws_secret_access_key=state.bucket.settings.secret_key.get_secret_value(), + region_name=state.bucket.settings.region, + config=Config( + signature_version="s3v4", + s3={"addressing_style": "path"}, + retries={"total_max_attempts": 1}, + connect_timeout=5, + read_timeout=30, + request_checksum_calculation="when_required", + response_checksum_validation="when_required", + ), + ) + old_store = MinIOObjectStore(bucket=state.bucket.name, client=client) + old_publisher = CorpusPublisher( + catalog=state.catalog, + readers=CorpusReaderCatalog(engine=state.engine), + raw_store=state.raw, + artifact_store=state.artifacts, + corpus_store=old_store, + ) + owners: list[int] = [] + + def publish_old() -> None: + with state.catalog.locked(deployment_id=source.deployment_id) as lock: + owners.append(lock.backend_pid) + old_publisher.publish_corpus( + deployment_id=source.deployment_id, doc_id=source.doc_id, lock=lock + ) + + try: + with ThreadPoolExecutor(max_workers=1) as pool: + pending = pool.submit(publish_old) + try: + assert relay.received.wait(timeout=10), "PUT never reached relay" + assert not pending.done() + with state.engine.begin() as connection: + assert connection.execute( + text("SELECT pg_terminate_backend(:pid)"), + {"pid": owners[0]}, + ).scalar_one() + state.change(title="ANNUAL REPORT") + assert state.publish() + updated = load_document_export( + state.selected()[0], artifact_store=state.artifacts + ) + assert ( + updated.path == original.path + and updated.revision != original.revision + ) + assert updated.revision.encode() in state.bucket.store.read_bytes( + key=key + ) + assert state.marker() == updated.revision + assert not pending.done() + finally: + relay.release.set() + with pytest.raises(CorpusLockLostError): + pending.result(timeout=10) + finally: + client.close() + # The old network request really committed after the newer successful marker. + assert state.bucket.store.read_bytes(key=key) == old_index.content + assert state.bucket.store.sha256_of(key=key) == old_index.sha256 + assert state.marker() == updated.revision + state.publisher.reconcile(deployment_id=source.deployment_id, verify=True) + state.assert_tree() + assert updated.revision.encode() in state.bucket.store.read_bytes(key=key) + assert state.marker() == updated.revision + + +@dataclass(frozen=True) +class _DelayedPut: + """One received network request, held until the test permits forwarding.""" + + endpoint_url: str + received: threading.Event + release: threading.Event + + +@contextmanager +def _delayed_put( + *, endpoint_url: str, delay_path: str | None = None +) -> Iterator[_DelayedPut]: + """Relay a complete signed PUT to real MinIO after a deterministic delay.""" + upstream = urlsplit(endpoint_url) + assert upstream.scheme == "http" and upstream.hostname + hostname = upstream.hostname + received, release = threading.Event(), threading.Event() + + class Relay(BaseHTTPRequestHandler): + """Preserve the signed Host and payload while delaying network delivery.""" + + def do_PUT(self) -> None: + self._forward(delay=delay_path is None or self.path == delay_path) + + def do_GET(self) -> None: + self._forward() + + def do_HEAD(self) -> None: + self._forward() + + def do_POST(self) -> None: + self._forward() + + def do_DELETE(self) -> None: + self._forward() + + def _forward(self, *, delay: bool = False) -> None: + """Preserve the signed request and forward every real provider response.""" + body = self.rfile.read(int(self.headers.get("Content-Length", "0"))) + if delay: + received.set() + assert release.wait(timeout=25), "test did not release in-flight PUT" + connection = HTTPConnection(host=hostname, port=upstream.port, timeout=10) + try: + connection.request( + method=self.command, + url=self.path, + body=body, + headers=dict(self.headers), + ) + response = connection.getresponse() + content = response.read() + self.send_response(response.status) + for name, value in response.getheaders(): + if name.lower() not in { + "content-length", + "transfer-encoding", + "connection", + }: + self.send_header(name, value) + self.send_header("Content-Length", str(len(content))) + self.end_headers() + self.wfile.write(content) + finally: + connection.close() + + def log_message(self, format: str, *args: object) -> None: # noqa: A002 + """Keep routine HTTP request logging out of the test output.""" + + with ThreadingHTTPServer(("127.0.0.1", 0), Relay) as server: + thread = threading.Thread( + target=server.serve_forever, kwargs={"poll_interval": 0.05} + ) + thread.start() + try: + yield _DelayedPut( + endpoint_url=f"http://127.0.0.1:{server.server_port}", + received=received, + release=release, + ) + finally: + release.set() + server.shutdown() + thread.join(timeout=10) + assert not thread.is_alive() diff --git a/src/tests/adapters/test_minio_corpus_publication.py b/src/tests/adapters/test_minio_corpus_publication.py new file mode 100644 index 000000000..9f6bbaf55 --- /dev/null +++ b/src/tests/adapters/test_minio_corpus_publication.py @@ -0,0 +1,1368 @@ +"""D155 slice 3: real PostgreSQL + MinIO, with no hosted model calls. + +Only the fixture binds the dormant publication handler to class/pushed runners; +production profile activation and lifecycle delete/forget/restore stay separate. +""" + +from collections.abc import Callable +from collections.abc import Iterator +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass +from dataclasses import replace +from datetime import datetime +import posixpath +from typing import Any +from urllib.parse import unquote +from uuid import UUID +from uuid import uuid4 + +from markdown_it import MarkdownIt +import pytest +from sqlalchemy import text +from sqlalchemy.engine import Engine + +from rememberstack.adapters.selfhost import MinIOObjectStore +from rememberstack.adapters.testing.model_provider import FakeModelProvider +from rememberstack.core.corpus_export import CopyFile +from rememberstack.core.corpus_export import corpus_policy_version +from rememberstack.core.corpus_export import corpus_suffix +from rememberstack.core.corpus_export import CorpusDocument +from rememberstack.core.corpus_export import CorpusPolicy +from rememberstack.core.corpus_export import DEFAULT_CORPUS_POLICY +from rememberstack.core.corpus_export import desired_export_revision +from rememberstack.core.corpus_export import render_navigation +from rememberstack.model import ClaimedWork +from rememberstack.model import ObjectKey +from rememberstack.model import PipelineStage +from rememberstack.model import QueueRoute +from rememberstack.model import RunResultOutcome +from rememberstack.profiles import run_task +from rememberstack.profiles import SelfHostProfile +from rememberstack.profiles import SelfHostSettings +from rememberstack.spine.corpus_export import CorpusReaderCatalog +from rememberstack.spine.corpus_publication import corpus_changed_on +from rememberstack.spine.corpus_publication import CorpusLockLostError +from rememberstack.spine.corpus_publication import CorpusPublicationCatalog +from rememberstack.spine.document_metadata import merge_converter_metadata_on +from rememberstack.spine.new_work import announce_new_work +from rememberstack.spine.new_work import collect_new_work +from rememberstack.spine.work_ledger import WorkLedger +from rememberstack.spine.work_ledger import WorkLedgerSettings +from rememberstack.workers.corpus_export import load_document_export +from rememberstack.workers.corpus_publication import CorpusPublisher +from rememberstack.workers.corpus_publication import PublishCorpusHandler +from tests.adapters.test_minio_object_operations import _Bucket +from tests.adapters.test_minio_object_operations import bucket as bucket +from tests.adapters.test_minio_object_operations import minio_settings as minio_settings +from tests.corpus_export_support import digest +from tests.workers.test_corpus_reader_export_pg import _seed +from tests.workers.test_corpus_reader_export_pg import corpus as corpus +from tests.workers.test_corpus_reader_export_pg import engine as engine + + +@dataclass +class Publication: + engine: Engine + source: CorpusDocument + raw: MinIOObjectStore + artifacts: MinIOObjectStore + bucket: _Bucket + catalog: CorpusPublicationCatalog + publisher: CorpusPublisher + + def publish(self, doc_id: UUID | None = None) -> bool: + return self.publisher.publish_corpus( + deployment_id=self.source.deployment_id, doc_id=doc_id or self.source.doc_id + ) + + def selected(self) -> list[CorpusDocument]: + with CorpusReaderCatalog(engine=self.engine).documents( + deployment_id=self.source.deployment_id + ) as rows: + return list(rows) + + def marker(self) -> str | None: + with self.engine.connect() as connection: + return connection.execute( + text( + "SELECT corpus_published_revision FROM documents WHERE doc_id = :id" + ), + {"id": self.source.doc_id}, + ).scalar_one() + + def paths(self) -> set[str]: + with self.engine.connect() as connection: + return set( + connection.execute( + text("SELECT corpus_paths FROM documents WHERE doc_id = :id"), + {"id": self.source.doc_id}, + ).scalar_one() + or () + ) + + def change( + self, + *, + title: str | None = None, + topic: str | None = None, + source_kind: str | None = None, + deleted: bool = False, + ) -> UUID: + with self.engine.begin() as connection: + connection.execute( + text("SELECT doc_id FROM documents WHERE doc_id = :id FOR UPDATE"), + {"id": self.source.doc_id}, + ) + if title is not None: + connection.execute( + text( + "UPDATE document_metadata SET title = :title WHERE version_id = :v" + ), + {"title": title, "v": self.source.version_id}, + ) + if topic is not None: + connection.execute( + text( + "UPDATE document_sections SET placement_path = :topic WHERE section_id = :g" + ), + {"topic": topic or None, "g": self.source.structure_generation_id}, + ) + if source_kind: + connection.execute( + text("UPDATE documents SET source_kind = :kind WHERE doc_id = :id"), + {"kind": source_kind, "id": self.source.doc_id}, + ) + if deleted: + connection.execute( + text("UPDATE documents SET deleted_at = now() WHERE doc_id = :id"), + {"id": self.source.doc_id}, + ) + return corpus_changed_on( + connection=connection, + deployment_id=self.source.deployment_id, + doc_id=self.source.doc_id, + ).processing_id + + def expected(self) -> dict[str, bytes]: + documents = self.selected() + files = render_navigation(documents, policy=self.publisher.policy) + for document in documents: + export = load_document_export( + document, artifact_store=self.artifacts, policy=self.publisher.policy + ) + for file in export.files: + content = ( + (self.raw if file.store == "raw" else self.artifacts).read_bytes( + key=ObjectKey(file.uri) + ) + if isinstance(file, CopyFile) + else file.content + ) + files[export.path + "/" + file.path] = content + return files + + def assert_tree(self) -> dict[str, bytes]: + expected = self.expected() + actual = { + key.root: self.bucket.store.read_bytes(key=key) + for key in self.bucket.store.iter_keys(prefix="") + } + assert actual == expected + for name, content in expected.items(): + assert self.bucket.store.sha256_of(key=ObjectKey(name)) == digest(content) + assert self.bucket.store.storage_class_of(key=ObjectKey(name)) == "hot" + if name.endswith(".md") or name == "llms.txt": + for token in MarkdownIt().parse(content.decode()): + for child in token.children or (): + if child.type in {"link_open", "image"}: + url = child.attrGet( + "href" if child.type == "link_open" else "src" + ) + assert isinstance(url, str) + assert ( + posixpath.normpath( + posixpath.join( + posixpath.dirname(name), unquote(url) + ) + ) + in expected + ) + return actual + + +@pytest.fixture +def publication(engine: Engine, corpus, bucket: _Bucket) -> Iterator[Publication]: + source, artifacts, raw = corpus + names = [f"d155-raw-{uuid4().hex}", f"d155-artifacts-{uuid4().hex}"] + stores = [MinIOObjectStore(bucket=name, client=bucket.client) for name in names] + for store, authority in zip(stores, (raw, artifacts), strict=True): + store.ensure_bucket() + for name, content in authority.objects.items(): + store.write_bytes(key=ObjectKey(name), content=content, storage_class="hot") + catalog = CorpusPublicationCatalog(engine=engine) + publisher = CorpusPublisher( + catalog=catalog, + readers=CorpusReaderCatalog(engine=engine), + raw_store=stores[0], + artifact_store=stores[1], + corpus_store=bucket.store, + ) + try: + yield Publication( + engine, source, stores[0], stores[1], bucket, catalog, publisher + ) + finally: + for name, store in zip(names, stores, strict=True): + store.purge_objects(keys=tuple(store.iter_keys(prefix="")), prefixes=()) + bucket.client.delete_bucket(Bucket=name) + + +@pytest.mark.parametrize("change", ["title", "topic", "type", "no_topic", "delete"]) +def test_create_move_remove_and_duplicate_replay( + publication: Publication, change: str +) -> None: + state = publication + assert state.publish() + before = state.assert_tree() + assert state.paths() == {state.source.path} + assert state.marker() == desired_export_revision(state.selected()[0]) + assert state.publish() + assert state.assert_tree() == before + state.change( + **{ + "title": {"title": "Renamed"}, + "topic": {"topic": "New/Topic"}, + "type": {"source_kind": "email"}, + "no_topic": {"topic": ""}, + "delete": {"deleted": True}, + }[change] + ) + assert state.marker() is None + assert state.publish() + state.assert_tree() + if change == "delete": + assert state.marker() is None + assert state.paths() == set() + assert not any( + corpus_suffix(state.source.doc_id) in key for key in state.expected() + ) + else: + assert state.paths() == {state.selected()[0].path} + assert state.marker() == desired_export_revision(state.selected()[0]) + + +@pytest.mark.parametrize( + "boundary", + ["clear", "copy", "metadata", "ready", "old_last", "navigation", "marker"], +) +def test_retry_after_each_publication_boundary( + publication: Publication, monkeypatch: pytest.MonkeyPatch, boundary: str +) -> None: + state = publication + state.publish() + old_path = state.source.path + state.change(title="New folder", topic="Another/Branch") + new_path = state.selected()[0].path + original_put = state.bucket.store.replace_stream + original_delete = state.bucket.store.delete + failed = [] + + def crash() -> None: + if not failed: + failed.append(True) + raise RuntimeError("injected crash") + + def put(**kwargs: Any) -> None: + original_put(**kwargs) + key = kwargs["key"].root + if ( + (boundary == "copy" and key.endswith("/original.pdf")) + or (boundary == "metadata" and key == new_path + "/document.json") + or (boundary == "ready" and key == new_path + "/_index.md") + or (boundary == "navigation" and key == "pdf/_index.md") + ): + crash() + + def delete(**kwargs: Any) -> None: + original_delete(**kwargs) + if ( + boundary == "old_last" + and kwargs["key"].root.startswith(old_path + "/") + and not list(state.bucket.store.iter_keys(prefix=old_path)) + ): + crash() + + with monkeypatch.context() as patch: + patch.setattr(state.bucket.store, "replace_stream", put) + patch.setattr(state.bucket.store, "delete", delete) + if boundary in {"clear", "marker"}: + name = "clear" if boundary == "clear" else "finish" + operation = getattr(state.catalog, name) + + def catalog_crash(**kwargs: Any) -> Any: + result = operation(**kwargs) + crash() + return result + + patch.setattr(state.catalog, name, catalog_crash) + with pytest.raises(RuntimeError, match="injected crash"): + state.publish() + assert failed + assert state.paths() == ( + {old_path} + if boundary == "clear" + else {new_path} + if boundary == "marker" + else {old_path, new_path} + ) + if boundary == "ready": + assert list(state.bucket.store.iter_keys(prefix=old_path)) + assert b"State: ready" in state.bucket.store.read_bytes( + key=ObjectKey(new_path + "/_index.md") + ) + if boundary == "marker": + assert state.marker() is not None + else: + assert state.marker() is None + if boundary == "old_last": + assert not list(state.bucket.store.iter_keys(prefix=old_path)) + assert list(state.bucket.store.iter_keys(prefix="pdf/finance")), ( + "stale index-only remnant must exist" + ) + assert state.publish() + assert state.paths() == {new_path} + state.assert_tree() + + +@pytest.mark.parametrize("change", ["replay", "title", "topic", "type", "delete"]) +def test_ordinary_publish_lists_only_recorded_folders_and_ancestor_pages( + publication: Publication, monkeypatch: pytest.MonkeyPatch, change: str +) -> None: + state = publication + for topic, kind in (("Unrelated/Branch", "upload"), ("Other/Branch", "email")): + _seed( + state.engine, + replace( + state.source, + doc_id=uuid4(), + version_id=uuid4(), + representation_id=uuid4(), + structure_generation_id=uuid4(), + title="Control", + placement_path=topic, + source_kind=kind, + ), + ) + state.publisher.reconcile(deployment_id=state.source.deployment_id) + old_path = state.source.path + if change != "replay": + state.change( + **{ + "title": {"title": "Moved"}, + "topic": {"topic": "New/Branch"}, + "type": {"source_kind": "chat"}, + "delete": {"deleted": True}, + }[change] + ) + paths = { + old_path, + *(doc.path for doc in state.selected() if doc.doc_id == state.source.doc_id), + } + ancestors = {""} + for path in paths: + parent = posixpath.dirname(path) + while parent: + ancestors.add(parent) + parent = posixpath.dirname(parent) + allowed_prefixes = paths | {posixpath.join(parent, "~") for parent in ancestors} + listed: list[str] = [] + touched: list[str] = [] + original_list = state.bucket.store.iter_keys + + def listing(*, prefix: str) -> Iterator[ObjectKey]: + assert prefix in allowed_prefixes, f"unrelated/root listing: {prefix!r}" + listed.append(prefix) + yield from original_list(prefix=prefix) + + def recording(operation: Callable[..., Any]) -> Callable[..., Any]: + def call(**kwargs: Any) -> Any: + key = kwargs["key"].root + touched.append(key) + if any(key.startswith(path + "/") for path in paths): + # A separate connection proves path state committed before IO. + assert any(key.startswith(path + "/") for path in state.paths()) + return operation(**kwargs) + + return call + + with monkeypatch.context() as patch: + patch.setattr(state.bucket.store, "iter_keys", listing) + for name in ("sha256_of", "replace_stream", "delete"): + patch.setattr( + state.bucket.store, name, recording(getattr(state.bucket.store, name)) + ) + assert state.publish() + assert listed and "" not in listed + for key in touched: + assert ( + key == "llms.txt" + or any(key.startswith(path + "/") for path in paths) + or posixpath.dirname(key) in ancestors + or any( + key.startswith(posixpath.join(parent, "~") + "/") + for parent in ancestors + ) + ), f"unrelated object touched: {key}" + state.assert_tree() + + +def test_first_publish_does_not_list_the_store_root( + publication: Publication, monkeypatch: pytest.MonkeyPatch +) -> None: + original = publication.bucket.store.iter_keys + prefixes = [] + + def listing(*, prefix: str) -> Iterator[ObjectKey]: + assert prefix, "ordinary publish must not discover the full store" + prefixes.append(prefix) + yield from original(prefix=prefix) + + with monkeypatch.context() as patch: + patch.setattr(publication.bucket.store, "iter_keys", listing) + assert publication.publish() + assert publication.source.path in prefixes + publication.assert_tree() + + +@pytest.mark.parametrize("damage", ["mismatch", "missing_metadata", "missing_object"]) +def test_verify_repairs_bytes_behind_a_matching_marker( + publication: Publication, damage: str +) -> None: + state = publication + state.publish() + key = ObjectKey(state.source.path + "/document.md") + marker = state.marker() + if damage == "missing_object": + state.bucket.store.delete(key=key) + else: + state.bucket.client.put_object( + Bucket=state.bucket.name, + Key=key.root, + Body=b"stale", + Metadata={"sha256": digest(b"stale")} if damage == "mismatch" else {}, + ) + assert state.marker() == marker + assert ( + state.publisher.reconcile(deployment_id=state.source.deployment_id, verify=True) + == 1 + ) + state.assert_tree() + assert state.marker() == marker + + +@pytest.mark.parametrize("change", ["title", "version", "delete"]) +def test_authority_changes_mid_copy_leave_fresh_work( + publication: Publication, monkeypatch: pytest.MonkeyPatch, change: str +) -> None: + state = publication + original = state.bucket.store.replace_stream + changed = [] + + def copy(**kwargs: Any) -> None: + original(**kwargs) + if not changed: + changed.append(True) + if change == "version": + raw = b"new version bytes" + new = replace( + state.source, + version_id=uuid4(), + representation_id=uuid4(), + structure_generation_id=uuid4(), + version_no=2, + content_hash=digest(raw), + raw_uri="registered/new", + title="New version", + ) + state.raw.write_bytes( + key=ObjectKey(new.raw_uri), content=raw, storage_class="hot" + ) + _seed(state.engine, new) + state.change() + else: + state.change( + title="Changed mid copy" if change == "title" else None, + deleted=change == "delete", + ) + + with monkeypatch.context() as patch: + patch.setattr(state.bucket.store, "replace_stream", copy) + assert not state.publish() + assert state.marker() is None + with state.engine.connect() as connection: + assert ( + connection.execute( + text( + "SELECT count(*) FROM processing_state WHERE stage = 'publish_corpus'" + ) + ).scalar_one() + >= 2 + ) + state.publish() + state.assert_tree() + + +def test_incremental_and_empty_store_reconcile_converge_and_clean_orphans( + publication: Publication, +) -> None: + state = publication + other = replace( + state.source, + doc_id=uuid4(), + version_id=uuid4(), + representation_id=uuid4(), + structure_generation_id=uuid4(), + title="Control", + ) + _seed(state.engine, other) + state.publish(other.doc_id) + state.publish() + state.change(title="B", topic="Move") + state.publish() + state.change(title="Annual Report", topic="Finance/Annual Reports") + state.publish() + incremental = state.assert_tree() + orphan = f"pdf/former/lost--{corpus_suffix(uuid4())}/original.pdf" + for key in (orphan, "pdf/stale/~page/_index.md", "unknown/loose"): + state.bucket.store.replace_stream( + key=ObjectKey(key), chunks=(b"orphan",), storage_class="hot" + ) + state.bucket.client.create_multipart_upload(Bucket=state.bucket.name, Key=orphan) + state.publisher.reconcile(deployment_id=state.source.deployment_id, verify=True) + assert state.assert_tree() == incremental + + assert not state.bucket.client.list_multipart_uploads(Bucket=state.bucket.name).get( + "Uploads" + ) + for key in state.bucket.store.iter_keys(prefix=""): + state.bucket.store.delete(key=key) + state.publisher.reconcile(deployment_id=state.source.deployment_id, verify=True) + assert state.assert_tree() == incremental + + +def test_reconcile_repairs_path_state_missed_by_database( + publication: Publication, +) -> None: + state = publication + state.publish() + other = replace( + state.source, + doc_id=uuid4(), + version_id=uuid4(), + representation_id=uuid4(), + structure_generation_id=uuid4(), + title="Deleted", + ) + _seed(state.engine, other) + missed = f"pdf/former/old--{corpus_suffix(state.source.doc_id)}" + for path in (missed, other.path): + state.bucket.store.replace_stream( + key=ObjectKey(path + "/document.md"), chunks=(b"old",), storage_class="hot" + ) + with state.engine.begin() as connection: + connection.execute(text("UPDATE documents SET corpus_paths = NULL")) + connection.execute( + text( + "UPDATE documents SET deleted_at = now(), corpus_paths = :paths WHERE doc_id = :doc" + ), + {"doc": other.doc_id, "paths": [other.path, "pdf/empty/former"]}, + ) + state.publisher.reconcile(deployment_id=state.source.deployment_id) + assert state.paths() == {state.source.path} + with state.engine.connect() as connection: + assert ( + connection.execute( + text("SELECT corpus_paths FROM documents WHERE doc_id = :doc"), + {"doc": other.doc_id}, + ).scalar_one() + is None + ) + state.assert_tree() + + +def test_shared_indexes_are_regenerated_without_recopying_unrelated_files( + publication: Publication, monkeypatch: pytest.MonkeyPatch +) -> None: + state = publication + other = replace( + state.source, + doc_id=uuid4(), + version_id=uuid4(), + representation_id=uuid4(), + structure_generation_id=uuid4(), + title="Control", + ) + _seed(state.engine, other) + state.publisher.reconcile(deployment_id=state.source.deployment_id) + state.bucket.client.put_object( + Bucket=state.bucket.name, Key="pdf/_index.md", Body=b"stale navigation" + ) + original = state.bucket.store.replace_stream + writes = [] + + def record(**kwargs: Any) -> None: + writes.append(kwargs["key"].root) + original(**kwargs) + + with monkeypatch.context() as patch: + patch.setattr(state.bucket.store, "replace_stream", record) + state.change(title="ANNUAL REPORT") + state.publish() + assert "pdf/_index.md" in writes + assert not any(key.startswith(other.path + "/") for key in writes) + assert not any( + key.endswith(("original.pdf", "plot.png", "document.md")) for key in writes + ) + state.assert_tree() + + +def test_two_writers_sharing_ancestors_serialize_and_keep_both_members( + publication: Publication, +) -> None: + state = publication + other = replace( + state.source, + doc_id=uuid4(), + version_id=uuid4(), + representation_id=uuid4(), + structure_generation_id=uuid4(), + title="Control", + ) + _seed(state.engine, other) + with ThreadPoolExecutor(max_workers=2) as pool: + pending = [ + pool.submit(state.publish, doc_id) + for doc_id in (state.source.doc_id, other.doc_id) + ] + assert all(job.result(timeout=30) for job in pending) + state.assert_tree() + + +def test_asset_component_cannot_impersonate_another_document( + publication: Publication, +) -> None: + state = publication + other = replace( + state.source, + doc_id=uuid4(), + version_id=uuid4(), + representation_id=uuid4(), + structure_generation_id=uuid4(), + title="Control", + ) + _seed(state.engine, other) + state.publish(other.doc_id) + fake = ObjectKey( + other.path + + "/media/fake--" + + corpus_suffix(state.source.doc_id) + + "/original.pdf" + ) + state.bucket.store.replace_stream( + key=fake, chunks=(b"control asset",), storage_class="hot" + ) + state.change(deleted=True) + state.publish() + assert state.bucket.store.read_bytes(key=fake) == b"control asset" + + +@pytest.mark.parametrize( + ("claims", "facts"), [(False, False), (True, False), (True, True)] +) +def test_same_sources_export_for_every_layer_profile( + publication: Publication, claims: bool, facts: bool +) -> None: + from rememberstack.spine.processing_layers import ProcessingLayerCatalog + + state = publication + ProcessingLayerCatalog(engine=state.engine).reconcile_settings( + deployment_id=state.source.deployment_id, + claims_enabled=claims, + facts_enabled=facts, + ) + state.publish() + state.assert_tree() + + +@pytest.mark.parametrize("served", [False, True]) +def test_parked_new_upload_keeps_served_original( + publication: Publication, served: bool +) -> None: + state = publication + if not served: + with state.engine.begin() as connection: + connection.execute(text("UPDATE documents SET current_version_id = NULL")) + state.publish() + before = state.assert_tree() + with state.engine.begin() as connection: + version = uuid4() + connection.execute( + text("""INSERT INTO document_versions (deployment_id, doc_id, version_id, version_no, + content_hash, status) VALUES (:d, :doc, :v, 2, :h, 'ingesting')"""), + { + "d": state.source.deployment_id, + "doc": state.source.doc_id, + "v": version, + "h": state.source.content_hash, + }, + ) + connection.execute( + text("""INSERT INTO processing_state (processing_id, deployment_id, target_kind, target_id, + stage, component_version, content_hash, status, defer_reason) VALUES (:p, :d, 'document_version', :v, + 'convert', 'test', :h, 'pending', 'no_route')"""), + { + "p": uuid4(), + "d": state.source.deployment_id, + "v": version, + "h": state.source.content_hash, + }, + ) + state.publish() + assert state.assert_tree() == before + + +class RecordingQueue: + def __init__(self, *, fail: bool = False) -> None: + self.rows: list[UUID] = [] + self.fail = fail + + def announce( + self, + *, + processing_id: UUID, + route_snapshot: QueueRoute, + not_before_snapshot: datetime, + ) -> None: + self.rows.append(processing_id) + if self.fail: + raise RuntimeError("delivery lost") + + +@pytest.fixture +def runner( + publication: Publication, monkeypatch: pytest.MonkeyPatch +) -> SelfHostProfile: + """Explicit test-only binding, leaving both production profiles unactivated.""" + import rememberstack.profiles.selfhost as profile + + state = publication + handler = PublishCorpusHandler(publisher=state.publisher) + monkeypatch.setattr( + profile, + "_SUPPORTED_WORKER_STAGES", + (*profile._SUPPORTED_WORKER_STAGES, PipelineStage.PUBLISH_CORPUS), + ) + monkeypatch.setitem( + profile.WORKER_CLASSES, + "llm", + (*profile.WORKER_CLASSES["llm"], PipelineStage.PUBLISH_CORPUS), + ) + settings = SelfHostSettings(deployment_id=state.source.deployment_id) + context = SelfHostProfile( + settings=settings, + engine=state.engine, + raw_store=state.raw, + artifact_store=state.artifacts, + corpusfs_store=state.bucket.store, + task_queue=RecordingQueue(), + model_provider=FakeModelProvider(), + ) + monkeypatch.setattr(context, "_handler", lambda *, stage: handler) + return context + + +def test_transactional_enqueue_rollback_and_fresh_events_after_success( + publication: Publication, runner: SelfHostProfile +) -> None: + state = publication + state.publish() + marker = state.marker() + with pytest.raises(RuntimeError, match="rollback"), collect_new_work(): + with state.engine.begin() as connection: + corpus_changed_on( + connection=connection, + deployment_id=state.source.deployment_id, + doc_id=state.source.doc_id, + ) + raise RuntimeError("rollback") + assert state.marker() == marker + with state.engine.connect() as connection: + assert ( + connection.execute( + text("SELECT count(*) FROM processing_state") + ).scalar_one() + == 0 + ) + for title in ("B", "Annual Report", "B", "Annual Report"): + with collect_new_work() as work: + event = state.change(title=title) + assert [item.processing_id for item in work] == [event] + queue = RecordingQueue(fail=True) + announce_new_work(queue=queue, work=work) + assert queue.rows == [event] + # Lost announcements do not remove due rows; janitor can reannounce them. + ledger = WorkLedger(engine=state.engine, settings=WorkLedgerSettings()) + assert ledger.due_routes( + deployment_id=state.source.deployment_id, + routes=((PipelineStage.PUBLISH_CORPUS, None),), + ) == ((PipelineStage.PUBLISH_CORPUS, None),) + ledger.wake(processing_id=event) + assert ( + run_task(context=runner, processing_id=event).outcome + == RunResultOutcome.SUCCEEDED + ) + assert ( + run_task(context=runner, processing_id=event).outcome + == RunResultOutcome.NO_WORK + ) + state.assert_tree() + + +def test_duplicate_reordered_events_and_selfhost_class_claim( + publication: Publication, runner: SelfHostProfile +) -> None: + state = publication + first = state.change(title="B") + last = state.change(title="Annual Report") + assert ( + run_task(context=runner, processing_id=last).outcome + == RunResultOutcome.SUCCEEDED + ) + # The ordinary class loop claims the older event and recomputes A, not B. + loop = runner.worker_loop(worker_class="llm", concurrency=1) + results = loop.drain_due() + assert len(results) == 1 + result = results[0] + assert ( + result.processing_id == first and result.outcome == RunResultOutcome.SUCCEEDED + ) + state.assert_tree() + + +def test_inactive_policy_cannot_write_and_seeding_uses_current_events( + publication: Publication, runner: SelfHostProfile, monkeypatch: pytest.MonkeyPatch +) -> None: + state = publication + old = CorpusPolicy(builder_version="old") + with state.engine.begin() as connection: + event = corpus_changed_on( + connection=connection, + deployment_id=state.source.deployment_id, + doc_id=state.source.doc_id, + policy=old, + ).processing_id + assert ( + run_task(context=runner, processing_id=event).outcome + == RunResultOutcome.SUCCEEDED + ) + assert list(state.bucket.store.iter_keys(prefix="")) == [] + with state.engine.connect() as connection: + rows = ( + connection.execute( + text( + "SELECT processing_id, target_kind, target_id, component_version, payload, lane FROM processing_state ORDER BY enqueued_at" + ) + ) + .mappings() + .all() + ) + assert len(rows) == 2 + current = rows[1] + assert current["target_kind"] == "corpus_publication" + assert current["component_version"] == corpus_policy_version(DEFAULT_CORPUS_POLICY) + assert ( + current["payload"] == {"doc_id": str(state.source.doc_id)} + and current["lane"] is None + ) + assert current["target_id"] != rows[0]["target_id"] + assert ( + state.catalog.seed_current_policy( + deployment_id=state.source.deployment_id, batch_size=1 + ) + == 0 + ) + assert ( + run_task(context=runner, processing_id=current["processing_id"]).outcome + == RunResultOutcome.SUCCEEDED + ) + state.assert_tree() + + +@pytest.mark.parametrize("loss", ["lease", "lock"]) +def test_lost_owner_refuses_further_publication_requests( + publication: Publication, monkeypatch: pytest.MonkeyPatch, loss: str +) -> None: + state = publication + event = state.change() + ledger = WorkLedger(engine=state.engine, settings=WorkLedgerSettings()) + claimed = ledger.claim_one( + deployment_id=state.source.deployment_id, + stage=PipelineStage.PUBLISH_CORPUS, + lane=None, + processing_id=event, + ) + assert isinstance(claimed, ClaimedWork) + with state.catalog.locked( + deployment_id=state.source.deployment_id, work=claimed + ) as lock: + if loss == "lease": + with state.engine.begin() as connection: + connection.execute( + text( + "UPDATE processing_state SET lease_until = now() - interval '1 second' WHERE processing_id = :p" + ), + {"p": event}, + ) + else: + lock.connection.execute(text("SELECT pg_advisory_unlock_all()")) + with pytest.raises(CorpusLockLostError): + state.publisher.publish_corpus( + deployment_id=state.source.deployment_id, + doc_id=state.source.doc_id, + lock=lock, + ) + assert list(state.bucket.store.iter_keys(prefix="")) == [] + + +def test_canonical_title_transaction_enqueues_and_rolls_back( + publication: Publication, +) -> None: + from rememberstack.model.document_metadata import DocumentMetadata + + state = publication + with state.engine.begin() as connection: + connection.execute( + text( + "UPDATE document_metadata SET title = NULL, provenance = '{}' WHERE version_id = :v" + ), + {"v": state.source.version_id}, + ) + state.publish() + with state.engine.begin() as connection, collect_new_work() as events: + merge_converter_metadata_on( + connection=connection, + deployment_id=state.source.deployment_id, + version_id=state.source.version_id, + metadata=DocumentMetadata(title="Canonical title"), + mapping_version="test", + ) + assert len(events) == 1 and state.marker() is None + state.publish() + state.assert_tree() + + +def test_navigation_split_merge_preserves_survivor_files( + publication: Publication, monkeypatch: pytest.MonkeyPatch +) -> None: + state = publication + state.publisher.policy = CorpusPolicy(member_limit=32) + extras = [ + replace( + state.source, + doc_id=uuid4(), + version_id=uuid4(), + representation_id=uuid4(), + structure_generation_id=uuid4(), + title=f"Control {number}", + ) + for number in range(33) + ] + for document in extras: + _seed(state.engine, document) + assert ( + state.catalog.seed_current_policy( + deployment_id=state.source.deployment_id, + policy=state.publisher.policy, + batch_size=7, + ) + == 34 + ) + assert ( + state.catalog.seed_current_policy( + deployment_id=state.source.deployment_id, + policy=state.publisher.policy, + batch_size=7, + ) + == 0 + ) + state.publisher.reconcile(deployment_id=state.source.deployment_id, verify=True) + before = state.assert_tree() + shard_keys = {key for key in before if "/~" in key} + assert shard_keys + removed = extras[:3] + with state.engine.begin() as connection: + for document in removed: + connection.execute( + text("UPDATE documents SET deleted_at = now() WHERE doc_id = :doc"), + {"doc": document.doc_id}, + ) + corpus_changed_on( + connection=connection, + deployment_id=document.deployment_id, + doc_id=document.doc_id, + policy=state.publisher.policy, + ) + written = [] + original = state.bucket.store.replace_stream + + def record(**kwargs: Any) -> None: + written.append(kwargs["key"].root) + original(**kwargs) + + with monkeypatch.context() as patch: + patch.setattr(state.bucket.store, "replace_stream", record) + for document in removed: + state.publish(document.doc_id) + after = state.assert_tree() + assert shard_keys.isdisjoint(after) + assert not any( + key.endswith(("original.pdf", "document.md", "plot.png")) for key in written + ) + for document in [state.source, *extras[3:]]: + assert ( + after[document.path + "/original.pdf"] + == before[document.path + "/original.pdf"] + ) + + +@pytest.mark.parametrize("failure", ["session", "lease", "hash"]) +def test_multipart_publication_stops_and_cleans_on_owner_or_source_loss( + publication: Publication, monkeypatch: pytest.MonkeyPatch, failure: str +) -> None: + state = publication + state.publish() + old_original = state.bucket.store.read_bytes( + key=ObjectKey(state.source.path + "/original.pdf") + ) + content = b"%PDF-1.7\n" + b"v" * (18 * 1024 * 1024) + current = replace( + state.source, + version_id=uuid4(), + representation_id=uuid4(), + structure_generation_id=uuid4(), + version_no=2, + content_hash=digest(content), + raw_uri="new-large-original", + ) + state.raw.write_bytes( + key=ObjectKey(current.raw_uri), + content=content if failure != "hash" else b"bad" + content[3:], + storage_class="cold", + ) + _seed(state.engine, current) + state.source = current + event = state.change() + ledger = WorkLedger(engine=state.engine, settings=WorkLedgerSettings()) + work = ledger.claim_one( + deployment_id=current.deployment_id, + stage=PipelineStage.PUBLISH_CORPUS, + lane=None, + processing_id=event, + ) + assert isinstance(work, ClaimedWork) + parts = [] + upload = state.bucket.client.upload_part + with state.catalog.locked(deployment_id=current.deployment_id, work=work) as lock: + + def part(**kwargs: Any) -> Any: + result = upload(**kwargs) + parts.append(kwargs["PartNumber"]) + if len(parts) == 1: + with state.engine.begin() as connection: + if failure == "session": + connection.execute( + text("SELECT pg_terminate_backend(:pid)"), + {"pid": lock.backend_pid}, + ) + elif failure == "lease": + connection.execute( + text( + "UPDATE processing_state SET lease_until = now() - interval '1 second' WHERE processing_id = :p" + ), + {"p": event}, + ) + return result + + with monkeypatch.context() as patch: + patch.setattr(state.bucket.client, "upload_part", part) + with pytest.raises( + ValueError if failure == "hash" else CorpusLockLostError + ): + state.publisher.publish_corpus( + deployment_id=current.deployment_id, + doc_id=current.doc_id, + lock=lock, + ) + assert parts == ([1, 2] if failure == "hash" else [1]) + assert ( + state.bucket.store.read_bytes(key=ObjectKey(current.path + "/original.pdf")) + == old_original + ) + assert state.marker() is None + assert not state.bucket.client.list_multipart_uploads(Bucket=state.bucket.name).get( + "Uploads" + ) + if failure == "hash": + state.raw.replace_stream( + key=ObjectKey(current.raw_uri), chunks=(content,), storage_class="cold" + ) + state.publisher.reconcile(deployment_id=current.deployment_id, verify=True) + state.assert_tree() + + +def test_ordinary_retry_and_dlq_preserve_attempts_and_replay( + publication: Publication, runner: SelfHostProfile, monkeypatch: pytest.MonkeyPatch +) -> None: + state = publication + event = state.change() + with state.engine.begin() as connection: + connection.execute( + text( + "UPDATE processing_state SET max_attempts = 2 WHERE processing_id = :p" + ), + {"p": event}, + ) + original = state.bucket.store.replace_stream + + def fail(**kwargs: Any) -> None: + original(**kwargs) + raise RuntimeError("store interrupted") + + with monkeypatch.context() as patch: + patch.setattr(state.bucket.store, "replace_stream", fail) + assert ( + run_task(context=runner, processing_id=event).outcome + == RunResultOutcome.RETRY_SCHEDULED + ) + with state.engine.begin() as connection: + connection.execute( + text( + "UPDATE processing_state SET not_before = now() WHERE processing_id = :p" + ), + {"p": event}, + ) + assert ( + run_task(context=runner, processing_id=event).outcome + == RunResultOutcome.DEAD_LETTERED + ) + assert state.marker() is None + ledger = WorkLedger(engine=state.engine, settings=WorkLedgerSettings()) + replayed = ledger.replay_dead_letter( + deployment_id=state.source.deployment_id, processing_id=event + ) + assert replayed.attempts == 2 and replayed.max_attempts == 3 + assert ( + run_task(context=runner, processing_id=event).outcome + == RunResultOutcome.SUCCEEDED + ) + state.assert_tree() + + +def test_real_metadata_change_rolls_back_its_event_and_marker( + publication: Publication, +) -> None: + from rememberstack.model.document_metadata import DocumentMetadata + + state = publication + with state.engine.begin() as connection: + connection.execute( + text( + "UPDATE document_metadata SET title = NULL, provenance = '{}' WHERE version_id = :v" + ), + {"v": state.source.version_id}, + ) + state.publish() + marker = state.marker() + with pytest.raises(RuntimeError, match="rollback"): + with state.engine.begin() as connection: + merge_converter_metadata_on( + connection=connection, + deployment_id=state.source.deployment_id, + version_id=state.source.version_id, + metadata=DocumentMetadata(title="Rolled back"), + mapping_version="test", + ) + raise RuntimeError("rollback") + assert state.marker() == marker + with state.engine.connect() as connection: + assert ( + connection.execute( + text("SELECT count(*) FROM processing_state") + ).scalar_one() + == 0 + ) + state.assert_tree() + + +def test_mime_repair_in_same_family_enqueues_served_lineages( + publication: Publication, +) -> None: + from rememberstack.spine.document_metadata import refresh_family_on + + state = publication + with state.engine.begin() as connection: + connection.execute(text("UPDATE content_objects SET mime = 'audio/mpeg'")) + connection.execute(text("UPDATE document_metadata SET family = 'media'")) + state.publish() + with state.engine.begin() as connection, collect_new_work() as events: + connection.execute(text("UPDATE content_objects SET mime = 'video/mp4'")) + refresh_family_on( + connection=connection, + deployment_id=state.source.deployment_id, + content_hash=state.source.content_hash, + mime="video/mp4", + ) + assert len(events) == 1 and state.marker() is None + state.publish() + state.assert_tree() + + +@pytest.mark.parametrize("loss", ["lock", "lease"]) +def test_owner_loss_between_deletes_refuses_the_next_request( + publication: Publication, monkeypatch: pytest.MonkeyPatch, loss: str +) -> None: + state = publication + state.publish() + old_path = state.source.path + event = state.change(title="Moved") + ledger = WorkLedger(engine=state.engine, settings=WorkLedgerSettings()) + work = ledger.claim_one( + deployment_id=state.source.deployment_id, + stage=PipelineStage.PUBLISH_CORPUS, + lane=None, + processing_id=event, + ) + assert isinstance(work, ClaimedWork) + deleted = [] + original = state.bucket.store.delete + with state.catalog.locked( + deployment_id=state.source.deployment_id, work=work + ) as lock: + + def delete(**kwargs: Any) -> None: + original(**kwargs) + deleted.append(kwargs["key"].root) + if loss == "lock": + lock.connection.execute(text("SELECT pg_advisory_unlock_all()")) + else: + with state.engine.begin() as connection: + connection.execute( + text( + "UPDATE processing_state SET lease_until = now() - interval '1 second' WHERE processing_id = :p" + ), + {"p": event}, + ) + + with monkeypatch.context() as patch: + patch.setattr(state.bucket.store, "delete", delete) + with pytest.raises(CorpusLockLostError): + state.publisher.publish_corpus( + deployment_id=state.source.deployment_id, + doc_id=state.source.doc_id, + lock=lock, + ) + assert len(deleted) == 1 + assert list(state.bucket.store.iter_keys(prefix=old_path)) + assert state.marker() is None + state.publish() + state.assert_tree() + + +def test_structure_change_is_transactional_and_retry_does_not_enqueue_again( + publication: Publication, monkeypatch: pytest.MonkeyPatch +) -> None: + from rememberstack.model import SectionTreeRecord + from rememberstack.model import SkeletonStats + from rememberstack.model import SnappedSection + from rememberstack.model import StructureRouteTag + import rememberstack.spine.corpus_publication as publication_spine + from rememberstack.spine.document_catalog import DocumentCatalog + + state = publication + state.publish() + source = state.source + uri = "new-structure/active-pageindex.json" + state.artifacts.write_bytes( + key=ObjectKey(uri), + content=b'{"generation":"new","sections":[]}\n', + storage_class="hot", + ) + stats = SkeletonStats.model_validate( + {field: None for field in SkeletonStats.model_fields} + | {"stats_version": "test", "section_count": 0} + ) + record = SectionTreeRecord( + deployment_id=source.deployment_id, + doc_id=source.doc_id, + version_id=source.version_id, + representation_id=source.representation_id, + structure_generation_id=uuid4(), + sections=( + SnappedSection( + node_path="0", + parent_path=None, + title=source.title or "", + role="body", + block_start=0, + block_end=0, + char_start=0, + char_end=10, + summary="New stored summary", + ordinal=0, + ), + ), + placement_path="Reclassified", + structurer_name="test", + structurer_version="test", + skeleton_version="test", + skeleton_hash="test", + skeleton_producer_family="N/A", + skeleton_check_version=None, + roles_version="test", + summary_version="test", + placement_version="test", + selecting_check_id=None, + route_tag=StructureRouteTag.PARSER, + candidate_skeleton_hash="test", + stats_version="test", + stats=stats, + pageindex_uri=uri, + ) + catalog = DocumentCatalog(engine=state.engine) + with collect_new_work() as events: + catalog.record_section_tree(record=record) + assert len(events) == 1 and state.marker() is None + with collect_new_work() as repeated: + catalog.record_section_tree(record=record) + assert repeated == [] + state.publish() + before = state.assert_tree() + marker = state.marker() + + def fail_enqueue(**kwargs: Any) -> Any: + raise RuntimeError("enqueue rolled back") + + with monkeypatch.context() as patch: + patch.setattr(publication_spine, "enqueue_on", fail_enqueue) + with pytest.raises(RuntimeError, match="enqueue rolled back"): + catalog.record_section_tree( + record=record.model_copy( + update={ + "structure_generation_id": uuid4(), + "placement_path": "Never committed", + } + ) + ) + assert state.marker() == marker + assert state.selected()[0].structure_generation_id == record.structure_generation_id + assert state.assert_tree() == before diff --git a/src/tests/adapters/test_minio_store.py b/src/tests/adapters/test_minio_store.py index 008a64c12..aa6f8adce 100644 --- a/src/tests/adapters/test_minio_store.py +++ b/src/tests/adapters/test_minio_store.py @@ -538,3 +538,44 @@ def delete_object(self, *, Bucket: str, Key: str) -> object: store.delete(key=ObjectKey("missing")) else: store.delete(key=ObjectKey("missing")) + + +def test_s3_requests_have_configured_bounds_and_no_automatic_retries() -> None: + from pydantic import SecretStr + + from rememberstack.adapters.selfhost.minio import _client + from rememberstack.adapters.selfhost.minio import MinIOSettings + + client = _client( + settings=MinIOSettings( + endpoint_url="https://s3.example.invalid", + access_key=SecretStr("key"), + secret_key=SecretStr("secret"), + connect_timeout_s=2, + read_timeout_s=7, + ) + ) + config = client.meta.config # type: ignore[attr-defined] + assert (config.connect_timeout, config.read_timeout) == (2, 7) + assert config.retries["total_max_attempts"] == 1 + client.close() # type: ignore[attr-defined] + + +@pytest.mark.parametrize("field", ["connect_timeout_s", "read_timeout_s"]) +@pytest.mark.parametrize("value", [0, -1, float("inf"), float("nan")]) +def test_s3_timeout_bounds_must_be_positive_and_finite( + field: str, value: float +) -> None: + from pydantic import ValidationError + + from rememberstack.adapters.selfhost.minio import MinIOSettings + + with pytest.raises(ValidationError): + MinIOSettings.model_validate( + { + "endpoint_url": "https://s3.example.invalid", + "access_key": "key", + "secret_key": "secret", + field: value, + } + ) diff --git a/src/tests/adapters/test_object_operations.py b/src/tests/adapters/test_object_operations.py index ead93e851..1de096e6c 100644 --- a/src/tests/adapters/test_object_operations.py +++ b/src/tests/adapters/test_object_operations.py @@ -116,3 +116,18 @@ def fail(fd: int) -> None: assert store.read_bytes(key=key) == b"old" assert store.storage_class_of(key=key) == "cold" assert not list((tmp_path / ".objects.metadata").glob("tmp*")) + + +def test_local_purge_includes_orphaned_digest_metadata(tmp_path: Path) -> None: + store = LocalFSObjectStore(root=tmp_path / "corpus") + key = ObjectKey("folder/document.md") + store.replace_stream( + key=key, chunks=(b"source",), storage_class="hot", sha256="a" * 64 + ) + (tmp_path / "corpus" / key.root).unlink() + (tmp_path / ".corpus.metadata" / "classes" / key.root).unlink() + with pytest.raises(RuntimeError, match="purge verification"): + store.verify_objects_purged(keys=(), prefixes=(ObjectKey("folder"),)) + store.purge_objects(keys=(), prefixes=(ObjectKey("folder"),)) + store.verify_objects_purged(keys=(), prefixes=(ObjectKey("folder"),)) + assert not list((tmp_path / ".corpus.metadata" / "digests").rglob("*.md")) diff --git a/src/tests/core/test_corpus_export.py b/src/tests/core/test_corpus_export.py index e2f4b02bb..a51c3058f 100644 --- a/src/tests/core/test_corpus_export.py +++ b/src/tests/core/test_corpus_export.py @@ -46,6 +46,32 @@ def test_suffix_uses_uuid_bytes_and_needs_no_retained_metadata() -> None: ) +@pytest.mark.parametrize("limit", [32, 150]) +def test_ancestor_navigation_matches_full_render_and_omits_other_branches( + limit, +) -> None: + documents = [ + document(doc_id=UUID(int=index + 1), placement_path=topic, source_kind=kind) + for index, (topic, kind) in enumerate( + [("Finance/Annual", "upload")] * 70 + + [("Finance/Other", "upload")] * 3 + + [("Unrelated/Branch", "upload")] * 70 + + [("Unrelated/Branch", "email")] * 70 + ) + ] + ancestors = {"", "pdf", "pdf/finance", "pdf/finance/annual", "pdf/vanished"} + policy = CorpusPolicy(member_limit=limit) + full = render_navigation(documents, policy=policy) + partial = render_navigation(iter(documents), policy=policy, ancestors=ancestors) + expected = { + path: content + for path, content in full.items() + if path == "llms.txt" or posixpath.dirname(path).split("/~", 1)[0] in ancestors + } + assert partial == expected + assert "pdf/vanished/_index.md" not in partial + + @pytest.mark.parametrize( ("source", "mime", "family", "route", "attachment", "expected"), [ diff --git a/src/tests/database_reset.py b/src/tests/database_reset.py index d3deab303..f16e8ab23 100644 --- a/src/tests/database_reset.py +++ b/src/tests/database_reset.py @@ -56,6 +56,8 @@ def reset_database(*, config: Config) -> None: "p9_47_0068", "p9_48_0069", "p9_49_0070", + "p9_50_0071", + "p9_51_0072", } or connection.execute( text("SELECT to_regclass('public.fact_applications') IS NOT NULL") diff --git a/src/tests/object_store_contract.py b/src/tests/object_store_contract.py index 5a8a20bfe..6e70bb539 100644 --- a/src/tests/object_store_contract.py +++ b/src/tests/object_store_contract.py @@ -6,6 +6,7 @@ import pytest +from rememberstack.core.object_transfer import object_transfer_scope from rememberstack.model import ObjectAlreadyExistsError from rememberstack.model import ObjectKey from rememberstack.model import ObjectKeyEscapesRootError @@ -180,3 +181,37 @@ def test_read_chunk_size_must_be_positive( ) -> None: with pytest.raises(ValueError, match="positive"): list(store.iter_bytes(key=ObjectKey("unused"), chunk_size=size)) + + def test_digest_metadata_and_mutation_guard(self, store: OperationStore) -> None: + key = ObjectKey("digest") + assert store.sha256_of(key=key) is None + store.write_bytes(key=key, content=b"old", storage_class="hot") + assert store.sha256_of(key=key) is None + digest = sha256(b"new").hexdigest() + called = [] + store.replace_stream( + key=key, + chunks=(b"new",), + storage_class="hot", + sha256=digest, + before_write=lambda: called.append(True), + ) + assert called and store.sha256_of(key=key) == digest + + def lost() -> None: + raise RuntimeError("lock lost") + + with object_transfer_scope() as transfer: + with pytest.raises(RuntimeError, match="lock lost"): + store.replace_stream( + key=key, + chunks=(b"stale",), + storage_class="hot", + sha256=sha256(b"stale").hexdigest(), + before_write=lost, + ) + assert transfer.bytes_written == 0 + assert store.read_bytes(key=key) == b"new" + assert store.sha256_of(key=key) == digest + store.delete(key=key) + assert store.sha256_of(key=key) is None diff --git a/src/tests/spine/test_migrations.py b/src/tests/spine/test_migrations.py index 094923644..af9c7eb61 100644 --- a/src/tests/spine/test_migrations.py +++ b/src/tests/spine/test_migrations.py @@ -153,6 +153,8 @@ def test_revision_graph_is_one_linear_structural_chain() -> None: "p9_47_0068", "p9_48_0069", "p9_49_0070", + "p9_50_0071", + "p9_51_0072", ) assert len(script.get_heads()) == 1 @@ -694,7 +696,7 @@ def test_postgresql_fresh_downgrade_reupgrade_mutation_and_noop_lifecycle() -> N head_before_noop = _head_revision(database_url=database_url) command.upgrade(config=config, revision="head") head_after_noop = _head_revision(database_url=database_url) - assert head_before_noop == head_after_noop == "p9_49_0070" + assert head_before_noop == head_after_noop == "p9_51_0072" assert _inventory(database_url=database_url) == restored_inventory @@ -1311,7 +1313,7 @@ def test_fresh_setup_runs_on_a_server_without_sql_pgq() -> None: assert graph_catalog_problems(connection=connection) == () finally: engine.dispose() - assert _head_revision(database_url=database_url) == "p9_49_0070" + assert _head_revision(database_url=database_url) == "p9_51_0072" def test_citation_projection_migration_round_trips_graph_metadata() -> None: @@ -1464,7 +1466,7 @@ def test_d122_refuses_a_populated_store() -> None: engine.dispose() reset_database(config=config) command.upgrade(config=config, revision="head") - assert _head_revision(database_url=database_url) == "p9_49_0070" + assert _head_revision(database_url=database_url) == "p9_51_0072" def test_d150_refuses_to_drop_staged_originals() -> None: @@ -1508,7 +1510,7 @@ def test_d150_refuses_to_drop_staged_originals() -> None: engine.dispose() reset_database(config=config) command.upgrade(config=config, revision="head") - assert _head_revision(database_url=database_url) == "p9_49_0070" + assert _head_revision(database_url=database_url) == "p9_51_0072" _BACKFILL_MIMES = ( @@ -1717,7 +1719,7 @@ def families() -> dict[object, str]: engine.dispose() reset_database(config=config) command.upgrade(config=config, revision="head") - assert _head_revision(database_url=database_url) == "p9_49_0070" + assert _head_revision(database_url=database_url) == "p9_51_0072" def test_d134_own_document_name_span_downgrade_guard() -> None: @@ -1776,7 +1778,7 @@ def span_column_exists() -> bool: engine.dispose() reset_database(config=config) command.upgrade(config=config, revision="head") - assert _head_revision(database_url=database_url) == "p9_49_0070" + assert _head_revision(database_url=database_url) == "p9_51_0072" def test_d138_downgrade_guard_protects_search_only_readings() -> None: @@ -1911,4 +1913,4 @@ def eligibility_column_exists() -> bool: engine.dispose() reset_database(config=config) command.upgrade(config=config, revision="head") - assert _head_revision(database_url=database_url) == "p9_49_0070" + assert _head_revision(database_url=database_url) == "p9_51_0072" diff --git a/src/tests/test_queue_port_contract.py b/src/tests/test_queue_port_contract.py index 0693680ab..6086063fa 100644 --- a/src/tests/test_queue_port_contract.py +++ b/src/tests/test_queue_port_contract.py @@ -45,6 +45,7 @@ "dispatch_knowledge", "hard_forget", "review_fact_windows", + "publish_corpus", ) diff --git a/src/tests/workers/test_corpus_export_inventory.py b/src/tests/workers/test_corpus_export_inventory.py index 53adfb2fd..f5747f233 100644 --- a/src/tests/workers/test_corpus_export_inventory.py +++ b/src/tests/workers/test_corpus_export_inventory.py @@ -2,7 +2,6 @@ from dataclasses import replace import json -import posixpath import pytest @@ -270,9 +269,7 @@ def test_large_asset_tables_split_and_merge_without_renaming_any_reader_file() - } files["../_index.md"] = b"parent" _check_indexes(files, 32) - assert any( - posixpath.basename(posixpath.dirname(path)).startswith("~") for path in files - ) + assert any(path.startswith("~/") for path in files) old_copies = {file.path: file for file in small.files if isinstance(file, CopyFile)} new_copies = {file.path: file for file in large.files if isinstance(file, CopyFile)} assert all(new_copies[path] == file for path, file in old_copies.items()) diff --git a/src/tests/workers/test_corpus_reader_export_pg.py b/src/tests/workers/test_corpus_reader_export_pg.py index d2a3b93d9..62d281f32 100644 --- a/src/tests/workers/test_corpus_reader_export_pg.py +++ b/src/tests/workers/test_corpus_reader_export_pg.py @@ -71,17 +71,18 @@ def _seed(engine: Engine, source: CorpusDocument) -> None: "family": source.family, "route": source.route, "date": source.source_date, + "version_no": source.version_no, "placement": source.placement_path, "summary": source.root_summary, "source_kind": source.source_kind, } statements = ( """INSERT INTO documents (doc_id, deployment_id, source_kind, source_ref, title) - VALUES (:doc, :d, :source_kind, :doc, :lineage_title)""", + VALUES (:doc, :d, :source_kind, :doc, :lineage_title) ON CONFLICT DO NOTHING""", """INSERT INTO content_objects (deployment_id, content_hash, mime, byte_size, raw_uri) VALUES (:d, :hash, :mime, 100, :raw) ON CONFLICT DO NOTHING""", """INSERT INTO document_versions (version_id, deployment_id, doc_id, content_hash, - version_no, status, source_modified_at) VALUES (:v, :d, :doc, :hash, 1, 'ready', :date)""", + version_no, status, source_modified_at) VALUES (:v, :d, :doc, :hash, :version_no, 'ready', :date)""", """INSERT INTO document_metadata (deployment_id, version_id, doc_id, family, title, file_name, metadata_mapping_version) VALUES (:d, :v, :doc, :family, :title, :filename, 'test')""", """INSERT INTO document_representations (representation_id, deployment_id, version_id, @@ -403,13 +404,15 @@ def test_attachment_type_uses_its_own_format(engine: Engine, corpus) -> None: assert _select(engine, doc_id=attachment.doc_id)[0] == selected -def test_schema_change_is_only_one_nullable_marker(engine: Engine) -> None: +def test_schema_change_is_only_nullable_marker_and_cleanup_paths( + engine: Engine, +) -> None: def shape(): with engine.connect() as connection: return set( connection.execute( text("""SELECT table_schema, table_name, column_name, - data_type, is_nullable, column_default FROM information_schema.columns + data_type, udt_name, is_nullable, column_default FROM information_schema.columns WHERE table_schema IN ('public', 'memory_v1')""") ).tuples() ) @@ -420,7 +423,16 @@ def shape(): try: before = shape() assert after - before == { - ("public", "documents", "corpus_published_revision", "text", "YES", None) + ( + "public", + "documents", + "corpus_published_revision", + "text", + "text", + "YES", + None, + ), + ("public", "documents", "corpus_paths", "ARRAY", "_text", "YES", None), } assert before - after == set() finally: diff --git a/src/tests/workers/test_processing_layers_pg.py b/src/tests/workers/test_processing_layers_pg.py index ba975f388..4506d5e4f 100644 --- a/src/tests/workers/test_processing_layers_pg.py +++ b/src/tests/workers/test_processing_layers_pg.py @@ -1814,8 +1814,18 @@ def observe() -> None: ) assert rig.gap(version_id=version.version_id, layer="facts") is None # (readiness pins production chunk parameters; this rig's are small) + # This E-layer rig deliberately leaves D155's publisher unbound. Its two + # serving-change events stay pending; every layer job must still succeed. assert ( - rig.scalar("SELECT count(*) FROM processing_state WHERE status <> 'succeeded'") + rig.scalar( + "SELECT count(*) FROM processing_state WHERE stage = 'publish_corpus' AND status = 'pending'" + ) + == 2 + ) + assert ( + rig.scalar( + "SELECT count(*) FROM processing_state WHERE stage <> 'publish_corpus' AND status <> 'succeeded'" + ) == 0 ) assert rig.stage_rows(stages=("label_relation",)) > 0 diff --git a/website/public/llms-full.txt b/website/public/llms-full.txt index ac09b9ce0..da45981c9 100644 --- a/website/public/llms-full.txt +++ b/website/public/llms-full.txt @@ -7235,6 +7235,7 @@ and three values Compose sets itself, which win over `.env`: |---|---| | `REMEMBERSTACK_DATABASE_URL` | Built from `REMEMBERSTACK_POSTGRES_USER`, `_PASSWORD` and `_DB`, pointing at the `postgres` service. | | `REMEMBERSTACK_MINIO_ENDPOINT_URL` | `http://object-store:8333`, the bundled SeaweedFS store. | +| `REMEMBERSTACK_MINIO_CONNECT_TIMEOUT_S`, `REMEMBERSTACK_MINIO_READ_TIMEOUT_S` | Per-request S3 connect/read timeouts, 5/30 seconds by default. Automatic S3 retries are disabled; failed pipeline work uses the durable work ledger retry path. | | `REMEMBERSTACK_SELFHOST_API_PORT` | `8000`. In `.env` the same variable is the host port Compose publishes. | A variable exported in your shell overrides `.env` only if it is on the @@ -19242,6 +19243,8 @@ Read by `compose.yaml` from `.env`, not by the engine. | `REMEMBERSTACK_MINIO_ACCESS_KEY` | required | secret | Object-store access key; also the bundled SeaweedFS store's admin access key. `.env.example` ships none; generate it at install. | | `REMEMBERSTACK_MINIO_SECRET_KEY` | required | secret | Object-store secret key; also the bundled SeaweedFS store's admin secret key. `.env.example` ships none; generate it at install. | | `REMEMBERSTACK_MINIO_REGION` | `us-east-1` | string | S3 region name used for signing. | +| `REMEMBERSTACK_MINIO_CONNECT_TIMEOUT_S` | `5` | finite seconds, > 0 | Connection timeout for each S3 request. | +| `REMEMBERSTACK_MINIO_READ_TIMEOUT_S` | `30` | finite seconds, > 0 | Socket read timeout for each S3 request. Multipart uploads send at most 8 MiB per part. | | `REMEMBERSTACK_SELFHOST_RAW_BUCKET_NAME` | `remember-raw` | string | Bucket for original files. Fixed after the first start. | | `REMEMBERSTACK_SELFHOST_ARTIFACTS_BUCKET_NAME` | `remember-artifacts` | string | Bucket for converted Markdown and artifacts. Fixed after the first start. | | `REMEMBERSTACK_SELFHOST_CORPUSFS_BUCKET_NAME` | `remember-corpusfs` | string | Bucket for filesystem-view snapshots. Fixed after the first start. | @@ -20708,6 +20711,11 @@ absent from the current release; nothing here has a date. ## Knowledge +- **Self-contained document folders on mounted filesystems.** The current + [filesystem view](https://remember.dev/docs/self-hosting/filesystem-views) links to originals + and converted artifacts; it does not place their bytes together in one + document folder. + - **Compiled pages.** RememberStack does not write summary pages that combine what it knows about a topic; the envelope's `pages` field and the `compiled` grain exist but stay empty, and the `k` install extra installs diff --git a/website/src/app/docs/project/not-built-yet/page.mdx b/website/src/app/docs/project/not-built-yet/page.mdx index 7c9933ad5..d72130e10 100644 --- a/website/src/app/docs/project/not-built-yet/page.mdx +++ b/website/src/app/docs/project/not-built-yet/page.mdx @@ -54,6 +54,11 @@ absent from the current release; nothing here has a date. ## Knowledge +- **Self-contained document folders on mounted filesystems.** The current + [filesystem view](/docs/self-hosting/filesystem-views) links to originals + and converted artifacts; it does not place their bytes together in one + document folder. + - **Compiled pages.** RememberStack does not write summary pages that combine what it knows about a topic; the envelope's `pages` field and the `compiled` grain exist but stay empty, and the `k` install extra installs diff --git a/website/src/app/docs/reference/configuration/page.mdx b/website/src/app/docs/reference/configuration/page.mdx index 13651f679..5e7abfaf4 100644 --- a/website/src/app/docs/reference/configuration/page.mdx +++ b/website/src/app/docs/reference/configuration/page.mdx @@ -100,6 +100,8 @@ Read by `compose.yaml` from `.env`, not by the engine. | `REMEMBERSTACK_MINIO_ACCESS_KEY` | required | secret | Object-store access key; also the bundled SeaweedFS store's admin access key. `.env.example` ships none; generate it at install. | | `REMEMBERSTACK_MINIO_SECRET_KEY` | required | secret | Object-store secret key; also the bundled SeaweedFS store's admin secret key. `.env.example` ships none; generate it at install. | | `REMEMBERSTACK_MINIO_REGION` | `us-east-1` | string | S3 region name used for signing. | +| `REMEMBERSTACK_MINIO_CONNECT_TIMEOUT_S` | `5` | finite seconds, > 0 | Connection timeout for each S3 request. | +| `REMEMBERSTACK_MINIO_READ_TIMEOUT_S` | `30` | finite seconds, > 0 | Socket read timeout for each S3 request. Multipart uploads send at most 8 MiB per part. | | `REMEMBERSTACK_SELFHOST_RAW_BUCKET_NAME` | `remember-raw` | string | Bucket for original files. Fixed after the first start. | | `REMEMBERSTACK_SELFHOST_ARTIFACTS_BUCKET_NAME` | `remember-artifacts` | string | Bucket for converted Markdown and artifacts. Fixed after the first start. | | `REMEMBERSTACK_SELFHOST_CORPUSFS_BUCKET_NAME` | `remember-corpusfs` | string | Bucket for filesystem-view snapshots. Fixed after the first start. | diff --git a/website/src/app/docs/self-hosting/configuration/page.mdx b/website/src/app/docs/self-hosting/configuration/page.mdx index e799650f4..2e08bb457 100644 --- a/website/src/app/docs/self-hosting/configuration/page.mdx +++ b/website/src/app/docs/self-hosting/configuration/page.mdx @@ -57,6 +57,7 @@ and three values Compose sets itself, which win over `.env`: |---|---| | `REMEMBERSTACK_DATABASE_URL` | Built from `REMEMBERSTACK_POSTGRES_USER`, `_PASSWORD` and `_DB`, pointing at the `postgres` service. | | `REMEMBERSTACK_MINIO_ENDPOINT_URL` | `http://object-store:8333`, the bundled SeaweedFS store. | +| `REMEMBERSTACK_MINIO_CONNECT_TIMEOUT_S`, `REMEMBERSTACK_MINIO_READ_TIMEOUT_S` | Per-request S3 connect/read timeouts, 5/30 seconds by default. Automatic S3 retries are disabled; failed pipeline work uses the durable work ledger retry path. | | `REMEMBERSTACK_SELFHOST_API_PORT` | `8000`. In `.env` the same variable is the host port Compose publishes. | A variable exported in your shell overrides `.env` only if it is on the