Collecting WeakMap keys requires multiple GC passes

Open
#581 2 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 5 days

@jluxenberg is already working on this.

Since Oct 27, 2026.

  • #582 by @jluxenberg — open

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
48/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
c

Research direction

Start with the attached weakmap_gc_repro.c and run it using the build commands in the issue to confirm both cases. Then trace QuickJS's WeakMap and weak-reference handling in the GC; the issue does not name source files or tests, so locate the relevant code and existing GC tests. Done means the self-referencing key is collected and the chain of keys is freed after a fixed number of GC passes.

Written by the indexing model from the issue text.

Description

Issue

I think I've found two bugs related to weak references / WeakMap handling by the GC.

(1) An entry whose value references its own key is never collected while the WeakMap is alive.
/* Case 1: the value references its own key. */
(function () {
  var key = {};
  map.set(key, { backRef: key });
  globalThis.selfRef = new WeakRef(key);
})();

Expected result:

  • key is collected after one pass of the GC

Actual result:

  • key is never collected by the GC but should be collected on the first pass.
(2) A chain of entries (each value references the next entry's key) takes n JS_RunGC() calls to free
/* Case 2: a chain of 20 entries; each value references the next key. */
(function () {
  var key = {};
  for (var i = 0; i < 20; i++) {
    var next = {};
    map.set(key, { child: next });
    key = next;
  }
  globalThis.chainTail = new WeakRef(key);
})();

Expected result:

  • All 20 keys is collected after a fixed number (ideally one) passes of the GC.

Actual result:

  • Collecting n keys appears to require n passes of the GC.
Repro

Here's a program that reproduces the issue. Compile it like this:

quickjs $ make libquickjs.a
quickjs $ cc -O2 -I. weakmap_gc_repro.c libquickjs.a -lm -lpthread -o weakmap_gc_repro
quickjs $ ./weakmap_gc_repro

weakmap_gc_repro.c

Dominant language
C
Stars
11.1k
Forks
1.2k
PR merge metrics
No merged PRs in 30d

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from bellard/quickjs

All issues in bellard/quickjs

Similar issues

More C issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.