Skip to content

Read only the selector shapes the sheet test can prove, and refuse the rest - #11089

Merged
danielhanchen merged 53 commits into
mainfrom
fix/selector-guard-pins-and-fallthrough
Sep 21, 2026
Merged

danielhanchen merged 53 commits into
mainfrom
fix/selector-guard-pins-and-fallthrough

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 16, 2026 •

Copy link
Copy Markdown
Member

Problem

test_preset_sheet_reacts_to_a_reasoning_budget_change asserts that ChatSettingsPanel subscribes to reasoningBudget and reasoningBudgetMessage, so the Update button and the summary re-render when only the budget changes. #11065 made the check behavioural through _selector_reads, which decides whether a zustand selector's result depends on the field. Codex found two ways that predicate accepted a stale selector (a guard naming the field "rescued" an arm it did not pin, and a block that falls through returns undefined).

Root cause

_selector_reads tried to accept any legal refactor of the selector and never accept a stale one, over arbitrary JavaScript, with regexes. Those two goals do not converge: every construct it read to stay permissive (blocks, switch, try, loops, const inlining, templates, escapes, destructuring) needed its own soundness patch, and each patch exposed the next shape. None of those shapes is reachable from the sheet. They are hypothetical rewrites of one selector.

Fix

Invert the policy. The predicate now reads only a small subset it can read completely, and refuses everything else:

  • An arrow with an expression body, or { return expr; }, taking s or a destructured field.
  • Expressions made of member reads, s["x"], calls, number/string/null/true/false/undefined literals, ternaries, ?? and comparisons.

Every ternary path must return the field itself (optionally through ??, or as a call argument), or return exactly the literal a guard pins the field to on that path (s.budget === -1 ? -1 : s.budget). Only strict === taken, or !== not taken, pins a value, and zero never does (Object.is(-0, 0) is false). An arm with a comparison, &&, ||, ! or a nested ternary anywhere in it, or a property read off the field (.length), is refused.

Assignment, arrow functions, statements, templates, regexes, escapes, arithmetic, optional chaining and the comma operator are refused by the tokenizer, so nothing can bind, write, hide a statement or skip a read. Against main, the file is +275/-213.

Intentional boundaries

  • A refused selector fails the test loudly and asks for a plainer spelling. That is the intended trade: false negatives on unusual spellings, no false positives inside the subset.
  • A call on the field, or ??, is taken as a transform of it, as main already documented: source cannot prove formatBudget(x) keeps distinct budgets distinct. The sheet's own selector depends on this, since its ?? s.reasoningBudget arm returns the requested budget while the budget equals the loaded one.

Verification

  • tests/studio/test_chat_preset_load_config.py: 16 passed. The broader -k preset selection under tests/studio: 29 passed.
  • Every selector case accumulated across the review rounds (about 220, including each Codex counterexample) was run against the new predicate. None that was expected to be refused is accepted. The 40 that change verdict are permissive refactor forms that are now refused.
  • Mutations of the real sheet: pointing the selector at another field, returning a value the budget only steers, and returning s.reasoningBudget > 0 all fail the test. A { return s.reasoningBudget; } rewrite passes.

Two holes Codex found in #11065's selector predicate. The review landed at the moment that PR was
merged, so they are fixed here rather than before it went in. Both let a broken refactor keep
`test_preset_sheet_reacts_to_a_reasoning_budget_change` green.

## A guard cannot rescue a subpath it does not pin

`(s) => s.reasoningBudget != null ? (s.enabled ? s.reasoningBudget : s.other) : null` passed. One
arm returned the field, which was taken as enough to let the outer budget guard account for the
rest. It is not: with `enabled` false, the budget moving between two non-null values leaves the
result at `s.other` and the sheet does not re-render.

Every path now either returns the field, or is reachable for only one value of it. Only a
comparison that fixes the field at a literal on the branch taken counts, so `budget === -1` taken
true and `budget != null` taken false both qualify, while `budget > 0` and a bare truthiness test
qualify for nothing. Guards carry which way they fell for this reason.

That also corrects a case I had recorded as a subscription in #11065:
`{ const v = s.reasoningBudget; return v ? s.reasoningBudget : -1; }`. A budget of 0 and a budget
of null both land on -1, so it does not track every change. It is a rejection now.

## A block that falls through returns undefined

`(s) => { if (s.enabled) return s.reasoningBudget; }` passed, because the only extracted result
was the field-bearing return. When `enabled` is false the selector returns `undefined`, which is
as steady as any other constant. A block that is not a plain "last statement is an unconditional
return" now contributes that path explicitly, including the unbraced `if (x) return y;` shape
that looks like a final statement but is not.

## Verification

13 shapes checked directly, both new cases and eleven behaviours from #11065 that must not move.
Mutations against the real sheet: the nested guarded subpath fails, the falling-through block
fails, and the same block returning the field on both paths stays green.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-19T00:56:45.819741Z 8111a7a Manual request
🔒 Security Review ✅ Completed 2026-09-18T17:42:11.742954Z 3295bef Manual request
ℹ️ About Codex in GitHub

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

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

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 2 commits September 16, 2026 09:22
`_pins` asked two independent questions, whether the guard names the field and
whether it compares something to a literal, so the two answers could come from
different operands. `s.budget > 0 && s.mode === "x"` read as pinning the budget
because the field matched one half and the literal the other, and every budget
above zero still returned the same arm.

The comparison is anchored to the field now, on either side of the operator.

Polarity follows from that. Taken true, a conjunction still implies its parts,
so `budget === -1 && mode === "x"` pins; a disjunction does not, so the same
shape with `||` does not. Taken false, only the bare comparison pins, because
negating `budget != null && mode === "x"` gives a disjunction that leaves the
budget free.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Two ways a pinned path was still dishonest.

The comparison matched the field on any receiver, so `defaults.reasoningBudget
=== -1` read as a statement about the store while `s.reasoningBudget` moved
underneath it. It is matched against the field read off the selector's own
parameter now, with a lookbehind, because `s.reasoningBudget` otherwise matches
inside `defaults.reasoningBudget`.

Being reachable for one value of the field does not make a constant result
honest: `s.budget === -1 ? 0 : s.budget` pins the first arm at -1 and returns 0,
which is exactly what the other arm returns once the budget IS 0, so the -1 to 0
change produces no change at all. A pinned arm now has to return the value the
field holds there, which is the literal it was pinned to.

`_pins` became `_pinned_literal` for that: the branch reports which value it
fixes rather than answering yes or no.

Mutations: a comparison on another object's field fails, and a pinned arm
returning a colliding constant fails.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

`!(s.budget === -1)` was read as pinning the budget to -1, because the equality
was found without regard to the Boolean context around it. The branch implies
the opposite, and every transition among the other values keeps returning the
same arm. A guard carrying a logical not is refused rather than interpreted.

The reverse form of the comparison had a boundary before the access and none
after, so `-1 === s.budgetExtra` matched on the `s.budget` prefix. Both ends are
bounded now.

Mutations: a negated equality fails, and a comparison against a longer field
name that starts with this one fails.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Two ways a guard could read as pinning a value it does not pin.

The numeric alternative stopped at the first digit run, so `1e3` matched as `1` and
`s.reasoningBudget === 1e3 ? 1 : s.reasoningBudget` passed: a budget of 1000 and a budget of 1
both return 1, which is the collision the check exists to catch. The pattern now spells
exponent and radix forms and refuses to end mid-token.

The equality only had to appear somewhere in the guard, so
`(s.reasoningBudget === -1) === false` counted: that arm is taken for every budget except -1,
the opposite of what the inner comparison reads as. The comparison now has to be one of the
guard's top-level `&&` conjuncts, matched end to end, so an inner equality fed to another
operator no longer pins anything.
@danielhanchen

Copy link
Copy Markdown
Member Author

Both correct, both fixed in 9457d29.

Bound numeric literals before treating them as pins. The numeric alternative ended at the first digit run, so 1e3 matched as 1 and (s) => s.reasoningBudget === 1e3 ? 1 : s.reasoningBudget was accepted: budgets of 1000 and 1 both return 1, which is exactly the collision the pin check exists to reject. The pattern now spells exponent and radix forms and carries a trailing (?![\w$.]), so a literal has to be consumed whole or not matched at all.

Require equality to be a positive guard conjunct. Presence was all that was checked, so (s.reasoningBudget === -1) === false counted as a pin while the arm is in fact taken for every budget except -1. The comparison now has to be one of the guard's top-level && conjuncts, matched end to end by re.fullmatch, with _top_level_conjuncts splitting only at bracket depth zero. An equality fed to another operator is no longer a pin.

Five cases added: the === false shape, 1e3 pinned to 1 (rejected) and to 1e3 (accepted), and a hex pin.

Both fixes mutation-tested. Reverting the literal bound and reverting the conjunct requirement to a plain re.search each leave the suite at 1 failed, 15 passed.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

`==` relates a class of values to one literal rather than pinning the field to it: a message
of "" and a message of "0" both satisfy `msg == 0`, so an arm returning 0 there holds still
while the field moves between them. Only `===` and `!==` are read as pins now. That drops
`s.reasoningBudget != null ? s.reasoningBudget : null`, which is false for null and undefined
alike; the strict spelling of the same selector is still accepted.

Normalisation stripped whitespace everywhere, including inside quoted literals, so a guard
pinning the field to "a b" matched an arm returning "ab" and the collision it exists to catch
read as a match. Whitespace is now only removed between tokens.
@danielhanchen

Copy link
Copy Markdown
Member Author

Both correct, both fixed in f510b64. Reproduced your two calls first: each returned True before the change and returns False after.

Restrict pinned comparisons to strict equality. == relates a class of values to one literal instead of pinning the field to it, so the branch is not a single-value path. Only === and !== are read as pins now. That also drops s.reasoningBudget != null ? s.reasoningBudget : null, which was accepted before and should not have been: the null arm is taken for null and for undefined alike, so the selector returns null across that change. Its strict spelling is accepted, and both are now in the case table with the reason.

Preserve whitespace inside literals. _normalised stripped whitespace everywhere, so a guard pinning the field to "a b" matched an arm returning "ab" and read as honest. Whitespace is now removed only between tokens: the normaliser walks string literals and copies them through untouched.

Both mutation-tested. Restoring the loose spellings, and restoring the blanket whitespace strip, each leave the suite at 1 failed, 15 passed.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

A loop header carries its own semicolons, so taking the last one as the statement boundary hid
the `for` from the fall-through check and `{ for (let i = 0; i < s.list.length; i++) return
s.reasoningBudget; }` read as an unconditional return. An empty list falls through to undefined,
which tracks nothing. Delimiters now count only at bracket depth zero.
@danielhanchen

Copy link
Copy Markdown
Member Author

Correct, fixed in 9aa15ff. Your call returned True before the change and returns False after.

The fall-through check located the preceding statement with a raw rfind(";"), so a for (let i = 0; i < n; i++) header's own semicolons were taken as the boundary and the for fell outside the slice being scanned for a control keyword. The loop body then read as an unconditional return, when an empty list falls through to undefined. Delimiters now count only at bracket depth zero, in _statement_start.

Two cases added: the loop-header shape you gave, and a loop whose body and follower both return the field, which stays accepted.

Mutation-tested: restoring the raw rfind leaves the suite at 1 failed, 15 passed.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 16, 2026
Collapses the multi-line explanations on the internal helpers to what they need to say. No
code change: comment_tools.py check reports comments only.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

`(s) => (s.reasoningBudget === -1) ? -1 : s.reasoningBudget` was rejected: the conjunct arrives
wrapped and the end-to-end match against it failed, so a reformatting of a selector this test
accepts made it red. That is the class of guard this test replaced.

Redundant outer parentheses are stripped before the match, one pair at a time and only when the
opening one closes at the very end, so `(budget === -1) === false` keeps its meaning and is
still refused.
@danielhanchen

Copy link
Copy Markdown
Member Author

Correct, fixed in 17e8127. Your selector returned False before the change and returns True after.

The conjunct arrives wrapped, so the end-to-end match against it failed and a reformatting of a selector this test accepts made it red. That is exactly the class of guard this test replaced, so the false negative matters as much as the false positives from the earlier rounds.

_unwrapped strips redundant outer parentheses one pair at a time, and only when the opening parenthesis closes at the very end. (s.reasoningBudget === -1) === false therefore keeps its meaning and is still refused.

Four cases added: the parenthesised guard, a doubly parenthesised one, a parenthesised pinned value, and the === false shape alongside them so the distinction is pinned down.

On coverage, so it is not overstated: removing the unwrap on the conjunct leaves the suite at 1 failed, 15 passed. The "closes at the very end" condition is not mutation-covered, and I could not construct a case that observes it: stripping a non-matching pair yields a string with an unbalanced parenthesis, and the comparison pattern contains none, so such a string can never match either way. It is there so the helper is correct on its own terms, not because a case reaches it.

I also dropped an unwrap I had added on the returned expression: _split_ternary already removes those parentheses, and the mutation showed the line was dead.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

`{ if (s.enabled) return s.reasoningBudget; else return s.reasoningBudget; }` returns the field
on every path, and the fall-through check invented an undefined path for it: it only recognised
a trailing unconditional return, so an exhaustive if/else read as a block that can fall off the
end. That is a semantics-preserving refactor of a selector this test accepts, failing it.

The check now consumes the block's own statements. A return at that level ends it, a braced
block is entered, and an if/else counts when both arms always return. A loop still never counts,
since its body may not run at all. Consuming statements also binds `else` to the nearest `if`,
which the regex could not, and keeps a helper declared mid-block from swallowing the return
after it.
@danielhanchen

Copy link
Copy Markdown
Member Author

Correct, fixed in 152caca. Your selector returned False before the change and returns True after.

This is the third false negative in a row from the same source: the fall-through check was looking for a trailing unconditional return with a regex, which cannot see that an exhaustive if/else leaves no path to the end. Rather than special-case it, the check now consumes the block's own statements. A return at that level ends the block, a braced block is entered, and an if/else counts when both arms always return.

What the walk buys beyond the reported case:

  • else binds to the nearest if, so { if (a) { if (b) return f; } else return f; } is correctly not exhaustive, which the regex could not express.
  • A helper declared mid-block no longer swallows the return after it, since a brace-bodied statement ends at its brace rather than at the next semicolon.
  • A loop still never counts. Its body may not run, so for (...) return f; and while (...) return f; both fall through.

switch and try/catch are deliberately refused rather than analysed. Neither appears in a store selector, and refusing is the safe direction.

Eight cases added, covering both arms braced and bare, a non-exhaustive else, the dangling-else binding both ways, a bare nested block and the while shape.

Mutation-tested, three ways, each leaving the suite at 1 failed, 15 passed: dropping the exhaustive-arms check, treating a missing else as exhaustive, and not consuming a loop body.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

Two legal refactors the predicate refused.

A quoted literal is a value, not syntax, but `!`, `||` and `&&` were searched for across the
whole guard, so a message spelling one of them made a selector that returns the field unchanged
read as a guard carrying a negation or a disjunction. Those operators, and the bracket scan that
splits conjuncts, now run against a copy with literal contents blanked out.

A `switch` was consumed as a statement but never analysed, so an exhaustive one reported
fall-through and the caller appended an undefined result that no path produces. A defaulted
switch whose every arm returns now counts. Undefaulted does not, since a value matching nothing
falls past the closing brace, and neither does a `break`, which leaves the switch with no value.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 18, 2026

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4251478b7b

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines +396 to +398
if kind == "call":
depth += 1 if text == "(" else -1
elif depth == 0 and text in _COLLAPSING:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Analyze collapsing expressions inside call arguments

Ignoring collapsing operators while inside a call makes _selector_reads('(s) => String(s.loadedIsDiffusion ? s.reasoningBudget : s.nBatch)', 'reasoningBudget') return True. When loadedIsDiffusion is false, budget changes leave this selector fixed at String(s.nBatch), so Zustand does not re-render and the stale-sheet contract passes; ternary/comparison/logical paths inside call arguments must be analyzed before treating the call as a field transform.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reproduced: returned True. Fixed in e14ea5f: a comparison, logical operator or branch anywhere in an arm, call arguments included, now refuses the selector. A call is still taken on trust as a transform of its argument, but only an argument that is the field itself. The case is in SELECTOR_CASES.

return False
size = len(access)
return any(
arm[index : index + size] == access and (index == 0 or arm[index - 1][1] not in (".", "?."))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Bound the tracked access on its right side

This match accepts a field access even when the selector returns a subsequent property: _selector_reads('(s) => s.reasoningBudgetMessage.length', 'reasoningBudgetMessage') returns True. Two messages of the same length produce the same selector result, so a message-only change can leave both capture memos stale while the contract remains green; require the matched access itself to be the returned value, except for explicitly modeled transforms such as calls.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reproduced: returned True. Fixed in e14ea5f: the access has to be the value itself. It must be followed by the end of the arm, ??, a call argument separator or the call's closing parenthesis, so .length, .toString() and (s.reasoningBudget).length are refused. Those cases are in SELECTOR_CASES. String(s.reasoningBudget) stays accepted.

@unslothai unslothai deleted a comment from danielhanchen Sep 18, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 18, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 18, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 18, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 18, 2026
@oobabooga

Copy link
Copy Markdown
Member

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e14ea5fdac

ℹ️ About Codex in GitHub

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

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

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

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

)
# Operators that end the value a selector hands zustand at a comparison or a branch: an arm
# holding one at its own level returns a boolean, or picks between values unscored.
_COLLAPSING = frozenset({"===", "!==", "==", "!=", "<", ">", "<=", ">=", "&&", "||", "!", "?"})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject optional chains that can skip the tracked read

When the tracked field is passed to a method behind an optional chain, _selector_reads('(s) => s.other?.format(s.reasoningBudget)', 'reasoningBudget') returns True. If s.other is nullish, JavaScript skips both the call and argument evaluation and the selector remains undefined across budget changes, so Zustand does not re-render and this contract can stay green for a stale sheet. Treat ?. as collapsing when it appears anywhere before the tracked call argument, or otherwise model its short-circuit path.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reproduced: returned True. Fixed in 7ef7e45 by taking ?. out of the subset instead of modelling its short circuit: the tokenizer refuses it, so the selector is refused. The case is in SELECTOR_CASES.

@oobabooga

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@oobabooga

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 7ef7e457c8

ℹ️ About Codex in GitHub

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

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

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

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

@oobabooga

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@oobabooga

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 8111a7a81a

ℹ️ About Codex in GitHub

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

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

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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants