Skip to content

fix(shopping-list): follow recipe references all the way down - #515

Merged
dubadub merged 6 commits into
mainfrom
fix/shopping-list-deep-references
Sep 18, 2026
Merged

dubadub merged 6 commits into
mainfrom
fix/shopping-list-deep-references

Conversation

@dubadub

@dubadub dubadub commented Sep 17, 2026 •

Copy link
Copy Markdown
Member

Fixes #509.

cook shopping-list expanded recipe references two levels down and stopped. Anything deeper was left out of the list, with no warning and exit code 0 — a weekly menu referencing dinners referencing sauces referencing a prep recipe lost the prep recipe entirely.

The cause

Expansion in crates/core/src/shopping_list/mod.rs was two hand-rolled levels rather than recursion: a recipe's references were expanded, then one further loop covered "references inside the referenced recipe, one level further down". The third level was never visited.

The fix

The second hand-rolled level is gone, replaced by recursion through an Expansion struct that carries what stays the same all the way down (where to look recipes up, and what to accumulate into).

Two things bound the descent:

  • The ancestors chain added for shopping-list silently double-counts ingredients when recipes reference each other #424 refuses a reference that leads back up its own chain, so a → b → c → a is caught and warned about just as a → b → a already was.
  • MAX_REFERENCE_DEPTH = 100 catches a chain long enough to exhaust the stack without ever repeating itself. A generated 2000-deep acyclic chain aborted the process with fatal runtime error: stack overflow — that bound came free when expansion stopped three files in, and the recursion took it away. It now stops with a warning naming where the list ends.

Behaviour changes worth a look

The duplicated level had drifted from the one above it, and unifying them settles the difference in favour of the documented top-level semantics:

  • The scale reaches the bottom of the chain. A reference with no quantity of its own inherits the factor the recipe that named it was scaled by. It used to stop one recipe in, so cook shopping-list menu.cook:2 doubled the dinner but left the sauce at its authored amounts. A reference naming a target (@./dinner{6%servings}) now passes the factor it reached on down, worked out by a new target_factor that mirrors Recipe::scale_to_target — cooklang applies the factor without reporting it, so there is no way to ask.
  • A nested reference's unit means what it means one level up. The old nested branch treated any unit other than servings as a plain multiplier, so @./sauce{2%cups} two levels down silently multiplied by 2 while the same reference one level up raised a CoreError::Reference. That case is now the error, rather than a quantity that is quietly wrong.
  • A bare @recipe{} reference now resolves at the top level too. The nested level already special-cased a reference with no path components; the top level passed it to RecipeReference::path, which prepends the separator, so it was looked up as /recipe. Unifying the two carries the nested level's handling upward. A fix that falls out of the change rather than a regression, in case anyone bisects to here later.
  • Insertion order is now uniform. The old nested level added a referenced recipe's own ingredients after its children, while the top level added the starting recipe's before its children; the recursion applies the top level's order everywhere. This only affects the order of AggregatedList::items (what --plain prints) for nested recipes, never what is on the list or how much. The old "so they are not counted twice" comment was misleading — double-counting was prevented by add_recipe(..., false) skipping reference ingredients, not by the ordering.

Verification

Seven new tests in crates/core/src/shopping_list/tests.rs, each watched failing against the code it guards:

  • references_are_expanded_however_deep_the_chain_runs — the issue's exact four-file chain
  • the_request_scale_reaches_every_recipe_down_the_chain
  • a_scaled_reference_passes_the_factor_it_reached_further_down
  • a_cycle_that_closes_three_recipes_down_is_still_refused
  • a_chain_deeper_than_any_real_collection_stops_and_says_so
  • a_yield_target_passes_the_factor_it_reached_further_down — added in review; mutation-checked, a wrong yield base gives 100000 g instead of 100 g
  • a_yield_target_in_another_unit_is_a_reference_error — added in review, pinning that scale_to_yield compares units as plain strings and converts nothing, which is what makes target_factor comparing them the same way correct
  • a_servings_target_on_a_recipe_without_servings_is_a_reference_error — added in review, the servings half of what an_unscalable_reference_is_a_reference_error already pinned for yields
  • a_fractional_servings_target_rounds_the_same_way_all_the_way_down — added in review; mutation-checked, dropping the rounding gives 12.8 instead of 12

cargo test --workspace, cargo fmt --check and cargo clippy --workspace --all-targets are all clean. The issue's shell reproduction now lists paprika, and the 2000- and 10000-deep chains exit 0 with a diagnostic instead of aborting.

Expansion was two hand-rolled levels — the named recipe, what it
references, and what *those* reference — so anything deeper fell off the
list with no warning and a clean exit. A weekly menu referencing dinners
referencing sauces referencing a prep recipe lost the prep recipe
entirely.

Replace the second hand-rolled level with recursion. Nothing new bounds
it: the ancestor chain added for #424 already refuses a reference that
leads back up its own chain, so a finite collection of recipes is a
finite descent.

Two things the duplicated level had drifted on now hold at every depth:
the scale asked for reaches the bottom of the chain rather than stopping
one recipe in, and a reference naming a target ("6 servings") passes the
factor it reached on down instead of leaving what it references at its
authored amounts.

Fixes #509
@claude

claude Bot commented Sep 17, 2026

Copy link
Copy Markdown

Review

Nice fix — replacing the two hand-rolled expansion levels with real recursion through Expansion is the right shape for this problem, and the four new tests (especially the_request_scale_reaches_every_recipe_down_the_chain and a_scaled_reference_passes_the_factor_it_reached_further_down) do a good job proving the scale-inheritance math end-to-end. The doc comments are excellent and make the intent (ancestors bound the recursion, included applies one level only, etc.) easy to verify against the code.

One correctness concern and a coverage gap, both centered on the new target_factor helper (crates/core/src/shopping_list/mod.rs:721-740):

target_factor's yield branch doesn't take a Converter, but scale_to_target does — possible silent factor of 1.0

```rust
Some(unit) => {
let (value, yield_unit) = recipe.metadata.get("yield")?.as_str()?.split_once('%')?;
if yield_unit != unit {
return None;
}
value.parse::().ok()?
}
```

This does a bare string comparison between the requested unit and the recipe's declared yield unit. But the real scaling call two lines below,

```rust
ref_recipe.scale_to_target(target_value, quantity.unit(), self.converter)
```

is handed a Converter, which strongly suggests scale_to_target/scale_to_yield in cooklang-rs can convert between compatible units (e.g. a recipe with yield: 1%kg scaled via @./sauce{500%g}) rather than requiring an exact string match.

If that's right, then for a reference like @./dinner{500%g} against a recipe whose yield is declared in kg, scale_to_target would succeed (scaling correctly), but target_factor would return None ("kg" != "g"), and the code falls back to reached.unwrap_or(1.0) — so everything underneath that reference would inherit a scale factor of 1.0 instead of the real one. That's exactly the "quietly wrong quantity" failure mode this PR's own description calls out as worse than an explicit error (re: issue #424), except here it wouldn't even raise a diagnostic — it would just silently under/over-count ingredients several levels down.

I couldn't build against the vendored cooklang crate in this sandbox to confirm scale_to_yield's actual unit-conversion behavior, so this is a plausible-but-unverified concern — worth a quick check against the crate source (or an explicit test, see below) before merging. If scale_to_target really does require an exact unit string match with no conversion, this is a non-issue and the current code is fine.

No test exercises target_factor's non-servings branch at all

All the new scale-propagation tests (the_request_scale_reaches_every_recipe_down_the_chain, a_scaled_reference_passes_the_factor_it_reached_further_down) use either no quantity or a %servings quantity on the middle reference. The existing an_unscalable_reference_is_a_reference_error test only exercises the error path (no yield metadata at all).

There's no test where a recipe has yield: N%unit metadata, is referenced with a matching-unit quantity (e.g. @./sauce{500%g} against yield: 1000%g), and itself references something further down with no quantity — which is the only way to observe whether the propagated reached factor from the yield branch is actually correct. Given this is a brand-new code path with its own arithmetic (parsing value%unit out of metadata by hand), it'd be worth a dedicated test similar to a_scaled_reference_passes_the_factor_it_reached_further_down but using a yield-based target instead of servings, and ideally one more covering unit conversion (kg yield scaled via a g target) to settle the concern above either way.

Minor: recursion is now unbounded by depth, only by the cycle check

Previously expansion was hard-capped at three levels, which incidentally bounded stack usage. Now a long acyclic reference chain (not a cycle, so the ancestor check won't stop it) recurses one native stack frame per level. Given cook server parses recipes from arbitrary directories, a very deep chain (accidental or adversarial) could risk a stack overflow rather than a graceful error. Probably fine in practice for real recipe collections, but worth a thought — either an explicit depth cap with a clear diagnostic, or converting the recursion to an explicit work-list if this is ever a concern.

Nits

  • target.round() in the servings branch is commented as matching how scale_to_servings rounds — if that's based on reading the crate source rather than assumption, might be worth a one-line note on why (e.g. link/reference) since it's a subtle behavior to get right and easy to silently drift from if cooklang-rs changes its rounding.
  • Nice catch fixing the reference.components.is_empty() bare-@recipe{} case while unifying the two levels — worth calling out that this was a latent bug in the old nested-level code path (per the comment) that's now fixed for the top level too, not just carried over.

Overall this is a solid, well-tested fix for the actual reported bug (#509) and a nice simplification. The main thing I'd want resolved before merge is confirming whether scale_to_yield's unit handling matches target_factor's exact-string assumption — that's the one place a silent wrong-quantity bug could hide.

A chain of about two thousand references — long, but never repeating, so
the ancestor check has nothing to refuse — overflowed the stack and
aborted the process. That bound came free when expansion stopped three
files in; recursion took it away. Stop at a hundred levels instead, with
a warning naming where the list stops, so a pathological collection is a
diagnostic rather than a crash.

Also test `target_factor`'s yield branch, which nothing reached: one case
for the factor it passes down, and one pinning that a target in another
unit is an error. `scale_to_yield` compares the yield's unit to the
target's as plain strings and converts nothing — the `Converter` it takes
only refits quantities once the factor is known — so `target_factor`
comparing them the same way is right. If that ever changes, the second
test fails before the propagated factor can go quietly wrong.
@dubadub

dubadub commented Sep 17, 2026

Copy link
Copy Markdown
Member Author

Thanks — all three points were worth raising. Two led to changes, one I could settle from the crate source.

The yield branch's unit comparison — checked, no conversion happens

I read scale_to_yield in the exact resolved dependency (cooklang 0.18.7, from Cargo.lock, not the sibling checkout):

let current_unit = parts[1].to_string();
if current_unit != target_unit {
    return Err(ScaleError::UnitMismatch { ... });
}
let factor = target_value / current_value;
self.scale(factor, converter);

A bare string comparison, and the Converter is only forwarded to self.scale to refit quantities after the factor is known — it plays no part in matching the yield's unit to the target's. So yield: 1%kg referenced as @./sauce{500%g} raises CoreError::Reference; it never reaches reached.unwrap_or(1.0). target_factor comparing them the same way is correct.

That is an assumption about another crate, though, so it is now pinned rather than asserted: a_yield_target_in_another_unit_is_a_reference_error fails first if cooklang ever starts converting, before the propagated factor can go quietly wrong.

The yield branch had no test — it does now

a_yield_target_passes_the_factor_it_reached_further_down: a sauce with yield: 1000%g, referenced as @./sauce{500%g}, itself referencing a stock with no quantity. Tomatoes come out halved and so does the stock's bones, so the propagated factor is observable. I mutation-checked it — substituting 1.0 for the parsed yield base gives 100000 g instead of 100 g, so the test does hold that arithmetic down rather than passing by construction.

The depth concern is real, and reproducible

You were right to push on this, and it is worse than "worth a thought". A generated acyclic chain — no cycle, so the ancestor check has nothing to refuse:

depth before
500 exit 0, 500 items
2000 fatal runtime error: stack overflow, aborting (SIGABRT)
10000 same

That bound came free when expansion stopped three files in, and the recursion took it away, so it is this PR's to restore. Added MAX_REFERENCE_DEPTH = 100 — checked against ancestors.len(), which already is the depth, so it costs nothing — raising a warning that names where the list stops rather than truncating silently. The same chains now exit 0 with Stopped at recipe reference './r100': references are nested more than 100 deep here. Anything below it is not on the list.

A hundred leaves well over an order of magnitude of headroom below where an unoptimised build ran out of stack, and a menu of dinners of sauces of preparations is four. a_chain_deeper_than_any_real_collection_stops_and_says_so covers it.

Nits

  • The target.round() comment now points at where it comes from: scale_to_target does let servings = target_value.round() as u32; before delegating to scale_to_servings. Read from the resolved 0.18.7 source, not assumed.
  • Agreed on the bare @recipe{} path — it was a latent bug fixed only in the nested level, and unifying the two carried the fix up to the top level. The comment at the call site says so.

cargo fmt, cargo clippy --workspace --all-targets and cargo test --workspace are clean on the updated branch.

@claude

claude Bot commented Sep 17, 2026

Copy link
Copy Markdown

Review

Nice fix. Replacing the hand-unrolled two-level expansion with a real recursive Expansion struct is the right move — it doesn't just add a third level, it removes the whole class of bug (an Nth level silently missing) by construction, and the doc comments explaining the "why" for each piece (ancestors vs. "everything seen", the MAX_REFERENCE_DEPTH stack-overflow guard, why target_factor must read metadata before scale_to_target mutates it) are genuinely useful for the next person touching this file.

Potential issue: target_factor's None → 1.0 fallback

In the custom-unit branch of target_factor (mod.rs:762-769), a recipe with no yield metadata at all returns None, and back in expand() that becomes reached.unwrap_or(1.0) — i.e. "assume unscaled" for whatever this reference points to further down.

The doc comment asserts this is safe because scale_to_target "raises the error for each of those [cases], so nothing here has to" — meaning the function should already have returned early via the ? on scale_to_target's Result before that fallback is ever used. That's explicitly pinned by a_yield_target_in_another_unit_is_a_reference_error for the wrong-unit case, but I don't see an equivalent test for the no yield key at all case (custom unit target on a recipe with no yield metadata whatsoever). If cooklang's scale_to_target/scale_to_yield ever tolerates that case differently than target_factor assumes, this would silently reintroduce exactly the class of bug this PR fixes (issue #424 style) — just one level further down, and only for custom-unit targets. Given how carefully the rest of this PR pins these assumptions with tests, it'd be worth adding one more case for "no yield metadata, custom-unit target" to close the gap, or reasoning explicitly about why it can't happen.

Minor / non-blocking

  • PR description undercounts tests: the description says "four new tests," but the diff adds seven (references_are_expanded_however_deep_the_chain_runs, the_request_scale_reaches_every_recipe_down_the_chain, a_scaled_reference_passes_the_factor_it_reached_further_down, a_yield_target_passes_the_factor_it_reached_further_down, a_yield_target_in_another_unit_is_a_reference_error, a_cycle_that_closes_three_recipes_down_is_still_refused, a_chain_deeper_than_any_real_collection_stops_and_says_so). Worth updating the description since the actual coverage is better than advertised.
  • Insertion order changed: the old code added a referenced recipe's own ingredients after its nested references ("so they are not counted twice"); the new recursive structure adds them before recursing into its own references. Quantities aggregate the same either way, but AggregatedList::items/the --plain output preserves insertion order, so the order items appear in an unexpanded/uncategorised list could shift for deeply-nested recipes. Not a correctness bug, and not called out in the two "behaviour changes worth a look" — just flagging in case it's unintentional.
  • Diagnostics volume at the depth boundary: each reference that hits MAX_REFERENCE_DEPTH gets its own warning (its subtree is never visited, so this doesn't blow up exponentially, but a recipe with many siblings all bottoming out at depth 100 would produce one warning per sibling). Very unlikely to matter for real recipe collections; not asking for a change.

Nice to see

  • Recursion is now hard-bounded (MAX_REFERENCE_DEPTH = 100) independently of the cycle check, which turns a plausible stack-overflow crash (cook server/cook sync pointed at a large or adversarial collection) into a clean diagnostic — a real robustness/availability win, not just a correctness fix.
  • The target_factor / scale_to_target ordering (read metadata, then scale) is called out explicitly in a comment — easy mistake to make silently, good that it's guarded by a comment for future editors.
  • Test style is strong: each new test explains what would have failed under the old code and why, not just what it asserts.

Overall: solid fix, well-tested, matches the file's existing documentation conventions. The one thing I'd actually want addressed before merge is pinning (or ruling out) the untested target_factor fallback case above; everything else is optional polish.

🤖 Generated with Claude Code

…e error

`an_unscalable_reference_is_a_reference_error` already pins that a yield
target against a recipe with no yield is refused. The servings equivalent
was not covered, and it is the other case where `target_factor` declines
to answer and expansion would fall back to a factor of one.

The sauce carries a sub-recipe so the test says what the fallback would
cost if `cooklang` ever stopped refusing: the stock counted at the
sauce's authored amounts, silently.
@dubadub

dubadub commented Sep 17, 2026

Copy link
Copy Markdown
Member Author

Addressed the blocking item; notes on the rest.

The None → 1.0 fallback

The yield half of it was already pinned, by a test that predates this PR and so does not show in the diff — an_unscalable_reference_is_a_reference_error, which references a sauce with no yield metadata as @./sauce{500%ml} and asserts CoreError::Reference. That is exactly the "no yield key at all" case: scale_to_target refuses it, the ? returns, and reached.unwrap_or(1.0) is never reached.

The servings half genuinely was not covered, so that is now a_servings_target_on_a_recipe_without_servings_is_a_reference_error. It puts a sub-recipe below the reference on purpose, so the test states what the fallback would cost if cooklang ever stopped refusing — the stock counted at the sauce's authored amounts, silently — rather than just asserting an error type.

While checking this I worked through every input where target_factor returns None but scale_to_target succeeds. There is exactly one class: a zero base, servings: 0 or yield: 0%g. cooklang computes target / 0 and scales the recipe by infinity; target_factor returns None and descendants inherit 1.0. Both are garbage-in, and confining the nonsense to the recipe cooklang itself scaled seemed better than propagating infinity down the tree, so I have left it — flagging it rather than leaving you to find it.

Insertion order — intentional, and it is the old code that was inconsistent

Good catch, and worth stating plainly rather than leaving as a maybe. The old nested level added a referenced recipe's ingredients after its children; the top level added the starting recipe's before its children. The recursion picks the top level's order and applies it uniformly, so what changed is that the second level now matches the first.

The "so they are not counted twice" comment on the old ordering was misleading: double-counting was prevented by add_recipe(..., false) skipping reference ingredients, never by the order. Nothing depended on it. I have added this to the PR description as a third behaviour note.

Also updated the description

Right — seven tests, not four. Fixed, with the two later ones attributed to this review.

Diagnostics volume at the boundary

Agreed it is not worth changing. It matches how cycles already report (one warning per refused reference), and a collection with many siblings all bottoming out at exactly depth 100 has a larger problem than the warning count.

@claude

claude Bot commented Sep 17, 2026

Copy link
Copy Markdown

Review

Nice fix — recursion cleanly replaces the two hand-rolled levels, the doc comments explain why at each bound (ancestor-chain cycle check + MAX_REFERENCE_DEPTH), and the seven new tests each target a specific behavior (deep chain, scale propagation, yield vs. servings targets, cycle three levels down, depth-limit abort). The write-up in the PR description of the three behavior deltas (scale reaching the bottom, nested-unit semantics, insertion order) is exactly the kind of thing that should be called out for reviewers of a refactor like this.

A few things worth a look:

1. target_factor / scale_to_target coupling is a bit fragile (crates/core/src/shopping_list/mod.rs:749)
reached.unwrap_or(1.0) (line 715) silently falls back to "the caller's factor doesn't propagate, use 1.0" whenever target_factor can't work out an answer. That's only safe because, today, every case where target_factor returns None is also a case where scale_to_target/scale_to_yield errors out first via the ? above it — so the fallback is dead code in practice. You've pinned that coupling with a_yield_target_in_another_unit_is_a_reference_error and a_servings_target_on_a_recipe_without_servings_is_a_reference_error, which is the right way to guard it, but it's still relying on an external crate's error behavior staying in lockstep with a local re-derivation of its arithmetic. Worth a quick check of these two tests whenever the cooklang dependency version is bumped, since that's the failure mode the comment at line 746 already calls out.

2. Depth-limit warning isn't attached to a file (crates/core/src/shopping_list/mod.rs:650-657)
cycle_warning attaches .at_file(path.clone()) so a diagnostic can be grouped/shown against the recipe it concerns. The new depth-limit diagnostic doesn't call .at_file at all, so it comes back with location: None. At the point it's raised, ancestors.last() is the currently-being-expanded recipe's resolved path (already on disk), which seems like a reasonable thing to attach it to for consistency with the rest of this module's diagnostics — otherwise a shopper/UI has to parse the file name back out of the message text.

3. Minor: warning spam at the depth cutoff
If the recipe sitting right at MAX_REFERENCE_DEPTH has several references, each one gets its own "Stopped at recipe reference…" warning (line 650 is inside the per-reference loop, so it fires once per sibling, not once per recipe). Not wrong, just noisy for a pathological/generated collection — might be worth collapsing to one warning per recipe if this is likely to come up in practice (e.g. cook sync scanning a large imported collection).

4. Test coverage: fractional servings target
target_factor's servings branch rounds the target (target.round() / base) to mirror scale_to_servings. The new tests use whole-number servings targets (6 servings of a 2-serving recipe), so the rounding path itself isn't exercised — a test with something like a 6.4%servings or 2.5%servings target would pin that the local rounding actually matches scale_to_servings's rounding rather than just happening to agree on integers.

5. Nice incidental fix, but undocumented
The unified ref_path computation (line 638-645) now applies the nested level's existing bare-reference handling (@recipe{} → reference.name, not reference.path(...)) to the top level too. Previously a bare top-level reference would've been looked up under a leading-separator path per the comment above it. That looks like a genuine (welcome) bugfix that falls out of the unification, but it isn't mentioned in the "Behaviour changes worth a look" section of the description alongside the other three — might be worth a line there so it doesn't get mistaken for a regression by someone bisecting later.

None of these block the fix — the recursion is correctly bounded on both axes (cycle chain + hard depth cap), the scale/target propagation logic looks right by inspection, and the test suite is unusually thorough about pinning why each assertion holds rather than just what it expects. I wasn't able to run cargo test/clippy/fmt in this sandbox to independently confirm the "all clean" claim in the description, so that's worth a human (or CI) double-check before merge if it hasn't already run there.

…rning's file

`target_factor` rounds a servings target the way `scale_to_servings`
rounds it, but every test asked for whole servings, where the two agree
whatever either does. Ask for 6.4 and the rounding is observable: without
it the sauce below the reference comes out at 12.8 rather than 12.

The depth warning carried no file, so a caller had to read the recipe's
name back out of the message — `cycle_warning` next to it does attach
one. Attribute it to the recipe holding the reference.

Also note on the `cooklang` dependency which two tests to re-run when it
is bumped: they pin that crate's error behaviour, not its results, and
`target_factor`'s fallback is only safe while those cases stay errors.
@claude

claude Bot commented Sep 17, 2026

Copy link
Copy Markdown

Reviewed the diff (crates/core/Cargo.toml, crates/core/src/shopping_list/mod.rs, crates/core/src/shopping_list/tests.rs). Nice fix overall — replacing the two hand-rolled expansion levels with real recursion bounded by the existing ancestor/cycle check plus a new MAX_REFERENCE_DEPTH is the right shape for #509, and the doc comments explaining why (not just what) make the tricky parts of this (target vs. multiplier scaling, ordering, the depth bound) easy to follow later. The seven new tests are thorough, including two that pin cooklang's error behavior specifically because target_factor` depends on it.

A few things worth a look before/after merge:

1. target_factor's None fallback silently assumes scale_to_target always errors in the same cases — worth a test for fractional-servings bases.
crates/core/src/shopping_list/mod.rs (target_factor, ~line 757-770): when target_factor can't work out a factor, the caller does reached.unwrap_or(1.0) and carries on without raising a diagnostic — unlike every other "can't proceed cleanly" case in this file (cycles, depth limit), which pushes a Diagnostic::warning. The correctness of that silent fallback rests entirely on the invariant documented in the new Cargo.toml comment: "safe only while every [such] case is one this crate refuses outright."

One case that isn't obviously covered: src/util/menu_scale.rs's existing RecipeInfo::default_servings doc comment notes "the cooklang API only exposes [servings] as u32, so fractional defaults like servings: 1.5 appear as None." target_factor's servings arm has exactly this shape (recipe.metadata.servings()?.as_number()?), so a reference like @./dinner{6%servings} where dinner.cook declares servings: 1.5 would make target_factor return None → factor silently defaults to 1.0 for everything under that reference. None of the new tests use a fractional base servings value (only a fractional target, e.g. 6.4%servings), so it's not verified here whether scale_to_target actually errors in that case too (making the fallback unreachable, as intended) or succeeds (making the fallback silently wrong — the exact "quietly wrong quantities" failure mode #424/#509 were about). Worth adding as an eighth pinning test alongside the other two "pins the crate's error behavior" tests, given how explicitly the PR already worries about this exact class of drift.

2. Related: unit-name matching is case-sensitive here but case-insensitive in the sibling implementation.
target_factor matches units with Some("servings") | Some("serving") and compares yield units with plain != (~lines 764, 771). The pre-existing reference_scale_factor in src/util/menu_scale.rs, which computes a very similar target→factor conversion for the menu feature, uses eq_ignore_ascii_case throughout. If cooklang's own scaling is case-insensitive anywhere here, that's another way for target_factor to return None while scale_to_target succeeds, hitting the same silent-1.0-fallback path as above. Probably low practical risk (recipes overwhelmingly write servings lowercase), but given target_factor and reference_scale_factor are solving the same problem for two different features (recipe references vs. menus) with diverging fallback philosophies (silent 1.0 vs. a tracing::warn! + raw multiplier), it might be worth a short note on why they can't share an implementation, for whoever next has to keep them in sync.

3. Minor: dead None arm.
self.diagnostics.push(match ancestors.last() { Some(path) => ..., None => stopped }) (in the depth-limit branch) — the comment already notes ancestors is guaranteed non-empty at that point since ancestors.len() >= MAX_REFERENCE_DEPTH (100) must hold to get there. Not a bug, just could be .expect(...) to make the invariant explicit instead of a silently-unreachable match arm.

4. Test coverage nit.
The doc comment on Expansion::expand's included parameter is explicit that top-level included_references filtering "applies to this level only" and the recursive calls always pass None. That's existing (not new) behavior, but I didn't see a test with a 3-level chain confirming a filter chosen for the top recipe doesn't also filter out a same-named reference two levels down — worth adding given how much this PR already hardens the deep-chain path.

Nothing here blocks the fix — #1 is the one I'd actually want resolved (or explicitly ruled out with a test) before relying on this for correctness the same way the PR relies on the yield/servings-error tests it already added, since it's the same category of "depends on an upstream crate behavior that could quietly change."

@dubadub

dubadub commented Sep 17, 2026

Copy link
Copy Markdown
Member Author

Took four of the five; the fifth I've left with a reason.

2. Depth warning now names its file. Right — cycle_warning beside it attaches one and this did not, so a caller had to read the recipe's name back out of the message. Attributed to ancestors.last(), the recipe holding the reference, which is non-empty there by construction (it is long enough to have hit the limit). The depth test now asserts the location is set, so it cannot quietly go back to None.

4. Fractional servings target. A real gap — every existing test asked for whole servings, where rounding and not-rounding agree whatever either does, so target.round() was decoration as far as the suite was concerned. a_fractional_servings_target_rounds_the_same_way_all_the_way_down asks for 6.4 servings of a 2-serving recipe; mutation-checked, dropping the .round() gives 12.8 instead of 12.

5. The bare @recipe{} fix. Added to the description's behaviour list. Worth stating precisely: the nested level already special-cased a reference with no path components, while the top level passed it to RecipeReference::path, which prepends the separator — so it was looked up as /recipe. Unifying the two carries the nested handling upward.

1. The coupling. Nothing to change in the code, but the warning belongs where someone will actually trip over it, so it is now a comment on the cooklang dependency in crates/core/Cargo.toml naming the two tests to re-run on a version bump and why they exist — they pin that crate's error behaviour rather than its results, which is the only thing making the unwrap_or(1.0) fallback unreachable. The module already has this convention for its other cross-cutting dependency notes.

3. Warning volume at the cutoff — left as is. It matches how cycles already report, one warning per refused reference rather than per recipe, and collapsing it here would make the two inconsistent for no gain. With .at_file now attached a UI can group them by recipe, which is the part that was actually awkward. A collection with many siblings bottoming out at exactly depth 100 has a bigger problem than its warning count.

cargo test --workspace, cargo fmt --check and cargo clippy --workspace --all-targets clean.

`cooklang` exposes servings as a `u32`, so `servings: 1.5` reaches
`as_number()` as `None` just as a missing value would — which would have
made `target_factor` decline while `scale_to_target` carried on, and the
sauce under that reference would have been counted at a factor of one
without a word said. It does not: the scale is refused. Pinned, alongside
the other two tests that hold that crate's error behaviour still.

Also cover that `included_references` filters the top level only, which
the recursion made worth stating: a stock excluded where the menu names
it directly is still counted where the sauce calls for it.

The depth warning's dead `None` arm becomes an `if let`, its doc says why
matching unit names exactly is the point rather than an oversight — the
menu feature's `reference_scale_factor` deliberately differs — and the
public doc no longer links a private constant, which rustdoc warned about.
@dubadub

dubadub commented Sep 18, 2026

Copy link
Copy Markdown
Member Author

1 — ruled out, and now pinned. Good catch on the u32; that was the sharpest of the four. Checked it rather than reasoning about it: servings: 1.5 referenced as @./dinner{6%servings} raises CoreError::Reference. scale_to_servings takes metadata.servings()?.as_number()? and refuses what it cannot represent exactly as firmly as it refuses what is not there, so the fallback stays unreachable. a_servings_target_against_a_fractional_base_is_a_reference_error now holds that still, next to the other two. The sauce below the reference is in the fixture on purpose, so the test says what the drift would cost rather than only which error it expects.

2 — the divergence is deliberate, and now says so. cooklang matches Some("servings") | Some("serving") and compares yield units with a plain !=, both case-sensitive. target_factor is a shadow of that arithmetic, so matching more loosely would be the bug: it would answer where scale_to_target refuses, which is precisely the one way the caller's fallback becomes reachable. reference_scale_factor is solving a different problem — it is a policy about what a menu author probably meant, which is why it can afford eq_ignore_ascii_case and a raw-multiplier fallback. That is now in target_factor's doc comment, including why the two cannot share an implementation while they disagree about it.

3 — done, as an if let rather than an expect. The invariant holds, but an unattributed warning is a better answer to being wrong about it than a panic in a library, so the comment now says that instead of leaving a dead arm to wonder at.

4 — done. included_references_filter_the_top_level_only: main names both a sauce and a stock, the sauce also calls for that stock, and only the sauce is included. Bones come out at 1 kg — counted where the sauce reaches them, not counted where main names them directly. Both halves of the claim in one assertion.

One thing to flag that none of the reviews raised: the MAX_REFERENCE_DEPTH doc link I added was to a private constant from public documentation, which cargo doc warns about. main emits six such warnings and this branch had seven, so I have dropped the link. Same class as ddc6e35.

cargo test --workspace, cargo fmt --check, cargo clippy --workspace --all-targets clean, and cargo doc -p cookcli-core is back to main's six.

@claude

claude Bot commented Sep 18, 2026

Copy link
Copy Markdown

Review

This is a careful, well-documented fix. The Expansion struct cleanly replaces the old two-level hand-rolled unrolling with real recursion, the doc comments accurately describe the new semantics, and the test suite is unusually thorough — it even pins the error cases of target_factor (fractional servings, mismatched yield units, missing servings) via mutation-checked tests so a future cooklang upgrade that changes those error boundaries is caught rather than silently producing a wrong scale factor. The Cargo.toml comment flagging which tests to re-run on a version bump is a nice touch given that risk.

A few points worth considering:

Depth limit bounds stack depth, not total work (performance)

MAX_REFERENCE_DEPTH = 100 protects against stack overflow on a long, non-branching chain (confirmed by the a_chain_deeper_than_any_real_collection_stops_and_says_so test at depth 150). But nothing bounds the total number of recipes expanded when references branch — each recipe can reference several others, and the same sub-recipe reached via different paths is legitimately re-parsed and re-counted each time (as a_recipe_referenced_by_two_others_is_counted_for_both documents as intentional). With the old code, that fan-out was capped at 2-3 levels, so even a wide branching factor stayed cheap. Now a collection that branches at, say, 3 references per level for even 20-30 levels (well under the depth-100 cap, and not caught by cycle detection since no path repeats an ancestor) could blow up combinatorially in parse/expand work long before the depth limit or cycle check ever fires. This is unlikely from a hand-written recipe collection, but cook server processes arbitrary recipe directories, so it's worth at least a conscious call on whether a "total nodes expanded" guard (in addition to the depth guard) is warranted, or whether this is accepted as out of scope for this fix.

Silent unwrap_or(1.0) fallback in target_factor

When target_factor returns None, the code falls back to treating the reached scale as 1.0 (crates/core/src/shopping_list/mod.rs:726). The PR's own reasoning — and the tests — establish that today every None case is also a case where scale_to_target itself errors out first, so the fallback is currently unreachable. That's good, but it does mean correctness here rests entirely on target_factor staying in lockstep with a private implementation detail of the cooklang crate's error behavior rather than on a type-level guarantee. Given the PR is explicitly about eliminating a different class of "quietly wrong, exit code 0" bug, it might be worth having the fallback push a diagnostic (or debug_assert!) rather than silently defaulting, so a future divergence fails loudly in a debug build instead of just being caught by tests-that-happen-to-exist.

Minor: doc comment on attribution is slightly inaccurate

The comment above the depth-limit diagnostic says it's "Attributed to the recipe holding the reference, the way cycle_warning attributes itself" (mod.rs:657-659). Looking at cycle_warning, it actually attributes to entry.path() — the target being referenced (which happens to coincide with an ancestor, since that's what makes it a cycle) — not the recipe that holds the offending reference. The depth-limit diagnostic attributes to ancestors.last(), the holder. Both are reasonable choices, but the comment's claim that they attribute "the same way" isn't quite right; worth a tweak so the invariant is accurately documented for the next reader.

Nit

Given the file's own convention of very deliberate, "why not what" comments, the recursive Expansion::expand doesn't have any inline comment noting that the recursion depth is intentionally bounded by the MAX_REFERENCE_DEPTH check happening before recursing (rather than as a counter parameter) — it's documented at the const and in the function doc, so this is genuinely minor, just flagging in case it's useful.

None of the above are blockers — the fix is correct for the bug it targets (verified by reading through the recursion, the target_factor derivation, and the tests), and the test coverage is genuinely excellent. I wasn't able to execute cargo test/clippy myself in this environment, so I'm relying on the PR description's claim that they're clean — worth a CI check before merge if not already covered.

🤖 Generated with Claude Code

…nd when target_factor can decline

Two comments claimed more than they should. The depth warning does not
attribute itself the way `cycle_warning` does — that one names the recipe
being referenced, which in a cycle is the interesting end of it, and this
one names the recipe holding the reference, because a reader wants to know
where the list stopped. And `target_factor` declining does not always mean
`scale_to_target` refused: a zero base divides to infinity over there and
returns `None` here, which is why its caller falls back to one rather than
asserting. Both now say so.
@dubadub

dubadub commented Sep 18, 2026

Copy link
Copy Markdown
Member Author

Both comment corrections are right — those were my claims, and they overreached. Fixed.

Attribution. You are correct that cycle_warning names entry.path(), the recipe being referenced, not the holder. Both choices are defensible for their own diagnostic and the difference is not accidental: in a cycle the target is the interesting end, because it is the recipe that turns out to be its own ancestor. At the depth limit the target is unremarkable — one of possibly several references that all stop in the same place — and what a reader wants is where the list stopped. The comment now says that instead of claiming the two match.

The fallback. Also right that it rested on a claim stronger than the code supports, and correcting it answers the debug_assert! suggestion too — I'd have taken it otherwise. The invariant has a real exception, which I flagged a few rounds up but had not written into the doc: a zero base, servings: 0 or yield: 0%g. cooklang divides by it and scales the recipe by infinity; target_factor returns None and what the recipe references is left alone. So a debug_assert! would fire on a real, if silly, recipe, and turn a nonsense collection into a panic for anyone running a debug build. That is why the fallback is a 1 and not an assertion, and the doc now says so rather than claiming the case cannot arise.

Pushing a diagnostic instead is tempting, but it would fire only for a zero base, which is a recipe problem rather than a shopping-list one and is better said by whatever validates recipes. cook doctor is where that belongs; happy to file it separately if you think it is worth saying out loud.

Inline comment on where the bound is checked — left alone. It is already stated at the constant and in expand's doc, and a third copy next to the code is the one most likely to drift out of step with the other two. The check sits in plain sight immediately before the recursive call.

On the last line of your review: the checks do run in CI here — Test on ubuntu/macOS/windows, UI Tests and this review job, all green on every push, including this one once it lands.

@claude

claude Bot commented Sep 18, 2026

Copy link
Copy Markdown

Review

Solid fix. The problem is well-diagnosed (two hand-rolled expansion levels standing in for recursion, so anything past 3 files deep silently dropped off the list), the fix is a clean, minimal recursion built on the existing ancestor-chain cycle guard from #424, and the new MAX_REFERENCE_DEPTH cap replaces the stack-safety that the old hard-coded depth used to provide for free. The commit history shows this already went through a few rounds of tightening (attributing the depth warning to a file, covering the yield/servings edge cases, fixing doc claims) — good discipline.

Code quality

  • The Expansion struct (base_path/converter/list/diagnostics) is a clean way to thread shared state through the recursion instead of a long parameter list.
  • Doc comments are unusually good at explaining why, not just what — target_factor's doc in particular walks through every case it declines to answer and why unwrap_or(1.0) is safe there.
  • Minor nit: strip_dot_slash (mod.rs, in the included_references filter) is a nested fn defined inside the for &ref_index in ref_indices loop body. Harmless — it's not re-created per iteration — but reads a little oddly; a free function above expand would be more conventional.

Potential correctness gap

  • target_factor's servings branch matches both "servings" and "serving" (mod.rs:792). The docstring is explicit that this function must match cooklang::Recipe::scale_to_target's own unit matching exactly, since any mismatch lets the unwrap_or(1.0) fallback fire silently instead of erroring. cooklang isn't vendored in this repo so I couldn't check its matcher directly, and none of the seven new tests exercise the singular serving form — only "servings" is tested. Worth either a quick test with @./x{6%serving} or a comment confirming this was checked against cooklang's source (it looks like it may have been carried over from menu_scale.rs::reference_scale_factor, which the docstring itself says is a deliberately looser, case-insensitive implementation for a different feature).

Performance

  • MAX_REFERENCE_DEPTH bounds recursion depth per branch, not total expand() calls. A collection with heavy branching at every level (a menu of many dinners, each of many sauces, …) isn't caught by the depth check and could still do a lot of work — nowhere near the original stack-overflow risk, but since cook server can be pointed at an arbitrary recipe collection, a large generated one could still be slow. Not something this PR needs to solve, just flagging that the bound is depth-only.
  • ancestors.to_vec() clones once per reference (O(depth) per clone), trivial at the 100-level cap.

Security

  • Nothing new here — same local filesystem reads under base_path as before. The depth cap is itself a hardening improvement: an uncontrolled stack-overflow abort becomes a bounded, reported diagnostic.

Test coverage

  • Strong. Seven new tests cover the original 4-deep-chain bug, scale propagation through the whole chain, absolute-target factor propagation for both servings and yield, fractional-servings rounding parity with cooklang, both target_factor-declines cases (fractional servings base, missing servings), a cycle closing three levels down, and the depth-limit warning (including that it's attributed to a file). included_references_filter_the_top_level_only is a good addition given the recursion makes that distinction observable for the first time.
  • Only gap I found is the untested singular serving unit noted above.

I reviewed statically (couldn't run cargo fmt/clippy/test in this sandboxed environment) — the PR description says all three are clean, which I have no reason to doubt given the care evident in the diff.

🤖 Generated with Claude Code

@dubadub
dubadub merged commit 6034ee1 into main Sep 18, 2026
6 checks passed
@dubadub
dubadub deleted the fix/shopping-list-deep-references branch September 18, 2026 12:04
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.

shopping-list silently drops ingredients more than two references deep

1 participant