Skip to content

Limit the memory of the JavaScript runtime - #12

Merged
marcobambini merged 4 commits into
sqliteai:mainfrom
davidschachterADFA:limit-javascript-memory
Nov 12, 2026
Merged

marcobambini merged 4 commits into
sqliteai:mainfrom
davidschachterADFA:limit-javascript-memory

Conversation

@davidschachterADFA

@davidschachterADFA davidschachterADFA commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

The JavaScript runtime has no memory limit (the JS_SetMemoryLimit call is commented out), so code that keeps allocating takes all the memory of the process. On a phone, the operating system then kills the process, and in an app that is the app.

This sets a default limit of 64 MB per connection and adds js_set_memory_limit(bytes) to change it at run time; 0 means no limit, as in JS_SetMemoryLimit(). -DSQLITE_JS_DEFAULT_MEMORY_LIMIT=bytes changes the default at build time, and 0 there keeps today's behavior, if you prefer that default. Code that needs more fails with an "out of memory" error, and the connection stays usable. A QuickJS context takes about 54 KB, so 64 MB leaves room for over a thousand aggregate contexts at once. The README documents the function.

QuickJS cannot always recover from running out of memory while it creates a context: it can crash. So the limit is set once the connection's context exists, and the context of each aggregate or window function, and the trial one that js_create_aggregate() and js_create_window() make, is created with the limit lifted; the limit then applies again to the code that runs in it.

Test: a new Memory limit test covers allocations under and over the default, code that never stops allocating, raising, removing and lowering the limit, and invalid arguments, and it creates and runs an aggregate under small limits and with little memory left, which crashed while QuickJS created the aggregate's context under the limit. make test passes on x86_64 Linux, also under ASan and UBSan.

These are six separate pull requests, #11 to #16, so each can be taken or declined on its own; only #15 depends on another (#14). They add tests at the same places in test/main.c, and #11 and #12 both add code just above globaljs_init(), so those merged later will need a small rebase, which we will do.

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

Update, 2026-11-12. An independent review of this change found two problems, both fixed in 56e82d8:

  • With more than two thirds of the memory limit in use, QuickJS's garbage-collection threshold was past the limit, so cyclic garbage filled it and code that fits failed. The threshold is now kept between the memory in use and the limit.
  • Running out of memory through small allocations reported "Unknown JavaScript exception", because QuickJS throws null when even its error does not fit. It now reports "out of memory".

The fix runs from the interrupt handler that #11 adds, so this PR now includes #11 (merge d70657b). test/main.c passes, also under ASan and UBSan, and its new checks fail without the fix.

davidschachterADFA and others added 2 commits November 10, 2026 22:29
The JavaScript runtime had no memory limit (the JS_SetMemoryLimit call
was commented out), so code that keeps allocating took all the memory of
the process. On a phone that ends with the operating system killing the
process, which in an app takes the app down with it.

Set a default limit of 64 MB per connection, which SQLITE_JS_DEFAULT_
MEMORY_LIMIT changes at build time, and add js_set_memory_limit(bytes)
to change it at run time; 0 means no limit, as in JS_SetMemoryLimit().
Code that needs more fails with an "out of memory" error, and the
connection stays usable. A QuickJS context takes about 54 KB, so the
default leaves room for over a thousand aggregate contexts at once.

QuickJS cannot always recover from running out of memory while it
creates a context: it can crash. So the limit is set once the
connection's context exists, and the context of each aggregate or
window function, and the trial one that js_create_aggregate() and
js_create_window() make, is created with the limit lifted; the limit
then applies again to the code that runs in it.

Add a Memory limit test: allocations under and over the default, code
that never stops allocating, raising, removing and lowering the limit,
and invalid arguments. It also creates and runs an aggregate under
small limits and with little memory left, which crashed while QuickJS
created its context under the limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw
JavaScript runs inside the SQL statement that calls it, but QuickJS had
no interrupt handler, so sqlite3_interrupt() could not stop code that
never returns to SQLite. `SELECT js_eval('while (true) {}')` hung the
sqlite3 shell, where Ctrl-C calls sqlite3_interrupt(), and an app could
not cancel the query.

Install a QuickJS interrupt handler that reports the connection's
sqlite3_is_interrupted(). QuickJS then stops the code with an
uncatchable "interrupted" error, and the statement fails as interrupted.
sqlite3_is_interrupted() is new in SQLite 3.41.0, so the handler is only
installed when the library is at least that version.

Add an Interrupt test that interrupts endless loops in js_eval() and in a
scalar function from another thread, and checks that the connection
still works afterwards.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw
davidschachterADFA and others added 2 commits November 11, 2026 18:47
…t-memory

The next commit keeps garbage collection working near the memory limit
from the interrupt handler that sqliteai#11 adds, so this PR now includes sqliteai#11.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw
From an independent review of this PR:

QuickJS collects cyclic garbage only when its memory use passes a
threshold, which it resets after each collection to 1.5 times the
memory still in use. With more than two thirds of the limit in use the
threshold was past the limit, so garbage filled the rest and code that
fits failed. The interrupt handler, js_set_memory_limit() and each
aggregate's setup now lower it, after a collection, to halfway between
the memory in use and the limit.

When the limit leaves no room even for the "out of memory" error,
QuickJS throws null, which reported "Unknown JavaScript exception". The
runtime now allocates through functions that count its memory as QuickJS
does, and a null exception after the memory in use reached the limit
reports "out of memory". JavaScript that catches it still receives
null; the README says so.

The Memory limit test adds: with 12 of 16 MB held, code that makes many
times the free memory in cyclic garbage runs, and so does an aggregate
over 300 groups; running out of memory through small allocations
reports "out of memory". Both fail without these changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw
marcobambini added a commit that referenced this pull request Nov 12, 2026
… in use

PR #12 left a connection permanently out of memory: QuickJS refuses every
allocation while its memory in use is over the limit, and it collects only
when it creates an object, which it cannot do without allocating. Lowering
the limit under memory that is garbage therefore killed the connection for
good, even for js_eval('1 + 1').

Collect at the two safe points where no JavaScript is running: as the limit
changes, and after an error that reached the limit.

The 'garbage is still collected' check also ran on a connection whose earlier
out-of-memory statements had left megabytes reachable, with 4 MB of headroom;
how much an object costs is up to the platform's allocator, which rounds up by
more once the heap is warm, so it failed on macOS/arm64. It now runs on a
connection of its own, scaled to 48 of 64 MB, keeping the ratio it tests.
@marcobambini
marcobambini merged commit 9c9e53e into sqliteai:main Nov 12, 2026
@marcobambini

Copy link
Copy Markdown
Member

Merged into main as part of a review of #11–#19 together — with two fixes on top (ef06558), because this one did not hold up on macOS/arm64. Details below, since both are worth understanding.

First, the parts that are right: I checked the accounting against QuickJS's internals and it mirrors them exactly. JS_MEM_OVERHEAD matches MALLOC_OVERHEAD (0 on Apple, 8 elsewhere, libs/quickjs.c:8637), JSMallocFunctions' field order matches, used = threshold / 3 * 2 correctly inverts malloc_gc_threshold = malloc_size * 1.5 (libs/quickjs.c:11787), and malloc_limit == 0 really does mean unlimited because malloc_limit - 1 wraps to SIZE_MAX. Creating aggregate contexts with the limit lifted is also well judged.

1. A connection could be left permanently out of memory

QuickJS refuses every allocation while its memory in use is over the limit, and it triggers a collection only from JS_NewObjectFromShape — which cannot run without allocating. That is a deadlock with no way out. Lowering the limit under memory that is pure garbage therefore killed the connection for good:

SELECT js_set_memory_limit(0);
SELECT js_eval('globalThis.g = []; for (let i = 0; i < 200000; i++) { const o = {}; o.o = o; g.push(o); } g.length');
SELECT js_eval('delete globalThis.g; 0');   -- all of it is garbage now
SELECT js_set_memory_limit(4 * 1024 * 1024);
SELECT js_eval('1 + 1');                    -- out of memory, and never recovers

Every statement after that fails, js_eval('1 + 1') included, which contradicts "the connection stays usable". I traced it to confirm: JS_RunGC would have freed all of it.

The fix collects at the two points where no JavaScript is running and a collection is safe — as the limit changes, and after an error that reached the limit — then puts the threshold back under the new limit. There is a new regression test for exactly the sequence above; it fails without the fix.

I also documented the case that remains, because it is inherent rather than a bug: if the memory over the limit is live (a large value held in a global), nothing can be allocated until the limit is raised again. Raising it does fully revive the connection, so there is a way out.

2. The "garbage is still collected" check was not portable

It ran on a connection whose earlier out-of-memory statements had left several megabytes reachable, leaving about 4 MB of the 16 MB limit free. How much an object costs is up to the platform's allocator, and macOS rounds up more once the process heap is warm — so it failed here while passing on glibc. I reproduced it outside the test binary to be sure it was the allocator and not the test harness.

It now runs on a connection of its own and is scaled to 48 of 64 MB, which keeps the 3:4 ratio the check is actually about. I confirmed it still fails with the threshold clamp disabled, so it has not been weakened into a no-op.

Neither of these is a criticism of the design — the feature is valuable and the implementation is unusually careful about QuickJS's internals. They are just the kind of thing only a second allocator shakes out. Thanks for a genuinely useful change.

@davidschachterADFA

Copy link
Copy Markdown
Contributor Author

Thank you for finding and fixing both. We reproduced the first with the code our package ships (built for x86_64 Linux): after your sequence, js_eval('1 + 1') and every later statement fail with "out of memory" until the limit is raised again. We'll take ef06558 into that package.

This reply originated with AI: Claude, Anthropic's AI model, wrote it for App Dev For All. Contact: [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