Skip to content

Measure the stack of the thread each call runs on - #19

Merged
marcobambini merged 3 commits into
sqliteai:mainfrom
davidschachterADFA:measure-stack-of-each-calls-thread
Nov 12, 2026
Merged

marcobambini merged 3 commits into
sqliteai:mainfrom
davidschachterADFA:measure-stack-of-each-calls-thread

Conversation

@davidschachterADFA

Copy link
Copy Markdown
Contributor

QuickJS measures the stack from the top it recorded on the thread that created the runtime. A connection used on another thread gets the wrong limit. On x86_64 Linux, a connection opened on the main thread and used on another thread fails at once with "Maximum call stack size exceeded", even for recursion 100 levels deep. One opened on another thread and used on the main thread never trips the check, so code that calls itself without end crashes the process. Android apps hit the first case: Room runs a connection's queries on a pool of threads. js_set_max_stack_size(0), which the 1.3.7 changelog suggests for a connection used from several threads, turns the check off, with the same crash.

This calls JS_UpdateStackTop(), quickjs-ng's function for a runtime that changes thread, on each call from SQLite into JavaScript: scalar, aggregate and window callbacks, collations, js_eval and the js_create_* functions. It also keeps the size within what that thread's stack has left, using #17's js_stack_room().

  • A call nested in another (JavaScript running SQL through db.exec that calls JavaScript) is on the same thread and keeps the outer call's limit.
  • Each thread's stack bounds are found once and kept in a thread-local variable, because on Linux finding the main thread's stack reads /proc/self/maps.
  • 0 still turns the check off; the README no longer suggests it for several threads.

Test: a new Stack on other threads test checks that:

  • a connection opened on one thread and used on another, also on a thread with a 512 KB stack, runs recursion 100 levels deep and stops endless recursion with "Maximum call stack size exceeded";
  • so does a connection opened on another thread and used on the main thread.

It fails without this change. make test passes on x86_64 Linux, also under ASan and UBSan, and the extension compiles for Android (arm64 and armv7, NDK r29). The Windows and Apple branches of js_stack_room() are #17's, now cached per thread; I had no such machine to test them on.

This is a ninth pull request, after #11 to #18. It changes #17's js_stack_room(), so it is built on #17 and contains #17's two commits; please review #17 first. A connection used from Android also needs a way to stop runaway JavaScript, since Android cancels a query with a progress handler, which SQLite never calls while a function runs. We carry that ourselves for now.

This pull request originated with AI. Claude, Anthropic's AI model, wrote the code, the tests and this description while packaging sqlite-js for Code on the Go, App Dev For All's Android IDE, which ships sqlite-js with this change. Contact: [email protected]

🤖 Generated with Claude Code

https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw

davidschachterADFA and others added 3 commits November 11, 2026 11:53
QuickJS stops code that calls itself too deeply when the stack falls
below a limit it computes from the size it was given. It trusts that
size, so a size larger than the thread's stack never trips the check,
and code that calls itself without end crashes the process instead of
failing with "Maximum call stack size exceeded".

js_set_max_stack_size() passed its argument to JS_SetMaxStackSize()
unchecked, through sqlite3_value_int(): text such as '1MB' or 'abc'
read as 1 or 0, and a size above the thread's stack, such as 16 MB on
a thread with 8 MB, crashed sqlite3 on endless recursion. The 1 MB
default could itself be too large: on a thread with 512 KB of stack,
endless recursion crashed at the default, and Windows gives a main
thread 1 MB, apps often their threads no more.

Measure the calling thread's stack (pthread_getattr_np() on Linux and
Android, pthread_get_stackaddr_np() and pthread_get_stacksize_np() on
Apple platforms, VirtualQuery() on Windows) and keep a margin,
SQLITE_JS_STACK_MARGIN (256 KB), for the native code that runs between
two of QuickJS's checks, such as SQLite when JavaScript runs SQL
through db.exec. js_set_max_stack_size() now accepts an integer up to
what the stack allows, and reports the largest size in its error
message; elsewhere it allows up to the default. When the extension is
loaded, the default is lowered to what the loading thread's stack
allows. The stack position is read the way QuickJS reads it, because
under AddressSanitizer a local variable lives on a separate stack.

0 still turns the check off, as the 1.3.7 changelog documents for a
connection used from several threads, and test_thread relies on.

Add a Stack size test: endless recursion fails at the default, invalid
sizes are errors, and endless recursion, also through db.exec, fails
cleanly just below the largest size allowed and at a smaller one. It
fails without this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw
Whether an SQL error in db.exec() reaches next() as false, as now, or
as an exception, as a separate pull request proposes, the recursion
ends with the same "stopped" error, so the test passes either way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw
QuickJS measures the stack from the top it recorded on the thread that
created the runtime. A connection used on another thread, as in an
app's connection pool, failed at once with "Maximum call stack size
exceeded", or code that called itself without end was never stopped and
crashed the process; js_set_max_stack_size(0) was the workaround.

Each call into JavaScript from SQLite now calls JS_UpdateStackTop() for
its thread and keeps the size within what that thread's stack has left.
Nested calls (JavaScript running SQL that runs JavaScript) keep the
outer limit. Each thread's stack bounds are found once and cached in a
thread-local variable, since on Linux finding the main thread's stack
reads /proc/self/maps.
@marcobambini

Copy link
Copy Markdown
Member

Merged into main as part of a review of #11–#19 together, with one fix to the test (8820e1c).

Verified on macOS/arm64, all three scenarios, with js_create_scalar-defined recursive functions:

connection 100 levels deep endless recursion still usable after
opened on main, used on another thread OK stopped with an error OK
opened on main, used on a 512 KB thread OK stopped with an error OK
opened on another thread, used on main OK stopped with an error OK

And it is required: with js_enter neutered, the suite kills the process (exit 138). Clean under ASan + UBSan, no new warnings on either arch.

I checked the depth bookkeeping at every call site, since an unbalanced js_enter/js_leave would silently pin the limit to the wrong thread. All balanced — the early returns in js_execute_value and js_execute_inverse sit before js_enter, and restructuring js_execute_step so the js_setup_aggregate failure path no longer returns early is exactly what that needed. Caching the stack bounds in a thread-local is sound, since a thread's stack does not move, and thread_low != 0 is a safe sentinel in practice.

One fix needed on merge: the two worker threads relied on the platform's default stack size and on the frame sizes of an optimized build. A default pthread stack is 8 MB on Linux but 512 KB on macOS, which leaves 100 levels very little room once the 256 KB margin is kept free — so under ASan, whose frames are larger, SELECT deep(100) failed. Both threads now ask for a stack explicitly: 1 MB for the first, and 768 KB for the one that still exercises lowering the size to fit, since that is still under JS_DEFAULT_STACK_SIZE. The product behaviour was correct throughout — it reported a clean error rather than crashing — it was only the test's headroom that was too thin.

On your closing note: you are right that a connection driven from Android also needs a way to stop runaway JavaScript, since SQLite never calls the progress handler while a function runs. #11 gives you sqlite3_interrupt(), which does reach JavaScript now; if that is not enough for Room's cancellation path, open an issue and let's look at it.

Thanks — this and #17 together make the stack check actually mean something on a connection pool.

@davidschachterADFA

Copy link
Copy Markdown
Contributor Author

Thank you for verifying all three cases and for the test fix.

On cancellation from Android: sqlite3_interrupt() isn't reachable on that path. The SQLite wrapper Room uses here, requery's sqlite-android (like the framework's), cancels a query by setting a flag that its progress handler returns (nativeCancel in android_database_SQLiteConnection.cpp), never calls sqlite3_interrupt(), and doesn't give the app the native handle to call it with. So our package carries one more patch, sqlitejs_cancel_all(), which stops the JavaScript running at that moment in every connection of the process and interrupts those connections. We'd be glad to open an issue with the details and the patch if you'd like to look at it.

This reply originated with AI: Claude, Anthropic's AI model, wrote it for App Dev For All. Contact: [email protected]

marcobambini added a commit that referenced this pull request Nov 12, 2026
Nine PRs landed since 1.3.7 (#11 through #19) and none of it was released or
recorded in the changelog. Bump SQLITE_JS_VERSION and write the entry.

Every claim was checked against a build of 1.3.7 rather than taken from the PR
descriptions, which corrected four of them:

- js_set_max_stack_size() already existed in 1.3.7, so what changed is that it
  now rejects a size larger than the calling thread's stack, not the function.
- Whole numbers were not simply REAL before. 1.3.7 branched on the value's tag
  in the engine, JS_TAG_INT, not on the value, so a function returning its REAL
  argument gave back 3.0 while one computing 6 / 2 gave the integer 3. The entry
  describes that inconsistency instead of a blanket "REAL became INTEGER".
- The BLOB work covers more than results: a typed array passed to db.exec() used
  to bind NULL, and a function could not return the BLOB it was handed, since a
  BLOB argument arrives as an ArrayBuffer and returning it produced NULL.
- A buffer whose bytes cannot be read, detached or resized out of its view, used
  to bind NULL and report success. That is a 1.3.7 bug, so it is under Fixed.

The memory limit is listed as a breaking change, not only as a feature. 1.3.7
had no limit, so SQL that allocates more than the new 64 MB default now fails
with "out of memory"; it is the change most likely to stop working queries, and
the entry gives both ways back (js_set_memory_limit(0) and the build flag), each
verified.

Package.swift is left alone, since the release job rewrites its URL and checksum
once the assets exist.

Co-Authored-By: Claude Opus 5 <[email protected]>
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.

2 participants