Repository navigation
Do not let a db.exec result set outlive the call that created it - #26
Merged
Merged
Conversation
A result set holds a statement that is still running, which caused two bugs, one of them a crash. Dropping a result set partway through a query that computes a JavaScript window function freed memory still in use. The statement still held the function's state, so sqlite3_finalize() ran its final, which is JavaScript, from inside js_rowset_finalizer: that is, from inside QuickJS's free_object or its cycle collector, where JavaScript must not run. When that final allocated, it could start a collection that freed the very object being freed. In the sqlite3 shell this ended with "double free or corruption" or with SIGSEGV; 60 iterations are enough without a sanitizer, 20 under AddressSanitizer, which reports a heap use after free in free_object or, for a result set that is cyclic garbage, in JS_FreeValueRT. Reported as issue #25, with the diagnosis this follows. A result set that JavaScript kept, in a global say, leaked the whole connection. Its statement stayed open, so sqlite3_close() returned SQLITE_BUSY and never closed the connection, and sqlite3_close_v2() left it a zombie for good: only closing frees the JavaScript runtime, and only freeing the runtime frees the result set that holds the statement. About 63 KB of SQLite memory per connection, plus the runtime's own. A statement that is not busy holds no aggregate or window state, so finalizing it from the finalizer cannot come back into JavaScript and still happens there. A busy one is left listed and ended from js_end_rowsets(), which runs where JavaScript may run: when the call into JavaScript returns, and at the top of db.exec, which a loop that drops one on every turn passes through -- waiting only for the call to return let 2,000 statements pile up until the loop ran out of memory. js_end_rowsets() now also ends every result set still open when the call returns, not only on an interrupted connection, so none outlives its call and nothing keeps the connection from closing. **This changes behavior**: reading a result set after the call into JavaScript that created it has returned now throws, where it reported the end of its rows. Keeping one across calls never worked as it looked: it held a read transaction open, kept an interrupt in effect, and leaked the connection. next(), toArray(), get() and name() all say so, and an interrupted one still says "interrupted", as it has since #24. Test: a new *Result set lifetime* test drops a result set computing a window function 200 times, by reference count and as a cycle, then keeps one in a global and checks that the four reads throw, that a result set read to its end still reports the end of its rows, and that sqlite3_close() then closes the connection. On main it crashes the process. The suite passes 16 of 16 on macOS arm64, and on Linux glibc and musl, arm64 and x86_64, and under AddressSanitizer and UndefinedBehaviorSanitizer. Co-Authored-By: Claude Opus 5 <[email protected]>
deep(100) does not fit the small thread stacks of that test under AddressSanitizer: a level of JavaScript recursion takes about 1.5 KB of native stack in an ordinary build, where 100 levels fit easily in the 512 KB a 768 KB thread leaves after SQLITE_JS_STACK_MARGIN, but several times that under a sanitizer. The stack check then stopped deep() with "Maximum call stack size exceeded" and the test failed where nothing was wrong: on Linux glibc and musl, x86_64 and arm64, the suite has been 15 of 16 under AddressSanitizer while passing 16 of 16 without it, which hides any real sanitizer finding in that test. The depth is now 32 under a sanitizer and 100 otherwise; 50 still fit, so 32 leaves room. __has_feature cannot be tested in the same #if that checks for it, since GCC before 14 does not have it at all and rejects the line, so the test is nested. The suite now passes 16 of 16 under AddressSanitizer and UndefinedBehaviorSanitizer as well. Co-Authored-By: Claude Opus 5 <[email protected]>
An Unreleased section for the four fixes that have landed since 1.4.1 and are not yet recorded: the two garbage collection cases of #23, the interrupted result sets of #24, and the two result set bugs of this branch, one of which changes behavior and so has an entry under Changed as well. The project has written its entries at release time so far, so the section is named the way Keep a Changelog, which this file follows, names one; rename it when the version is bumped. The README gains the rule that a result set does not outlive the call into JavaScript that created it, under Running SQL from JavaScript, which the Interrupting JavaScript section now points at instead of stating its own version of it; and js_set_memory_limit() now lists the three moments garbage is collected, where it named two of them. Co-Authored-By: Claude Opus 5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
A
db.exec()result set holds a statement that is still running, which caused two bugs: one crashes the process, the other leaks the whole connection. Both come from the same place, and fixing one without the other leaves the suite's memory check failing, so they are one commit.A result set dropped partway through a window function crashed the process
Dropping a result set that is partway through a query computing a JavaScript window function freed memory still in use. The statement still held the function's state, so
sqlite3_finalize()ran itsfinal, which is JavaScript, from insidejs_rowset_finalizer— that is, from inside QuickJS'sfree_objector its cycle collector, where JavaScript must not run. When thatfinalallocated, it could start a collection that freed the very object being freed.In the
sqlite3shell this ends withdouble free or corruptionor with SIGSEGV. 60 turns of a loop are enough without a sanitizer, 20 under AddressSanitizer, which reports a heap use after free infree_object, or inJS_FreeValueRTfor a result set that is cyclic garbage and so is freed by the collector rather than by the reference count. Reported as issue #25, whose diagnosis this follows.Only a busy statement holds aggregate or window state:
sqlite3_stmt_busy()was true in every failing case, and a result set read to its end reaches the finalizer with no statement at all. One that is not busy is still finalized in the finalizer, where it cannot come back into JavaScript. A busy one is left listed and ended fromjs_end_rowsets(), which runs where JavaScript may run: when the call into JavaScript returns, and at the top ofdb.exec. That second point matters — waiting only for the call to return let 2,000 statements pile up until the issue's own 20,000-iteration reproducer ran out of memory, since the whole loop is inside onejs_eval.A result set kept in a global leaked the connection
Its statement stayed open, so
sqlite3_close()returned SQLITE_BUSY and never closed the connection, andsqlite3_close_v2()left it a zombie for good: only closing frees the JavaScript runtime, and only freeing the runtime frees the result set that holds the statement. About 63 KB of SQLite memory went with each connection, plus the runtime's own. Measured before and after:js_end_rowsets()now ends every result set still open when the call into JavaScript returns, not only on an interrupted connection, so none outlives its call and nothing keeps a connection from closing.This changes behavior
Reading a result set after the call into JavaScript that created it has returned now throws, where
next()reported the end of its rows andtoArray()returned an empty array. Keeping one across calls never worked as it looked: it held a read transaction open, kept an interrupt in effect until the connection closed, and leaked the connection.next(),toArray(),get()andname()all say so, and an interrupted one still says "interrupted", as it has since #24. The CHANGELOG has it under Changed and the README states the rule under Running SQL from JavaScript.Also here
deep(100)does not fit that test's small thread stacks under AddressSanitizer, where a level of JavaScript recursion takes several times the 1.5 KB it takes otherwise, so the stack check stoppeddeep()and the test failed where nothing was wrong: on Linux the suite has been 15 of 16 under ASan while passing without it, which hides any real sanitizer finding in that test. The depth is 32 under a sanitizer and 100 otherwise.[Unreleased]CHANGELOG section for the four fixes landed since 1.4.1 and not yet recorded: the two garbage collection cases of Collect garbage after any out-of-memory error and on any new limit #23, the interrupted result sets of End the result sets an interrupt leaves open #24, and the two here. The project has written its entries at release time, so rename the section when the version is bumped.Testing
A new Result set lifetime test drops a result set computing a window function 200 times, by reference count and as a cycle, then keeps one in a global and checks that all four reads throw, that a result set read to its end still reports the end of its rows, and that
sqlite3_close()then closes the connection. Onmainit crashes the process (exit 139).Plus the issue's reproducer at 20,000 iterations and a 10-case matrix of ways to drop a result set, both clean under ASan and in a plain build with
MALLOC_PERTURB_; no leaks under ASan leak detection; no new warnings on gcc, clang or mingw-w64.Not fixed here: on musl x86_64 the suite crashes in the deliberate out-of-memory part of the Memory limit test, on 1.4.1 unchanged and with these fixes alike. It is not a stack problem (a 64 MB stack does not help) and it does not reproduce with that statement in isolation, so it depends on the allocator's state; it belongs to QuickJS's out-of-memory handling. Seen only under x86_64 emulation on Apple silicon, so it wants confirming on real hardware.
🤖 Generated with Claude Code