Repository navigation
Studio: close seven detection gaps in the deliberate-crash guard - #8788
Conversation
Follow-up to #8783. Seven holes in the AST scan, all reproduced against synthetic files before changing anything. Three of them fail CI on correct code, which is the worse direction for a guard to be wrong in. False positives, code that is already safe but was reported: * A script assembled through an annotated assignment (SCRIPT: str = SUP + ...) was not folded, so the crash half was judged alone with no suppression beside it. The fold now walks every Assign and AnnAssign rather than the module body. * Any string literal counted as a candidate child script, so an ordinary expectation such as assert "ctypes.string_at(0)" in script was reported as a deliberate crash. A string now only counts if it reaches a call argument, directly or through a name, a list, or a concatenation, which is what handing it to a child interpreter looks like. * A crash function calling a suppress_core() helper was reported, because the helper body sits outside the crash function's scope. One level of local helper is now followed. Factoring the suppression out is good practice and must not fail. Misses, code that dumps a core but passed: * The prefilter reused the exact crash markers, so ctypes.string_at( 0) was skipped before it was ever parsed. It now matches the call name and lets the AST decide precision, which is the right split of responsibility between the two. * Suppression counted anywhere in the scope, so a prctl placed after the fault passed. It must now precede the crash line. * Only symbolic signal names were recognised, so raise_signal(11) and os.kill(pid, 6) slipped through. Numeric forms count too. * Script snippets were matched textually, so from os import abort; abort() was missed. Snippets are Python, so they are parsed and run through the same call detector, which also picks up aliased and differently spaced forms for free. Ten new fixtures, one per hole plus the negatives that must stay quiet: Playwright's route.abort(), a variable re-raise, and os.kill with SIGKILL, which never dumps. 19 passed in 1.32s. 32 of 1049 files parsed, 833ms scan. Reverting the two guarded files to their pre-#8783 state still fails the guard and names both.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f7b7231e36
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| return { | ||
| node.name: node | ||
| for node in ast.walk(tree) | ||
| if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) | ||
| } |
There was a problem hiding this comment.
Resolve helper calls in their lexical scope
When two helpers share a name in different scopes, this global name map collapses them into one entry. If a module-level suppress_core() is a no-op but an unrelated nested suppress_core() clears dumpability, a child that calls the module helper before ctypes.string_at(0) is treated as suppressed, so CI misses a real core dump; helper lookup needs to use the function visible at the call site rather than whichever AST node has that name.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. Two helpers sharing a name in different scopes, where the outer is a no-op and an unrelated nested one clears dumpability, needs real lexical scope resolution for the helper map, and the pattern does not occur in this suite. I did take the neighbouring half of it: helper following is now restricted to bare ast.Name calls, so obj.suppress_core() no longer resolves to a local def suppress_core, and an async def helper only counts when the call is awaited. Both of those were reachable, this one is not.
| env = module_env if module_pass else scoped.setdefault(id(scope), dict(module_env)) | ||
| folded, _ = _fold(pair[1], env) | ||
| if folded is not None: | ||
| env[pair[0].id] = folded |
There was a problem hiding this comment.
Resolve string names at the call position
The per-scope string environment is built once for the whole scope, so a later reassignment overwrites the value used by an earlier subprocess call. For example, SCRIPT = "import ctypes; ctypes.string_at(0)"; subprocess.run([... , SCRIPT]); SCRIPT = "print(1)" now analyzes only the final safe value and misses the real crash; name folding needs to use bindings that are in effect at each call site, not the final assignment in the scope.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one either. Making the string environment flow-sensitive, so a name resolves to the binding in effect at each call position rather than the last in the scope, is a real change to how the whole analysis is structured, and it buys a case that reads backwards: assign the crashing script, run it, then reassign the name to something safe. I did fix the collision that does happen, which is the same name bound in two different scopes, in the previous round. Happy to revisit if a real file shows up written this way.
Four of the eight review findings were reproducible misses, each verified
against the guard before and after:
* A command vector bound to a name. `CMD = [sys.executable, "-c", SCRIPT]`
then `subprocess.run(CMD)` resolved nothing, because the name environment
folds only strings and a list does not fold. That is ordinary subprocess
usage, not a contrivance, so the child script went unread entirely.
* A crash imported under an alias. `from os import abort as die` binds `die`,
the rules are keyed on `abort`, and the alias map was a set of bound names
with no way back to the rule. The file was also skipped before parsing,
since the prefilter looks for call shapes and an aliased call contains
none, so the alias handling could never have run. Both ends fixed: the map
is now bound name to rule name, and the prefilter matches import spellings.
* `obj.suppress_core()` credited to an unrelated local `def suppress_core`.
Helper following now requires a bare local call.
* An `async def` suppressor that is called but not awaited builds a coroutine
and runs no prctl, so the fault after it still dumps. Only awaited calls
count now.
Declined, with reasons rather than silence. Three findings (a name reassigned
after the call that uses it, a nested scope rebinding a name used at module
level, two same-named helpers in different scopes) are one underlying issue:
resolution that ignores position and scope nesting. Fixing it properly needs a
flow-sensitive analyser, and fixing it partially is how a guard starts failing
CI for innocent code. The triggering shapes are contrived, and this is a
heuristic backstop rather than a soundness proof. The fourth, an exec snippet
inside an already-suppressed snippet, is exotic and errs toward a loud false
positive rather than a silent miss.
Seven cases added to the table, two of them negative, so the four fixes cannot
regress and the two behaviours that must stay allowed (awaited async helpers,
rebound aliases) are pinned. Prefilter still admits 32 of 1049 files, so the
widening costs nothing. Stale timing in the comment corrected: the scope and
alias analysis added over this PR moved the full pass from 496ms to ~1.5s.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: db4df84981
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| for argument in list(node.args) + [kw.value for kw in node.keywords]: | ||
| collect(argument, env) |
There was a problem hiding this comment.
Limit top-level snippets to executable call arguments
This loop collects strings from every call argument, so a normal helper such as record("from os import abort\nabort()") is now parsed as a child script and reported as an unsuppressed crash even though nothing executes that string. Because aliased aborts are newly recognized inside snippets, this creates a new false CI failure for safe expectation/logging/helper calls; collect only arguments to APIs that actually execute child code.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Disagreeing on this one, with evidence. I implemented it, restricting collection to a fixed executor set, and the guard then found ZERO deliberate-crash files in the repo: its own test_the_scan_finds_the_files_it_is_meant_to_guard failed. The reason is that the dominant shape here is a local runner, not a direct subprocess call. studio/backend/tests/test_torch_device_probe.py does _run_script(monkeypatch, _CRASHING_SCRIPT), and test_rag_embeddings.py is the same. An executor allowlist cannot see through a helper, so it turns the guard off for exactly the two files it exists to protect. Reverted, and pinned with a crash_shaped_string_handed_to_a_local_runner fixture so this cannot be re-introduced. The false positive you describe needs a helper that takes a crash-shaped Python string and does not run it, which does not occur here, and I would rather over-collect and let _snippet_state decide.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: eb367015cb
ℹ️ 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".
| # resolution that would have caught it never ran. The import spelling is the one piece of | ||
| # text such a file must contain, so match on that too. Costs one more scan of files that | ||
| # import these names and nothing else. | ||
| _PREFILTER += ("import abort", "import string_at", "import raise_signal", "import kill") |
There was a problem hiding this comment.
Broaden the prefilter for parenthesized alias imports
When a direct crash import uses standard parenthesized formatting, such as from os import (\n abort as die,\n), the source contains neither abort( nor import abort. _analyze therefore returns before parsing, and a subsequent die() is missed even though the new alias resolution would recognize it; the prefilter should also admit these multiline import forms.
Useful? React with 👍 / 👎.
| if _called_name(node) in _NESTED_EXEC: | ||
| argument = node.args[0] if node.args else None | ||
| if isinstance(argument, ast.Constant) and isinstance(argument.value, str): | ||
| yield argument.value |
There was a problem hiding this comment.
Resolve named strings passed to nested exec
When a child script stores its payload in a name, for example INNER = "import os; os.abort()"; exec(INNER), this branch ignores the argument because it accepts only string constants. The parsed outer snippet contains no crash call itself, so _snippet_state reports no crash and allows the real nested child core dump; fold name-bound strings here as is already done for top-level child scripts.
Useful? React with 👍 / 👎.
| "".join( | ||
| part.value | ||
| for part in node.values | ||
| if isinstance(part, ast.Constant) and isinstance(part.value, str) | ||
| ) |
There was a problem hiding this comment.
Preserve parseability when reducing f-string scripts
When an interpolation is syntactically required, such as f"import ctypes; x={v}; ctypes.string_at( 0)", dropping every formatted value produces the invalid snippet x=; .... Parsing then falls back to the old exact textual markers, where the whitespace in string_at( 0) is not recognized, so the analyzer returns no crash; replace interpolations with a parseable placeholder rather than deleting them.
Useful? React with 👍 / 👎.
| "annotated_script_constant": ( | ||
| "import subprocess, sys\n" | ||
| 'SUP: str = "import ctypes\\nctypes.CDLL(None).prctl(4, 0, 0, 0, 0)\\n"\n' | ||
| 'SCRIPT: str = SUP + "ctypes.string_at(0)\\n"\n' | ||
| 'subprocess.run([sys.executable, "-c", SCRIPT])\n', | ||
| False, # an annotated assignment folds like any other |
There was a problem hiding this comment.
Assert that suppressed fixtures are recognized as crashes
This fixture is intended to prove that an annotated child-script constant is folded and recognized as a safely suppressed crash, but the shared test only asserts crashes when want_violations is true. Consequently, returning (False, ()) here would pass just like correct recognition, so regressions that stop detecting this and the other newly added suppressed-crash fixtures are not caught; track and assert the expected crash state separately from the expected violation state.
Useful? React with 👍 / 👎.
| if _clears_dumpable_before(target, _AFTER_EVERYTHING): | ||
| return True |
There was a problem hiding this comment.
Respect early returns in suppression helpers
When a helper returns before its prctl, such as def suppress_core(): return; prctl(4, 0, ...), _clears_dumpable_before(target, _AFTER_EVERYTHING) still finds the unreachable call and credits the helper as suppressing a later crash. This is a regression from following helper bodies: suppress_core(); ctypes.string_at(0) is now accepted even though the helper never clears dumpability, so helper analysis must exclude suppression calls unreachable after an unconditional return.
Useful? React with 👍 / 👎.
| for child in ast.iter_child_nodes(scope): | ||
| if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef)): | ||
| continue |
There was a problem hiding this comment.
Do not skip executable class bodies
Class bodies execute immediately when the class statement runs, but _iter_executable skips ClassDef in the same way as deferred function and lambda bodies. A class body that calls prctl(4, 0, ...) and then deliberately faults is therefore reported as unsuppressed even though the suppression ran first; class definitions need their body evaluated in execution order while still excluding method bodies.
Useful? React with 👍 / 👎.
Follow-up to #8783. Seven gaps in the deliberate-crash guard, all raised in review of that PR and all reproduced against synthetic files before anything was changed.
Three of them fail CI on code that is already correct, which is the worse direction for a guard to be wrong in. A guard that misses a case costs you the case. A guard that fails on correct code costs you the guard, because the first person it blocks for no reason will want it gone.
False positives: safe code that was reported
SCRIPT: str = SUP + "ctypes.string_at(0)\n"was not folded, because the fold only handled unannotated module-level assignments. The crash half was then judged on its own with no suppression beside it. The fold now walks everyAssignandAnnAssign, so an annotated constant, or one assembled inside a test function, folds like any other.assert "ctypes.string_at(0)" in scriptwas reported as a deliberate crash. A string now only counts if it reaches a call argument, directly or through a name, a list, or a concatenation. That is whatsubprocess.run([sys.executable, "-c", SCRIPT])looks like, and an assertion operand is not it.suppress_core()helper first was reported, because the helper body sits outside the crashing function's scope. One level of local helper is now followed. Factoring the suppression out is the natural thing to do once more than one test needs it, and it must not fail.Misses: code that dumps a core but passed
ctypes.string_at( 0)was skipped before it was ever parsed. The prefilter only decides what to parse, so it should over-match and leave precision to the AST. It now matches the call name._scope_suppresseswalked the whole function without regard to order, so aprctlplaced after the crash counted. By then the core is already written. Suppression must now precede the crash line.signal.raise_signal(11)andos.kill(pid, 6)slipped through. They dump exactly the same core as the symbolic forms.from os import abort; abort()was missed. Snippets are Python source, so they are now parsed and run through the same call detector as real code. That picks up aliased and differently spaced forms for free, rather than needing a marker per spelling.Tests
Ten new fixtures, one per gap, plus the negatives that have to stay quiet:
route.abort('failed')and atask.abort(), which share the name and crash nothingsignal.raise_signal(signum)re-raising a variable after restoring the default handler, the terminal-prompt idiomos.kill(pid, signal.SIGKILL), which never dumps and is the recommended alternative when a test only needs the child to vanishNegative control unchanged: reverting the two files guarded by #8783 to their pre-merge state still fails the guard and names both.
Cost
32 of 1049 files parsed, 833 ms for the scan, 1.32 s for the pytest run. Up from 496 ms, which buys the snippet parsing and the helper following. The raw-text prefilter still does the heavy lifting: the other 1017 files are never parsed.
Why this is worth a second pass
Measured on a shared build box while #8783 was open: the unsuppressed
ctypes.string_at(0)onmainproduced 188 apport log lines in a single hour from one workspace running the suite, and roughly 1700 across the day from several. The dominant entry in that log was that one line. So the pattern really does get executed at volume by ordinary review and CI work, and the guard is the thing standing between that and the next person who copies the idiom.