diff --git a/AGENTS.md b/AGENTS.md index 94ad4953..7f3e92d2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,12 +9,12 @@ Single library + binary crate, not a workspace. Stable contract is MCP tools (10 From project root. CI pins Rust 1.89 (`rust-version` in `Cargo.toml`); edition 2021. ```bash -make check # canonical gate (= CI): fmt + clippy + no-default check + all-features tests + hygiene + dependency-policy + packaging-check +make check # canonical gate (= CI): fmt + clippy + no-default check + documents feature-off parity + all-features tests + hygiene + dependency-policy + packaging-check make release-check # check + docs + release build + publish dry-run make bench-check # compile-check the Criterion perf harness (characterization only, never a threshold); fuzz: make fuzz-smoke ``` -Feature flags: `pdf` and `browser` are enabled by Cargo defaults; `mock` is the test-only engine harness (**required for integration/corpus tests**, and plain `cargo test` misses most of them); `egress` is opt-in and excluded from prebuilt/default binaries; `live-smoke` implies `mock`; `live-mcp-smoke` is the opt-in real MCP/network smoke that retains default `pdf`/`browser` and does not enable `mock`. Both live smoke targets are ignored by default. Tests must pass keyless: CI blanks all credential env vars, so missing credentials are provider-scoped skips, never global failures. Tests must not require network. +Feature flags: `pdf`, `browser`, and `documents` are enabled by Cargo defaults; `mock` is the test-only engine harness (**required for integration/corpus tests**, and plain `cargo test` misses most of them); `egress` is opt-in and excluded from prebuilt/default binaries; `live-smoke` implies `mock`; `live-mcp-smoke` is the opt-in real MCP/network smoke that retains default `pdf`/`browser`/`documents` and does not enable `mock`. Both live smoke targets are ignored by default. Tests must pass keyless: CI blanks all credential env vars, so missing credentials are provider-scoped skips, never global failures. Tests must not require network. ```bash cargo test --locked --features mock --test web_search_integration # single suite diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e9aaa08..db215b93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- Container-document extraction (DOCX, XLSX, PPTX, EPUB, CSV/TSV) is now part of the default feature set of every published binary and the Python wheel. `[fetch].documents_enabled` remains the operator switch; a CSV URL now returns a `document` object instead of the previous table preview. + - The advertised `tools/list` surface is re-pinned: full+full fingerprint `678e2a042ab5b39b` (33,983 bytes) becomes `d7968115e378f708` (34,226 bytes, +243), and the compact profile becomes `4922171e414dc480` (22,405 bytes). The growth is the three selector-honest descriptions that now state the accepted forms for `repo_search`, `repo_map`, and `security_search`, plus the corrected `provider_status` disclaimer; `fetch.items` gained a description too. A byte reduction was not achieved. Hosts cache by fingerprint plus server version, so refresh the cached surface. - `repo_map` now publishes `next_actions` alongside `suggested_fetches`. Each entry is an executable `fetch` call carrying the repo item the suggestion already resolved, so a caller never reconstructs a locator, and `suggested_fetches` stays populated as a typed convenience. diff --git a/Cargo.toml b/Cargo.toml index c806b1b9..0a84c10e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,7 +40,7 @@ name = "eggsearch" path = "src/main.rs" [features] -default = ["pdf", "browser"] +default = ["pdf", "browser", "documents"] mock = [] pdf = ["dep:lopdf", "dep:flate2"] browser = ["dep:chromiumoxide"] diff --git a/Makefile b/Makefile index dc77804e..56b3f4c2 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ -.PHONY: check ci fmt clippy feature-check test hygiene dependency-policy packaging-check producer-drift release-check release-candidate-check docs-check release-build publish-check bench-check fuzz-smoke live-smoke live-mcp-smoke live-release-smoke eval-tool-surface eval-retrieval-quality native-forge-smoke-github native-forge-smoke-gitlab native-forge-smoke-codeberg native-forge-smoke-gitea native-forge-smoke-all +.PHONY: check ci fmt clippy feature-check parity-check test hygiene dependency-policy packaging-check producer-drift release-check release-candidate-check docs-check release-build publish-check bench-check fuzz-smoke live-smoke live-mcp-smoke live-release-smoke eval-tool-surface eval-retrieval-quality native-forge-smoke-github native-forge-smoke-gitlab native-forge-smoke-codeberg native-forge-smoke-gitea native-forge-smoke-all -check: fmt clippy feature-check test hygiene dependency-policy packaging-check +check: fmt clippy feature-check parity-check test hygiene dependency-policy packaging-check ci: check @@ -13,6 +13,11 @@ clippy: feature-check: cargo check --locked --no-default-features +# The default feature set is what ships, so the feature-off half of +# tests/documents.rs would otherwise only ever run by hand. +parity-check: + cargo test --locked --no-default-features --test documents + test: cargo test --locked --all-features diff --git a/architecture/build.md b/architecture/build.md index c3ea8747..9717893c 100644 --- a/architecture/build.md +++ b/architecture/build.md @@ -199,15 +199,19 @@ cargo run -- mcp stdio cargo run -- mcp serve ``` -Feature-scoped runs (default features already include `pdf` and `browser`, so the -flags below are only needed after `--no-default-features` or to be explicit): +Feature-scoped runs (Cargo defaults include `pdf`, `browser`, and `documents`, so a +narrower build starts from `--no-default-features`): ```bash cargo run --features mock -- search "test query" -cargo run --features pdf -- fetch https://example.com/doc.pdf -cargo run --features browser -- fetch https://example.com +cargo run --no-default-features --features pdf -- fetch https://example.com/doc.pdf +cargo run --no-default-features --features browser -- fetch https://example.com ``` +To reproduce the previous artifact posture without container-document +extraction, build with `--no-default-features --features pdf,browser`. This +retains PDF extraction and browser rendering but leaves `documents` out. + Diagnostics: ```bash diff --git a/architecture/fetch.md b/architecture/fetch.md index f2c60a94..47344dc4 100644 --- a/architecture/fetch.md +++ b/architecture/fetch.md @@ -237,11 +237,13 @@ per-tier byte budgets with exact accounting (drift self-heals in `stats()`). - `DerivedCacheKey { scope, raw_content_hash, extraction_key }` where the hash is `xxh3_64(body)` (`build_raw_response_hash`) and `ExtractionCacheKey` covers `extract_mode`, exact `max_chars`, `include_links`, `pdf_pages`, - `pdf_ocr`, `include_media`, `renderer_version: 5`, and `sanitize_output`. - Version 5 isolates document-scoped extraction; version 4 isolates the - encrypted-PDF refusal behavior; version 3 isolates entries derived before - PDF page classification stopped depending on `include_media`; version 2 - isolated entries written before representation negotiation existed. + `pdf_ocr`, `include_media`, `renderer_version: 6`, and `sanitize_output`. + Version 6 covers the extraction-fidelity and bound changes and invalidates + every derived-cache entry class, not only container-document entries. Version + 5 isolated document-scoped extraction; version 4 isolates the encrypted-PDF + refusal behavior; version 3 isolates entries derived before PDF page + classification stopped depending on `include_media`; version 2 isolated + entries written before representation negotiation existed. - `DerivedDocumentCacheEntry` stores the extracted title/description/text, `raw_text`, links, truncation flags, the structured `FetchDocument` (blocks, outline, chunks), trust markers, and transport tag. @@ -377,23 +379,58 @@ matches every ZIP. ODF, legacy binary Office, and RTF resolve to resolves to `document_encrypted`. `FetchClient` mirrors its PDF early return with a document path: the pre-body -gate admits a supported format only when the feature is compiled in, the body is -read under a 16 MiB document cap, and the same extraction runs from a fresh -response and from raw-cache re-derivation. With the feature off, every path -behaves exactly as before. +gate admits a supported format only when the feature is compiled in. The +extractor input ceiling is 16 MiB (`MAX_INPUT_BYTES`), additionally clamped by +`[fetch].max_bytes` (2,000,000 bytes by default); extraction sees only the +admitted body. The same extraction runs from a fresh response and from +raw-cache re-derivation. With the feature off, every path behaves exactly as +before. Bounds are enforced on real inflated bytes, not on central-directory sizes, -which the archive controls: 64 MiB decompressed, a 100:1 inflation ratio, 4,096 -archive entries, 4,096 parts, 200,000 characters before the caller budget, and -XML depth 64. The archive is pre-scanned before `calamine` inflates it. Entries -are never extracted to disk, absolute and parent-traversal names are rejected, -and no DTD, external entity, `XInclude`, or external relationship is resolved. +which the archive controls: `MAX_DECOMPRESSED_BYTES` is 64 MiB, the inflation +ratio is 100:1, and the archive-entry and part bounds are 4,096 each. +`MAX_DOCUMENT_CHARS` caps extracted text at 200,000 characters per document. +The rendered per-part budget defaults to 12,000 characters +(`[fetch].max_chars_default`) and can be addressed up to `[fetch].max_chars_cap` +(50,000 by default); those budget defaults are not the hard extracted-text +ceiling. XML nesting depth is 64. `MAX_XML_TOKENS` is 262,144 for the +token-scanned DOCX body, PPTX slide documents, and EPUB spine documents. + +Workbook extraction bounds 200,000 observed cells (`MAX_CELL_COUNT`) across +the workbook. Because the spreadsheet reader allocates a dense rectangle over +observed cells, the bounding rectangle spanned by those cells is bounded too. +The sheet-size scan streams sheet XML and counts observed `` elements +instead of collecting a token vector; declared `` and the +column-times-row product are not treated as content. Thus a sheet declaring +`A1:XFD1048576` but populating one cell extracts normally, while a genuinely +over-cap sheet is refused. CSV has the same 200,000-cell bound and enforces it +incrementally during the scan, refusing at the cap rather than after building +a row. + +For XML text extraction, the five predefined XML entities (`&`, `<`, +`>`, `"`, `'`) and decimal and hexadecimal character references +are decoded into the surrounding text run. An undeclared named reference such +as ` ` is preserved as its literal source text, neither dropped nor +expanded; there is deliberately no HTML entity table, so output never depends +on a table version. Adjacent character data, CDATA, and references merge into +one text run, so no separator is inserted inside a word. + +A plain `` with no internal subset and no `SYSTEM` or `PUBLIC` +identifier is accepted. A doctype body containing `[`, `SYSTEM`, or `PUBLIC` +(case-insensitive) is refused as `document_malformed`. No entity is ever +resolved from a doctype, and no external entity, `XInclude`, or external +relationship is resolved. Entries are never extracted to disk, and absolute +and parent-traversal names are rejected. A malformed container returns +`document_malformed`, never an empty success. Ordering is fixed and independent of ZIP directory order: DOCX body order, PPTX `presentation.xml` slide order, workbook sheet order, EPUB spine order, and fixed 100-row CSV blocks. `FetchDocument` carries `format`, `parts`, and `parts_total` additively; the response-level `text` remains the bounded concatenation, so an agent that never reads `parts` still sees the document. +Each part carries its extractor truncation flag: the part that reaches its +character budget is flagged, later parts are not, and `document_truncated` is +true when any part was cut. The document path is admitted before the ordinary HTML/text/PDF rejection, so a container format is no longer refused as an unsupported content type when the feature is compiled in; with the feature off, that rejection is unchanged. diff --git a/architecture/packaging.md b/architecture/packaging.md index 0c3faca1..4bd17a90 100644 --- a/architecture/packaging.md +++ b/architecture/packaging.md @@ -29,13 +29,14 @@ Executable names are stable and carry no version; the tag `vX.Y.Z` is the version namespace. Windows assets keep the `.exe` suffix, non-Windows assets never do. Linux GNU builds use pinned Zig/cargo-zigbuild with a glibc 2.17 floor. Default features build every release asset, so each published binary -carries PDF extraction and browser rendering; `egress` stays a non-default -source-build feature and is never a binary product. +carries PDF extraction, browser rendering, and container-document extraction; +`egress` stays a non-default source-build feature and is never a binary product. The Python wheel is a separate distribution, not a second binary SKU. `bindings/python/Cargo.toml` builds the crate with -`default-features = false, features = ["pdf"]`, so the wheel carries PDF -extraction but not browser rendering, which still needs a system Chrome/Chromium. +`default-features = false, features = ["pdf", "browser", "documents"]`, so the wheel +carries PDF extraction, browser rendering, and container-document extraction. +Browser rendering still needs a system Chrome/Chromium executable. Asset names, the seven targets, and the 19-name release inventory are unchanged. `src/platform.rs` mirrors the same seven rows as `RELEASE_TARGETS` with diff --git a/architecture/python-library.md b/architecture/python-library.md index fc3f9f39..0a80b795 100644 --- a/architecture/python-library.md +++ b/architecture/python-library.md @@ -53,10 +53,11 @@ PyO3 and Python packaging dependencies must not enter the root crate's default dependency graph or change its binary artifact inventory. Python import is side-effect-free. The binding owns Python types and lifecycle adaptation; all execution delegates through `src/sdk.rs`. The binding compiles -`pdf` and `browser` with default features disabled; this is the single feature -set used across Python wheel targets, and `egress` is not compiled. The browser -feature uses a system Chrome/Chromium executable at runtime and never bundles -one. Missing Chrome does not block installation, import, process startup, +`pdf`, `browser`, and `documents` with default features disabled; this is the +single feature set used across Python wheel targets, and `egress` is not compiled. +The wheel includes PDF extraction, browser rendering, and container-document +extraction. The browser feature uses a system Chrome/Chromium executable at +runtime and never bundles one. Missing Chrome does not block installation, import, process startup, search, or HTTP fetch. For a missing executable, explicit browser requests raise `EggsearchError` with `code == "browser_unavailable"` and the cause in `message`; `auto` retains the HTTP outcome and adds a structured diff --git a/architecture/testing.md b/architecture/testing.md index be3bf675..d9c6e747 100644 --- a/architecture/testing.md +++ b/architecture/testing.md @@ -15,7 +15,7 @@ Per-suite counts live in `docs/test-inventory.md`; suite placement rules live in |----------|---------| | `tests/mcp_tools.rs`, `web_search_integration.rs`, `web_fetch_integration.rs`, `provider_routing.rs`, `provider_probe_conformance.rs`, `repo_workflow.rs`, `research_workflow.rs`, `security_workflow.rs`, `evidence_contract.rs` | Behavioral MCP/workflow contracts | | `tests/snapshot_change.rs` | Durable deterministic fetch snapshots, sanitized stored text, brief projection, disabled and corrupt-store degradation, and caller-key validation | -| `tests/documents.rs` | Container-document extraction for CSV/TSV, EPUB, DOCX, XLSX, and PPTX, deterministic ordering, typed outcomes, and feature-off parity | +| `tests/documents.rs` | Container-document extraction for CSV/TSV, EPUB, DOCX, XLSX, and PPTX, deterministic ordering, typed outcomes, and feature-off parity (11 cases with the feature, 3 without) | | `tests/support/mod.rs` | Shared integration-test harness: git fixture and mock/local state builders, imported with `mod support;` (a module, never a suite target) | | `tests/corpus_runner.rs` + `tests/corpus/scenarios/` | Multi-step workflow regression | | `tests/corpus/adversarial/` + `tests/adversarial_corpus.rs` | Malformed-input structural validation | @@ -43,7 +43,7 @@ Use behavioral suite names. Historical phase-suite names are retired; do not int | `web_search_integration` | Web search validation, sanitization, intent reranking, excerpt bounds, derived-intent reporting/applied reranking, search-result cache and coalescing equivalence | | `web_fetch_integration` | Fetch extraction, truncation, metadata-only mode, safety bounds | | `snapshot_change` | Persistent `new`/`same`/`changed`/`removed` comparison, content privacy, brief projection, disabled and corrupt-store degradation, and caller-key validation | -| `documents` | Bounded container-document extraction, deterministic part order, the four outcome kinds, and feature-off parity | +| `documents` | Bounded container-document extraction, deterministic part order, the four outcome kinds, and feature-off parity (11 cases with the feature, 3 without); fixtures include a DOCX with XML character references, an EPUB with a plain doctype, and delimiter-dense CSV refused at the cell bound | | `provider_routing` | Provider routing, code-host rewrites, diagnostics, capability-skip telemetry, keyless source-provider and credentialed-provider status/opt-in reporting, explicit-provider rejection classification matrix, `parse_shape` transitions and wire round-trip, CodeGG parity qualification journeys | | `provider_probe_conformance` | Shared probe service: configured/routable success, missing-key and config skips, unknown-provider skips, timeout, HTTP error (including 429 with `http_status`), parse and network failures, panic containment, probe-health isolation (no consecutive-failure or cooldown write), search-budget derivation and override, explicit-request-after-degraded semantics, bounded/sanitized messages, credential non-leakage, narrow-request budget observance, descriptor source-of-truth for native versus local domain filtering | | `repo_workflow` | Repository evidence discovery end to end | @@ -291,6 +291,7 @@ cargo test --locked --features mock --test fetch_proxy_route cargo test --locked --features mock --test site_map cargo test --locked --features mock --test snapshot_change cargo test --locked --all-features --test documents +cargo test --locked --no-default-features --test documents ``` Browser suites are gated by the `browser` feature: @@ -332,10 +333,11 @@ cargo test --locked --all-features --test schema_identity_registry ## Canonical commands -`make check` is the canonical gate: +`make check` is the canonical gate. Its `parity-check` lane runs 3 feature-off +cases from `tests/documents.rs`; the suite runs 11 cases with `documents` enabled. ```bash -make check # fmt + clippy + no-default check + all-features tests + hygiene + dependency-policy + packaging-check +make check # fmt + clippy + no-default check + documents feature-off parity + all-features tests + hygiene + dependency-policy + packaging-check ``` Target breakdown from the `Makefile`: @@ -346,6 +348,7 @@ Target breakdown from the `Makefile`: | `clippy` | `cargo clippy --locked --all-targets --all-features -- -D warnings` (zero warnings) | | `feature-check` | `cargo check --locked --no-default-features` (compile-only) | | `test` | `cargo test --locked --all-features` | +| `parity-check` | `cargo test --locked --no-default-features --test documents` (3 feature-off cases; 11 cases with `documents`) | | `hygiene` | `./packaging/check-repo-hygiene.sh` | | `dependency-policy` | `./packaging/check-dependency-policy.sh` (policy scripts plus pinned `cargo deny check` against `deny.toml`) | | `packaging-check` | `./packaging/check-contract.sh` | @@ -358,7 +361,7 @@ make release-check # check + docs + release build + publish dry-run which runs `release-candidate-check`, `docs-check` (`RUSTDOCFLAGS="-D warnings" cargo doc`), `release-build`, and `publish-check` (`cargo publish --dry-run`). MSRV is pinned by `rust-version = "1.89"` in `Cargo.toml`; edition 2021. -CI runs two jobs from `.github/workflows/ci.yml`: `ci` on `ubuntu-latest` invoking `make ci` (an alias of `make check`) with every credential env var blanked, and `windows-portability` on `windows-latest` running `cargo check --locked --all-features --target x86_64-pc-windows-msvc` at the pinned Rust 1.89 so Windows `cfg` breakage cannot hide behind Linux-green CI. `.github/workflows/dependency-security.yml` adds a weekly `cargo deny` policy run, and `.github/workflows/egress-feature-qualify.yml` is a path-filtered, non-publishing per-target `--features egress` compile-check. +CI runs two jobs from `.github/workflows/ci.yml`: `ci` on `ubuntu-latest` invoking `make ci` (an alias of `make check`, including the feature-off documents parity lane) with every credential env var blanked, and `windows-portability` on `windows-latest` running `cargo check --locked --all-features --target x86_64-pc-windows-msvc` at the pinned Rust 1.89 so Windows `cfg` breakage cannot hide behind Linux-green CI. `.github/workflows/dependency-security.yml` adds a weekly `cargo deny` policy run, and `.github/workflows/egress-feature-qualify.yml` is a path-filtered, non-publishing per-target `--features egress` compile-check. Individual suites: diff --git a/bindings/python/Cargo.lock b/bindings/python/Cargo.lock index ea8243d1..c1c632f8 100644 --- a/bindings/python/Cargo.lock +++ b/bindings/python/Cargo.lock @@ -163,6 +163,16 @@ dependencies = [ "tungstenite", ] +[[package]] +name = "atoi_simd" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3cdb3708a128e559a30fb830e8a77a5022ee6902806925c216658652b452a44" +dependencies = [ + "debug_unsafe", + "rustversion", +] + [[package]] name = "atomic-waker" version = "1.1.2" @@ -320,12 +330,36 @@ version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "bytes" version = "1.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" +[[package]] +name = "calamine" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f431b67cba6122a1f7d26b7adafc71bbdf07026095fe811f5efc025d8748e1d8" +dependencies = [ + "atoi_simd", + "byteorder", + "chrono", + "codepage", + "encoding_rs", + "fast-float2", + "log", + "quick-xml 0.42.0", + "serde", + "zip", +] + [[package]] name = "cbc" version = "0.2.1" @@ -494,6 +528,15 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" +[[package]] +name = "codepage" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdff162541cd8b79de82e2edcc7eff3a8c2a6dc3d75152636028f96d93de3b26" +dependencies = [ + "encoding_rs", +] + [[package]] name = "colorchoice" version = "1.0.5" @@ -524,6 +567,15 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" +[[package]] +name = "constant_time_eq" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7" +dependencies = [ + "rustversion", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -651,6 +703,12 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" +[[package]] +name = "debug_unsafe" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eed2c4702fa172d1ce21078faa7c5203e69f5394d48cc436d25928394a867a2" + [[package]] name = "derive_more" version = "2.1.1" @@ -817,6 +875,7 @@ dependencies = [ "anyhow", "axum", "base64 0.22.1", + "calamine", "chromiumoxide", "chrono", "clap", @@ -831,7 +890,7 @@ dependencies = [ "lru", "pbkdf2", "pulldown-cmark", - "quick-xml", + "quick-xml 0.41.0", "regex", "rmcp", "rusqlite", @@ -854,6 +913,7 @@ dependencies = [ "urlencoding", "windows-service", "xxhash-rust", + "zip", ] [[package]] @@ -923,6 +983,12 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" +[[package]] +name = "fast-float2" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6e8948ce679d00a02a94739ea185595dca7118ed04feb991127e443bd3d761f" + [[package]] name = "fastrand" version = "2.5.0" @@ -1110,9 +1176,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 6.0.0", "rand_core 0.10.1", + "wasm-bindgen", ] [[package]] @@ -1961,6 +2029,16 @@ dependencies = [ "memchr", ] +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "encoding_rs", + "memchr", +] + [[package]] name = "quote" version = "1.0.47" @@ -2989,6 +3067,12 @@ dependencies = [ "utf-8", ] +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + [[package]] name = "typenum" version = "1.20.1" @@ -3631,6 +3715,20 @@ name = "zeroize" version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] [[package]] name = "zerotrie" @@ -3665,6 +3763,26 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "zip" +version = "9.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9534624d547e3f516ecde0ed9a70d37788f01d340efcfdd03bf3ea8e163c1d0" +dependencies = [ + "constant_time_eq", + "crc32fast", + "flate2", + "getrandom 0.4.3", + "indexmap", + "libc", + "memchr", + "nix", + "typed-path", + "windows-sys 0.61.2", + "zeroize", + "zopfli", +] + [[package]] name = "zlib-rs" version = "0.6.8" @@ -3676,3 +3794,15 @@ name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] diff --git a/bindings/python/Cargo.toml b/bindings/python/Cargo.toml index 2fd21796..1b8b353f 100644 --- a/bindings/python/Cargo.toml +++ b/bindings/python/Cargo.toml @@ -13,7 +13,7 @@ name = "_native" crate-type = ["cdylib"] [dependencies] -eggsearch = { path = "../..", version = "=0.4.5", default-features = false, features = ["pdf", "browser"] } +eggsearch = { path = "../..", version = "=0.4.5", default-features = false, features = ["pdf", "browser", "documents"] } futures = "0.3" pyo3 = { version = "=0.30.1", features = ["abi3-py311", "extension-module", "macros"] } pyo3-async-runtimes = { version = "=0.30.0", features = ["tokio-runtime"] } diff --git a/docs/config.md b/docs/config.md index e0e90c17..eb47ec6b 100644 --- a/docs/config.md +++ b/docs/config.md @@ -641,13 +641,22 @@ batch_concurrency = 2 | `include_links_default` | `false` | | `sanitize_output` | `true` | | `pdf_enabled` | Compiled-in feature state. Enabled by default in current source builds, absent from published `v0.4.4` binaries, and disabled by `--no-default-features` | -| `documents_enabled` | Compiled-in `documents` feature state. `false` in every default build and in the Python wheel; when the feature is absent the setting is inert | +| `documents_enabled` | Compiled-in `documents` feature state. `true` in every published binary and the Python wheel; setting it to `false` refuses extraction with `document_disabled`. In builds without the feature, the setting is inert | | `pdf_max_pages` | `25` | | `pdf_max_chars_per_page` | `12_000` | | `pdf_max_total_chars` | `50_000` | | `pdf_max_bytes` | `16_777_216` | | `pdf_max_decompressed_bytes` | `67_108_864` | +For container documents, `MAX_INPUT_BYTES` is a 16 MiB extractor ceiling, not +the admitted-body size: the body is also clamped by `[fetch].max_bytes`, which +defaults to 2,000,000 bytes, and extraction sees only the admitted body. +`MAX_DOCUMENT_CHARS` is the 200,000-character extracted-text ceiling per +document. The rendered per-part budget defaults to 12,000 characters via +`[fetch].max_chars_default` and can be addressed up to `[fetch].max_chars_cap`, +which defaults to 50,000; those budget defaults are not the hard extracted-text +ceiling. + Fetch is bounded by byte and character budgets. The byte cap limits the response body. `max_chars_cap` limits how much text is extracted and made available in `document.blocks` and `document.chunks`; it is not the returned-text diff --git a/docs/features.md b/docs/features.md index 5dd86f43..655f48fe 100644 --- a/docs/features.md +++ b/docs/features.md @@ -189,23 +189,25 @@ unsupported. ## Document Formats -CSV, EPUB, DOCX, XLSX, and PPTX are read as bounded, addressable documents when -the binary includes the `documents` Cargo feature. PDF extraction is separate, -stays on by default, and is described under [PDF Extraction](#pdf-extraction). +The supported container formats are CSV/TSV, EPUB, DOCX, XLSX, and PPTX. PDF +extraction is separate, stays on by default, and is described under +[PDF Extraction](#pdf-extraction). ### Enabling -`documents` is not in the default feature set. A source build that needs the -container formats opts in explicitly: +Every published binary and the Python wheel carry container-document extraction; +no feature compilation is needed. + +Source builds include `documents` by default. To build without container-document +extraction and reproduce the previous artifact posture: ```bash -cargo build --features documents +cargo build --no-default-features --features pdf,browser ``` -The feature adds the `zip` and `calamine` dependencies. It is additive: with -the feature absent, every request behaves exactly as before, CSV keeps its -existing bounded table preview, and a `.docx` or `.epub` URL returns the -ordinary unsupported-content outcome. +The `documents` feature adds the `zip` and `calamine` dependencies. Without it, +CSV keeps the bounded table preview and container-document extraction is +unavailable. In a build that has the feature, `[fetch].documents_enabled` is the operator switch. It defaults to the compiled-in state; setting it to `false` refuses @@ -245,19 +247,49 @@ the web-fetch request shape has no part selector (only PDF page selection). | Bound | Value | |---|---| -| Input archive | 16 MiB | -| Total decompressed data | 64 MiB | +| Extractor input ceiling | 16 MiB (`MAX_INPUT_BYTES`) | +| Admitted body | Also clamped by `[fetch].max_bytes` (2,000,000 bytes by default) | +| Total decompressed data | 64 MiB (`MAX_DECOMPRESSED_BYTES`) | | Inflation ratio | 100:1 | | Archive entries | 4,096 | | Parts | 4,096 | -| Characters before the caller budget | 200,000 | -| XML depth | 64 | +| Extracted text per document | 200,000 characters (`MAX_DOCUMENT_CHARS` ceiling) | +| Rendered per-part budget | 12,000 characters by default (`[fetch].max_chars_default`); can be addressed up to `[fetch].max_chars_cap` (50,000 by default) | +| XML nesting depth | 64 | +| XML token bound | 262,144 (`MAX_XML_TOKENS`) for DOCX body, PPTX slide documents, and EPUB spine documents | +| Workbook observed cells | 200,000 (`MAX_CELL_COUNT`) across the workbook; the bounding rectangle spanned by observed cells is bounded too | +| CSV observed cells | 200,000; enforced incrementally during the scan, with refusal at the cap | + +The 16 MiB extractor ceiling is separate from body admission: the admitted body +is additionally clamped by `[fetch].max_bytes` (2,000,000 bytes by default), and +extraction sees only that admitted body. `MAX_DOCUMENT_CHARS` is the extracted-text +ceiling; the rendered per-part budget defaults to 12,000 characters and can be +addressed up to `max_chars_cap` (50,000 by default); those defaults are not the +hard extracted-text ceiling. ZIP central-directory sizes are attacker-controlled, so actual inflated bytes -are counted through a bounded reader and the archive is pre-scanned before a -spreadsheet parser inflates it. A bound breach is a typed error, never a partial -success. Nothing is written to disk, and absolute or parent-traversal entry -names are rejected defensively. No DTD, external entity, `XInclude`, or +are counted through bounded readers. The XLSX sheet-size scan streams sheet XML +and counts observed `` elements instead of collecting a token vector; the +declared `` and column-times-row product are not treated as content. +A sheet declaring `A1:XFD1048576` with one populated cell extracts normally, +while an over-cap sheet is refused. CSV enforces the same 200,000-cell bound +incrementally during the scan and refuses at the cap. A bound breach is a typed +error, never a partial success; a malformed container returns +`document_malformed`, never an empty success. Nothing is written to disk, and +absolute or parent-traversal entry names are rejected defensively. + +For XML text extraction, the five predefined XML entities (`&`, `<`, +`>`, `"`, `'`) and decimal and hexadecimal character references +are decoded into the surrounding text run. An undeclared named reference such +as ` ` is preserved as its literal source text, neither dropped nor +expanded; there is no HTML entity table, so output does not depend on a table +version. Adjacent character data, CDATA, and references merge into one text +run, so no separator is inserted inside a word. + +A plain `` with no internal subset and no `SYSTEM` or `PUBLIC` +identifier is accepted. A doctype body containing `[`, `SYSTEM`, or `PUBLIC` +(case-insensitive) is refused as `document_malformed`. No entity is resolved +from a doctype, and no external entity, `XInclude`, external relationship, or external media reference is resolved. ### Outcome Contract @@ -269,9 +301,15 @@ external media reference is resolved. | `document_unsupported` | ODF, legacy binary Office, or RTF | | `document_encrypted` | Password-protected OOXML (`EncryptedPackage`) | +At the tool boundary, `document_disabled` and `document_unsupported` report +`capability_unavailable`; `document_malformed`, `document_empty`, and +`document_encrypted` report `upstream_failed`. These fetch-layer code strings +are unchanged. + A supported format returns the document object instead of the ordinary text -body. ODF, legacy `.doc`/`.xls`/`.ppt`, and RTF are refused explicitly -rather than guessed at. +body. On a default install, a CSV URL returns a `document` object instead of +the former table preview. ODF, RTF, and legacy binary Office targets return +`document_unsupported`, rather than being guessed at. ### Limitations diff --git a/docs/python-library.md b/docs/python-library.md index 7eae9889..398543fd 100644 --- a/docs/python-library.md +++ b/docs/python-library.md @@ -160,8 +160,9 @@ python -m pip install --only-binary=:all: eggsearch Do not build the source distribution on an SBC. The source distribution is a developer fallback for environments outside the published wheel matrix. The extension package builds the Rust crate with `default-features = false, -features = ["pdf", "browser"]`: the wheel compiles both PDF extraction and -browser rendering; `egress` is not compiled. A wheel built from current source +features = ["pdf", "browser", "documents"]`: the wheel compiles PDF extraction, +browser rendering, and container-document extraction; `egress` is not compiled. +A wheel built from current source matches the CLI binaries built from the same source; the published `eggsearch==0.4.4` wheel is PDF-only. A system Chrome/Chromium executable is a runtime dependency only and is never bundled. If it is absent, diff --git a/docs/test-inventory.md b/docs/test-inventory.md index cc3e3492..225a742c 100644 --- a/docs/test-inventory.md +++ b/docs/test-inventory.md @@ -21,7 +21,7 @@ Ignored tests are live-network smoke tests (`corpus_runner`, `mcp_http` via `liv | `engine_api_conformance` | none | Table-driven conformance for the nine forge engines: 401/403/500 mapping, malformed-JSON `ParseFailed`, zero-result no-request, per-page limit, documented auth header, skipped invalid URLs, and one conversion case per engine | | `web_fetch_integration` | `mock` (mostly) | Fetch extraction, truncation, metadata-only mode, safety bounds, anti-bot challenge marking (`fetch_challenge_page` + `manual_interaction_required`), Anubis and ALTCHA solve-and-replay under `[search.challenge]`, fetch-side pass-cookie reuse, lifetime expiry, malformed-lifetime refusal, rejection eviction, in-call recovery from a refused pair set, and cross-origin isolation; plus auto-mode ordering (the solver owns a solvable wall and Chrome is never launched), unresolved-wall marking, interactive challenges staying manual, the deadline leaving no render time, the `browser_completions` counter, and the browser-gated status seam (a `429` and a `500` each escalate once, `402`/`403`/`404` never render, `http_only` never renders, a missing browser keeps the `http_status` error and names the unavailable escalation, a render that ends on `5xx` without a completed wall keeps the original error, and a served origin is not charged to the circuit breaker) | | `snapshot_change` | `mock` | Deterministic `new` → `same` → `changed` comparison of sanitized extracted text, SQLite privacy inspection, brief projection, and disabled-store warning/no-file behavior | -| `documents` | `documents` (feature-off cases run without it) | Bounded container-document extraction for CSV/TSV, EPUB, DOCX, XLSX, and PPTX: format detection by content type, extension, and container introspection; deterministic part order and one-based part addressing; spreadsheet dates and locale-independent numbers; the `document_empty`/`document_malformed`/`document_unsupported`/`document_encrypted` outcomes; the archive-entry, decompression, inflation-ratio, part, character, and XML-depth bounds; and feature-off parity for CSV and every container format | +| `documents` | `documents` (feature-off cases run without it) | Bounded container-document extraction for CSV/TSV, EPUB, DOCX, XLSX, and PPTX: format detection by content type, extension, and container introspection; deterministic part order and one-based part addressing; spreadsheet dates and locale-independent numbers; the `document_empty`/`document_malformed`/`document_unsupported`/`document_encrypted` outcomes; archive-entry, decompression, inflation-ratio, part, character, XML-depth, and cell bounds; feature-off parity for CSV and every container format; 11 cases with the feature and 3 without, including a DOCX with XML character references, an EPUB with a plain doctype, and delimiter-dense CSV refused at the cell bound | | `site_map` | `mock` | Bounded same-origin URL discovery as a `fetch` item: robots `Sitemap:` reading, declared and fallback sitemaps, one index level, duplicate collapse, query normalisation, malformed XML, gzip refusal, cross-origin refusal including a cross-origin redirect, URL/XML-depth truncation, deterministic ordering, and zero fetch of discovered URLs | | `provider_routing` | `mock` (mostly) | Provider routing, code-host rewrites, diagnostics, capability-skip telemetry, keyless source-provider routing/disabled-skip behavior, credentialed-provider opt-in/configured status reporting, explicit-provider rejection classification matrix (unknown/disabled/missing-credential/not-built), CodeGG parity qualification journeys | | `repo_workflow` | `mock` (mostly) | Repository evidence discovery end to end, explicit `github_repositories` discovery journey, prefer_local linked-worktree local redirect with no remote fetch, no-match remote fallback with an explicit local-skip reason, `repo_fetch` upstream error classification, and `repo_map` omitted-host and specific-over-generic warning behavior | @@ -110,7 +110,7 @@ Every case is generated synthetically by this repository; no third-party documen | `proxy_route_feasibility` | None (Eggress comparison under `egress`) | 11 (+1 with `egress`) | Loopback-only dynamic-proxy characterization: CONNECT authority and pinned-IP/Host/SNI behavior, HTTP forward and pin rejection, SOCKS5/SOCKS5H, authentication, proxy TLS, malformed route, timeout, pinned redirect, `NO_PROXY`, loopback refusal, handler-level pinned CONNECT and SOCKS5 targeting, proxy `407` mapping, redirect route-change refusal, and optional Eggress custom-dialer comparison | | `fetch_proxy_route` | `mock` | 7 | `[fetch.proxy]` handler contract: `no_proxy` reporting for single and batch items, direct route metadata omission, `proxy_required` plaintext refusal before any direct request, unreachable-endpoint fail-closed, missing credentials before target lookup, `cache_only` under a proxy route, and redacted `provider_status` without environment names | | `snapshot_change` | `mock` | 6 | Persistent deterministic comparison across `new`/`same`/`changed`/`removed`, sanitized storage and privacy, brief-projection retention, disabled and corrupt-store degradation, caller-key validation, and the no-store default | -| `documents` | `documents` (feature-off cases run without it) | 3 without the feature; 8 with it | Container-document extraction and outcome contract for CSV/TSV, EPUB, DOCX, XLSX, and PPTX, deterministic part order across repeated runs, the `documents_enabled` switch, the capability triad, and feature-off parity for CSV and container formats | +| `documents` | `documents` (feature-off cases run without it) | 3 without the feature; 11 with it | Container-document extraction and outcome contract for CSV/TSV, EPUB, DOCX, XLSX, and PPTX, deterministic part order across repeated runs, the `documents_enabled` switch, the capability triad, and feature-off parity for CSV and container formats | ## Forge Adapter Tests (`tests/forge_adapter.rs`) @@ -251,11 +251,15 @@ Deterministic `packaging/check-repo-hygiene.sh` runs in `make check` (`make hygi `cargo package --list`, so the published crate and the maturin sdist always compile from the tarball they ship. +Feature-off document parity is part of `make check` through `make parity-check`, +which runs `cargo test --locked --no-default-features --test documents`. This lane +runs 3 feature-off cases; the suite runs 11 cases with `documents` enabled. + ## CI Jobs | Job | Duration | Feature Combos | |-----|----------|----------------| -| `ci` | ~3min | fmt + clippy + no-default-features check + all-features tests + hygiene + packaging-check | +| `ci` | ~3min | fmt + clippy + no-default-features check + feature-off documents parity (`make parity-check`, 3 cases) + all-features tests + hygiene + packaging-check | | `windows-portability` | ~4min | `cargo check --locked --all-features --target x86_64-pc-windows-msvc` on `windows-latest` with pinned Rust 1.89; routine PR/main sentinel so Windows cfg breakage cannot hide behind Linux-green CI | | `python-native-qualification` | varies | Native wheel builds for five targets; exact abi3 qualification covers CPython 3.11–3.15 (25 smoke cells); native extension suite coverage is recorded separately below; extracted sdist offline rebuild and smoke; Cargo and Python dependency audits | diff --git a/plans/adrs/ADR-0027-container-document-default-enablement.md b/plans/adrs/ADR-0027-container-document-default-enablement.md new file mode 100644 index 00000000..c48f8085 --- /dev/null +++ b/plans/adrs/ADR-0027-container-document-default-enablement.md @@ -0,0 +1,263 @@ +# ADR-0027: Container Documents in the Default Artifact Set + +Status: accepted + +Date: 2026-11-26 + +Decision owners: project maintainers + +Accepted: 2026-11-26 by maintainer instruction ("the goal should be to ship this +as a default enabled feature, not gated") + +Supersedes: ADR-0026 § Decision 2, the non-default clause only. That decision's +format detection, dependency set, bounds, outcome taxonomy, and determinism +contract are adopted unchanged. + +Extends: ADR-0007 (the measured default-enablement template), ADR-0014 §4 (one +artifact per target), ADR-0024 §1 (single artifact alignment) and §5 (the size +review bar) + +Related specification sections: + +- `plans/000-long-term-specification.md` §4 +- `plans/001-terminology-and-domain-model.md` §4-5 + +Affected subsystem roadmaps: + +- `plans/subsystems/web-acquisition-expansion-roadmap.md` (M007, M008) +- `plans/subsystems/python-pypi-distribution-roadmap.md` + +Related records: ADR-0005 (Python native boundary), ADR-0006 (keyless +deterministic retrieval), ADR-0011 (document addressing), +`plans/closure/web-acquisition-expansion/004-status.md`, +`plans/closure/web-acquisition-expansion/006-status.md`. + +## Context + +M004 shipped CSV, EPUB, DOCX, XLSX, and PPTX extraction behind a non-default +`documents` feature. ADR-0026 required that promotion to the default set be a +separate packaging change carrying size measurements, and M006 added the +operator switch and the capability triad without touching defaults. The result +is a complete capability that no published artifact carries. + +In every default build and every published wheel today: + +- `provider_status.documents_capabilities` reports `compiled: false` and + therefore `configured: false`, `usable: false`; +- `[fetch].documents_enabled` defaults to `false` and is inert because the code + is absent; +- a `.docx`, `.epub`, `.xlsx`, or `.pptx` URL returns + `unsupported_content_type`, with a rebuild hint appended for DOCX and XLSX + only (`fetch_tool_error`, `src/mcp/tools/web_fetch_options.rs`); +- a CSV URL returns the bounded table preview as ordinary text rather than a + `document`; +- `docs/features.md` § Document Formats tells the reader to run + `cargo build --features documents`. + +ADR-0007 called exactly this shape a documentation defect rather than a lean +default: the product page advertises a format family the artifact cannot open. +The audience that needs it — standards bodies, procurement portals, filings, +shared drives — publishes DOCX, XLSX, and CSV as the normal case, and none of +those users has a Rust toolchain. + +Three further facts shape the decision. + +1. **The cost is now measurable.** At `v0.4.4` (public release assets, read + 2026-11-26) the seven targets publish 17,960,304 / 21,655,040 / 18,524,080 / + 17,710,392 / 19,779,368 / 25,869,312 / 21,457,240 bytes. Three of them + already exceed ADR-0024 §5's 20 MB figure carrying `pdf` and `browser` and + no container support, so that figure is a review trigger the project already + passes with a stated reason, not an absolute ceiling. +2. **The producer needs no change.** The generated release workflow builds with + neither `--features` nor `--no-default-features`, so default-set membership + is the only lever. No `release/eggpack/` file and no generated workflow + changes for this decision. +3. **The capability is not shippable yet.** An audit of the landed extraction on + `40e362f` found nine defects, two of them high severity: XML character and + entity references are dropped silently, so `Q&A` extracts as `QA`; and a + plain ``, ordinary in EPUB 2 and 3 XHTML, is refused as + malformed. Making the capability a default would ship those to every user. + Milestone M007 owns them and closes first. + +Forces in tension: one artifact per target with version-free asset names; a +Python wheel built from the same crate; an explicit preference for lean +defaults (ADR-0006); an equally explicit preference that a default be the happy +path and that a shipped default move be measured rather than asserted +(ADR-0007); and a documented policy against a second SKU (ADR-0006, ADR-0007, +ADR-0014, ADR-0024). + +## Decision drivers + +- One version, one artifact set: the CLI binary and the wheel advertise the same + capabilities. +- A default must be the capability's correct path, not a refusing path. +- Every default move is measured on the exact candidate before publication. +- No new operator surface, config key, tool, argument, or wire string is + introduced by enabling what already exists. +- A user who never fetches a container document must not acquire new files, + network behaviour, or payload fields. + +## Considered alternatives + +1. **Keep `documents` non-default and document source builds (status quo).** + Rejected. It preserves a lean default but leaves the published capability + unreachable for every installed user, which is the state ADR-0007 rejected + for PDF. It also keeps `provider_status` reporting a capability triad that + is uniformly false, which is diagnostic noise rather than information. +2. **Add `documents` to the default feature set and to the wheel feature list, + keeping `[fetch].documents_enabled` as an operator switch that defaults to + the compiled state.** Selected. It is ADR-0007 alternative 2 applied to the + container formats: one SKU, documentation matches the artifact, no packaging + surgery, and the existing bounds and outcome contract are untouched. +3. **Compile the feature in and also remove `[fetch].documents_enabled`.** + Rejected. It would be the only format family without an operator refusal + path, it would change a documented config key and collapse the + `configured` dimension of `documents_capabilities`, and it buys nothing the + switch costs. +4. **Publish a second, documents-enabled asset per target.** Rejected on the + same grounds as ADR-0007 alternative 3: it doubles the release matrix and + contradicts version-free asset names. +5. **Load container support at runtime.** Rejected: it is alternative 2 or 4 + with more moving parts. +6. **Enable the default before fixing the audit findings.** Rejected. A default + build would silently drop `&` and refuse ordinary EPUB XHTML, which is + worse than the current honest refusal. + +## Decision + +This ADR selects **alternative 2**, subject to the conditions in § Evidence gate. + +1. `documents` joins the default feature set: + `default = ["pdf", "browser", "documents"]` in `Cargo.toml`. `egress` + stays outside the default set and `mock` stays test-only. +2. The Python wheel keeps `default-features = false` and adds the feature + explicitly: `features = ["pdf", "browser", "documents"]` in + `bindings/python/Cargo.toml`. One wheel per platform; no variant, no second + project name. +3. `bindings/python/Cargo.lock` is regenerated. It is a tracked release input + and currently contains neither `zip` nor `calamine`, so the `--locked` + qualification build fails until it is. +4. `[fetch].documents_enabled` remains an operator switch and keeps its + feature-derived default (`cfg!(feature = "documents")`, + `src/core/config.rs:431` and `src/fetch/limits.rs:208`). Because the default + is already derived from the feature, adding the feature to the default set + flips the shipped default to `true` with no config change. + `document_disabled` remains an explicit, documented outcome. +5. Membership in the default set is the only release lever. No + `release/eggpack/` file, no generated workflow, no asset name, and no + installer changes. +6. **Prerequisite.** Milestone M007 (extraction fidelity and bound correctives) + closes before the default flips. Its `renderer_version` bump is what makes + the flip safe: derived cache keys carry no feature bit, so without the bump + a CSV URL cached by a feature-off build could be served as a plain table + preview under a build that should return a `document`. Both milestones land + in the same release, so the released artifact carries the bumped version and + no reachable pre-bump entry. + +### Artifact and configuration contract + +| Concern | Before | After | +|---|---|---| +| `Cargo.toml` default | `["pdf", "browser"]` | `["pdf", "browser", "documents"]` | +| Wheel features | `["pdf", "browser"]` | `["pdf", "browser", "documents"]` | +| Wheel lockfile | no `zip`, no `calamine` | regenerated, both present | +| `[fetch].documents_enabled` default | `false` | `true` | +| `documents_capabilities.compiled` | `false` | `true` | +| `provider_status.server_capabilities.container_documents` | `false` | `true` | +| A DOCX/EPUB/XLSX/PPTX URL | `unsupported_content_type` | extracted content, or a typed `document_*` outcome | +| A CSV URL | bounded table preview as text | `document.format = "csv"` with parts | +| ODF, RTF, legacy binary Office | `unsupported_content_type` | `document_unsupported` | +| Release assets | 7 names | unchanged: the same 7 names | + +## Evidence gate + +Acceptance of the decision is not evidence of the move. Before the default +change is published, the candidate must record: + +- the per-target size delta against the `v0.4.4` bytes above, on the exact + candidate, with each target's absolute size stated rather than only the + delta, and a written reason for any target whose absolute size grows past the + 20 MB review figure that three targets already exceed; +- the wheel size delta, following ADR-0024's measured form; +- `make check`, `make docs-check`, `make packaging-check`, + `make dependency-policy`, and the MSRV 1.89 all-features build on the + candidate; +- the hosted `Python native qualification` matrix green on the wheel feature + change; +- M007's closure record, which is the precondition for any of the above. + +If a target fails to build with the new default, or the wheel matrix fails to +qualify, stop and return to alternative 1 rather than introducing a second SKU. + +## Consequences and tradeoffs + +Advantages: the artifact matches the documentation; an agent stops hitting a +capability wall on ordinary office and data sources; `provider_status` reports +one coherent story; one qualification path; the size cost is measured per +target. + +Costs and risks: every target and wheel grows by the measured delta; `zip` and +`calamine` move from the all-features graph to the default graph, so their +licence, advisory, and MSRV posture must pass `make dependency-policy` and the +1.89 default build rather than only `--all-features`; a container-parser +regression can now affect the default install, which raises the bar on M007 +landing first; `bindings/python/Cargo.lock` becomes a mandatory regeneration +input; and the `documents` feature stops being a free way to keep the binary +lean for a source builder, who must now pass +`--no-default-features --features pdf,browser` to reproduce the old shape — a +shape that must keep compiling and keep its `unsupported_content_type` and +`document_disabled` behaviour. + +Deferral: alternative 1 remains a complete and shippable position if M007 or the +measurement gate fails, and every M007 corrective is correct under either +alternative, which is why it is not gated on this decision. + +## Compatibility and migration + +Additive for configuration and protocol; genuinely changing for two default-path +behaviours, which is why they are named here rather than in a changelog only: + +- A CSV fetch in a default build returns `representation: "document"` with + `document.format`, `document.parts`, and `document.parts_total` instead of a + table preview read as text. A caller that pattern-matched on extracted text + for `.csv` sees a different shape. +- An ODF, RTF, or legacy binary Office URL returns `document_unsupported` + instead of `unsupported_content_type`. After M007 both classify as + `capability_unavailable` at the tool boundary, which is the intended class for + a capability this build does not have. + +Unchanged: nine advertised tools plus three aliases, every argument name, every +existing wire string, `pdf_not_compiled_in` and `document_disabled` in the +taxonomy for builds that disable the features, the trust framing, the SSRF and +redirect policy, byte caps, the seven release asset names, and the installer +contract. `unsupported_content_type` remains reachable for a body that is +neither text, HTML, PDF, nor a recognised container. + +## Security implications + +Container parsing stays in memory and never extracts to disk; actual inflated +bytes are counted by a bounded reader; no DTD subset, external entity, +`XInclude`, or external relationship is resolved; ZIP entry, ratio, part, cell, +character, and XML-depth bounds are unchanged by this decision. The exposure +that does change is breadth: every install now parses attacker-supplied +archives and spreadsheets by default, so the M007 bounds work is a security +precondition, not a tidy-up. M007 in particular closes a CSV structural +amplification in which a delimiter-dense body reaches roughly 30× its admitted +size, and the flip raises the worst case from "0 bytes parsed" to "the full +membrane under a default install". + +## Verification and status + +This ADR is **accepted** (maintainer instruction, 2026-11-26). Acceptance settles +the selection and supersedes ADR-0026 Decision 2's non-default clause. It does +not supply the evidence: the size measurements, the packaging and dependency +gates, the hosted wheel qualification, and M007's closure are conditions on +roadmap M008, which owns them. No production default changes on the strength of +this record alone. + +## Supersession + +This record supersedes ADR-0026 Decision 2's "non-default for the first release +that carries it" clause and nothing else. If the format set, the dependency +choice, or the bounds contract later changes, a new ADR supersedes that part of +ADR-0026 or this record and links to both. diff --git a/plans/closure/web-acquisition-expansion/007-status.md b/plans/closure/web-acquisition-expansion/007-status.md new file mode 100644 index 00000000..b3f3f6dc --- /dev/null +++ b/plans/closure/web-acquisition-expansion/007-status.md @@ -0,0 +1,178 @@ +# Web Acquisition M007 — Container-Document Extraction Fidelity and Bound Correctives — Status + +Status: closed +Date: 2026-11-26 +Milestone: M007 — Container-Document Extraction Fidelity and Bound Correctives +Milestone class: corrective +Decision authority: ADR-0027 (default enablement); ADR-0026 Decision 2 (format, +dependency, bounds, outcome, and determinism contract — unchanged); M004 and M006 +closure records +Baseline: `40e362f1b16f6d2fb5efb4fb91a0c01a85c64144` +Plan: `plans/implementation/web-acquisition-expansion/007-container-document-extraction-fidelity-correctives.md` + +## Candidate and changes + +Candidate: `cd075fc704b5c03dc2bc28f6a5c5408a320801a4` on +`m008-documents-default-qualification`, the baseline plus this change set, committed +and pushed so the hosted matrix could compile it. The change is library-internal: no +tool, argument, wire string, config key, or dependency moves. + +- `src/fetch/documents/extract.rs` (1,411 lines / 49,337 bytes; ordinary ceiling 1,600 + lines / 80 KB): `Event::GeneralRef` handling through `decode_general_ref`, the + `text_token` merge of adjacent character data, doctype acceptance, qualified + attribute keys, the streamed XLSX size scan with observed-content bounds, the + incremental CSV cell count, and per-part truncation carried on `RawPart`. +- `src/fetch/documents/tests.rs` (595 lines): one fixture per defect plus the observed + bounding-rectangle refusal. +- `tests/documents.rs` (418 lines): three end-to-end cases across the tool boundary. +- `src/mcp/tools/web_fetch_options.rs`: `document_unsupported` classified as a + capability miss. +- `tests/mcp_tools.rs`: the tool-boundary case for both sides of that classification. +- `src/fetch/cache.rs` and `src/fetch/cache/tests.rs`: `renderer_version` 6 and its + isolation case. + +## Per-defect evidence + +| # | Defect | Baseline observation at `40e362f` | Candidate case | Candidate observation | +|---|---|---|---|---| +| 1 | XML character and entity references discarded | `Q&A <tag> café "x"` extracted as `QA tag caf x` | `xml_references_resolve_into_the_surrounding_text_run` (unit, exact equality) and `docx_character_references_survive_the_tool_boundary` (integration) | `Q&A caf\u{e9} "x" 'y'` exactly; an undeclared ` ` survives as the literal `a b` | +| 2 | A plain `` refused | `document_malformed: DTD is not supported` | `xml_accepts_plain_doctypes_and_still_refuses_dtd_payloads` (unit) and `epub_documents_with_a_plain_doctype_extract` (integration) | plain doctype extracts; internal subset, `SYSTEM`, and `PUBLIC` still refuse, in either case | +| 3 | Namespace-qualified attributes collide on the local name | producer attribute order decided whether the slide relationship resolved | `pptx_relationship_ids_are_independent_of_attribute_order` | both orderings extract `Slide Two` with equal titles and no truncation | +| 4 | The declared `` is treated as content | a sheet declaring `A1:XFD1048576` with one populated cell refused | `xlsx_declared_dimension_does_not_bound_observed_cells` | the sheet extracts `Only data` | +| 5 | The token bound binds before the cell bound | 45,000 one-cell rows reached the token bound | `xlsx_many_rows_reach_the_cell_bound_not_the_token_bound` | the sheet extracts: 45,000 cells is under the 200,000-cell bound and the streamed scan applies no token bound to it | +| 5 | Row-by-column product treated as content | an over-cap sheet refused without naming a real bound | `xlsx_cell_count_and_bounding_area_are_bounded_on_observed_cells` | a two-cell `A1`/`XFD1048576` sheet refuses at the observed bounding rectangle | +| 6 | CSV cell count enforced after the row is built | refusal only after the whole delimiter-dense row existed | `csv_cell_bound_refuses_during_the_scan` and `delimiter_dense_csv_is_refused_at_the_cell_bound` | refusal raised at the cap during the scan; peak allocation in the table below | +| 7 | Ceilings documented as if they were defaults | see the plan's defect table | documentation diff in `docs/features.md`, `docs/config.md`, `architecture/fetch.md` | ceilings and defaults stated separately | +| 8 | `document_unsupported` reports as an upstream failure | tool code `upstream_failed` | `document_unsupported_container_is_capability_unavailable` and `malformed_container_remains_upstream_failed` | `capability_unavailable` with `data.code = document_unsupported`; `document_malformed` still `upstream_failed` | +| 9 | Truncation inferred at document level from the last part | the last part was flagged whatever part was cut | `truncation_is_attributed_to_the_part_that_was_cut` | the cut part is flagged, later parts are not, `document_truncated` is true | + +## Exact extracted strings + +The two high-severity cases assert equality rather than containment. + +- DOCX body `Q&A <tag> café "x" 'y'` extracts to + `Q&A caf\u{e9} "x" 'y'` — one text run, so no separator enters `Q&A`. +- EPUB content `a b` extracts to `a b`. `nbsp` is not declared by the + document and there is deliberately no HTML entity table, so the source text survives + instead of being expanded or dropped. + +## Deliberate substitutions from the plan + +1. **The XLSX size scan streams instead of deriving `MAX_XML_TOKENS`.** Package 4 asked + for `MAX_XML_TOKENS` to be derived from `MAX_CELL_COUNT` with a per-row factor and a + fixed overhead. That derivation would raise the token ceiling to roughly 1.4 million + `XmlToken` values, which is not a bound worth having. The sheet scan instead streams + quick-xml events and never materialises a token vector, so there is no second bound to + drift: the cell bound is the only bound on a sheet. `MAX_XML_TOKENS` stays 262,144 and + governs the token-scanned formats only (DOCX body, PPTX slide documents, EPUB spine + documents). The plan's stop condition for a CSV streaming rewrite is not met; the CSV + count is incremental inside the existing scan. +2. **The observed bounding rectangle is bounded, not only the cell count.** Calamine's + sparse-to-dense conversion allocates the rectangle between the minimum and maximum + observed column and row, so two cells at `A1` and `XFD1048576` are two cells and + sixteen billion allocation slots. The plan named the cell count; the implementation + bounds both, and the refusal names the rectangle. +3. **The defect-9 fixture uses the EPUB heading cap (4,096 characters), not the document + character budget.** `document_chars.min(MAX_DOCUMENT_CHARS)` is consumed in part order, + so a document whose first part reached the budget always loses every later part, which + makes "part 1 cut, later parts uncut" unreachable through the document budget. The + heading cap produces the same shape honestly: part 1 is cut and flagged, part 2 is + whole. + +## CSV peak allocation + +Fixture: one delimiter-dense CSV row of `a,` pairs, 4,194,304 bytes admitted +(4 MiB), so the row carries 2,097,152 cells — 10.5 times the 200,000-cell bound. +Probe: a release-profile binary that calls +`extract_document(&body, DocumentFormat::Csv, ..)` once, identical in both trees and +differing only in the tree it is compiled from; peak resident set from +`/usr/bin/time -l`. The two binaries were confirmed byte-different, and the +outcomes differ, so the same code was not measured twice. + +| Tree | Peak resident | Ratio to admitted body | Outcome | +|---|---|---|---| +| `40e362f` | 70,582,272 bytes (67.31 MiB) | 16.83x | `document_malformed` | +| candidate | 20,201,472 bytes (19.27 MiB) | 4.82x | `document_malformed` | + +The refusal is the same bound in both trees; what changed is when it is raised. Before, +the whole row was materialised before the count, so peak tracked the separator count. +After, the count is enforced during the scan, so peak is a small multiple of the +admitted body — a 3.49x reduction on this fixture, bounded by `MAX_CELL_COUNT` rather +than by the input. + +## Derived cache version + +`renderer_version` is 6 (`src/fetch/cache.rs`), covering packages 1, 2, 5, and 6 — every +one of them either changes extracted text or produces text where a refusal was cached. The +invalidation is global by design: it drops every derived entry class, not only container +documents, because the version is part of the derived key rather than per-format state. +`cache_derived_does_not_serve_pre_container_fidelity_entries` stores a version-5 entry and +shows it is not served. There is exactly one bump in this change set. + +## Tool-boundary error codes + +| Fetch code | Tool error code before | Tool error code after | +|---|---|---| +| `document_unsupported` | `upstream_failed` | `capability_unavailable` | +| `document_disabled` | `capability_unavailable` | `capability_unavailable` | +| `document_malformed` | `upstream_failed` | `upstream_failed` | +| `document_empty` | `upstream_failed` | `upstream_failed` | +| `document_encrypted` | `upstream_failed` | `upstream_failed` | + +The fetch-layer code strings are unchanged; only the tool error code for the capability +miss moved, which is why no `FetchErrorKind` was added. + +## Feature-off parity + +`cargo test --locked --no-default-features --test documents` (the `make parity-check` +lane) runs the three parity +cases and passes: `docx_without_the_feature_keeps_the_unsupported_outcome`, +`capability_report_is_honest_without_the_feature`, and +`csv_without_the_feature_keeps_the_table_preview`. A container URL still returns +`unsupported_content_type` and a CSV URL still returns the table preview. + +## Independent audit and remediation + +An independent verifier audited this change set against the plan and returned a narrow +FAIL: every behavioural fix worked and every executed suite was green, but four +acceptance-letter items were unmet and two observations were recorded. Each finding was +either remediated in code and fixtures or recorded here as a property of the design; none +is left silent. + +| Finding | Severity | Resolution | +|---|---|---| +| 1. The "no `Cargo.toml` change" invariant is breached by the co-mingled M008 work | Medium | Expected and owned elsewhere: M008 is the default-set flip, and no M007 behaviour depends on it. The feature-off parity lane now runs through `make parity-check` rather than a hand-typed `--no-default-features` command. | +| 2. WP4's derived `MAX_XML_TOKENS` bound and its guard are absent | Medium | Structural alternative, not an omission: the streamed sheet scan has no token vector to bound, so a derivation would create a second bound with nothing to enforce it. Recorded as substitution 1 above. | +| 3. "Across the workbook" contradicted per-sheet enforcement | Medium | Counters hoisted. The cell count is workbook-wide; the bounding rectangle stays per sheet, because that rectangle is the allocation the reader performs. The documented phrase now matches the code. | +| 4. The doctype and ` ` cases were weaker than the acceptance text | Medium | Strengthened at the extractor boundary: the unit cases now assert `assert_eq!` on the exact extracted text, and the reference fixture there gained a hexadecimal reference and a CDATA section adjacent to character data. The two cross-boundary cases keep `contains`, because their job is to prove the references survive the MCP projection, not to re-assert the exact string the unit case owns; the doctype case also asserts `parts_total == 1`. | +| 5. Two XLSX halves pass at `40e362f` as well | Low | Characterization, not regression. Both the 200,001-cell half and the sparse `A1`/`XFD1048576` half already refused at baseline with the same message, so they lock in refusal identity rather than prove a fix. Only the dimension sheet and the 45,000-row sheet are fail-on-baseline for defects 4 and 5, and the table above now says so. | +| 6. `TokenKind::Truncated` is a new inert token kind | Low | Accepted redundancy. The variant's `kind` is unused, but the token is the carrier of the `truncated` flag that DOCX, EPUB, and PPTX OR into their own state, so removing it would lose the clip signal. Replacing the marker with a returned flag is a follow-up refinement, not a corrective. | +| 7. The briefing's file list omitted the documentation diff | Info | The documentation exists and defect 7 is closed by it. | + +## Verification on this candidate + +| Command | Result | +|---|---| +| `cargo test --locked --features documents --lib fetch::documents` | 15 passed | +| `cargo test --locked --features documents --test documents` | 11 passed | +| `cargo test --locked --no-default-features --test documents` | 3 passed | +| `cargo test --locked --all-features --test mcp_tools document_error_mapping` | 2 passed | +| `cargo test --locked --all-features --lib fetch::cache` | 59 passed | +| `cargo test --locked --all-features --test static_guards` | 69 passed | +| `make check` (canonical gate) | exit 0; 6,699 cases across 101 suites; `parity-check` lane present | +| Hosted `Python native qualification`, run 46115248218 on `cd075fc` | 41/41 jobs succeeded, so this change set compiles and passes in the wheel's platforms and interpreters, not only on the host | + +The canonical `make check` result above is the final run, on the tree that carries the +remediation in the audit section, and it covers the four documents cases itself. An +earlier gate run had completed before the last fixture edits were compiled; those cases +were re-run directly on the current sources and then re-covered by the final gate. + +## Limitations + +- The nine defects are closed against the plan's own observations at `40e362f`; no + third-party corpus was re-run, and `tests/tool_surface_live.rs` is `--ignored` and + model-gated, so it is not evidence here. +- `MAX_XML_TOKENS` is no longer derived from `MAX_CELL_COUNT` because the sheet scan has no + token bound to derive. This is a substitution, recorded above, not a completed package. +- No hosted qualification was run. The documented provider-side smokes are unaffected by + this change, but this record does not claim them. diff --git a/plans/closure/web-acquisition-expansion/008-status.md b/plans/closure/web-acquisition-expansion/008-status.md new file mode 100644 index 00000000..553f4720 --- /dev/null +++ b/plans/closure/web-acquisition-expansion/008-status.md @@ -0,0 +1,261 @@ +# Web Acquisition M008 — Container-Document Default Enablement — Status + +Status: closed +Date: 2026-11-26 +Milestone: M008 — Container-Document Default Enablement +Milestone class: capability +Decision authority: ADR-0027 (accepted 2026-11-26); ADR-0026 Decision 2; +ADR-0007; ADR-0014 §4; ADR-0024 §1 and §5 +Baseline: `40e362f1b16f6d2fb5efb4fb91a0c01a85c64144` +Plan: `plans/implementation/web-acquisition-expansion/008-container-document-default-enablement.md` +Builds on: M007 (`plans/closure/web-acquisition-expansion/007-status.md`) + +## Candidate and changes + +Qualified candidate: `cd075fc704b5c03dc2bc28f6a5c5408a320801a4` on +`m008-documents-default-qualification`, the baseline plus the M007 change set plus +this change set, committed and pushed to `origin` so the hosted matrix could run +against it. The milestone is a build-configuration and distribution change; no +production source line moved. The hosted-evidence section below was written after +that run, so `cd075fc` carries this record without it. + +- `Cargo.toml`: `default = ["pdf", "browser", "documents"]`. +- `bindings/python/Cargo.toml`: `features = ["pdf", "browser", "documents"]`. +- `bindings/python/Cargo.lock`: regenerated by resolving against the committed + lock rather than by `cargo generate-lockfile`, so the existing pins are + preserved. It grows by 12 packages (378 → 390) — `zip` 9.8.1, `calamine` + 0.38.0, and their closure — with no unrelated version change. +- `Makefile`: a `parity-check` target running + `cargo test --locked --no-default-features --test documents`, wired into + `check` beside `feature-check`. +- `tests/static_guards.rs`: `default_features_ship_pdf_and_browser` now + requires `documents`, still rejects `egress`, and gains a + `default_documents_enabled` clause mirroring the browser one so the config + default cannot drift from the feature. + +## Declared default feature set + +`cargo metadata --locked --format-version 1 --no-deps` on the candidate reports +`{'eggsearch': ['pdf', 'browser', 'documents']}`. The guard passes all 69 cases. +`egress` remains outside the default set and `mock` remains test-only. + +## Lockfile and wheel + +`grep -n 'name = "calamine"' bindings/python/Cargo.lock` and the same for `zip` +both resolve on the candidate; at baseline neither did. `cargo metadata --locked +--manifest-path bindings/python/Cargo.toml` exits 0, so the lockfile is +consistent under `--locked` for the new feature edge. + +The hosted matrix builds every wheel and the sdist with `--locked` against this +lockfile and all 41 jobs passed, so the resolved closure is qualified rather than +merely parseable. See Hosted Python native qualification below. + +## Hosted Python native qualification + +Run [46115248218](https://github.com/eggstack/eggsearch/actions/runs/46115248218), +`workflow_dispatch` against `m008-documents-default-qualification`, head +`cd075fc704b5c03dc2bc28f6a5c5408a320801a4`, created 2026-11-28T06:08:47Z and +completed 06:27:35Z. **41 of 41 jobs succeeded.** The wheel builds, installs into a +clean consumer environment outside the checkout, and passes the binding suite on all +five platform rows across CPython 3.11–3.15, including the Chrome render case, both +explicit browser-absence cases, the ARMv7 cross build with its emulated +installed-wheel smoke, and the offline rebuild of the extracted sdist. + +The run also executed the canaries the plan names: package name `eggsearch`, MIT +license, `requires-python >=3.11,<3.16`, one `abi3`/`cp311`-tagged wheel per target, +and the three version fields agreeing at `0.4.5`. `cargo deny check` ran against +both the root and the binding graph on the new dependency closure. Every wheel stayed +under the workflow's 20 MB threshold, the largest at 17.87 MB. + +### Wheel delta + +Bytes are read from the two runs' own step summaries. The baseline is run +`46072717384`, the last pre-flip qualification of `main` at `057a86d`, whose wheel +was built without `documents`; the candidate is this run. Both are `0.4.5`, so the +difference is the feature plus the M007 corrections in the same compilation graph. + +| Wheel | Pre-flip bytes | Candidate bytes | Delta | +|---|---|---|---| +| `macosx_10_12_x86_64` | 16,260,226 | 16,654,714 | +394,488 (+2.43%) | +| `macosx_11_0_arm64` | 15,730,450 | 16,156,596 | +426,146 (+2.71%) | +| `manylinux2014_aarch64` | 17,027,887 | 17,477,555 | +449,668 (+2.64%) | +| `manylinux2014_x86_64` | 17,352,428 | 17,815,648 | +463,220 (+2.67%) | +| `manylinux_2_39_x86_64` (rebuilt from the extracted sdist) | 17,392,704 | 17,867,056 | +474,352 (+2.73%) | +| `win_amd64` | 15,471,670 | 15,812,137 | +340,467 (+2.20%) | +| `eggsearch-0.4.5.tar.gz` | 1,709,188 | 1,714,989 | +5,801 (+0.34%) | + +The wheel cost is 2.20–2.73% per target, consistent with the +2.34% measured on the +host binary. No wheel approaches the 20 MB review figure, so the plan's written-reason +requirement is not triggered on the wheel side; that requirement still applies to the +seven release assets, which the measured candidate in the size section shows exceeding it on +all seven targets. + +## Capability report on a default build + +Read from a default-feature debug build over the MCP stdio transport, calling +`provider_status`: + +| Configuration | `documents_capabilities` | `server_capabilities.container_documents` | +|---|---|---| +| `default = ["pdf", "browser", "documents"]`, `documents_enabled` unset | `{"compiled": true, "configured": true, "usable": true, "formats": ["csv", "epub", "docx", "xlsx", "pptx"]}` | `true` | +| same build, `[fetch].documents_enabled = false` | `{"compiled": true, "configured": false, "usable": false, "formats": ["csv", "epub", "docx", "xlsx", "pptx"]}` | `false` | + +The feature-absent rows are the M006 closure record's, unchanged by this +milestone: a build without the feature reports `compiled = false`, +`configured = false`, `usable = false`, and returns +`unsupported_content_type` for a container URL. `tests/config_validation.rs` +(105 cases) and `tests/mcp_tools.rs` (32 cases) are green **unmodified by this +milestone**, which is the plan's canary: the config default is feature-derived, +so no source change was needed. The runtime-discovered absence of a browser does +not affect the document triad, which reads the compiled feature and the config +field only. + +## Feature-off parity lane + +`make parity-check` runs `cargo test --locked --no-default-features --test +documents` and executes 3 cases, not 3 skipped ones: +`docx_without_the_feature_keeps_the_unsupported_outcome`, +`capability_report_is_honest_without_the_feature`, and +`csv_without_the_feature_keeps_the_table_preview`. The lane is in `check`, so +the feature-off half of the suite can no longer become green-by-absence. Cost: +one additional no-default test build of the crate (about one minute on the host +target, warm dependency cache), which is why it sits beside `feature-check` +rather than duplicating the whole `test` target. + +## Size and footprint + +Local release profile: `lto = "thin"`, `codegen-units = 1`, `strip = true`. +Host target `aarch64-apple-darwin`, rustc 1.89.0, same source, two feature sets +so the delta is the feature's cost and nothing else: + +| Configuration | Bytes | MiB | Delta | +|---|---|---|---| +| `--no-default-features --features pdf,browser` (the pre-flip artifact shape) | 29,370,512 | 28.01 | — | +| `--no-default-features --features pdf,browser,documents` (the new default) | 30,058,304 | 28.67 | +687,792 bytes (+2.34%, +0.66 MiB) | + +The per-target table below is the producer's own candidate build, not a local +substitute. Run `46117453196` (`workflow_dispatch`, `candidate_sha` +`cd075fc704b5c03dc2bc28f6a5c5408a320801a4`) built and qualified all seven lanes in +27.8 minutes with 25 of 25 jobs green. Its `summary.json` records +`source_revision: cd075fc704b5c03dc2bc28f6a5c5408a320801a4`, `release_id: v0.4.5` +and `outcome: complete`, and the bytes below are read from the finalized release +directory it produced — the directory publication would use. The producer builds +through the crate's own `[profile.release]`, so these are stripped release binaries +comparable to the published ones. + +| Target | `v0.4.4` published | Candidate | Delta | Over 20 MB | +|---|---|---|---|---| +| `aarch64-apple-darwin` | 17,960,304 | 29,368,752 | +11,408,448 (+63.5%) | yes | +| `aarch64-pc-windows-msvc` | 21,655,040 | 35,251,712 | +13,596,672 (+62.8%) | yes | +| `aarch64-unknown-linux-gnu` | 18,524,080 | 29,984,432 | +11,460,352 (+61.9%) | yes | +| `armv7-unknown-linux-gnueabihf` | 17,710,392 | 29,356,628 | +11,646,236 (+65.8%) | yes | +| `x86_64-apple-darwin` | 19,779,368 | 32,369,512 | +12,590,144 (+63.7%) | yes | +| `x86_64-pc-windows-msvc` | 25,869,312 | 42,128,384 | +16,259,072 (+62.9%) | yes | +| `x86_64-unknown-linux-gnu` | 21,457,240 | 34,714,936 | +13,257,696 (+61.8%) | yes | + +### Review-threshold reason + +ADR-0024 §5's 20 MB figure was already exceeded by three published `v0.4.4` +targets, and the candidate exceeds it on all seven. The reason, applicable to every +row: **this milestone contributes about +0.69 MB (+2.3%); the rest of the increase +predates it.** + +That attribution is measured rather than assumed. The local two-feature-set build +above isolates the feature at +687,792 bytes (+2.34%), and the hosted wheels agree at ++2.20–2.73% per target. On the host target the candidate is +11,408,448 bytes against +`v0.4.4`, of which the feature accounts for roughly 6%. The remaining ~10.7 MB is +not this milestone's: a `documents`-off build of the same source is 29,370,512 +bytes, within 1,760 bytes of the producer's `documents`-on 29,368,752, so enabling +the feature is not what separates this candidate from `v0.4.4`. + +The growth is **attributed but not explained**. It predates M008 and is reproduced by +the producer, so it is not an artifact of this worktree, but its cause is not +identified here and would require bisecting the release history between `v0.4.4` and +this candidate. The plan's stop condition for an unexplained size figure is therefore +live at the aggregate level, even though this milestone's own share is explained and +small. + +## Gates + +| Gate | Result | +|---|---| +| `cargo fmt --check` | clean | +| `cargo test --locked --all-features --test static_guards` | 69 passed | +| `make parity-check` | 3 passed | +| `cargo test --locked --all-features --test config_validation` | 105 passed | +| `cargo test --locked --all-features --test mcp_tools` | 32 passed | +| `make dependency-policy` | advisories, bans, licenses, sources all ok | +| `make packaging-check` | ok; 19-name inventory, 25 producer jobs, 7 targets | +| `make producer-drift` | `ci check: match (75695 bytes)`, no producer edit | +| `make hygiene` | `repo-hygiene: ok` | +| `make check` (canonical gate) | exit 0; 6,699 cases across 101 suites, including the new `parity-check` lane | +| `cargo check --locked --no-default-features` | passes, so the lean shape still compiles | +| `cargo test --locked --no-default-features --test documents` | 3 passed, rebuilt from current sources | +| Hosted `Python native qualification`, run 46115248218 | 41/41 jobs succeeded on `cd075fc`: wheel and sdist built `--locked`, installed and tested on five platforms across CPython 3.11–3.15 | +| Hosted eggpack candidate qualification, run 46117453196 | 25/25 jobs succeeded; all seven lanes built and finalized from `candidate_sha` `cd075fc`, `outcome: complete` | + +The `make check` row is the final run on the finished tree and covers the four documents +cases as well as the rest of the gate. An earlier run preceded the last M007 fixture +edits, which is why those cases were also executed directly: 15 unit, 11 integration, 3 +parity, 2 mapping, all green. + +## Documentation and release facts + +Corrected, in the same change: `docs/features.md` (the opening now describes the +shipped artifact and the source-build shape is secondary; the two behaviour +changes a default install sees — a CSV URL returns a `document` and ODF/RTF/legacy +binary Office return `document_unsupported` — are stated), +`docs/config.md` (`documents_enabled` defaults to the compiled state, which is on +in every published artifact, and remains the operator refusal path), +`architecture/build.md`, `architecture/packaging.md` (including the stale wheel +feature list, which said `["pdf"]`), `architecture/python-library.md`, +`docs/python-library.md`, `docs/test-inventory.md`, `architecture/testing.md`, +`skills/eggsearch-dev/SKILL.md`, and `AGENTS.md` (the `make check` composition +and the default feature list). The release the next cut produces carries +`renderer_version: 6`, recorded in `architecture/fetch.md`. + +`CHANGELOG.md` has an appended `Unreleased` entry; the version is not bumped +here. + +## Closure conditions + +All three conditions the plan names are met. + +1. **Hosted wheel qualification is green.** Run `46115248218` passed 41 of 41 jobs on + `cd075fc`. +2. **The per-target size evidence comes from the producer's candidate.** Run + `46117453196` passed 25 of 25 jobs and produced the seven sizes above, with + `source_revision: cd075fc704b5c03dc2bc28f6a5c5408a320801a4` and + `outcome: complete`. +3. **The size review is decided.** On 2026-11-28 the maintainer accepted the candidate + for review instead of taking ADR-0027 alternative 1: the default flip stays, and the + written reason in the review-threshold section travels with the release. + +### Size review decision + +Decision: **keep the default feature set and send `v0.4.5` to size review**, taken +2026-11-28 on the evidence above, in place of the plan's alternative-1 recovery. + +The decision rests on the attribution rather than the aggregate. This milestone's cost +is +0.69 MB (+2.3%), measured twice — once by the local two-feature-set build and once +by the hosted wheels — while the ~+60% pre-existing growth is a release-candidate +question that the review answers. + +Carried forward rather than closed by this decision: the cause of that pre-existing +growth is still unidentified. It is a known issue for the release candidate and would +need a bisect between `v0.4.4` and this candidate. If the review rejects the growth, +ADR-0027 alternative 1 remains the documented recovery. + +## Limitations + +- **The candidate's aggregate size growth has no identified cause.** All seven assets + exceed the 20 MB review figure, and about 60% of the increase against `v0.4.4` + predates this milestone. It is reproduced by the producer, so it is not a worktree + artifact, but attributing it needs a bisect of the release history this milestone + does not own. The size-review decision accepts it as a carried-forward known issue + rather than a closure blocker. +- **A `workflow_dispatch` run's `headSha` is its dispatch ref, not its candidate.** + Run `46117453196` reports `headSha` `40e362f` because it was dispatched from + `main`; the build source is the `candidate_sha` input. `summary.json` records + `source_revision` `cd075fc`, and the `resolve` job fails unless the checked-out + `HEAD` equals that input, so read the input rather than the run field. diff --git a/plans/implementation/web-acquisition-expansion/007-container-document-extraction-fidelity-correctives.md b/plans/implementation/web-acquisition-expansion/007-container-document-extraction-fidelity-correctives.md new file mode 100644 index 00000000..36cba4b3 --- /dev/null +++ b/plans/implementation/web-acquisition-expansion/007-container-document-extraction-fidelity-correctives.md @@ -0,0 +1,308 @@ +# M007 — Container-Document Extraction Fidelity and Bound Correctives + +Status: closed +Date: 2026-11-26 +Subsystem: web acquisition expansion +Milestone class: corrective +Baseline: `40e362f1b16f6d2fb5efb4fb91a0c01a85c64144` +Decision authority: ADR-0027 (default enablement); ADR-0026 Decision 2 (format, +dependency, bounds, outcome, and determinism contract — unchanged); M004 and +M006 closure records. + +References: `plans/closure/web-acquisition-expansion/004-status.md`; +`plans/closure/web-acquisition-expansion/006-status.md`; +`src/fetch/documents/extract.rs`; `src/fetch/documents/tests.rs`; +`src/fetch/client.rs`; `src/fetch/cache.rs`; `src/fetch/types.rs`; +`src/mcp/tools/web_fetch_options.rs`; `tests/documents.rs`; +`architecture/fetch.md` § Container documents; `docs/features.md` +§ Document Formats; `docs/config.md`. + +Long-term requirements: `plans/000-long-term-specification.md` §4 (bounded +acquisition — every fetched byte is capped, sanitised, and deterministic); +`plans/001-terminology-and-domain-model.md` §4-5 (document, part, and format +identity). + +Readiness: no hard dependency. The baseline is clean and every defect below is +reproduced on it, so this plan is dependency-ready as written. + +## Objective + +Make container-document extraction correct on the inputs its own format +specification allows, and make its bounds bind on the thing they claim to bound, +before ADR-0027 makes the capability a default of every published artifact. Nine +defects are in scope; each is independently observable today and each is +reproduced below with a probe result. + +Scoped to fidelity and bounds. No new format, no OCR, no layout reconstruction, +no part selector, no payload-economy change. + +This is corrective work, so it is a new plan rather than an amendment to M004 or +M006. + +## Why the original verification did not catch these + +M004's corpus was generated by a script that emitted the smallest archive that +satisfied each parser, and asserted outcome kinds, part counts, and ordering. It +never asserted extracted text equality against a reference string containing an +XML character reference, a doctype, or two attributes whose local names collide; +and it never measured peak allocation for a body whose separators are denser than +its content. The suite answered "did the right branch run" rather than "is the +text what the document says", which is exactly the gap a generated corpus leaves +open. Every work package below therefore adds the missing shape as a fixture, not +only as a unit case. + +## Defects in scope + +| # | Severity | Defect | Anchor | Observed | +|---|---|---|---|---| +| 1 | High | XML character and entity references are discarded | `extract.rs:1223` (`Ok(_) => continue`) | `Q&A <tag> café "x"` extracts as `QA tag caf x`; EPUB `a < b & c` as `a b c` | +| 2 | High | A plain `` is refused | `extract.rs:1217` | EPUB 2/3 XHTML returns `document_malformed: DTD is not supported` | +| 3 | Medium | OOXML attributes are keyed by local name, so `r:id` and `id` collide | `extract.rs:1257` | `r:id` written after `id` yields `PPTX slide relationship missing` | +| 4 | Medium | A declared `` is treated as content | `extract.rs:759` | a one-cell sheet declaring `A1:XFD1048576` returns `spreadsheet cell bound exceeded` | +| 5 | Medium | The XML token cap binds before the cell cap | `extract.rs:17` | 45,000 one-cell rows return `XML token bound exceeded`; the cell bound is unreachable | +| 6 | Medium | CSV cell count is bounded after the row is built | `extract.rs:321` | a 2,000,000-byte comma-only body peaks at 59,589,016 B against 1,753,424 B for a normal CSV | +| 7 | Low | Documentation states ceilings as defaults | `docs/features.md` § Document Formats | 16 MiB and 200,000 chars are ceilings; defaults are 2,000,000 B and 50,000 chars | +| 8 | Low | `document_unsupported` reports as `upstream_failed` | `web_fetch_options.rs:103` | the capability-miss rule assigns `capability_unavailable` | +| 9 | Low | Per-part `truncated` is attributed to the last part | `extract.rs:199` | truncation inside part 1 of 5 marks part 5 | + +Findings 1–6 and 9 were reproduced through the public extraction API on `40e362f` +with generated fixtures; 7 and 8 are static readings of the cited anchors. The +probe is not a retained artifact: the closure record must cite regenerated +fixtures and commands from this plan, not a transcript. + +## Current implementation evidence + +- `xml_tokens` (`extract.rs:1138`) unescapes `Event::Text` and `Event::CData` + but routes every other event kind to `Ok(_) => continue`. quick-xml 0.41 emits + a separate `Event::GeneralRef` for `&`, `<`, `'`, `"`, and + numeric references, so those characters are dropped rather than merged. +- `Ok(Event::DocType(_))` returns `DocumentMalformed("DTD is not supported")`. + ADR-0026 requires that no DTD is *resolved*; it does not require that the + declaration be refused, and EPUB 2/3 XHTML commonly carries + ``. +- `parse_attributes` inserts into `HashMap` under + `local_name(...)`, which lowercases and discards the prefix. `r:id` and `id` + therefore share one slot and source order decides the survivor, so the same + archive extracts differently depending on its producer. +- `check_xlsx_sheet_sizes` fails on the declared `` area before + observing a single cell, and separately fails on `max_column * max_row`. Both + are declaration-shaped bounds. +- `MAX_XML_TOKENS = 262_144` and `MAX_CELL_COUNT = 200_000` are independent + literals; a row costs several tokens, so the token cap is reachable first and + the cell cap is dead in practice. +- `parse_csv` pushes a cell on every separator with no running count; the + `MAX_CELL_COUNT` check that exists elsewhere in the module runs only after the + row vector is fully materialised. +- `build_result` receives a document-level `source_truncated: bool` and applies + it to `raw_parts.last_mut()` (`extract.rs:199`). `RawPart` already carries `truncated`, and the + XML path already knows which token was cut, so the information is discarded + rather than unavailable. +- `FetchError::DocumentUnsupported` maps to `FetchErrorKind::ExtractError` + (`types.rs:322`), which reaches `_ => ToolErrorCode::UpstreamFailed`. The + code string `document_unsupported` is available at that call site and + `fetch_tool_error` already branches on code strings for `proxy_` and + `unsupported_content_type`. +- `src/fetch/documents/extract.rs` is 1,317 lines and 46,362 bytes against the + ordinary-file ceiling of 1,600 lines and 80 KB; it carries no ratchet row, so + the ordinary ceiling applies. +- The documents module has no live network path and writes nothing to disk; all + nine defects are reachable from a body already admitted by the pre-body gate. + +## Invariants that cannot regress + +- Exactly nine advertised tools plus three callable aliases; no argument, wire + string, or tool-contract change. +- Deterministic part order and one-based part addressing: DOCX body order, PPTX + `presentation.xml` slide order, workbook sheet order, EPUB spine order, fixed + CSV row blocks. No ordering may become hash- or directory-order dependent. +- Bounds remain enforced on real inflated bytes, never on central-directory + sizes: 64 MiB decompressed, 100:1 ratio, 4,096 entries, 4,096 parts, XML + depth 64. No DTD subset, external entity, `XInclude`, or external + relationship is resolved. +- A malformed container never returns an empty success. `document_empty`, + `document_malformed`, `document_unsupported`, `document_encrypted`, and + `document_disabled` keep their meanings. +- Feature-off behaviour is byte-identical to `40e362f`: a container URL still + returns `unsupported_content_type` and CSV still returns its table preview. +- Sanitisation is applied after extraction and is not bypassed by any new text + path. +- No new dependency, no MSRV move, no `FetchErrorKind` variant. + +## Expected production changes + +| File | Change | +|---|---| +| `src/fetch/documents/extract.rs` | reference resolution; doctype acceptance; qualified attribute keys; observed-content XLSX bounds; derived token bound; incremental CSV cell bound; per-part truncation attribution | +| `src/fetch/documents/tests.rs` | unit cases per defect and the constant-derivation guard | +| `src/mcp/tools/web_fetch_options.rs` | capability-miss classification for `document_unsupported` | +| `src/fetch/cache.rs` | `renderer_version` 6 | +| `src/fetch/cache/tests.rs` | isolation case for the bump | +| `tests/documents.rs` | the end-to-end regression cases listed per package | +| `docs/features.md`, `docs/config.md`, `architecture/fetch.md` | ceilings versus defaults; reference and doctype behaviour; observed-content bounds | +| `docs/test-inventory.md`, `architecture/testing.md` | suite counts and the new fixture shapes | + +`extract.rs` has roughly 280 lines of headroom. If the work packages push it +past the ordinary ceiling, decompose by concern (archive, spreadsheet, xml, +csv) inside `src/fetch/documents/` rather than adding a ratchet row. + +## Failure semantics + +Extraction runs after the body is admitted and is bounded by caps, never by the +fetch deadline: a wall-clock bound would make output non-deterministic, which +ADR-0026 rejects. A malformed container never returns an empty success, a +refusal always names the bound or the shape it tripped, and no work package adds +a timeout, a retry, or a fallback to reading bytes as text. + +## Ordered work packages + +1. **Reference and entity resolution.** Handle `Event::GeneralRef` in + `xml_tokens`: decode the five predefined XML entities and decimal and + hexadecimal character references into the surrounding text run, and preserve + an undeclared named reference as its literal source text rather than dropping + it. Solves defect 1. Do not embed an HTML entity table; a name the document + never declared stays visible, which is honest and keeps output independent of + a table version. Fixture: DOCX body `Q&A <tag> café "x" 'y'` + asserting exact extracted text, plus an EPUB spine document using ` ` + asserting the literal survives countably. +2. **Doctype acceptance without entity expansion.** Accept a `DOCTYPE` whose + body contains no internal subset and no external identifier; refuse a body + containing `[`, `SYSTEM`, or `PUBLIC` (case-insensitive) exactly as today. + Solves defect 2 while keeping ADR-0026's no-resolution contract. Fixtures: an + EPUB whose content documents start with ``; a container whose + doctype declares an internal subset, which must still fail. +3. **Namespace-qualified attribute identity.** Key parsed attributes by + `(prefix, local)` with the prefix preserved, and make the relationship lookup + ask for `r:id` explicitly. Solves defect 3 and removes producer-order + dependence. Fixture: one PPTX written with `r:id` first and one with `id` + first, both asserting the same slide text and relationship resolution. +4. **XLSX bounds that bind on observed content.** Stop treating the declared + `` and the `column * row` product as content; bound on cells + actually materialised, stopping iteration at the cap. Derive + `MAX_XML_TOKENS` from `MAX_CELL_COUNT` with a stated per-row factor and a + fixed overhead so the cell cap is the binding constraint and the two cannot + drift apart again. Solves defects 4 and 5. Fixtures: a one-cell sheet + declaring `A1:XFD1048576`, which must extract; 45,000 one-cell rows, which + must reach the cell bound rather than the token bound; and a genuine + over-cap sheet, which must still refuse. +5. **CSV structural bound.** Enforce the cell count incrementally during the + scan, so the refusal happens at the cap rather than after the row is built, + and bound the total across the document. Solves defect 6. Evidence: the peak + allocation of a delimiter-dense fixture before and after, measured with the + retained command form in this plan, with the admitted body size stated beside + each figure. The target is a peak that is a multiple of the admitted body, not + a multiple of the separator count. +6. **Truncation attribution.** Carry the truncation point out of each extractor + into the `RawPart` it belongs to and drop the document-level inference in + `build_result`. Solves defect 9. Fixture: a multi-part document whose first + part reaches the character budget, asserting the first part is flagged and + the later parts are not, with `document_truncated` still true. +7. **Capability-miss classification.** Map `document_unsupported` to + `capability_unavailable` at the tool boundary, alongside `document_disabled` + and `pdf_not_compiled_in`. Solves defect 8 using the existing code-string + branch; no new `FetchErrorKind`. Test: an RTF or ODT target asserting the + tool error code, with `document_malformed` still reporting `upstream_failed`. + The case goes in the behavioural suite that `architecture/testing.md` assigns + to `fetch` tool errors — `tests/mcp_tools.rs` holds the adjacent capability + triad — not in `extract.rs` unit tests, because the mapping is a tool-boundary + decision. +8. **Derived cache version.** Bump `renderer_version` from 5 to 6, because + packages 1, 2, 5, and 6 change extracted text or produce content where a + refusal was cached. Add the isolation case proving a pre-bump entry is not + served. Note in the closure record that the bump is global — it invalidates + every derived entry class, not only container documents — and that this is + the mechanism ADR-0027 relies on for the CSV path when the feature default + flips. +9. **Documentation, guard, and suite inventory.** Correct `docs/features.md` + § Document Formats and `docs/config.md` to state ceilings versus defaults + (defect 7), record reference and doctype behaviour in + `architecture/fetch.md` § Container documents, and update the + `docs/test-inventory.md` and `architecture/testing.md` suite counts for the + cases added above. + +## Verification + +Focused: + +```bash +RUSTUP_TOOLCHAIN=1.89.0 cargo test --locked --features documents --lib fetch::documents +RUSTUP_TOOLCHAIN=1.89.0 cargo test --locked --features documents --test documents +RUSTUP_TOOLCHAIN=1.89.0 cargo test --locked --test documents +RUSTUP_TOOLCHAIN=1.89.0 cargo test --locked --all-features --test mcp_tools +``` + +The third command is the feature-off parity run and must stay green without the +feature. The fourth covers the tool boundary defect 8 lives behind; +`tests/static_guards.rs` runs inside `make check`. `tests/tool_surface_live.rs` is +`--ignored` and model-gated by `EGGSEARCH_EVAL_MODEL`, so it is not evidence for +this milestone and is not a required command. + +Peak-allocation evidence for package 5 uses the same fixture generator twice, +before and after, with a release-profile probe binary and the platform's peak +resident measurement; the closure record cites the generator and the command, +not a transcript. + +Broad: `make check` (the canonical gate, formatting through packaging), and +`make packaging-check` because the suite and documentation inventory move. + +## Acceptance and stop conditions + +- Each behavioural defect (1–6, 8, 9) has a case that fails at `40e362f` and + passes on the candidate; the two high-severity ones assert exact extracted + text, not a substring. Defect 7 is closed by the documentation diff. +- Feature-off behaviour is unchanged: the parity run passes and + `unsupported_content_type` still reaches a container URL. +- `renderer_version` is 6 and a pre-bump cached entry is demonstrably not + served. +- The declared-dimension sheet extracts; the genuinely over-cap sheet still + refuses; the 45,000-row sheet reports the cell bound. +- The delimiter-dense CSV peak is bounded by a small multiple of the admitted + body and the figure is recorded beside the before value. +- `extract.rs` stays under 1,600 lines and 80 KB, or the concern decomposition + lands in the same change. +- **Stop and re-plan** if the CSV bound needs a streaming rewrite of + `parse_csv` rather than an incremental count — that is a bound-architecture + change and belongs to its own milestone. +- **Stop and record a limitation** if accepting a plain doctype cannot be done + without resolving an entity; keep the refusal and document it rather than + weakening ADR-0026's no-resolution contract. +- **Stop and re-plan** if cache isolation for the version bump would require the + derived key to carry a feature bit; that is a cache-contract change. +- **Do not** change the default feature set, the config surface, the tool + surface, or any bound value other than the two named constants in package 4 + and the incremental count in package 5. Default enablement is M008. + +## Non-goals + +- Making `documents` a default feature, or any packaging, wheel, or producer + change. ADR-0027 and M008 own that. +- A part selector, per-part payload controls, or any payload-economy change. +- ODF, RTF, legacy binary Office, or any new format. +- An HTML entity table, character-set transcoding beyond the XML declaration, or + Unicode normalisation of extracted text. +- CSS-aware extraction, hidden-text detection, or structural anomaly reporting. +- A new `FetchErrorKind`, a new outcome code, or a new warning code. +- Rewriting the CSV parser as a streaming state machine, unless a stop condition + above is met and a separate milestone is filed. + +## Handoff notes + +Start from the failing observation, not from the fix: write the fixture and the +assertion first so the case fails on the baseline, then change the parser. The +four defects that change extracted text or produce content where a refusal was +cached (packages 1, 2, 5, 6) all ride the single version bump in package 8 — do +not add a second bump, and do not split the bump from the change that needs it. +The `extract.rs` headroom is small; check the line count after each package +rather than at the end. + +## Closure evidence + +`plans/closure/web-acquisition-expansion/007-status.md` records: the candidate +SHA; a per-defect table with the failing `40e362f` observation and the passing +candidate observation, each naming its test; the exact extracted strings for the +reference and doctype fixtures; the CSV peak-allocation before and after figures +with the fixture generator and command; the `renderer_version` bump with its +isolation case and the statement that the invalidation is global; the tool-error +code evidence for `document_unsupported` and `document_malformed`; the +feature-off parity run; `extract.rs` line and byte counts against the ordinary +ceiling; the documentation diff; and `make check` plus `make packaging-check` +outcomes on the exact candidate. diff --git a/plans/implementation/web-acquisition-expansion/008-container-document-default-enablement.md b/plans/implementation/web-acquisition-expansion/008-container-document-default-enablement.md new file mode 100644 index 00000000..3a83a32b --- /dev/null +++ b/plans/implementation/web-acquisition-expansion/008-container-document-default-enablement.md @@ -0,0 +1,312 @@ +# M008 — Container-Document Default Enablement + +Status: closed +Date: 2026-11-26 +Subsystem: web acquisition expansion +Milestone class: capability +Baseline: `40e362f1b16f6d2fb5efb4fb91a0c01a85c64144` +Decision authority: ADR-0027 (accepted 2026-11-26); ADR-0026 Decision 2, format, +dependency, bounds, and outcome contract preserved; ADR-0007 (the measured +default-enablement template); ADR-0014 §4; ADR-0024 §1 and §5. + +References: `plans/adrs/ADR-0027-container-document-default-enablement.md`; +`plans/implementation/web-acquisition-expansion/007-container-document-extraction-fidelity-correctives.md`; +`plans/closure/web-acquisition-expansion/006-status.md`; `Cargo.toml`; +`bindings/python/Cargo.toml`; `bindings/python/Cargo.lock`; `Makefile`; +`tests/static_guards.rs`; `tests/documents.rs`; `tests/config_validation.rs`; +`src/core/config.rs`; `src/fetch/limits.rs`; `release/eggpack/pack.toml`; +`docs/features.md`; `docs/config.md`; `docs/python-library.md`; +`architecture/build.md`; `architecture/packaging.md`; +`architecture/python-library.md`; `architecture/fetch.md`; +`docs/test-inventory.md`; `architecture/testing.md`; +`skills/eggsearch-dev/SKILL.md`. + +Long-term requirements: `plans/000-long-term-specification.md` §4 (bounded +acquisition) and §6-7 (artifact and distribution obligations); +`plans/001-terminology-and-domain-model.md` §4-5 (document and format +identity). + +## Dependencies + +- **Hard: M007 (satisfied).** Its `renderer_version` bump is what makes the flip + safe for a URL a feature-off build already cached, and its extraction fixes are + what make the capability shippable at all. M007's candidate is recorded in + `plans/closure/web-acquisition-expansion/007-status.md`. +- **Operational: hosted wheel qualification.** The `Python native qualification` + matrix must be green on the feature change; a local wheel build is not + evidence. +- **Soft: Python PyPI distribution.** The wheel feature list is shared state; + this milestone changes it, and the Python roadmap records the change rather + than owning it. + +## Readiness + +Dependency-ready: M007 is closing, and its `renderer_version` 6 bump and +extraction correctives are on the candidate this milestone builds on. ADR-0027 is +accepted, so no architectural decision is outstanding; the interface contract this +milestone consumes — the `documents_capabilities` triad, +`[fetch].documents_enabled`, and the `document_*` outcome set — is already shipped +and documented by M006. + +## Objective + +Make container-document extraction a property of the artifact an operator +installs. `documents` joins the default feature set so the one published binary +per target and the shipped wheel carry it, the wheel lockfile carries its +dependencies, the feature stays switchable off by an operator without a rebuild, +and the per-target size cost is measured on the candidate rather than asserted. + +User-visible exit: installing the published binary or wheel is enough to read a +DOCX, XLSX, PPTX, EPUB, or CSV from an explicit URL, `provider_status` reports +`documents_capabilities.compiled` as `true`, and the documentation no longer +asks the user to compile anything. + +## Non-goals + +- No extraction, bound, or outcome change. M007 owns all of it; if a defect + appears during this milestone, it is a new corrective plan, not a silent fix + here. +- No new MCP tool, alias, argument, config key, error kind, or wire string. +- No second SKU, no feature-suffixed asset, no release-matrix growth, no + installer change. The seven asset names and the 19-name public inventory are + unchanged. +- No change to `browser` or `pdf` availability; `egress` stays out of the + default set and `mock` stays test-only. +- No removal of `[fetch].documents_enabled` — ADR-0027 alternative 3 is + rejected and the switch is the operator refusal path. +- No MSRV move and no new dependency edge beyond what the `documents` feature + already declares. +- No payload or projection change: enabling a format family must not alter the + size of a response that does not contain one. + +## Current implementation evidence + +- `Cargo.toml:43` is `default = ["pdf", "browser"]`; `documents` is + `["dep:zip", "dep:calamine"]` with `zip = "=9.8.1"` and `calamine = "0.38"`. +- `tests/static_guards.rs:1911` `default_features_ship_pdf_and_browser` asserts + that `default` contains `pdf` and `browser`, that it does not contain + `egress`, and that `default_browser_enabled` is feature-derived. It does not + mention `documents`, so it neither blocks nor protects this change. +- `[fetch].documents_enabled` is already feature-derived: + `default_documents_enabled()` is `cfg!(feature = "documents")` + (`src/core/config.rs:431`, used by the serde default at `:761` and + `FetchSection::default` at `:871`), and `FetchLimits::default` sets the same + expression (`src/fetch/limits.rs:208`). `Config::fetch_limits()` copies the + config field (`src/core/config.rs:1377`), so no code change is needed for the + shipped default to become `true`; the change is the feature set itself. +- `tests/config_validation.rs:9` asserts + `config.fetch.documents_enabled == cfg!(feature = "documents")` and therefore + passes in both worlds; `tests/mcp_tools.rs:313` already loops the full + four-combination capability matrix. Neither needs an edit, and a candidate + that requires one has changed production behaviour and violated this plan. +- `bindings/python/Cargo.toml:16` is + `default-features = false, features = ["pdf", "browser"]`. +- `bindings/python/Cargo.lock` contains neither `zip` nor `calamine` (378 + packages); the root `Cargo.lock` contains both. The lockfile is a tracked + release input (`packaging/release-inputs.txt`) and qualification builds with + `--locked`, so it must be regenerated in the same change. +- The producer needs no edit: the generated release workflow builds with neither + `--features` nor `--no-default-features`, so default-set membership is the + only lever. `release/eggpack/` carries no feature information. +- `make check` is `fmt clippy feature-check test hygiene dependency-policy + packaging-check`; `feature-check` is `cargo check --locked + --no-default-features` and `test` is `cargo test --locked --all-features`. + **No target runs the test suite with default features disabled**, so once + `documents` is default the feature-off parity half of `tests/documents.rs` + becomes unreachable in CI while remaining green-by-absence. +- Measured at `v0.4.4` (public release assets, read 2026-11-26) with `pdf` and + `browser` and no container support: `aarch64-apple-darwin` 17,960,304; + `aarch64-pc-windows-msvc` 21,655,040; `aarch64-unknown-linux-gnu` 18,524,080; + `armv7-unknown-linux-gnueabihf` 17,710,392; `x86_64-apple-darwin` 19,779,368; + `x86_64-pc-windows-msvc` 25,869,312; `x86_64-unknown-linux-gnu` 21,457,240 + bytes. Three already exceed ADR-0024 §5's 20 MB review figure, so that figure + is a review trigger satisfied by a written reason, not an absolute ceiling. +- Six documents state the pre-decision posture and are falsified by the change: + `docs/features.md` § Document Formats (not in the default set; `cargo build + --features documents`), `docs/config.md` (`documents_enabled` is `false` in + every default build and in the wheel), `architecture/build.md` (default + features include `pdf` and `browser`), `architecture/packaging.md` (default + features build every release asset; wheel feature list), + `architecture/python-library.md` (wheel compiles `pdf` and `browser`), and + `docs/python-library.md` (the same wheel feature list). + +## Invariants that cannot regress + +- Seven release asset names, `.exe` suffixes on the two Windows rows, `.sha256` + sidecars, version-free naming, and the 19-name public inventory are unchanged. + `make producer-drift` stays clean without a producer edit. +- Exactly nine advertised tools plus three aliases; every argument name and wire + string unchanged. +- `document_disabled` remains reachable and documented: an operator who sets + `[fetch].documents_enabled = false` refuses every detected container before + parsing, on both the pre-body path and raw-cache re-derivation. +- `unsupported_content_type` remains reachable for a body that is neither text, + HTML, PDF, nor a recognised container, and is what a build with the feature + disabled still returns for a container URL. +- The feature-off build keeps compiling and keeps its behaviour, verified by a + gate rather than by inspection. +- Trust framing, sanitisation tiers, SSRF and redirect policy, and byte caps are + untouched. + +## Expected production changes + +| File | Change | +|---|---| +| `Cargo.toml` | `default = ["pdf", "browser", "documents"]` | +| `bindings/python/Cargo.toml` | `features = ["pdf", "browser", "documents"]` | +| `bindings/python/Cargo.lock` | regenerated with `zip` and `calamine` | +| `Makefile` | the feature-off parity target described in package 3 | +| `tests/static_guards.rs` | the default-set guard covers `documents` and still rejects `egress` | +| `tests/documents.rs` | only if an invocation or gate change requires it; no assertion weakening | + +No production source change is expected in `src/`. If package 3 cannot be +satisfied without one, stop rather than widen the milestone. + +## Ordered work packages + +1. **Default feature set.** Add `documents` to `Cargo.toml` `default`. Confirm + `cargo check --locked --no-default-features` still passes so the lean shape + stays compilable, and that the documented reproduction of the old build + (`--no-default-features --features pdf,browser`) builds. Extend + `tests/static_guards.rs` `default_features_ship_pdf_and_browser` to require + `documents` as well, keep the `egress` rejection, and add the assertion that + `default_documents_enabled` is feature-derived, mirroring the browser clause + so the config default cannot drift from the feature. +2. **Wheel feature set and lockfile.** Add `documents` to + `bindings/python/Cargo.toml`, regenerate `bindings/python/Cargo.lock`, and + confirm the wheel imports and extracts from Python without a rebuild path. + A `--locked` build is the acceptance evidence. +3. **Feature-off parity lane.** `make check` no longer runs the test suite with + the feature disabled, so restore an explicit lane: a target that runs the + documents suite with defaults disabled, wired into `check` alongside + `feature-check`, with runtime cost stated in the closure record. Update + `docs/test-inventory.md`, `architecture/testing.md`, and + `skills/eggsearch-dev/SKILL.md` for the changed invocation, which the + repository requires when a suite's requirement changes. +4. **Default coherence.** Prove with no production change that the four + combinations still report honestly: feature compiled or not, setting true or + false, on both fetch paths, with `tests/config_validation.rs` and + `tests/mcp_tools.rs` green unmodified. A `document_disabled` refusal on a + default build is part of the evidence, not an edge case. +5. **Size and footprint.** Measure every target on the exact candidate against + the `v0.4.4` bytes above: absolute size per target, delta per target, and the + wheel delta. State a written reason for each target over the 20 MB review + figure. Do not present a delta percentage without the absolute figure beside + it. +6. **Packaging and dependency policy on the default path.** `make + dependency-policy` and `make packaging-check` must resolve `zip` and + `calamine` on the default graph rather than only under `--all-features`, and + `make producer-drift` must stay clean with no producer edit. The 1.89 MSRV + default build is part of this package; `zip 9.8.1` sits exactly on 1.89. +7. **Documentation and release facts.** Correct the six statements listed in + current evidence, document the two behaviour changes ADR-0027 names (a CSV + URL now returns a `document`; ODF, RTF, and legacy binary Office now return + `document_unsupported`), and add an `Unreleased` changelog entry for the + default move. Update `docs/features.md` § Document Formats so the first + sentence describes the shipped artifact and the source-build shape is the + secondary paragraph, and record the `renderer_version` value the release + carries. +8. **Capability report review.** Read `provider_status` output from a default + build and confirm the triad, `server_capabilities.container_documents`, and + the format list are accurate in every state a default install can reach, + including the runtime-discovered absence of a browser, which must not affect + the document triad. + +## Failure and recovery semantics + +The failure modes of this milestone are build and distribution failures, not +runtime ones, and each fails closed at a gate rather than at an operator: + +- **A target does not build with the new default.** The release workflow fails at + that target before publication; the milestone does not merge a partial matrix + and does not reorder assets. Recovery is ADR-0027 alternative 1 — revert the + default and keep the capability optional — not a per-target feature set. +- **The wheel does not build or does not qualify.** `--locked` fails on a stale + `bindings/python/Cargo.lock`; regeneration is part of the change, and a wheel + that imports but cannot extract is a failed qualification, not a partial pass. +- **A size figure is unexplained.** Publication pauses for review; there is no + automatic rollback and no silent threshold change. +- **The parity lane cannot run in the gate.** Stop and re-plan rather than + dropping the lane, because a lane that exists on paper is worse than none. + +No work package adds a timeout, a retry, or a runtime fallback: extraction +behaviour is M007's contract, and a fallback that reads a container as text would +violate it. + +## Verification + +```bash +RUSTUP_TOOLCHAIN=1.89.0 cargo check --locked --no-default-features +RUSTUP_TOOLCHAIN=1.89.0 cargo check --locked --no-default-features --features pdf,browser +RUSTUP_TOOLCHAIN=1.89.0 cargo test --locked --features documents --test documents +RUSTUP_TOOLCHAIN=1.89.0 cargo test --locked --no-default-features --test documents +RUSTUP_TOOLCHAIN=1.89.0 cargo test --locked --all-features +make check +make packaging-check +make dependency-policy +make producer-drift +``` + +Plus, outside the gate: a release-profile build of the candidate on at least the +host target for the size figures, and the hosted `Python native qualification` +matrix on the wheel change. Rotate the local probe form + +```bash +grep -n 'name = "calamine"' bindings/python/Cargo.lock +cargo metadata --locked --format-version 1 --no-deps | python3 -c 'import json,sys; d=json.load(sys.stdin); print({p["name"]: p["features"]["default"] for p in d["packages"]})' +``` + +to prove the lockfile and the declared default rather than reading them. At +baseline the first prints nothing with exit 1 and the second prints +`{'eggsearch': ['pdf', 'browser']}`; on the candidate the first names the +package and the second lists all three features. + +Broad: `make check` on the exact candidate, and the hosted workflows for the +wheel and the release candidate. A green local run is not qualification. + +## Acceptance and stop conditions + +- The candidate's default feature set is `["pdf", "browser", "documents"]`, the + guard enforces it, and `egress` is still excluded. +- `bindings/python/Cargo.lock` contains `zip` and `calamine` and a `--locked` + wheel build succeeds; the hosted matrix is green. +- A default build reports `compiled: true`, `configured: true`, `usable: true` + and extracts all five formats; setting `documents_enabled = false` yields + `document_disabled` on both fetch paths; a build with the feature disabled + still compiles and still returns `unsupported_content_type`. +- The feature-off parity lane runs in `make check` and its cases execute rather + than being skipped, demonstrable by count. +- Per-target absolute sizes and deltas are recorded, with a reason for every + target over the 20 MB review figure, and the wheel delta is recorded. +- `tests/config_validation.rs` and `tests/mcp_tools.rs` are green **unmodified**. +- **Stop and return to ADR-0027 alternative 1** if a target fails to build with + the new default, if the wheel matrix fails to qualify, or if a size figure is + unexplained past the review threshold. +- **Stop and re-plan** if the default flip requires a change in `src/`; the + config and capability defaults are already feature-derived and a source change + signals that assumption was wrong. +- **Stop and re-plan** if the feature-off parity lane cannot run within the gate + budget; a parity lane that exists on paper only is worse than none. + +## Handoff notes + +Re-measure the published baseline before writing any size figure; the ones in +this plan were read on 2026-11-26 at `v0.4.4` and a newer release invalidates +them. Run the parity lane before the default flip as well as after, so a case +that was already skipped is distinguishable from one the change skipped. Treat +`tests/config_validation.rs` and `tests/mcp_tools.rs` as canaries: if either +needs an edit, the assumption that the config default is feature-derived is +wrong and the milestone must stop. + +## Closure evidence + +`plans/closure/web-acquisition-expansion/008-status.md` records: the candidate +SHA and the M007 candidate it builds on; the declared default feature set with +the guard output; the regenerated lockfile evidence and the `--locked` wheel +build; the hosted `Python native qualification` run identifier; the +four-combination capability and refusal matrix on both fetch paths; the +feature-off parity lane with its executed case count; the per-target absolute +size and delta table against the `v0.4.4` figures with the review-threshold +reasons; the wheel size delta; `make check`, `make packaging-check`, +`make dependency-policy`, and `make producer-drift` outcomes; the documentation +diff; the changelog entry; and the `renderer_version` the release carries. diff --git a/plans/registry.md b/plans/registry.md index b8aee6da..1d2036b3 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -31,7 +31,7 @@ Closed or superseded implementation plans are archived under | PDF ingestion and extraction fidelity | closing | `plans/subsystems/pdf-ingestion-fidelity-roadmap.md` | M001/M002/M007 are implemented with closure records; M006 qualification remains open; M008 is active by user approval against the existing M001 implementation, with M001 exact-candidate status reconciliation still open; M003–M005 are ready. | | Adaptive fetch target routing and artifacts | active (M001 active; M002 and M003 closed) | `plans/subsystems/adaptive-fetch-routing-roadmap.md` | M002 closed on `24f045729f8409dadc96b4c2455253d8a9c7b6ec`; see `plans/closure/adaptive-fetch-routing/002-status.md`. M001's implementation remains committed on that candidate but its closure record is outstanding. M003 closed on candidate `59ff64ad00940573ee520ecf19d7b5c0abcb1c87`; see `plans/closure/adaptive-fetch-routing/003-status.md`. Local PDF behavior remains owned by PDF M008. | | Knowledge-delta research | active; M001–M007 closed | `plans/subsystems/knowledge-delta-roadmap.md` | Closure evidence is linked from the roadmap. | -| Web acquisition expansion | active; M001, M002, M003, M004, and M006 closed; M005 closed (no-go) | `plans/subsystems/web-acquisition-expansion-roadmap.md` | M001, M002, M003, M004, and M006 closed with records under `plans/closure/web-acquisition-expansion/`. ADR-0026 is accepted: Decision 1 governed M003, Decision 2 the M004 format and dependency set, and Decision 3 rejects M005. | +| Web acquisition expansion | active; M001, M002, M003, M004, M005, M006, M007, and M008 closed | `plans/subsystems/web-acquisition-expansion-roadmap.md` | M001, M002, M003, M004, and M006 closed with records under `plans/closure/web-acquisition-expansion/`. ADR-0026 is accepted: Decision 1 governed M003, Decision 2 the M004 format and dependency set, and Decision 3 rejects M005. ADR-0027 is accepted and supersedes Decision 2's non-default clause; M007 (extraction fidelity and bound correctives) is the hard predecessor of M008 (default enablement), and M008 proceeds only behind M007's `renderer_version` 6 bump and its measured bounds. M007 and M008 are closed. M008's default set, wheel feature list, lockfile, guard, and parity lane are landed; `make check` is green; hosted `Python native qualification` run 46115248218 (41/41) and eggpack candidate qualification run 46117453196 (25/25) are green on `cd075fc`; and all seven per-target asset sizes are recorded. The 2026-11-28 size-review decision kept the default flip with the written reason recorded, carrying the unidentified ~60% pre-existing growth as a release-candidate known issue. | | Dynamic-fetch proxy routing | closed; M001–M003 closed | `plans/subsystems/dynamic-fetch-proxy-routing-roadmap.md` | ADR-0025 accepted on the M001 loopback evidence; M002 and M003 closed with records under `plans/closure/dynamic-fetch-proxy-routing/`. `make check` passed under Rust 1.89. Eggress stays provider-upstream only. | ## Active and dependency-ready implementation plans @@ -66,6 +66,8 @@ Closed or superseded implementation plans are archived under | Web acquisition expansion | M004 document formats beyond PDF | closed | `plans/implementation/web-acquisition-expansion/004-document-formats-beyond-pdf.md` | Closed; see `plans/closure/web-acquisition-expansion/004-status.md`. ADR-0026 Decision 2: zip 9 + calamine behind a non-default `documents` feature. | | Web acquisition expansion | M006 documents capability reporting | closed | `plans/implementation/web-acquisition-expansion/006-documents-capability-reporting.md` | Closed; see `plans/closure/web-acquisition-expansion/006-status.md`. Corrective: M004 shipped extraction with no operator switch and no capability report. | | Web acquisition expansion | M005 instruction-signal screening | closed | `plans/implementation/web-acquisition-expansion/005-instruction-signal-screening.md` | ADR-0026 Decision 3: no-go. No field ships; the existing marker scan remains the contract. | +| Web acquisition expansion | M007 container-document extraction fidelity and bound correctives | closed | `plans/implementation/web-acquisition-expansion/007-container-document-extraction-fidelity-correctives.md` | Post-closure audit of M004/M006 at `40e362f`: XML character and entity references are dropped silently, a plain `` is refused, `r:id` and `id` collide, an XLSX declared dimension is treated as content, the XML token cap binds before the cell cap, CSV cell counting happens after the row is built (≈30× peak amplification), per-part `truncated` is attributed to the last part, `document_unsupported` reports as `upstream_failed`, and the documented figures are ceilings. Nine bounded packages, one `renderer_version` bump (5 → 6), no new `FetchErrorKind`, no default-set or tool change. Implemented with two recorded substitutions: the XLSX size scan streams instead of deriving `MAX_XML_TOKENS` (so the cell bound is the only bound on a sheet, and the observed bounding rectangle is bounded because the reader densely allocates it), and the defect-9 fixture uses the EPUB heading cap because the document budget cannot leave later parts uncut. Closure: `plans/closure/web-acquisition-expansion/007-status.md`. | +| Web acquisition expansion | M008 container-document default enablement | closed | `plans/implementation/web-acquisition-expansion/008-container-document-default-enablement.md` | Hard dependency M007 is closed, and its `renderer_version` bump is what makes the flip safe for a derived entry cached by a feature-off build. ADR-0027 (accepted) selects the default feature set, the wheel feature list, and a regenerated `bindings/python/Cargo.lock`; `make check` currently has no lane that tests with default features disabled, so the milestone restores one. Eight packages, per-target size measurement against the published `v0.4.4` figures, no production source change expected. Hosted `Python native qualification` run 46115248218 (41/41) and eggpack candidate qualification run 46117453196 (25/25) are green on `cd075fc`; the wheel delta and all seven per-target asset sizes are measured, and the 2026-11-28 size-review decision kept the default flip, carrying the unexplained pre-existing ~60% growth past the 20 MB review figure as a release-candidate known issue. Closure: `plans/closure/web-acquisition-expansion/008-status.md`. | | Dynamic-fetch proxy routing | M001 route feasibility and Eggress compatibility | closed | `plans/implementation/dynamic-fetch-proxy-routing/001-route-feasibility-and-eggress-compatibility.md` | Closed; see `plans/closure/dynamic-fetch-proxy-routing/001-status.md`. | | Dynamic-fetch proxy routing | M002 pinned proxy routing for dynamic fetch | closed | `plans/implementation/dynamic-fetch-proxy-routing/002-pinned-proxy-routing.md` | Closed; see `plans/closure/dynamic-fetch-proxy-routing/002-status.md`. | | Dynamic-fetch proxy routing | M003 qualification, packaging, and operator documentation | closed | `plans/implementation/dynamic-fetch-proxy-routing/003-qualification-packaging-and-operator-docs.md` | Closed; see `plans/closure/dynamic-fetch-proxy-routing/003-status.md`. | diff --git a/plans/subsystems/python-pypi-distribution-roadmap.md b/plans/subsystems/python-pypi-distribution-roadmap.md index 1ef1b5c5..9ccb956e 100644 --- a/plans/subsystems/python-pypi-distribution-roadmap.md +++ b/plans/subsystems/python-pypi-distribution-roadmap.md @@ -45,7 +45,7 @@ The term *experimental SBC support* covers hardware-model/runtime/footprint unce | M007 Python typed-surface parity correctives | invariant (corrective) | closed | interface: M006 typed surface; hard: hosted `Python native qualification` on `main` | Closed on `057a86d`; hosted run `46072717384` passed 41/41 jobs. Restores `provider_status.response_detail`, the `site` item type and its package export, and a schema-derived item-field guard; binding-only, with no Rust or schema change. Closure: `plans/closure/python-pypi-distribution/007-status.md`. | | M004 post-publication SBC benchmarking and tuning decision | blocked | operational: native ARMv7 32-bit runtime evidence | The published 0.4.4 aarch64 wheel passed native installed-wheel smoke and benchmark on a Libre Computer AML-S905X-CC. Full measurements are in `plans/closure/python-pypi-distribution/004-status.md` and `004-aarch64.json`. The maintainer deferred ARMv7 physical testing; keep that wheel experimental. | -M001–M003, M005, and M006 are closed. The first public release was manually dispatched through the configured PyPI Trusted Publisher and pre-created GitHub `pypi` environment; the maintainer directed that no required reviewer be used. M004 is post-publication. Its native aarch64 sample is complete; ARMv7 32-bit physical benchmarking is deferred by the maintainer and remains the only M004 blocker. Keep ARMv7 support experimental until that evidence exists. M006 qualifies source version `0.4.5`; it does not publish that version. See `plans/closure/python-pypi-distribution/006-status.md`. M007 is the typed-surface parity corrective surfaced by the first `main` push at `699f909`: `provider_status.response_detail` and `site` fetch items were advertised by the canonical schema but absent from the typed bindings. Binding-only; closed on `057a86d` with hosted run `46072717384` green (41/41 jobs). See `plans/implementation/python-pypi-distribution/007-typed-surface-parity-correctives.md` and `plans/closure/python-pypi-distribution/007-status.md`. +M001–M003, M005, and M006 are closed. The first public release was manually dispatched through the configured PyPI Trusted Publisher and pre-created GitHub `pypi` environment; the maintainer directed that no required reviewer be used. M004 is post-publication. Its native aarch64 sample is complete; ARMv7 32-bit physical benchmarking is deferred by the maintainer and remains the only M004 blocker. Keep ARMv7 support experimental until that evidence exists. M006 qualifies source version `0.4.5`; it does not publish that version. See `plans/closure/python-pypi-distribution/006-status.md`. M007 is the typed-surface parity corrective surfaced by the first `main` push at `699f909`: `provider_status.response_detail` and `site` fetch items were advertised by the canonical schema but absent from the typed bindings. Binding-only; closed on `057a86d` with hosted run `46072717384` green (41/41 jobs). See `plans/implementation/python-pypi-distribution/007-typed-surface-parity-correctives.md` and `plans/closure/python-pypi-distribution/007-status.md`. The wheel's compiled feature list is not owned here: web acquisition M008 adds `documents` to it under ADR-0027, and its hosted `Python native qualification` run is that milestone's evidence, not this roadmap's. Implementation handoffs: `plans/archive/implementation/python-pypi-distribution/001-python315-toolchain-and-abi3.md` through `004-post-publication-sbc-benchmarking.md`. Closure records go to `plans/closure/python-pypi-distribution/NNN-status.md`. Keep the registry aligned. diff --git a/plans/subsystems/web-acquisition-expansion-roadmap.md b/plans/subsystems/web-acquisition-expansion-roadmap.md index 4eef52eb..18858143 100644 --- a/plans/subsystems/web-acquisition-expansion-roadmap.md +++ b/plans/subsystems/web-acquisition-expansion-roadmap.md @@ -1,10 +1,10 @@ # Web Acquisition Expansion Roadmap -Status: active (M001, M002, M003, M004, and M006 closed; M005 closed as no-go) +Status: active (M001, M002, M003, M004, M005, M006, M007, and M008 closed) Planning baseline: `d932115d1f86af51710747d243455792ff63a6fb` (`docs/user-facing-polish-20261123`) Owner: fetch extraction, discovery, and document formats -References: `plans/000-long-term-specification.md` §§1-4; `plans/001-terminology-and-domain-model.md` §4-5; ADR-0001, ADR-0002, ADR-0006 (keyless deterministic retrieval), ADR-0011 (document addressing), ADR-0014 (render bounds), ADR-0022 (nine tools); ADR-0026 (snapshot persistence, container formats, and the M005 no-go); `architecture/fetch.md`; `docs/tool-matrix.md`. +References: `plans/000-long-term-specification.md` §§1-4; `plans/001-terminology-and-domain-model.md` §4-5; ADR-0001, ADR-0002, ADR-0006 (keyless deterministic retrieval), ADR-0011 (document addressing), ADR-0014 (render bounds), ADR-0022 (nine tools); ADR-0026 (snapshot persistence, container formats, and the M005 no-go); ADR-0027 (container documents in the default artifact set); `architecture/fetch.md`; `docs/tool-matrix.md`. ## 1. Purpose and ownership boundary @@ -71,7 +71,7 @@ fetch/scope.rs selector validation and DOM scoping (scraper) fetch/attributes.rs bounded CSS attribute extraction fetch/site_map.rs robots -> sitemap index -> sitemap (quick-xml) -> link fallback fetch/snapshots/ opt-in durable store (M003, gated by ADR) -fetch/documents/ format detection and per-format extraction (M004, feature-gated) +fetch/documents/ format detection and per-format extraction (M004; default from M008) ``` All of it surfaces through the existing `fetch` web item. No tool is added. @@ -82,8 +82,11 @@ All of it surfaces through the existing `fetch` web item. No tool is added. M001 selectors + cache-only ── interface ──> M003 change comparison (scope in snapshot key) M002 site discovery ────────── soft ───────> M003 (a changed page set becomes expressible) ADR-0026 Decision 1 ────────── hard ──> M003 (storage, scope, retention, diff guard) -M004 documents ─────────────── independent ──> (no downstream milestone) +M004 documents ─────────────── soft ───────> M006 (capability report), M007, M008 ADR-0026 Decision 2 ────────── hard ──> M004 (format and dependency set) +M006 capability report ─────── soft ───────> M008 (the triad must report the new default) +M007 fidelity and bounds ───── hard ──> M008 (corrective before any default) +ADR-0027 default enablement ── hard ──> M008 (artifact set and measurement gate) M005 screening ─────────────── rejected ──> closed (ADR-0026 Decision 3) ``` @@ -97,6 +100,8 @@ M005 screening ─────────────── rejected ──> cl | M004 — Document formats beyond PDF | capability | closed | `plans/implementation/web-acquisition-expansion/004-document-formats-beyond-pdf.md` | ADR-0026 Decision 2 (accepted); `documents` optional feature | An explicit URL to CSV, EPUB, DOCX, XLSX, or PPTX returns bounded structured text | | M005 — Instruction-signal screening | capability | closed (no-go) | `plans/implementation/web-acquisition-expansion/005-instruction-signal-screening.md` | ADR-0026 Decision 3 (rejected) | No field ships; the existing marker scan and its limits remain the contract | | M006 — Documents capability reporting and operator switch | corrective | closed | `plans/implementation/web-acquisition-expansion/006-documents-capability-reporting.md` | ADR-0026 Decision 2; M004 closure record | `provider_status` reports container-document support and `[fetch].documents_enabled` can refuse it, without changing non-default behaviour | +| M007 — Container-document extraction fidelity and bound correctives | corrective | closed | `plans/implementation/web-acquisition-expansion/007-container-document-extraction-fidelity-correctives.md` | ADR-0027; ADR-0026 Decision 2 bounds contract; M004 and M006 closure records | The text a container document says is the text an agent receives: references resolve, ordinary EPUB XHTML is accepted, OOXML attributes do not collide, and every bound binds on observed content rather than on a declaration or a separator count | +| M008 — Container-document default enablement | capability | closed | `plans/implementation/web-acquisition-expansion/008-container-document-default-enablement.md` | ADR-0027 (accepted); hard: M007; operational: hosted wheel qualification and candidate build (runs 46115248218 41/41 and 46117453196 25/25) | Installing the published binary or wheel is enough to read DOCX, XLSX, PPTX, EPUB, and CSV from an explicit URL, at a recorded per-target size cost | ## 8. Cross-cutting requirements @@ -122,6 +127,12 @@ M002; deterministic diff fixtures as unit cases for M003 (exact hunk lines and counts, byte-identical repeated builds); generated per-format archives for M004, including deliberately malformed, encrypted, and high-ratio inputs, so no binary corpus can drift from the parser. M005 has no corpus because it was rejected. +M007 asserts extracted text, not only outcome kinds, against bodies carrying +character references, a doctype, colliding attribute names, a declared +spreadsheet dimension, and delimiter-dense CSV, and records peak allocation for +the last of those before and after. M008 records per-target absolute size and +delta against the published `v0.4.4` figures, and runs the documents suite with +default features disabled because the canonical gate otherwise cannot. `make check` and `make docs-check` on every milestone. No test requires the network. @@ -139,6 +150,17 @@ network. explicit rather than silently truncated. - **Dependency weight.** M004 adds crates to a 1.89 MSRV build with strict packaging guards; the `pdf` feature history is the template. +- **Default enablement cost.** ADR-0027 puts container parsing in every + installed artifact, so a parser defect becomes a shipped defect rather than a + source-build inconvenience, and three of seven targets already exceed + ADR-0024 §5's 20 MB review figure at `v0.4.4` before the crates arrive. M007 + closes first, and M008 records absolute size per target with a written reason + rather than a delta percentage. +- **Bounds that bind on the wrong thing.** Three defects in this workstream + share one shape: a bound evaluated against what the input *declares* (a + spreadsheet dimension, a token count, a separator count) instead of what it + produces. Any new bound belongs on observed content and must stop work before + the allocation it bounds. - **Screening false positives.** M005 was rejected by ADR-0026 Decision 3: the proposed signal duplicates `scan_injection_markers`, and the precision bar is not reachable with fixed patterns. No field ships, and trust markers are diff --git a/skills/eggsearch-dev/SKILL.md b/skills/eggsearch-dev/SKILL.md index c020c124..bbef08e6 100644 --- a/skills/eggsearch-dev/SKILL.md +++ b/skills/eggsearch-dev/SKILL.md @@ -13,6 +13,7 @@ Use when building, testing, or contributing to eggsearch. Covers cargo commands, # Routine verification gate make check make packaging-check +make parity-check cargo test --locked --all-features update::tests # Individual targets @@ -35,9 +36,10 @@ cargo bench --locked --all-features --bench perf --no-run # characterization on | `mock` | Test-only mock engine (`src/meta/mock.rs`) | Integration/corpus tests | | `pdf` | PDF text extraction via `lopdf` | PDF tests | | `browser` | Headless Chrome/Chromium rendering via `chromiumoxide` | Browser rendering tests | +| `documents` | Container-document extraction for CSV/TSV, EPUB, DOCX, XLSX, and PPTX | `documents` suite | | `egress` | Optional listener-free HTTP/SOCKS proxy-chain route beneath eggfetch (provider upstreams only, source-build opt-in) | Egress routing tests | | `live-smoke` | Live network smoke tests (implies `mock`) | Manual only | -| `live-mcp-smoke` | Real MCP-protocol smoke against built-in keyless defaults; retains default `pdf`/`browser`, does not enable `mock` | Manual only | +| `live-mcp-smoke` | Real MCP-protocol smoke against built-in keyless defaults; retains default `pdf`/`browser`/`documents`, does not enable `mock` | Manual only | | `live-release-smoke` (make target) | The same ignored MCP smoke built with `--release`; the only valid measurement of challenge-solver and proof-of-work timing | Manual only | **Integration/corpus tests require `--features mock`.** Running `cargo test` without features misses most tests. @@ -55,7 +57,7 @@ cargo bench --locked --all-features --bench perf --no-run # characterization on | `tests/snapshot_change.rs` | `mock` | Deterministic persistent fetch comparison, sanitized storage, brief projection, and disabled-store warning | | `tests/site_map.rs` | `mock` | Bounded same-origin site URL discovery: robots/sitemap/index/link sources, normalization, malformed XML, bounds, determinism, and zero fetch of discovered URLs | | `tests/snapshot_change.rs` | `mock` | Durable deterministic change comparison: `new`/`same`/`changed`/`removed`, sanitized storage, disabled and corrupt-store degradation, and caller-key validation | -| `tests/documents.rs` | `documents` (feature-off cases run without it) | Container-document extraction for CSV/TSV, EPUB, DOCX, XLSX, and PPTX, deterministic ordering, typed outcomes, and feature-off parity | +| `tests/documents.rs` | `documents` (feature-off cases run without it) | Container-document extraction for CSV/TSV, EPUB, DOCX, XLSX, and PPTX, deterministic ordering, typed outcomes, and feature-off parity (11 cases with the feature, 3 without) | | `tests/structured_local_code_intelligence.rs` | `mock` | Structured local code intelligence: 4-language fixtures, definition ranking, regex fallback, budgets, repo-map enrichment | | `tests/corpus_runner.rs` | `mock` | Multi-step workflow regression | | `tests/property_*.rs` | None | Property tests (sanitize, identity, fetch, render, local FS, excerpt economy) | @@ -76,7 +78,7 @@ cargo bench --locked --all-features --bench perf --no-run # characterization on | `tests/security_applicability_corpus.rs` | None | Security applicability pipeline regression | | `tests/browser_profiles.rs` | `browser` | Browser profile management | | `tests/browser_transport.rs` | `browser` | Browser transport orchestration | -| `tests/mcp_http.rs` | `all-features`; live test via `live-mcp-smoke` | Loopback Streamable HTTP lifecycle, bounds, identity, shutdown, plus ignored real-provider MCP smoke exercising default PDF/browser features without `mock` | +| `tests/mcp_http.rs` | `all-features`; live test via `live-mcp-smoke` | Loopback Streamable HTTP lifecycle, bounds, identity, shutdown, plus ignored real-provider MCP smoke exercising default PDF/browser/documents features without `mock` | | `bindings/python/tests/test_native.py` | CPython 3.11–3.14 | Native asyncio bridge, input bounds, started-barrier cancellation with Rust drop/permit recovery, concurrent close and 32-call saturation recovery, and default-config selection | This table is representative, not exhaustive — 96 test suites exist. Full per-suite inventory lives in `docs/test-inventory.md`. @@ -97,6 +99,7 @@ cargo test --locked --all-features --test proxy_route_feasibility cargo test --locked --features mock --test fetch_proxy_route cargo test --locked --features mock --test site_map cargo test --locked --all-features --test documents +cargo test --locked --no-default-features --test documents # feature-off parity: 3 cases; 11 with the feature cargo test --locked --features mock --test snapshot_change cargo test --locked --all-features --test docs_config_snippets --test docs_provider_inventory --test docs_tool_names --test docs_safety_vocabulary --test docs_links --test static_guards ``` diff --git a/src/fetch/cache.rs b/src/fetch/cache.rs index 82750406..eecc489a 100644 --- a/src/fetch/cache.rs +++ b/src/fetch/cache.rs @@ -718,7 +718,7 @@ pub fn build_derived_key_scoped_with_route( pdf_pages: pdf_pages.map(|s| s.to_string()), pdf_ocr: pdf_ocr.map(|s| s.to_string()), include_media, - renderer_version: 5, + renderer_version: 6, sanitize_output, scoping_fingerprint, route_fingerprint, diff --git a/src/fetch/cache/tests.rs b/src/fetch/cache/tests.rs index d1942167..bdaeddd3 100644 --- a/src/fetch/cache/tests.rs +++ b/src/fetch/cache/tests.rs @@ -1051,7 +1051,7 @@ fn derived_key_renderer_version_isolates_pre_encryption_refusal_entries() { false, true, ); - assert_eq!(current.extraction_key.renderer_version, 5); + assert_eq!(current.extraction_key.renderer_version, 6); let mut legacy = current.clone(); legacy.extraction_key.renderer_version = 3; assert_ne!( @@ -1084,13 +1084,44 @@ async fn cache_derived_does_not_serve_pre_encryption_refusal_entries() { false, true, ); - assert_eq!(current.extraction_key.renderer_version, 5); + assert_eq!(current.extraction_key.renderer_version, 6); assert!( cache.get_derived(¤t).await.is_none(), "a derived entry written before the encryption-refusal bump must not be served" ); } +#[tokio::test] +async fn cache_derived_does_not_serve_pre_container_fidelity_entries() { + let cache = FetchCache::new(10, 10, 1_000_000, 1_000_000); + let mut legacy = make_derived_key(7); + legacy.extraction_key.renderer_version = 5; + let mut legacy_entry = make_derived_entry(7, 32); + legacy_entry.extraction_key = legacy.extraction_key.clone(); + cache.insert_derived(legacy.clone(), legacy_entry).await; + assert!( + cache.get_derived(&legacy).await.is_some(), + "the fixture entry must be retrievable under its own key" + ); + + let current = build_derived_key( + &CacheScope::Anonymous, + 7, + ExtractMode::Text, + ExtractionBudgetClass::document_scoped(50_000), + false, + None, + None, + false, + true, + ); + assert_eq!(current.extraction_key.renderer_version, 6); + assert!( + cache.get_derived(¤t).await.is_none(), + "a derived entry written before the container-fidelity bump must not be served" + ); +} + #[test] fn build_derived_key_distinguishes_pdf_pages() { let scope = CacheScope::Anonymous; diff --git a/src/fetch/documents/extract.rs b/src/fetch/documents/extract.rs index 6ef6b1ae..cf09d737 100644 --- a/src/fetch/documents/extract.rs +++ b/src/fetch/documents/extract.rs @@ -169,20 +169,12 @@ pub fn extract_document( DocumentFormat::Xlsx => extract_xlsx(body, markdown)?, DocumentFormat::Pptx => extract_pptx(body)?, }; - build_result( - format, - raw_parts.0, - raw_parts.1, - markdown, - document_chars, - window_chars, - ) + build_result(format, raw_parts, markdown, document_chars, window_chars) } fn build_result( format: DocumentFormat, - mut raw_parts: Vec, - source_truncated: bool, + raw_parts: Vec, markdown: bool, document_chars: usize, window_chars: usize, @@ -195,14 +187,9 @@ fn build_result( "part count bound exceeded".to_string(), )); } - if source_truncated { - if let Some(last) = raw_parts.last_mut() { - last.truncated = true; - } - } let parts_total = raw_parts.len(); let mut remaining = document_chars.min(MAX_DOCUMENT_CHARS); - let mut document_truncated = source_truncated; + let mut document_truncated = false; let mut parts = Vec::with_capacity(raw_parts.len()); for (offset, raw) in raw_parts.into_iter().enumerate() { let char_count = raw.text.chars().count(); @@ -246,7 +233,7 @@ fn extract_csv( url: &str, content_type: Option<&str>, markdown: bool, -) -> Result<(Vec, bool), FetchError> { +) -> Result, FetchError> { let input = String::from_utf8_lossy(body); if input.trim().is_empty() { return Err(FetchError::DocumentEmpty); @@ -271,8 +258,8 @@ fn extract_csv( let mut rows_in_part = Vec::with_capacity(100); let mut parts = Vec::new(); let mut rows_total = 0usize; - let mut source_truncated = false; - let mut emit_row = |row: Vec| -> Result<(), FetchError> { + let mut truncated_at_row = None; + let mut emit_row = |row: Vec, truncated_row: Option| -> Result<(), FetchError> { rows_total += 1; if rows_total > MAX_PARTS * 100 { return Err(FetchError::DocumentMalformed( @@ -281,50 +268,79 @@ fn extract_csv( } rows_in_part.push(row); if rows_in_part.len() == 100 { - push_csv_part(&mut parts, &mut rows_in_part, rows_total, markdown)?; + push_csv_part( + &mut parts, + &mut rows_in_part, + rows_total, + truncated_row, + markdown, + )?; } Ok(()) }; - for_each_delimited_row(&input, delimiter, &mut emit_row, &mut source_truncated)?; + for_each_delimited_row(&input, delimiter, &mut emit_row, &mut truncated_at_row)?; if !rows_in_part.is_empty() { - push_csv_part(&mut parts, &mut rows_in_part, rows_total, markdown)?; + push_csv_part( + &mut parts, + &mut rows_in_part, + rows_total, + truncated_at_row, + markdown, + )?; } if parts.is_empty() { return Err(FetchError::DocumentEmpty); } - Ok((parts, source_truncated)) + Ok(parts) } fn for_each_delimited_row( input: &str, delimiter: char, callback: &mut F, - truncated: &mut bool, + truncated_at_row: &mut Option, ) -> Result<(), FetchError> where - F: FnMut(Vec) -> Result<(), FetchError>, + F: FnMut(Vec, Option) -> Result<(), FetchError>, { let mut chars = input.chars().peekable(); let mut cell = String::new(); let mut row = Vec::new(); let mut quoted = false; let mut stored_chars = 0usize; + let mut rows_seen = 0usize; + let mut cells = 0usize; while let Some(character) = chars.next() { if character == '"' { if quoted && chars.peek() == Some(&'"') { chars.next(); - store_csv_char('"', &mut cell, &mut stored_chars, truncated); + store_csv_char( + '"', + &mut cell, + &mut stored_chars, + truncated_at_row, + rows_seen + 1, + ); } else { quoted = !quoted; } } else if character == delimiter && !quoted { row.push(std::mem::take(&mut cell)); + count_csv_cell(&mut cells)?; } else if character == '\n' && !quoted { row.push(std::mem::take(&mut cell)); - callback(std::mem::take(&mut row))?; + count_csv_cell(&mut cells)?; + rows_seen += 1; + callback(std::mem::take(&mut row), *truncated_at_row)?; } else if character == '\r' && !quoted && chars.peek() == Some(&'\n') { } else { - store_csv_char(character, &mut cell, &mut stored_chars, truncated); + store_csv_char( + character, + &mut cell, + &mut stored_chars, + truncated_at_row, + rows_seen + 1, + ); } } if quoted { @@ -334,17 +350,34 @@ where } if !cell.is_empty() || !row.is_empty() || !input.ends_with('\n') { row.push(cell); - callback(row)?; + count_csv_cell(&mut cells)?; + callback(row, *truncated_at_row)?; + } + Ok(()) +} + +fn count_csv_cell(cells: &mut usize) -> Result<(), FetchError> { + *cells += 1; + if *cells > MAX_CELL_COUNT { + return Err(FetchError::DocumentMalformed( + "CSV cell bound exceeded".to_string(), + )); } Ok(()) } -fn store_csv_char(character: char, cell: &mut String, stored: &mut usize, truncated: &mut bool) { +fn store_csv_char( + character: char, + cell: &mut String, + stored: &mut usize, + truncated_at_row: &mut Option, + row: usize, +) { if *stored < MAX_DOCUMENT_CHARS { cell.push(character); *stored += 1; } else { - *truncated = true; + truncated_at_row.get_or_insert(row); } } @@ -352,6 +385,7 @@ fn push_csv_part( parts: &mut Vec, rows: &mut Vec>, rows_total: usize, + truncated_at_row: Option, markdown: bool, ) -> Result<(), FetchError> { if parts.len() >= MAX_PARTS { @@ -384,17 +418,18 @@ fn push_csv_part( } } text.truncate(text.trim_end_matches('\n').len()); + let truncated = truncated_at_row.is_some_and(|row| rows_total >= row); parts.push(RawPart { kind: DocumentPartKind::TableBlock, title: Some(title), text, - truncated: false, + truncated, }); rows.clear(); Ok(()) } -fn extract_epub(body: &[u8]) -> Result<(Vec, bool), FetchError> { +fn extract_epub(body: &[u8]) -> Result, FetchError> { preflight_zip(body)?; let container = xml_tokens(&read_zip_entry(body, "META-INF/container.xml")?)?; let opf_path = container @@ -429,7 +464,6 @@ fn extract_epub(body: &[u8]) -> Result<(Vec, bool), FetchError> { } let base = opf_path.rsplit_once('/').map_or("", |(base, _)| base); let mut parts = Vec::with_capacity(spine.len()); - let mut source_truncated = false; for id in spine { let href = manifest .get(&id) @@ -438,7 +472,6 @@ fn extract_epub(body: &[u8]) -> Result<(Vec, bool), FetchError> { let path = resolve_archive_path(base, target)?; let tokens = xml_tokens(&read_zip_entry(body, &path)?)?; let (title, text, truncated) = extract_xhtml_text(&tokens); - source_truncated |= truncated; parts.push(RawPart { kind: DocumentPartKind::SpineItem, title: title.or(Some(id)), @@ -449,7 +482,7 @@ fn extract_epub(body: &[u8]) -> Result<(Vec, bool), FetchError> { if parts.iter().all(|part| part.text.trim().is_empty()) { return Err(FetchError::DocumentEmpty); } - Ok((parts, source_truncated)) + Ok(parts) } fn extract_xhtml_text(tokens: &[XmlToken]) -> (Option, String, bool) { @@ -525,7 +558,7 @@ fn extract_xhtml_text(tokens: &[XmlToken]) -> (Option, String, bool) { (title, text.trim().to_string(), truncated) } -fn extract_docx(body: &[u8], markdown: bool) -> Result<(Vec, bool), FetchError> { +fn extract_docx(body: &[u8], markdown: bool) -> Result, FetchError> { preflight_zip(body)?; let tokens = xml_tokens(&read_zip_entry(body, "word/document.xml")?)?; let mut parts = Vec::new(); @@ -534,11 +567,12 @@ fn extract_docx(body: &[u8], markdown: bool) -> Result<(Vec, bool), Fet let mut style = String::new(); let mut in_paragraph = false; let mut in_text = false; - let mut source_truncated = tokens.iter().any(|token| token.truncated); + let mut section_truncated = false; let mut section_title: Option = None; let mut section_text = String::new(); let mut section_chars = 0usize; for token in &tokens { + section_truncated |= token.truncated; match token.kind { TokenKind::Start if token.name == "p" => { in_paragraph = true; @@ -547,7 +581,7 @@ fn extract_docx(body: &[u8], markdown: bool) -> Result<(Vec, bool), Fet style.clear(); } TokenKind::Start | TokenKind::Empty if token.name == "pstyle" && in_paragraph => { - if let Some(value) = token.attributes.get("val") { + if let Some(value) = attribute(&token.attributes, "w:val", "val") { style = value.clone(); } } @@ -558,7 +592,7 @@ fn extract_docx(body: &[u8], markdown: bool) -> Result<(Vec, bool), Fet &mut paragraph_chars, &token.text, MAX_DOCUMENT_CHARS, - &mut source_truncated, + &mut section_truncated, ); } TokenKind::Empty if in_paragraph && token.name == "tab" => { @@ -567,7 +601,7 @@ fn extract_docx(body: &[u8], markdown: bool) -> Result<(Vec, bool), Fet &mut paragraph_chars, "\t", MAX_DOCUMENT_CHARS, - &mut source_truncated, + &mut section_truncated, ); } TokenKind::Empty if in_paragraph && token.name == "br" => { @@ -576,7 +610,7 @@ fn extract_docx(body: &[u8], markdown: bool) -> Result<(Vec, bool), Fet &mut paragraph_chars, "\n", MAX_DOCUMENT_CHARS, - &mut source_truncated, + &mut section_truncated, ); } TokenKind::End if token.name == "t" => in_text = false, @@ -589,8 +623,9 @@ fn extract_docx(body: &[u8], markdown: bool) -> Result<(Vec, bool), Fet kind: DocumentPartKind::Section, title: section_title.take(), text: std::mem::take(&mut section_text), - truncated: false, + truncated: section_truncated, }); + section_truncated = false; section_chars = 0; } section_title = Some(value.to_string()); @@ -604,7 +639,7 @@ fn extract_docx(body: &[u8], markdown: bool) -> Result<(Vec, bool), Fet &mut section_chars, &heading, MAX_DOCUMENT_CHARS, - &mut source_truncated, + &mut section_truncated, ); } else { if !section_text.is_empty() { @@ -613,7 +648,7 @@ fn extract_docx(body: &[u8], markdown: bool) -> Result<(Vec, bool), Fet &mut section_chars, "\n", MAX_DOCUMENT_CHARS, - &mut source_truncated, + &mut section_truncated, ); } append_limited( @@ -621,7 +656,7 @@ fn extract_docx(body: &[u8], markdown: bool) -> Result<(Vec, bool), Fet &mut section_chars, value, MAX_DOCUMENT_CHARS, - &mut source_truncated, + &mut section_truncated, ); } } @@ -635,7 +670,7 @@ fn extract_docx(body: &[u8], markdown: bool) -> Result<(Vec, bool), Fet kind: DocumentPartKind::Section, title: section_title, text: section_text, - truncated: false, + truncated: section_truncated, }); } if parts.is_empty() { @@ -646,7 +681,7 @@ fn extract_docx(body: &[u8], markdown: bool) -> Result<(Vec, bool), Fet "part count bound exceeded".to_string(), )); } - Ok((parts, source_truncated)) + Ok(parts) } fn heading_level(style: &str) -> Option { @@ -659,9 +694,9 @@ fn heading_level(style: &str) -> Option { (1..=6).contains(&level).then_some(level) } -fn extract_xlsx(body: &[u8], markdown: bool) -> Result<(Vec, bool), FetchError> { +fn extract_xlsx(body: &[u8], markdown: bool) -> Result, FetchError> { preflight_zip(body)?; - let mut source_truncated = check_xlsx_sheet_sizes(body)?; + check_xlsx_sheet_sizes(body)?; let mut workbook = open_workbook_auto_from_rs(Cursor::new(body.to_vec())) .map_err(|error| FetchError::DocumentMalformed(error.to_string()))?; let sheet_names = workbook.sheet_names().to_vec(); @@ -681,6 +716,7 @@ fn extract_xlsx(body: &[u8], markdown: bool) -> Result<(Vec, bool), Fet .map_err(|error| FetchError::DocumentMalformed(error.to_string()))?; let mut text = String::new(); let mut text_chars = 0usize; + let mut sheet_truncated = false; for row in range.rows() { if text_chars > 0 { append_limited( @@ -688,7 +724,7 @@ fn extract_xlsx(body: &[u8], markdown: bool) -> Result<(Vec, bool), Fet &mut text_chars, "\n", MAX_DOCUMENT_CHARS.saturating_sub(extracted_chars), - &mut source_truncated, + &mut sheet_truncated, ); } for (index, cell) in row.iter().enumerate() { @@ -699,7 +735,7 @@ fn extract_xlsx(body: &[u8], markdown: bool) -> Result<(Vec, bool), Fet &mut text_chars, separator, MAX_DOCUMENT_CHARS.saturating_sub(extracted_chars), - &mut source_truncated, + &mut sheet_truncated, ); } let value = format_cell(cell); @@ -708,7 +744,7 @@ fn extract_xlsx(body: &[u8], markdown: bool) -> Result<(Vec, bool), Fet &mut text_chars, &value, MAX_DOCUMENT_CHARS.saturating_sub(extracted_chars), - &mut source_truncated, + &mut sheet_truncated, ); } } @@ -717,13 +753,13 @@ fn extract_xlsx(body: &[u8], markdown: bool) -> Result<(Vec, bool), Fet kind: DocumentPartKind::Sheet, title: Some(sheet_name), text, - truncated: false, + truncated: sheet_truncated, }); } if parts.iter().all(|part| part.text.trim().is_empty()) { return Err(FetchError::DocumentEmpty); } - Ok((parts, source_truncated)) + Ok(parts) } fn format_cell(cell: &Data) -> String { @@ -738,9 +774,8 @@ fn format_cell(cell: &Data) -> String { value.replace(['\r', '\n'], " ") } -fn check_xlsx_sheet_sizes(body: &[u8]) -> Result { +fn check_xlsx_sheet_sizes(body: &[u8]) -> Result<(), FetchError> { let mut archive = ZipArchive::new(Cursor::new(body)).map_err(map_zip_error)?; - let mut source_truncated = false; let mut sheet_paths = Vec::new(); for index in 0..archive.len() { let entry = archive.by_index(index).map_err(map_zip_error)?; @@ -749,56 +784,67 @@ fn check_xlsx_sheet_sizes(body: &[u8]) -> Result { sheet_paths.push(name); } } + let mut cells = 0usize; for path in sheet_paths { - let tokens = xml_tokens(&read_zip_entry(body, &path)?)?; - source_truncated |= tokens.iter().any(|token| token.truncated); - let mut cells = 0usize; - let mut max_row = 0usize; + let sheet = read_zip_entry(body, &path)?; + let xml = std::str::from_utf8(&sheet) + .map_err(|error| FetchError::DocumentMalformed(error.to_string()))?; + let mut reader = quick_xml::Reader::from_str(xml); + reader.config_mut().trim_text(false); + let mut min_column = usize::MAX; let mut max_column = 0usize; - for token in &tokens { - if token.name == "dimension" { - if let Some(reference) = token.attributes.get("ref") { - if cell_range_area(reference).is_some_and(|area| area > MAX_CELL_COUNT) { - return Err(FetchError::DocumentMalformed( - "spreadsheet cell bound exceeded".to_string(), - )); + let mut min_row = usize::MAX; + let mut max_row = 0usize; + loop { + let event = reader + .read_event() + .map_err(|error| FetchError::DocumentMalformed(error.to_string()))?; + match event { + Event::Start(element) | Event::Empty(element) => { + if element.local_name().as_ref() != b"c" { + continue; } - } - } - if token.name == "c" && matches!(token.kind, TokenKind::Start | TokenKind::Empty) { - cells += 1; - if cells > MAX_CELL_COUNT { - return Err(FetchError::DocumentMalformed( - "spreadsheet cell bound exceeded".to_string(), - )); - } - if let Some(reference) = token.attributes.get("r") { - if let Some((column, row)) = cell_position(reference) { - max_column = max_column.max(column); - max_row = max_row.max(row); - if max_column.saturating_mul(max_row) > MAX_CELL_COUNT { + cells += 1; + if cells > MAX_CELL_COUNT { + return Err(cell_bound_exceeded()); + } + for attribute in element.attributes().with_checks(false) { + let attribute = attribute + .map_err(|error| FetchError::DocumentMalformed(error.to_string()))?; + if attribute.key.local_name().as_ref() != b"r" { + continue; + } + let reference = attribute + .normalized_value(quick_xml::XmlVersion::Implicit1_0) + .map_err(|error| FetchError::DocumentMalformed(error.to_string()))?; + if reference.chars().count() > 4096 { return Err(FetchError::DocumentMalformed( - "spreadsheet cell bound exceeded".to_string(), + "XML attribute bound exceeded".to_string(), )); } + if let Some((column, row)) = cell_position(&reference) { + min_column = min_column.min(column); + max_column = max_column.max(column); + min_row = min_row.min(row); + max_row = max_row.max(row); + let columns = max_column.saturating_sub(min_column).saturating_add(1); + let rows = max_row.saturating_sub(min_row).saturating_add(1); + if columns.saturating_mul(rows) > MAX_CELL_COUNT { + return Err(cell_bound_exceeded()); + } + } } } + Event::Eof => break, + _ => {} } } } - Ok(source_truncated) + Ok(()) } -fn cell_range_area(reference: &str) -> Option { - let mut endpoints = reference.split(':'); - let first = cell_position(endpoints.next()?)?; - let last = cell_position(endpoints.next().unwrap_or(reference))?; - Some( - last.0 - .saturating_sub(first.0) - .saturating_add(1) - .saturating_mul(last.1.saturating_sub(first.1).saturating_add(1)), - ) +fn cell_bound_exceeded() -> FetchError { + FetchError::DocumentMalformed("spreadsheet cell bound exceeded".to_string()) } fn cell_position(reference: &str) -> Option<(usize, usize)> { @@ -825,14 +871,14 @@ fn cell_position(reference: &str) -> Option<(usize, usize)> { (column > 0 && row > 0).then_some((column, row)) } -fn extract_pptx(body: &[u8]) -> Result<(Vec, bool), FetchError> { +fn extract_pptx(body: &[u8]) -> Result, FetchError> { preflight_zip(body)?; let presentation = xml_tokens(&read_zip_entry(body, "ppt/presentation.xml")?)?; let relationships = xml_tokens(&read_zip_entry(body, "ppt/_rels/presentation.xml.rels")?)?; let mut ordered_ids = Vec::new(); for token in &presentation { if token.name == "sldid" && matches!(token.kind, TokenKind::Start | TokenKind::Empty) { - if let Some(id) = token.attributes.get("id") { + if let Some(id) = token.attributes.get("r:id") { ordered_ids.push(id.clone()); } } @@ -864,7 +910,6 @@ fn extract_pptx(body: &[u8]) -> Result<(Vec, bool), FetchError> { } } let mut parts = Vec::with_capacity(ordered_ids.len()); - let mut source_truncated = false; for id in ordered_ids { let target = targets.get(&id).ok_or_else(|| { FetchError::DocumentMalformed("PPTX slide relationship missing".to_string()) @@ -872,7 +917,6 @@ fn extract_pptx(body: &[u8]) -> Result<(Vec, bool), FetchError> { let path = resolve_archive_path("ppt", target)?; let tokens = xml_tokens(&read_zip_entry(body, &path)?)?; let (title, text, truncated) = extract_slide_text(&tokens); - source_truncated |= truncated; parts.push(RawPart { kind: DocumentPartKind::Slide, title, @@ -883,7 +927,7 @@ fn extract_pptx(body: &[u8]) -> Result<(Vec, bool), FetchError> { if parts.iter().all(|part| part.text.trim().is_empty()) { return Err(FetchError::DocumentEmpty); } - Ok((parts, source_truncated)) + Ok(parts) } fn extract_slide_text(tokens: &[XmlToken]) -> (Option, String, bool) { @@ -1140,7 +1184,7 @@ fn xml_tokens(bytes: &[u8]) -> Result, FetchError> { .map_err(|error| FetchError::DocumentMalformed(error.to_string()))?; let mut reader = quick_xml::Reader::from_str(xml); reader.config_mut().trim_text(false); - let mut tokens = Vec::new(); + let mut tokens: Vec = Vec::new(); let mut depth = 0usize; let mut total_text = 0usize; let mut truncated = false; @@ -1153,32 +1197,32 @@ fn xml_tokens(bytes: &[u8]) -> Result, FetchError> { "XML depth bound exceeded".to_string(), )); } - XmlToken { + Some(XmlToken { kind: TokenKind::Start, name: local_name(event.local_name().as_ref()), attributes: parse_attributes(&event)?, text: String::new(), truncated: false, - } + }) } - Ok(Event::Empty(event)) => XmlToken { + Ok(Event::Empty(event)) => Some(XmlToken { kind: TokenKind::Empty, name: local_name(event.local_name().as_ref()), attributes: parse_attributes(&event)?, text: String::new(), truncated: false, - }, + }), Ok(Event::End(event)) => { depth = depth.checked_sub(1).ok_or_else(|| { FetchError::DocumentMalformed("unbalanced XML end tag".to_string()) })?; - XmlToken { + Some(XmlToken { kind: TokenKind::End, name: local_name(event.local_name().as_ref()), attributes: HashMap::new(), text: String::new(), truncated: false, - } + }) } Ok(Event::Text(event)) => { let decoded = event @@ -1186,48 +1230,41 @@ fn xml_tokens(bytes: &[u8]) -> Result, FetchError> { .map_err(|error| FetchError::DocumentMalformed(error.to_string()))?; let value = quick_xml::escape::unescape(&decoded) .map_err(|error| FetchError::DocumentMalformed(error.to_string()))?; - let remaining = MAX_DOCUMENT_CHARS.saturating_sub(total_text); - let text: String = value.chars().take(remaining).collect(); - total_text += text.chars().count(); - truncated |= text.chars().count() < value.chars().count(); - XmlToken { - kind: TokenKind::Text, - name: String::new(), - attributes: HashMap::new(), - text, - truncated: false, - } + text_token(&mut tokens, &value, &mut total_text, &mut truncated) } Ok(Event::CData(event)) => { let value = event .decode() .map_err(|error| FetchError::DocumentMalformed(error.to_string()))?; - let remaining = MAX_DOCUMENT_CHARS.saturating_sub(total_text); - let text: String = value.chars().take(remaining).collect(); - total_text += text.chars().count(); - truncated |= text.chars().count() < value.chars().count(); - XmlToken { - kind: TokenKind::Text, - name: String::new(), - attributes: HashMap::new(), - text, - truncated: false, + text_token(&mut tokens, &value, &mut total_text, &mut truncated) + } + Ok(Event::DocType(event)) => { + let body = event + .decode() + .map_err(|error| FetchError::DocumentMalformed(error.to_string()))?; + let upper = body.to_ascii_uppercase(); + if body.contains('[') || upper.contains("SYSTEM") || upper.contains("PUBLIC") { + return Err(FetchError::DocumentMalformed( + "DTD is not supported".to_string(), + )); } + None } - Ok(Event::DocType(_)) => { - return Err(FetchError::DocumentMalformed( - "DTD is not supported".to_string(), - )); + Ok(Event::GeneralRef(event)) => { + let value = decode_general_ref(&event)?; + text_token(&mut tokens, &value, &mut total_text, &mut truncated) } Ok(Event::Eof) => break, - Ok(_) => continue, + Ok(_) => None, Err(error) => return Err(FetchError::DocumentMalformed(error.to_string())), }; - tokens.push(token); - if tokens.len() > MAX_XML_TOKENS { - return Err(FetchError::DocumentMalformed( - "XML token bound exceeded".to_string(), - )); + if let Some(token) = token { + tokens.push(token); + if tokens.len() > MAX_XML_TOKENS { + return Err(FetchError::DocumentMalformed( + "XML token bound exceeded".to_string(), + )); + } } } if depth != 0 { @@ -1247,6 +1284,33 @@ fn xml_tokens(bytes: &[u8]) -> Result, FetchError> { Ok(tokens) } +fn text_token( + tokens: &mut [XmlToken], + value: &str, + total_text: &mut usize, + truncated: &mut bool, +) -> Option { + let remaining = MAX_DOCUMENT_CHARS.saturating_sub(*total_text); + let text: String = value.chars().take(remaining).collect(); + let cut = text.chars().count() < value.chars().count(); + *total_text += text.chars().count(); + *truncated |= cut; + if let Some(previous) = tokens.last_mut() { + if previous.kind == TokenKind::Text { + previous.text.push_str(&text); + previous.truncated |= cut; + return None; + } + } + Some(XmlToken { + kind: TokenKind::Text, + name: String::new(), + attributes: HashMap::new(), + text, + truncated: cut, + }) +} + fn parse_attributes( event: &quick_xml::events::BytesStart<'_>, ) -> Result, FetchError> { @@ -1254,7 +1318,7 @@ fn parse_attributes( for attribute in event.attributes().with_checks(false) { let attribute = attribute.map_err(|error| FetchError::DocumentMalformed(error.to_string()))?; - let name = local_name(attribute.key.local_name().as_ref()); + let name = String::from_utf8_lossy(attribute.key.as_ref()).to_ascii_lowercase(); let value = attribute .normalized_value(quick_xml::XmlVersion::Implicit1_0) .map_err(|error| FetchError::DocumentMalformed(error.to_string()))?; @@ -1272,6 +1336,36 @@ fn local_name(value: &[u8]) -> String { String::from_utf8_lossy(value).to_ascii_lowercase() } +fn attribute<'a>( + attributes: &'a HashMap, + qualified: &str, + local: &str, +) -> Option<&'a String> { + attributes.get(qualified).or_else(|| attributes.get(local)) +} + +fn decode_general_ref(event: &quick_xml::events::BytesRef<'_>) -> Result { + let name = event + .decode() + .map_err(|error| FetchError::DocumentMalformed(error.to_string()))?; + let decoded = match &*name { + "amp" => Some('&'), + "lt" => Some('<'), + "gt" => Some('>'), + "apos" => Some('\''), + "quot" => Some('"'), + _ => None, + }; + if let Some(character) = decoded { + return Ok(character.to_string()); + } + match event.resolve_char_ref() { + Ok(Some(character)) => Ok(character.to_string()), + Ok(None) => Ok(format!("&{name};")), + Err(error) => Err(FetchError::DocumentMalformed(error.to_string())), + } +} + fn append_spaced( target: &mut String, target_chars: &mut usize, diff --git a/src/fetch/documents/tests.rs b/src/fetch/documents/tests.rs index ba0c1557..472a828b 100644 --- a/src/fetch/documents/tests.rs +++ b/src/fetch/documents/tests.rs @@ -291,3 +291,305 @@ fn xml_rejects_dtds_and_part_text_budget_marks_truncation() { assert!(!window.document_truncated); assert!(window.text_truncated); } + +fn stored_archive(entries: &[(&str, &str)]) -> Vec { + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + for (name, text) in entries { + writer + .start_file( + *name, + SimpleFileOptions::default().compression_method(CompressionMethod::Stored), + ) + .unwrap(); + writer.write_all(text.as_bytes()).unwrap(); + } + writer.finish().unwrap().into_inner() +} + +fn xlsx_with_sheets(sheets: &[(String, String)]) -> Vec { + let mut entries: Vec<(String, String)> = vec![ + ( + "[Content_Types].xml".to_string(), + r#""#.to_string(), + ), + ( + "_rels/.rels".to_string(), + r#""#.to_string(), + ), + ]; + let sheet_entries: Vec<(String, String)> = sheets + .iter() + .enumerate() + .map(|(index, (_, xml))| (format!("xl/worksheets/sheet{}.xml", index + 1), xml.clone())) + .collect(); + let workbook_sheets: String = sheets + .iter() + .enumerate() + .map(|(index, (name, _))| { + format!( + r#""#, + index + 1, + index + 2 + ) + }) + .collect(); + entries.push(( + "xl/workbook.xml".to_string(), + format!( + r#"{workbook_sheets}"# + ), + )); + let relationships: String = sheets + .iter() + .enumerate() + .map(|(index, _)| { + format!( + r#""#, + index + 2, + index + 1 + ) + }) + .collect(); + entries.push(( + "xl/_rels/workbook.xml.rels".to_string(), + format!( + r#"{relationships}"# + ), + )); + entries.extend(sheet_entries); + let refs: Vec<(&str, &str)> = entries + .iter() + .map(|(name, text)| (name.as_str(), text.as_str())) + .collect(); + stored_archive(&refs) +} + +fn sheet_xml(body: &str) -> String { + format!( + r#"{body}"# + ) +} + +fn pptx_with_slide_attributes(attributes: &str) -> Vec { + let presentation = format!( + r#""# + ); + archive(&[ + ("ppt/presentation.xml", presentation.as_str()), + ( + "ppt/_rels/presentation.xml.rels", + r#""#, + ), + ( + "ppt/slides/slide2.xml", + r#"Slide Two"#, + ), + ]) +} + +fn xlsx_error(body: &[u8]) -> FetchError { + extract_document( + body, + DocumentFormat::Xlsx, + "https://example.test/book.xlsx", + None, + false, + MAX_DOCUMENT_CHARS, + MAX_DOCUMENT_CHARS, + ) + .unwrap_err() +} + +fn assert_bound(error: FetchError, expected: &str) { + match error { + FetchError::DocumentMalformed(message) => { + assert!(message.contains(expected), "unexpected message: {message}"); + } + other => panic!("expected a malformed document, got {other:?}"), + } +} + +#[test] +fn xml_references_resolve_into_the_surrounding_text_run() { + let body = archive(&[( + "word/document.xml", + r#"Q&A <tag> café é "x" 'y'"#, + )]); + let result = extract(&body, DocumentFormat::Docx); + assert_eq!(result.parts.len(), 1); + assert_eq!( + result.parts[0].text, + "Q&A caf\u{e9} \u{e9} cdata \"x\" 'y'" + ); + + let epub = archive(&[ + ("mimetype", "application/epub+zip"), + ( + "META-INF/container.xml", + r#""#, + ), + ( + "OPS/book.opf", + r#""#, + ), + ( + "OPS/one.xhtml", + r#"

a b

"#, + ), + ]); + let text = extract(&epub, DocumentFormat::Epub); + assert_eq!(text.parts[0].text, "a b"); +} + +#[test] +fn xml_accepts_plain_doctypes_and_still_refuses_dtd_payloads() { + let tokens = xml_tokens(br#"

text

"#) + .expect("a doctype without an internal subset or external identifier is accepted"); + assert!(tokens.iter().any(|token| token.name == "p")); + assert!(xml_tokens(br#"]>&x;"#).is_err()); + assert!(xml_tokens(br#""#).is_err()); + assert!(xml_tokens(br#""#).is_err()); + assert!(xml_tokens(br#""#).is_err()); + assert!(xml_tokens(br#""#).is_err()); + + let epub = archive(&[ + ("mimetype", "application/epub+zip"), + ( + "META-INF/container.xml", + r#""#, + ), + ( + "OPS/book.opf", + r#""#, + ), + ( + "OPS/one.xhtml", + r#"

Doctype body

"#, + ), + ]); + assert_eq!( + extract(&epub, DocumentFormat::Epub).parts[0].text, + "Doctype body" + ); +} + +#[test] +fn pptx_relationship_ids_are_independent_of_attribute_order() { + let declared_first = extract( + &pptx_with_slide_attributes(r#"id="2" r:id="rId2""#), + DocumentFormat::Pptx, + ); + let qualified_first = extract( + &pptx_with_slide_attributes(r#"r:id="rId2" id="2""#), + DocumentFormat::Pptx, + ); + assert_eq!(declared_first.parts[0].text, "Slide Two"); + assert_eq!(qualified_first.parts[0].text, "Slide Two"); + assert_eq!( + declared_first.parts[0].title.as_deref(), + qualified_first.parts[0].title.as_deref() + ); + assert!(!declared_first.parts[0].truncated); + assert!(!qualified_first.parts[0].truncated); +} + +#[test] +fn xlsx_declared_dimension_does_not_bound_observed_cells() { + let body = xlsx_with_sheets(&[( + "Only".to_string(), + sheet_xml( + r#"Only data"#, + ), + )]); + let result = extract(&body, DocumentFormat::Xlsx); + assert_eq!(result.parts.len(), 1); + assert_eq!(result.parts[0].text.trim(), "Only data"); +} + +#[test] +fn xlsx_many_rows_reach_the_cell_bound_not_the_token_bound() { + let mut data = String::from(""); + for row in 1..=45_000usize { + data.push_str(&format!( + r#"1"# + )); + } + data.push_str(""); + let body = xlsx_with_sheets(&[("Rows".to_string(), sheet_xml(&data))]); + let result = extract(&body, DocumentFormat::Xlsx); + assert_eq!(result.parts.len(), 1); + assert!(result.parts[0].text.starts_with('1')); + assert!(result.parts[0].chars > 40_000); +} + +#[test] +fn xlsx_cell_count_and_bounding_area_are_bounded_on_observed_cells() { + let mut over_cap = String::from(""); + for row in 1..=200_001usize { + over_cap.push_str(&format!(r#""#)); + } + over_cap.push_str(""); + assert_bound( + xlsx_error(&xlsx_with_sheets(&[( + "Over".to_string(), + sheet_xml(&over_cap), + )])), + "spreadsheet cell bound exceeded", + ); + + let sparse = + sheet_xml(r#""#); + assert_bound( + xlsx_error(&xlsx_with_sheets(&[("Sparse".to_string(), sparse)])), + "spreadsheet cell bound exceeded", + ); +} + +#[test] +fn csv_cell_bound_refuses_during_the_scan() { + let body = ",".repeat(300_000); + let error = extract_document( + body.as_bytes(), + DocumentFormat::Csv, + "https://example.test/data.csv", + Some("text/csv"), + false, + MAX_DOCUMENT_CHARS, + MAX_DOCUMENT_CHARS, + ) + .unwrap_err(); + assert_bound(error, "CSV cell bound exceeded"); +} + +#[test] +fn truncation_is_attributed_to_the_part_that_was_cut() { + let heading = "h".repeat(5_000); + let first = format!(r#"

{heading}

First text

"#); + let body = archive(&[ + ("mimetype", "application/epub+zip"), + ( + "META-INF/container.xml", + r#""#, + ), + ( + "OPS/book.opf", + r#""#, + ), + ("OPS/one.xhtml", first.as_str()), + ( + "OPS/two.xhtml", + r#"

Middle text

"#, + ), + ( + "OPS/three.xhtml", + r#"

Last text

"#, + ), + ]); + let result = extract(&body, DocumentFormat::Epub); + assert_eq!(result.parts.len(), 3); + assert!(result.parts[0].truncated); + assert!(!result.parts[1].truncated); + assert!(!result.parts[2].truncated); + assert!(result.document_truncated); + assert!(result.parts[1].text.contains("Middle text")); +} diff --git a/src/mcp/tools/web_fetch_options.rs b/src/mcp/tools/web_fetch_options.rs index 428f9749..bbdade1b 100644 --- a/src/mcp/tools/web_fetch_options.rs +++ b/src/mcp/tools/web_fetch_options.rs @@ -74,6 +74,13 @@ pub(crate) fn fetch_tool_error(error: crate::fetch::FetchError) -> ToolError { "; DOCX/XLSX extraction is not compiled into this build; rebuild with --features documents (see docs/features.md)", ); } + if code == "document_unsupported" { + return ToolError::execution_with_data( + ToolErrorCode::CapabilityUnavailable, + message, + serde_json::json!({"code": code}), + ); + } if code.starts_with("proxy_") { return ToolError::execution_with_data( ToolErrorCode::UpstreamFailed, diff --git a/tests/documents.rs b/tests/documents.rs index a66c3a32..611b08fa 100644 --- a/tests/documents.rs +++ b/tests/documents.rs @@ -337,3 +337,82 @@ async fn malformed_container_is_distinguishable() { .expect_err("a malformed container is refused"); assert!(error_text(&error).contains("document_malformed")); } + +#[cfg(feature = "documents")] +#[tokio::test] +async fn docx_character_references_survive_the_tool_boundary() { + let server = MockServer::start(); + let body = archive(&[( + "word/document.xml", + r#"Q&A <tag> café"#, + )]); + server.mock(|when, then| { + when.method(GET).path("/references.docx"); + then.status(200) + .header("content-type", DOCX_CONTENT_TYPE) + .body(body.as_slice()); + }); + let response = fetch(server.url("/references.docx")).await; + assert_eq!(response["document"]["format"], "docx"); + let text = response["document"]["parts"][0]["text"].as_str().unwrap(); + assert!(text.contains("Q&A caf\u{e9}")); +} + +#[cfg(feature = "documents")] +#[tokio::test] +async fn epub_documents_with_a_plain_doctype_extract() { + let server = MockServer::start(); + let body = archive(&[ + ("mimetype", "application/epub+zip"), + ( + "META-INF/container.xml", + r#""#, + ), + ( + "OPS/book.opf", + r#""#, + ), + ( + "OPS/one.xhtml", + r#"

Chapter

Doctype body

"#, + ), + ]); + server.mock(|when, then| { + when.method(GET).path("/doctype.epub"); + then.status(200) + .header("content-type", EPUB_CONTENT_TYPE) + .body(body.as_slice()); + }); + let response = fetch(server.url("/doctype.epub")).await; + assert_eq!(response["document"]["format"], "epub"); + assert_eq!(response["document"]["parts_total"], 1); + assert!(response["document"]["parts"][0]["text"] + .as_str() + .unwrap() + .contains("Doctype body")); +} + +#[cfg(feature = "documents")] +#[tokio::test] +async fn delimiter_dense_csv_is_refused_at_the_cell_bound() { + let server = MockServer::start(); + let body = ",".repeat(300_000); + server.mock(|when, then| { + when.method(GET).path("/dense.csv"); + then.status(200) + .header("content-type", "text/csv") + .body(body.as_str()); + }); + let error = run_web_fetch( + state(), + WebFetchArgs { + url: server.url("/dense.csv"), + ..Default::default() + }, + ) + .await + .expect_err("a delimiter-dense body is refused at the cell bound"); + let payload = error_text(&error); + assert!(payload.contains("document_malformed")); + assert!(payload.contains("CSV cell bound exceeded")); +} diff --git a/tests/mcp_tools.rs b/tests/mcp_tools.rs index 9de4d777..cc3bf24a 100644 --- a/tests/mcp_tools.rs +++ b/tests/mcp_tools.rs @@ -1424,3 +1424,72 @@ mod document_budget { ); } } + +#[cfg(feature = "documents")] +mod document_error_mapping { + use super::*; + use httpmock::prelude::*; + + fn state() -> Arc { + let mut config = AppConfig::default(); + config.fetch.allow_localhost = true; + config.fetch.allow_private_network = true; + Arc::new(ServerState::build(config).expect("state builds")) + } + + fn fetch_args(url: String) -> WebFetchArgs { + WebFetchArgs { + url, + ..Default::default() + } + } + + #[tokio::test] + async fn document_unsupported_container_is_capability_unavailable() { + let server = MockServer::start(); + server.mock(|when, then| { + when.method(GET).path("/legacy.odt"); + then.status(200) + .header("content-type", "application/vnd.oasis.opendocument.text") + .body("legacy body"); + }); + let error = run_web_fetch(state(), fetch_args(server.url("/legacy.odt"))) + .await + .expect_err("unsupported document format is a capability miss"); + assert_eq!( + error.code(), + eggsearch::mcp::tools::ToolErrorCode::CapabilityUnavailable + ); + assert_eq!( + error.error_payload()["data"]["code"], + "document_unsupported" + ); + } + + #[tokio::test] + async fn malformed_container_remains_upstream_failed() { + let server = MockServer::start(); + server.mock(|when, then| { + when.method(GET).path("/broken.docx"); + then.status(200) + .header( + "content-type", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ) + .body(b"PK\x03\x04not-a-real-archive".as_slice()); + }); + let error = run_web_fetch(state(), fetch_args(server.url("/broken.docx"))) + .await + .expect_err("malformed document container is an upstream failure"); + assert_eq!( + error.code(), + eggsearch::mcp::tools::ToolErrorCode::UpstreamFailed + ); + let payload = error.error_payload(); + let message = payload["message"].as_str().expect("message is a string"); + assert!( + message.contains("document_malformed"), + "message names the fetch code: {message}" + ); + } +} diff --git a/tests/static_guards.rs b/tests/static_guards.rs index c761d16d..c1a67ee4 100644 --- a/tests/static_guards.rs +++ b/tests/static_guards.rs @@ -1915,7 +1915,7 @@ fn default_features_ship_pdf_and_browser() { .lines() .find(|line| line.trim_start().starts_with("default =")) .expect("Cargo.toml must declare a default feature set"); - for required in ["pdf", "browser"] { + for required in ["pdf", "browser", "documents"] { assert!( default_line.contains(&format!("\"{required}\"")), "the default feature set must ship `{required}`: {default_line}" @@ -1937,6 +1937,15 @@ fn default_features_ship_pdf_and_browser() { "browser rendering must default on exactly where the feature is compiled" ); + let documents_default = config + .split_once("fn default_documents_enabled() -> bool {") + .map(|(_, rest)| rest.chars().take(120).collect::()) + .expect("config must declare default_documents_enabled"); + assert!( + documents_default.contains("cfg!(feature = \"documents\")"), + "container documents must default on exactly where the feature is compiled" + ); + let release = fs::read_to_string(format!("{manifest}/.github/workflows/release-eggpack.yml")) .expect("generated release workflow readable"); for line in release.lines() {