Skip to content

fix(lua): stop a Lua pattern match at the command deadline - #306

Merged
ferdingler merged 4 commits into
strands-agents:mainfrom
priyasingh2111:feature/lua-pattern-deadline
Nov 16, 2026
Merged

ferdingler merged 4 commits into
strands-agents:mainfrom
priyasingh2111:feature/lua-pattern-deadline

Conversation

@priyasingh2111

@priyasingh2111 priyasingh2111 commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Description

Human readable section

Problem: Lua runs string.find, string.match, string.gmatch and string.gsub as 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.

# Issue Example Before the fix After the fix
1 A pattern with many ? repeats ignores the timeout (exponential backtracking) a? x 26 then a x 26 7.8 s, and the timeout was only reported after the call returned 1.5 s, execution timeout exceeded
2 Same, a little larger a? x 30 then a x 30 Still running at 90 s 1.5 s
3 Several lazy repeats over a long subject ignore the timeout (polynomial backtracking) .-.-.-x over 300 characters 4.2 s 1.5 s
4 Same .-.-.-x over 600 characters 67 s 1.5 s
5 Same .-.-.-x over 1,200 characters Still running at 120 s 1.5 s
6 Same, one more repeat .-.-.-.-x over 1,200 characters Still running at 120 s 1.5 s
7 All four functions, the method form, and numeric-string init and max arguments are affected, not only find find, match, gmatch, gsub, s:find(...), init as "1", max as "1000000" Each hangs the same way Each stops at the deadline (2 s limit, all within 8 s)
8 A plain-text find over repetitive data is quadratic and ignores the timeout A 3 MB subject and a 1.5 MB needle, 4 s limit 45 s 2.0 s
9 Lua's deprecated %z class (the NUL byte) 30 NUL bytes against %z? x 30, %z x 30, x, 4 s limit Over 60 s (stopped at a 60 s cutoff) 2.0 s
10 A host that embeds the Shell: a core pinned at 100%, the timeout ignored, and the host cannot exit A box with 4 hung lua calls and the 30 s default limit About 400% CPU for 70 s, 4 of 4 calls still running at 40 s, and the host never exited (stopped by hand) CPU back to idle after 15 s, 0 of 4 calls running at 40 s, and the host exited by itself
11 Unchanged by design: a pure Lua loop while true do end Stops at 3.00 s Stops at 3.00 s
12 Unchanged by design: a search that does not backtrack find of a 5,000-character needle in 100,000 characters 0.00 s 0.00 s
13 Behaviour change: a slow call that would finish can be refused a? x 22 then a x 22, debug build Finished in 0.45 s Refused at 1.5 s. A debug build's dry run is slower than Lua's C matcher. In a release build a case this size finishes (a? x 23: Lua 0.33 s, dry run 0.44 s).

What we tested:

Test Setup Result
Rust matcher against Lua's own matcher 100,000 random patterns and subjects in the suite (find, gsub, gmatch), and a one-off run of 2.5 million, with %z, NUL bytes, %b, %f, back-references and malformed patterns No differences. A case where Lua raises an error after the match (an open capture) is accepted by design.
Matcher against Lua, in an independent review 400,000 cases (320,736 usable once plain-text patterns and out-of-range starts are skipped) with patterns of up to 20 items, bytes 0x80 to 0xff, NUL, odd %b arguments, %f[\0], and []] 1,117 differences, all %z, before the fix. None after.
Deadline is enforced 17 cases through the real Shell with a 2 s limit: all four functions, the method form, numeric-string init and max, plain-text search, %z, [%z] Each stops within 8 s (the guard stops at 1 s) and reports a timeout
Unit tests 8: the matcher against Lua, gsub and gmatch against Lua, the exponential case, the polynomial case, a plain search, %z, and the gmatch scan state All pass. The %z fix removed makes 3 of them fail.
Results are unchanged 31 scripts (captures, %b, %f, back-references, replacement tables and functions, errors through pcall) run with and without a deadline Byte-identical output and exit status
Large inputs Trim and gsub over an 800 KB subject with a 30 s limit Correct result
Attempts to get around the guard An independent review tried argument coercion, the method form, replacing the functions, other functions that take patterns, and panics Found %z and the plain search (rows 8 and 9, both fixed). No panic, and no way to reach Lua's original functions.
Embedding host A box that embeds the Shell, with 4 hung lua calls and a 30 s limit See row 10. A fresh connection was answered in both cases.
Cost on ordinary calls A release build, 1 million small find calls, 1 million plain find calls, and a trim of 1 MB repeated 60 times +5%, +3% and +7%
WebAssembly wasm32-wasip2 with wasi-sdk 32 and wasmtime 50, using the shipped module plus a temporary --timeout option (not committed). 16 scripts, and 7 hostile cases with a 4 s limit. Builds. The 16 scripts print the same with and without a timeout. Each hostile case stops at about 2.3 s: 2.0 s of guard time plus 0.3 s for wasmtime to start. That covers all four functions, the plain-text search, and %z. A cheap find is not refused. (wasi-sdk 34 failed to link against Rust 1.97.1 with undefined symbol __wasi_init_tp; I did not look into it.)
Full check cargo xtask check --rust-only All checks pass (2,586 tests)

Not 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-wasm program 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.rs holds the matcher port, the dry-run drivers for each function, and install, which wraps the four functions in the string table. setup_lua_vm calls install next to the existing timeout hook.
  • The port follows lstrlib.c from 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.find with plain set, 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.gmatch is wrapped so each call of the iterator is checked, and the wrapper keeps the same scan state as Lua's iterator.
  • A pattern error or the nesting limit makes the dry run give up, and Lua's own call then reports the error with its usual message.

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 find and match first, then gmatch and gsub, 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.

  • I ran the relevant test suites for the bindings I touched (cargo test --workspace --all-targets, pytest tests/python, npm test)
    • cargo xtask check --rust-only passes. It runs cargo test --workspace --all-targets, fmt, clippy and cargo doc. I touched no Python or Node binding code, so I did not run pytest or npm test.
  • If I touched Rust, I ran cargo fmt and cargo clippy
    • cargo fmt --all --check passes. Clippy reports no warnings in the new file or the new tests. It does report the warnings that main already has in other files.

Checklist

  • I have read the CONTRIBUTING document
  • I have reviewed and understand every line of code in this PR, including any generated by AI tools, and I can explain why it works
  • My change is focused and reasonably small; I have split unrelated work into separate PRs
  • I have added any necessary tests that prove my fix is effective or my feature works
  • I have updated the documentation accordingly
  • I have added an appropriate example to the documentation to outline the feature, or no new docs are needed
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

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.
@priyasingh2111
priyasingh2111 marked this pull request as ready for review November 13, 2026 23:37
@ferdingler

Copy link
Copy Markdown
Collaborator

@strandly-the-agent please review

@strandly-the-agent strandly-the-agent left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

  • 🟡 %b overrun, 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 plain s: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.0 and 2.5 as init, negative and nil init, gsub max as a string or float, repl as nil, a table or a function, ^ in gmatch, an empty pattern, and malformed patterns.
  • Guard coverage: debug and load are nil. Method calls (s:find), a saved gmatch iterator, a coroutine, and a gsub callback that calls string.find are all guarded. The gsub dry run never calls repl, so callback side effects are not run twice.
  • Back-references stop on time: (.*)%1x and (.-)%1x over 20k to 300k bytes all stop at 1.00 s under a 2 s limit. while true do end still 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):

  1. 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?
  2. 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.

Comment thread src/builtins/lua_pattern.rs Resolved
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.
@priyasingh2111

Copy link
Copy Markdown
Contributor Author

Thanks. The %b overrun is fixed in 5b6e629 (see the inline thread). I merged current main in c0c53a9, and cargo xtask check --rust-only passes locally. I have not looked at the macOS flake. It sits in a non-Lua test, so I will re-run it if it fails again.

On the two questions:

  1. Refusing calls that would finish: yes, this is intended and bounded. The dry run is 1.1 to 2 times slower than Lua's C matcher, so the guard refuses a call that needs more than roughly a quarter to a half of the time left. The .-b example with timeout = 6 is a real instance of that. The alternative is no dry run, which means a hostile pattern can run for minutes. If maintainers prefer a smaller share of the deadline than half, that is a one-line constant (time_limit).
  2. Scope: no issue was opened first, and I should have said that sooner. The change is large because the guard has to replay Lua's matcher in Rust to count steps. A pattern-shape check would refuse legitimate patterns, and patching Lua's C source would not reach embedders that pin Shell by git revision. If you want a smaller first step, I can split it: the matcher with find and match first, then gmatch and gsub. I can also open an issue first, if you prefer. I will follow whichever approach a maintainer picks.

@ferdingler
ferdingler merged commit 2d36d74 into strands-agents:main Nov 16, 2026
30 checks passed
@priyasingh2111
priyasingh2111 deleted the feature/lua-pattern-deadline branch November 17, 2026 01:20
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.

3 participants