Repository navigation
fix(lua): stop a Lua pattern match at the command deadline - #306
Conversation
Lua runs string.find, string.match, string.gmatch and string.gsub as single C calls, so the timeout hook, which fires between VM instructions, cannot interrupt them. A pattern with many backtracking points, such as "a?" repeated 30 times or ".-.-.-x" over a few hundred characters, ignored the command timeout for minutes. A plain-text find over repetitive data has the same quadratic cost. Before each such call, replay the match in a Rust port of Lua's matcher that counts its steps and polls the deadline, and raise "execution timeout exceeded" when the match cannot finish in half the time left. Lua's own functions still produce every result, so a script that finishes in time sees no change. The guard is installed only when the command has a deadline. Tests: a differential test compares the port with Lua's own matcher on random patterns and subjects (find, gsub and gmatch), including %z, NUL bytes, and malformed patterns. Deadline tests cover each function, the plain-text search, and numeric-string arguments, and a result test checks that scripts print the same with and without a deadline.
|
@strandly-the-agent please review |
There was a problem hiding this comment.
Changes requested: %b still runs far past the deadline. The wrapper logic and Lua parity hold up, and I found no way around the guard. But balanced() (src/builtins/lua_pattern.rs:474-496) scans the subject with no clock check, so a %b pattern runs about 1024 full scans between two looks at the clock. Requested by @ferdingler.
- 🟡
%boverrun, release build,[limits] timeout = 2:string.find(string.rep("(",1e7),"%b()x")takes 6.0 s. A 30M-byte subject takes 18.0 s, and plains:gsub("%b()","")does the same. The overrun grows with the subject, up to the 100 MB memory cap. No test covers it. Fix: inline. - The macOS CI failure (
shell_integration.rs:5564) is unrelated: a 200 ms timing flake in a non-Lua test. Re-run it.
Verified, questions, and details
Verified (SHA 44aa528):
cargo test --lib --bins: 80 passed.cargo test --test lua_integration: 237 passed (debug,--locked).- Parity: 30 scripts run with and without a deadline gave identical output and error text. They cover
"2",2.0and2.5as init, negative and nil init, gsubmaxas a string or float, repl as nil, a table or a function,^in gmatch, an empty pattern, and malformed patterns. - Guard coverage:
debugandloadare nil. Method calls (s:find), a saved gmatch iterator, a coroutine, and a gsub callback that callsstring.findare all guarded. The gsub dry run never callsrepl, so callback side effects are not run twice. - Back-references stop on time:
(.*)%1xand(.-)%1xover 20k to 300k bytes all stop at 1.00 s under a 2 s limit.while true do endstill stops at 2.00 s. - Overhead: 200k short finds took 130 ms vs 132 ms, and 20 gsubs over 1.2 MB took 368 ms vs 371 ms (release).
Not verified: the wasm32 build. My adversarial pass did not finish (the subagent failed twice), so the edge-case search is narrower than usual.
Fix for %b: count the bytes balanced scans toward the clock check, the way plain_scan uses work, or call self.tick()? each byte (this makes balanced take &mut self). Test: string.find(string.rep("(", 3e6), "%b()x") under a 2 s limit should stop at about 1 s. It takes 1.76 s today.
Questions (non-blocking):
- The half-budget rule refuses some calls that would finish. The PR states this trade-off (row 13). One more data point: with
timeout = 6,string.find(string.rep("a",30000), ".-b")finishes in 5.7 s unguarded but is refused at 3.0 s. Is that acceptable? - Scope: a 974-line matcher port with no linked issue, against CONTRIBUTING's "open an issue first" and "keep changes small". A maintainer should decide on the approach before line-level review goes further.
Reviewed by strandly-the-agent; a human should confirm before merge.
balanced() scanned the rest of the subject with no clock check, so a %b pattern over a long subject ran far past the deadline. Count each scanned byte toward the clock check, and add a regression test.
|
Thanks. The On the two questions:
|
Description
Human readable section
Problem: Lua runs
string.find,string.match,string.gmatchandstring.gsubas single C calls. Shell's command timeout is a Lua hook that fires between VM instructions, so it cannot interrupt them. A pattern with many backtracking points runs for as long as it needs. For example, a 7-character pattern with three lazy repeats over a 600-character string ran 67 seconds against a 3-second limit, and a longer subject ran for minutes. A plain-text search over repetitive data is slow in the same way. A host that embeds the Shell sees a core pinned at 100% and a timeout that never fires.Solution: Before each of those four calls, Shell replays the same match in a small Rust port of Lua's matcher that counts its steps and checks the clock. If the match cannot finish in half of the time left before the command deadline, the call fails with
execution timeout exceeded. Otherwise Lua's own function runs and produces the result, so a script that finishes in time behaves exactly as before. The guard is installed only when the command has a deadline.Trade-off: The dry run is 1.1 to 2 times slower than Lua's C matcher in a release build, so a call that would need more than about a quarter to a half of the time left can be refused even though it would have finished. A hostile pattern still uses up to half of the deadline before it is refused. Ordinary calls cost 0 to 8% more. The change is large (see below).
Issues this solves, before and after the fix. Timings use a 3 s command limit and a debug build unless a row says otherwise. "Before" is upstream
main.?repeats ignores the timeout (exponential backtracking)a?x 26 thenax 26execution timeout exceededa?x 30 thenax 30.-.-.-xover 300 characters.-.-.-xover 600 characters.-.-.-xover 1,200 characters.-.-.-.-xover 1,200 charactersinitandmaxarguments are affected, not onlyfindfind,match,gmatch,gsub,s:find(...),initas"1",maxas"1000000"findover repetitive data is quadratic and ignores the timeout%zclass (the NUL byte)%z?x 30,%zx 30,x, 4 s limitluacalls and the 30 s default limitwhile true do endfindof a 5,000-character needle in 100,000 charactersa?x 22 thenax 22, debug builda?x 23: Lua 0.33 s, dry run 0.44 s).What we tested:
find,gsub,gmatch), and a one-off run of 2.5 million, with%z, NUL bytes,%b,%f, back-references and malformed patterns%barguments,%f[\0], and[]]%z, before the fix. None after.initandmax, plain-text search,%z,[%z]gsubandgmatchagainst Lua, the exponential case, the polynomial case, a plain search,%z, and thegmatchscan state%zfix removed makes 3 of them fail.%b,%f, back-references, replacement tables and functions, errors throughpcall) run with and without a deadlinegsubover an 800 KB subject with a 30 s limit%zand the plain search (rows 8 and 9, both fixed). No panic, and no way to reach Lua's original functions.luacalls and a 30 s limitfindcalls, 1 million plainfindcalls, and a trim of 1 MB repeated 60 timeswasm32-wasip2with wasi-sdk 32 and wasmtime 50, using the shipped module plus a temporary--timeoutoption (not committed). 16 scripts, and 7 hostile cases with a 4 s limit.%z. A cheapfindis not refused. (wasi-sdk 34 failed to link against Rust 1.97.1 withundefined symbol __wasi_init_tp; I did not look into it.)cargo xtask check --rust-onlyNot solved by this change: a hostile pattern still uses up to half of the deadline before it is refused (15 s by default). I have not checked other embedders of the Shell. On WASM the shipped
strands-shell-wasmprogram sets no command timeout, so the guard is off there; it applies to code that embeds the Shell for WASM and sets a timeout.Details
src/builtins/lua_pattern.rsholds the matcher port, the dry-run drivers for each function, andinstall, which wraps the four functions in thestringtable.setup_lua_vmcallsinstallnext to the existing timeout hook.lstrlib.cfrom Lua 5.4, with the C locale's character classes, including the deprecated%z. It looks at the clock every 1,024 steps, sooner for a long pattern.string.findwithplainset, or a pattern with no special characters, runs through a counted plain-text search. Lua's version compares the needle at every position that starts with its first byte, so it is quadratic on repetitive input.string.gmatchis wrapped so each call of the iterator is checked, and the wrapper keeps the same scan state as Lua's iterator.Size, and how to split it
This is about 640 lines of matcher port plus tests, which is more than Shell's guidance prefers, and I have not opened an issue first. I am opening it as a draft so the approach can be judged on working code. Smaller options I considered: a check on the shape of the pattern (it would refuse legitimate patterns such as trimming a long string), and patching Lua's C source (embedders that pin the Shell by git revision would not inherit it). If maintainers prefer, it can be split into the matcher port with
findandmatchfirst, thengmatchandgsub, or replaced with a smaller mechanism.Related Issues
None.
Documentation PR
None. No page describes how the Lua timeout works.
Type of Change
Bug fix
Testing
How have you tested the change? Verify that the changes do not break functionality or introduce new warnings.
cargo test --workspace --all-targets,pytest tests/python,npm test)cargo xtask check --rust-onlypasses. It runscargo test --workspace --all-targets, fmt, clippy andcargo doc. I touched no Python or Node binding code, so I did not runpytestornpm test.cargo fmtandcargo clippycargo fmt --all --checkpasses. Clippy reports no warnings in the new file or the new tests. It does report the warnings thatmainalready has in other files.Checklist
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.