Skip to content

fix(search): decode recipe files lossily instead of failing on invalid UTF-8 - #513

Merged
dubadub merged 3 commits into
mainfrom
fix/search-invalid-utf8
Sep 17, 2026
Merged

dubadub merged 3 commits into
mainfrom
fix/search-invalid-utf8

Conversation

@dubadub

@dubadub dubadub commented Sep 17, 2026 •

Copy link
Copy Markdown
Member

Fixes #498.

What was happening

$ cook search tuna
Error: Failed to read '/data/recipes'

Caused by:
    stream did not contain valid UTF-8

One recipe in the collection was not valid UTF-8 — a file saved from a Latin-1 editor, a stray byte from a bad paste — and it failed the whole search, taking every other recipe's results with it.

Only some queries failed, which is what made it puzzling: content scoring of the bad file silently fails, so it only entered the result set when the filename matched — cook search tuna against Tuna Mornay.cook. Searching for an ingredient in no recipe returned nothing, as reported.

Two independent readers were rejecting the file, in two crates.

This repo: a bad byte in the body

matches_every_term read every candidate with read_to_string for the AND filter. Now it reads the bytes and decodes them with String::from_utf8_lossy: a mis-encoded accent costs one wrong character in the haystack rather than the recipe, and only the bad bytes themselves stop matching — a term either side of one still does.

A file that cannot be read at all is still an error, pinned by an_unreadable_file_is_still_an_io_error. Lossy decoding is for bytes that are there and malformed, not for bytes that never arrived; treating an unreadable recipe as an empty one would turn a fixable problem into results that are quietly wrong.

cooklang-find 0.7.1: a bad byte in the front matter

RecipeEntry::from_path reads front matter through BufRead::lines, and search propagated the InvalidData rather than skipping the file the way build_tree in the same crate already does. That is the arm that reports the search root instead of the file, which is why the error named /data/recipes.

Fixed in cooklang/cooklang-find#13, released as 0.7.1. It also makes the content scorer lossy, so such a recipe becomes findable by an ingredient in its body rather than only by its file name.

Lockfile-only change here — the "0.7.0" requirement is a caret range that already admitted 0.7.1.

Verification

Against a real ISO-8859 recipe:

$ file 'Tuna Mornay.cook'
Tuna Mornay.cook: ISO-8859 text

$ cook search tuna          # was: Error: Failed to read '<root>'
"Tuna Mornay.cook"
$ cook search cheese        # ingredient after the bad byte
"Tuna Mornay.cook"
$ cook search "tuna cheese" # AND query
"Tuna Mornay.cook"
$ cook search flour         # rest of the collection unaffected
"pancakes.cook"

cook doctor validate still reports the file as an error, which is the right division of labour: search finds the recipe, doctor tells you the encoding is wrong.

Both regression tests fail without their fix and pass with it. The search test asserts a content-only term matches, so it cannot pass on a file-name match alone. cargo fmt, cargo clippy --all-targets -- -D warnings and cargo test are clean (22 test binaries, 0 failures).

Not covered

cooklang-reports pulls its own cooklang-find 0.6.1, which still has the upstream bug, so cook report could hit it on the same file. Out of scope here — it needs a cooklang-reports release.

…d UTF-8

`cook search tuna` died with

    Error: Failed to read '/data/recipes'
    Caused by:
        stream did not contain valid UTF-8

over a single recipe that was not valid UTF-8 — a file saved from a
Latin-1 editor, a stray byte from a bad paste — and took every other
recipe's results down with it. Only some queries failed, which is what
made it puzzling: the file had to score before anything read it.

`matches_every_term` read candidates with `read_to_string`, so one bad
byte anywhere in a matched recipe's body failed the whole search. Read
the bytes and decode them with `String::from_utf8_lossy` instead: a
mis-encoded accent now costs one wrong character in the haystack rather
than the recipe, and only the bad bytes themselves stop matching.

A file that cannot be read at all is still an error, and pinned by a
test. Lossy decoding is for bytes that are there and malformed, not for
bytes that never arrived; treating an unreadable recipe as an empty one
would turn a fixable problem into results that are quietly wrong.

Refs #498. The other half of that report — a bad byte in the *front
matter* — fails inside `cooklang-find`, which propagates it out of
`search` instead of skipping the file the way `build_tree` does. Fixed
in cooklang/cooklang-find#13 and picked up by a 0.7.1 bump.
@claude

claude Bot commented Sep 17, 2026

Copy link
Copy Markdown

Review: fix(search): decode recipe files lossily instead of failing on invalid UTF-8

Nicely scoped fix — one function changed, the change is exactly as wide as the bug, and the accompanying doc comments/tests make the "why" traceable back to #498. A few notes:

Correctness

  • The core fix is right: std::fs::read + String::from_utf8_lossy replaces the failure mode precisely where it was introduced (matches_every_term's read_to_string), while the genuine I/O error path (gone.cook) is left untouched and still surfaces as CoreError::Io. The distinction between "bytes that are malformed" vs. "bytes that never arrived" is exactly the right line to draw, and an_unreadable_file_is_still_an_io_error pins it well.
  • One behavioral side effect worth being aware of (not necessarily blocking): a .cook file that's actually binary garbage (wrong extension, corrupted file, etc.) will now silently be treated as searchable content full of U+FFFD instead of erroring loudly. Previously that surfaced as a clear "not valid UTF-8" failure a user could act on; now it's swallowed. Given the fix's actual target (a mostly-valid file with a stray non-UTF-8 byte, e.g. Latin-1), this tradeoff seems reasonable, but it's a slight widening of what counts as "not an error" beyond the motivating case.

Performance

  • No regression: both the old and new code read the full file into memory once per candidate for the AND filter. from_utf8_lossy borrows (no copy) when the input is already valid UTF-8, which is the common case, so there's no extra allocation there — the subsequent .to_lowercase() allocates either way, same as before.

Test coverage

  • Strong. a_recipe_that_is_not_valid_utf8_is_still_searchable reproduces the actual reported symptom (one bad file previously failing every query, not just ones touching it), and text_around_an_invalid_byte_still_matches isolates matches_every_term directly to verify that only the bad bytes themselves stop matching, both sides of them still do. an_unreadable_file_is_still_an_io_error guards the important non-regression (a missing file must still error, not silently become an empty match). Good discipline in the PR description noting these tests fail without the fix.

Security

  • No concerns. This only affects local file search over a bounded set of file types the walk already discovered; lossy decoding of untrusted bytes here can't cause anything worse than odd search results.

Minor/style

  • Doc comments are thorough to the point of being close to prose-in-code (the module doc, search's doc, and matches_every_term's doc each explain overlapping pieces of the same fix). Not a real problem, just a note that a future reader has three places to reconcile if this logic changes again — could consider trimming once the upstream cooklang-find half lands and this stops being "new."
  • The PR is explicitly presented as one half of a two-repo fix (upstream cooklang-find PR pending for the front-matter case). That's clearly communicated in the description, so nothing to flag beyond confirming the follow-up (cargo update -p cooklang-find) doesn't get lost once 0.7.1 ships.

Overall: solid, well-tested, appropriately narrow fix. No blocking issues from me.

…atter

Completes the fix for #498. The previous commit handled a bad byte in a
recipe's body, which this crate read; a bad byte in the *front matter*
failed inside `cooklang-find`, which propagated it out of its own walk
instead of skipping the file the way `build_tree` does. That is the arm
that named the search root rather than the file, and it is why the
report read "Failed to read '/data/recipes'".

0.7.1 (cooklang/cooklang-find#13) decodes those files lossily too, and
scores their contents rather than silently giving them zero — so such a
recipe is findable by an ingredient in its body, not only by its file
name. Lockfile only: the `0.7.0` requirement is a caret range that
already admitted it.

The regression test now covers both halves, and asserts a content-only
term matches, so it cannot pass on a file-name match alone.

`cooklang-reports` still pulls its own `cooklang-find` 0.6.1, which is
untouched by this.

Fixes #498
@claude

claude Bot commented Sep 17, 2026

Copy link
Copy Markdown

Review

Nicely scoped fix, I read through crates/core/src/search.rs in full (not just the diff) plus the Cargo.lock/Cargo.toml change and CoreError::Io. Summary: no blocking issues found; this is ready to merge as far as the code itself goes.

Code quality and correctness:

  • The core change (std::fs::read + String::from_utf8_lossy instead of read_to_string) is the right fix for the reported bug: from_utf8_lossy only allocates a new buffer when it actually hits invalid bytes (it returns Cow::Borrowed for already-valid UTF-8), so this isn't a performance regression relative to read_to_string, and genuine I/O failures (std::fs::read erroring) still surface as CoreError::Io -- the an_unreadable_file_is_still_an_io_error test pins that distinction well.
  • I double-checked the Cargo.lock-only bump: crates/core/Cargo.toml and the root Cargo.toml both declare cooklang-find = { version = "0.7.0", ... }, which is a caret requirement (>=0.7.0, <0.8.0), so pulling in 0.7.1 via the lockfile without touching Cargo.toml is correct and doesn't need a manifest change.
  • The doc comments are consistent with the rest of the file's (unusually thorough) documentation style, and the updated Errors section on search() correctly draws the line between "still an error" (unreadable file, bad front matter) and "no longer an error" (invalid UTF-8 bytes).

Test coverage:
Good coverage of the actual bug surface -- body-only bad byte vs. front-matter bad byte (both underlying causes), content-only match after the bad byte (proves it's not just a filename fallback), AND queries spanning a bad byte, title decoding surviving with U+FFFD, the "one bad file no longer kills unrelated queries" regression case, and the explicit non-regression check that a real I/O error (missing file) still errors.

One small gap: there's no test for a file that's entirely invalid bytes (e.g. a stray binary file with a .cook extension) rather than mostly-valid-with-one-bad-byte, though given the implementation is a straight from_utf8_lossy, I'd expect it to behave the same -- a minor completeness nit, not a real risk.

Minor nitpick (non-blocking):
search()'s doc comment links to matches_every_term, which is a private function. Since search is a public API and rustdoc is sometimes run with private_intra_doc_links warnings promoted, this could trip a doc lint in some configurations -- worth a quick check if cargo doc is ever run with -D warnings in CI, otherwise not a concern (the repo's pre-PR checklist only calls out fmt/clippy/test).

Security:
No concerns -- the change only affects how already-discovered local files are decoded for text search; no new path handling, no new trust boundary.

Scope:
Appreciate the explicit "Not covered" section calling out that cooklang-reports still pulls cooklang-find 0.6.1 and can hit the same bug via cook report -- good to flag rather than silently leave a related bug in a sibling code path.

…d file

Review notes on #513.

`search` is public and linked `[matches_every_term]`, which is not, so
rustdoc warned and rendered it as plain text anyway — plain backticks say
the same thing without the broken link. The three sibling warnings in
this crate are left alone; they are not this PR's.

And a test for the degenerate case: a file with no valid text in it at
all, rather than one bad byte among good ones.
@claude

claude Bot commented Sep 17, 2026

Copy link
Copy Markdown

Review

Solid, well-scoped fix. The distinction it draws — malformed-but-present bytes get lossy-decoded, genuinely unreadable files still error — is exactly the right one, and the PR description explains the two-crate root cause clearly.

Code quality

  • matches_every_term reads the same amount of data as before (fs::read + from_utf8_lossy costs about the same as the old read_to_string, and for valid-UTF-8 files from_utf8_lossy returns a borrowed Cow so there's no extra copy in the common case).
  • Doc comments on search() and matches_every_term are updated consistently with the new behavior, matching the file's existing convention of explaining why, not just what.
  • The Cargo.lock-only bump is correct: crates/core/Cargo.toml and the root Cargo.toml both pin cooklang-find = "0.7.0", which is a caret requirement that already admits 0.7.1, so no manifest change was needed.

Bugs / correctness

None found. an_unreadable_file_is_still_an_io_error correctly pins that a real I/O failure (e.g. NotFound) is still propagated as CoreError::Io, so the lossy-decoding change can't silently swallow a genuinely broken read.

Test coverage

Thorough — the four new tests cover: a bad byte in the body, a bad byte in the front matter (exercising the cooklang-find 0.7.1 fix too), text on both sides of the bad byte still matching an AND query, an all-invalid-bytes file matching nothing but still matching on filename, and the genuine-I/O-error case. One minor nit: a_recipe_that_is_not_valid_utf8_is_still_searchable calls run(&base, "salmon") twice (once for the path assertion, once to check hit[0].name) — could be collapsed into one call and reused, but it's a non-issue for a test.

Security

None. This only changes how bytes already read from local recipe files are decoded; no new I/O surface or injection vector.

Scope (not a blocker)

The PR description already flags cooklang-reports' pinned cooklang-find 0.6.1 as an out-of-scope gap for cook report. Worth being aware there's at least one more: recipe_content in src/server/handlers/recipes.rs (line 172) uses tokio::fs::read_to_string to serve a recipe's raw text to the web UI editor, so a recipe with the same kind of invalid byte would still 500 there even though cook search now finds it fine. Not something this PR needs to fix, but possibly worth a follow-up issue if the web UI hits the same collections.

Nice work overall — the fix, docs, and regression tests all match the standard this file already sets.

@dubadub
dubadub merged commit ae3b33e into main Sep 17, 2026
6 checks passed
@dubadub
dubadub deleted the fix/search-invalid-utf8 branch September 17, 2026 17:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Error searching for ingredients

1 participant