Skip to content

Fix memory lifetime bug in async array parameter handling for JS API - #8125

Merged
Nikolaj Bjorner (NikolajBjorner) merged 5 commits into
masterfrom
copilot/fix-assumption-extraction-bug
Jan 9, 2026
Merged

Nikolaj Bjorner (NikolajBjorner) merged 5 commits into
masterfrom
copilot/fix-assumption-extraction-bug

Conversation

Copilot AI commented Jan 8, 2026 •

Copy link
Copy Markdown
Contributor

Async functions with array parameters (e.g., solver.check() with assumptions) crashed due to use-after-free. Emscripten's ccall with 'array' type frees temporary memory immediately after the wrapper returns, but async wrappers spawn threads that access this memory later.

// This would crash with assertion violation in ast.cpp
const result = await solver.check(x.not(), y.not(), z.not());

Changes

TypeScript wrapper generation (make-ts-wrapper.ts)

  • Manually allocate persistent memory via Mod._malloc for async array parameters
  • Pass pointer as number instead of using ccall's automatic array handling
  • Free in finally block after async completion

C++ wrapper generation (make-cc-wrapper.ts)

  • Generate custom wrappers for async functions with array parameters
  • Allocate array copies with malloc/memcpy before thread spawn
  • Free copies after thread completion
  • Add null checks for allocation failures

Test coverage (high-level.test.ts)

  • Added test exercising solver.check() with multiple assumptions
  • Verifies unsat result and unsat core retrieval

API completion (types.ts and high-level.ts)

  • Added unsatCore() method to Solver class to retrieve unsat cores
  • Returns AstVector<Name, Bool<Name>> containing the Boolean expressions in the unsat core

Affects Z3_solver_check_assumptions and Z3_optimize_check.

Custom agent used: debug-agentic-workflow
Debug and refine agentic workflows using gh-aw CLI tools - analyze logs, audit runs, and improve workflow performance

Original prompt

This ts code crashes:

  async check(...exprs: (Bool<Name> | AstVector<Name, Bool<Name>>)[]): Promise<CheckSatResult> {
    const assumptions = _flattenArgs(exprs).map(expr => {
      _assertContext(expr);
      return expr.ast;
    });
    const result = await asyncMutex.runExclusive(() =>
      check(Z3.solver_check_assumptions(contextPtr, this.ptr, assumptions)),
    );

The test

const { Solver, Bool } = api.Context('main');
const solver = new Solver();
solver.set('unsat_core', true);
const x = Bool.const('x');
const y = Bool.const('y');
const z = Bool.const('z');

  // Add conflicting assertions
  solver.add(x.or(y));
  solver.add(x.or(z));

  // Check with assumptions that create a conflict
  const result = await solver.check(x.not(), y.not(), z.not());

causes an assertion violation in ast.cpp

There is probably a bug in how assumptions are extracted into a format that can be passed to the Z3_solver_check_assumptions function.

Custom agent used: debug-agentic-workflow
Debug and refine agentic workflows using gh-aw CLI tools - analyze logs, audit runs, and improve workflow performance


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Copilot AI and others added 3 commits January 8, 2026 23:15
Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>
Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>
Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix bug in assumption extraction for solver check Fix memory lifetime bug in async array parameter handling for JS API Jan 8, 2026
@NikolajBjorner

Copy link
Copy Markdown
Contributor

Kevin Gibbons (@bakkot) - FYI, copilot suggests that there is a life-time issue with the async functions and array parameters.

This is the bug! The async wrapper needs to handle array parameters specially to ensure the memory stays alive until the thread completes.

Let me verify this theory by checking if mk_and or mk_or are async:

View src/api/js/scripts/async-fns.ts
Perfect! Z3_solver_check_assumptions IS async (line 8), but Z3_mk_and and Z3_mk_or are NOT in this list, so they work fine!

Now I've found the root cause: The async wrapper doesn't handle array parameters correctly - it lets emscripten free the temporary memory before the async thread actually uses it.

arrayCopyNames.push(copyName);

// Allocate and copy with null check
arrayCopies.push(`${ptrType} ${copyName} = (${ptrType})malloc(sizeof(${p.cType}) * ${sizeParam.name});`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: as a matter of style, just use a single multiline template literal here rather than pushing individual lines to this array.

@bakkot

Copy link
Copy Markdown
Contributor

Sounds totally plausible.

@NikolajBjorner

Copy link
Copy Markdown
Contributor

Sounds totally plausible.

though, the current "fix" by copilot looks fishy. Can't we just call the _flatten functionality within the closure used by the async?

@NikolajBjorner

Copy link
Copy Markdown
Contributor

Copilot - could you instead use code like this to deal with the issue?

            const result = await asyncMutex.runExclusive(() => { 
                const assumptions = _flattenArgs(exprs).map(expr => {
                    _assertContext(expr);
                    return expr.ast;
                });
                check(Z3.solver_check_assumptions(contextPtr, this.ptr, assumptions));
            });
            
            ```

Copilot AI commented Jan 8, 2026

Copy link
Copy Markdown
Contributor Author

Copilot - could you instead use code like this to deal with the issue?

...

I want to make sure I understand your suggestion correctly.

The current high-level code creates the assumptions array outside asyncMutex.runExclusive():

const assumptions = _flattenArgs(exprs).map(expr => expr.ast);
const result = await asyncMutex.runExclusive(() =>
  check(Z3.solver_check_assumptions(contextPtr, this.ptr, assumptions))
);

Your suggestion moves it inside:

const result = await asyncMutex.runExclusive(() => { 
  const assumptions = _flattenArgs(exprs).map(expr => expr.ast);
  return check(Z3.solver_check_assumptions(contextPtr, this.ptr, assumptions));
});

However, I believe the memory issue occurs at a lower level in the generated wrapper. The problem is that Z3.solver_check_assumptions() uses emscripten's ccall with 'array' type, which allocates temporary memory, calls the C++ wrapper (which spawns a thread), then immediately frees the memory before the thread accesses it.

Moving the array creation inside asyncMutex.runExclusive() keeps it in JavaScript scope longer, but doesn't affect emscripten's heap memory management.

Could you clarify what you're suggesting? Are you proposing:

  1. Just moving the array creation as shown (and this would somehow fix the emscripten issue)?
  2. A different approach to avoid the async wrapper altogether?
  3. Something else I'm missing?

I want to make sure I implement the right solution!

@NikolajBjorner

Copy link
Copy Markdown
Contributor

Copilot OK got it

@bakkot

Copy link
Copy Markdown
Contributor

Test failure says it's trying to use unsatCore on Solver in the high-level API which is not implemented. Would presumably be completely trivial to add matching the Python implementation.

It's been a while since I touched this code but the explanation and fix sound right to me; if there's a test which fails before this fix and passes after, and there's no obvious leaks (I don't see any) I think it's probably good.

@NikolajBjorner

Copy link
Copy Markdown
Contributor

Copilot - add the missing method to extract unsatCore to Solver to fix failing build of js bindings

Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>

Copilot AI commented Jan 9, 2026

Copy link
Copy Markdown
Contributor Author

Copilot - add the missing method to extract unsatCore to Solver to fix failing build of js bindings

Added unsatCore() method to Solver class in commit e067c6e. The method calls Z3.solver_get_unsat_core() and returns AstVector<Name, Bool<Name>>.

@NikolajBjorner
Nikolaj Bjorner (NikolajBjorner) merged commit 7a35caa into master Jan 9, 2026
30 of 43 checks passed
@nunoplopes
Nuno Lopes (nunoplopes) deleted the copilot/fix-assumption-extraction-bug branch January 13, 2026 09:18
Nikolaj Bjorner (NikolajBjorner) added a commit that referenced this pull request Feb 19, 2026
…8125)

* Initial plan

* Fix async array parameter handling in JS API wrappers

Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>

* Add test for solver.check() with assumptions

Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>

* Address code review feedback: add null checks and improve readability

Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>

* Add unsatCore() method to Solver class

Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com>
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