Skip to content

Bun.CookieMap: validate before mutating in delete(), accept any existing key, O(1) lookup - #35918

Closed
robobun wants to merge 5 commits into
mainfrom
farm/f0d4948f/cookiemap-validate-hash-index
Closed

robobun wants to merge 5 commits into
mainfrom
farm/f0d4948f/cookiemap-validate-hash-index

Conversation

@robobun

@robobun robobun commented Jul 26, 2026 •

Copy link
Copy Markdown
Collaborator

Three related Bun.CookieMap fixes.

delete() mutated before it validated

const m = new Bun.CookieMap("session=tok; other=1");
try { m.delete("session", { path: "/;bad" }); } catch {}
m.has("session");          // false  (entry already evicted)
m.toSetCookieHeaders();    // []     (no deletion header queued)

CookieMap::remove() called removeInternal(name) before Cookie::create(name, "", domain, path, ...), which is where name/path/domain are validated. A throwing delete() had therefore already evicted the entry without queuing the Set-Cookie tombstone, leaving the server-side map and the client out of sync. set() with the same invalid options threw without mutating, so only delete() was torn.

remove() now validates path and domain up front and returns the exception before any mutation.

delete() rejected names the Cookie-header parser accepted

const m = new Bun.CookieMap("a b=1; ok=2");
m.get("a b");              // "1"
m.delete("a b");           // threw "Invalid cookie name", entry already evicted

The Cookie-header parser accepts names (spaces, CTLs, DEL, 0x80-0xFF) that isValidCookieName (the Set-Cookie emission grammar) rejects. Such cookies were readable via get()/has() but could never be deleted, and the throwing delete() still half-evicted them.

remove() now evicts by name unconditionally (removal is not creation), and queues a Set-Cookie tombstone only when the name is emittable. set() and new Bun.Cookie() keep the strict name validator unchanged. No parser change.

O(n) get/has/set/delete

const m = new Bun.CookieMap();
for (let i = 0; i < 20000; i++) m.set("c" + i, "v");
for (let i = 0; i < 20000; i++) m.get("c" + i);
for (let i = 0; i < 20000; i++) m.delete("c" + i);
// before: ~10900 ms release; after: 21 ms release

get()/has()/set()/delete() each scanned the backing vectors linearly (findIf / removeAllMatching), so a loop over N cookies was O(n^2). Both vectors are now indexed by a HashMap<String, ...> keyed on the cookie name. Originals are tombstoned in place (null key) so indices stay valid; set()/remove() reuse an existing m_modifiedCookies slot for the same name rather than appending, so repeated writes to one key do not grow the vector. The m_originalCookies index maps to a Vector<size_t> because a Cookie header may legally repeat a name: get() returns the first, delete() evicts all.

The iterator now tracks separate cursors for the modified and original vectors, so delete() during iteration no longer skips half the entries. The two iterator > delete in a loop tests now end at size === 0 (matching Map/Set), as the test comment had already asked for. Re-writing a name keeps its first-write position in toSetCookieHeaders() instead of moving to the end; two snapshots are updated accordingly.

Dead CookieMap::getAll() and the unused Vector<Ref<Cookie>> constructor are removed.

Supersedes #35908.

Verification

New tests in test/js/bun/cookie/cookie-map.test.ts cover each face (invalid path/domain on both parsed and set() entries; deleting unwritable names across space/CTL/DEL/non-ASCII; duplicate-name Cookie header; correctness over 2000 keys; repeated same-key writes staying at one Set-Cookie header; iteration/toJSON/toSetCookieHeaders with mid-sequence removals). test/js/bun/cookie/cookie.test.ts is updated for the new delete-by-name policy and header order.

Without src/ changes the new/updated tests fail; with them the full test/js/bun/cookie/ suite (178 tests) and the Bun.serve/bake cookie tests pass.

…O(1) lookup

CookieMap::remove() evicted the entry before building the Set-Cookie
tombstone, so a delete() that threw on an invalid path/domain/name had
already removed the cookie from the map without queuing a deletion
header. The Cookie-header parser also accepts names (spaces, CTLs,
0x80-0xFF) that isValidCookieName rejects, so such cookies were
readable but never deletable.

remove() now validates path/domain first and returns before any
mutation if either is invalid. It then evicts unconditionally and
queues a Set-Cookie tombstone only when the name satisfies the
emission grammar; set() and new Bun.Cookie() keep the strict name
validator.

get()/has()/set()/delete() were O(n) linear scans over the two backing
vectors, so a loop over N cookies was O(n^2). Both vectors are now
indexed by a HashMap<String, ...> keyed on the cookie name;
removeInternal() tombstones in place (null key / null RefPtr) so
indices stay valid, and readers skip tombstones. The iterator uses
separate cursors for the two vectors, so deleting during iteration no
longer skips entries.

Dead CookieMap::getAll() and the unused Vector<Ref<Cookie>>
constructor are removed.
@coderabbitai

coderabbitai Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 59ed19ab-2a1b-4e3a-aee1-ea1f016f6322

📥 Commits

Reviewing files that changed from the base of the PR and between 06231f2 and 26ed941.

📒 Files selected for processing (2)
  • src/jsc/bindings/CookieMap.cpp
  • test/js/bun/cookie/cookie-map.test.ts

Walkthrough

Changes

CookieMap now uses separate original and modified indices for lookup, mutation, iteration, serialization, cloning, and tombstone handling. Tests cover deletion validation, invalid names, duplicate cookies, iterator cleanup, and Set-Cookie output ordering.

CookieMap indexed storage

Layer / File(s) Summary
Indexed lookup and mutation
src/jsc/bindings/CookieMap.cpp, src/jsc/bindings/CookieMap.h
Original and modified cookies use separate indices; get, set, and remove handle updates, deletions, and tombstones through indexed storage.
Indexed cloning and views
src/jsc/bindings/CookieMap.cpp, src/jsc/bindings/CookieMap.h
Clone, size, JSON serialization, change retrieval, memory accounting, and iteration reflect null and empty modified entries.
Deletion and indexed behavior tests
test/js/bun/cookie/cookie-map.test.ts, test/js/bun/cookie/cookie.test.ts
Tests cover deletion validation, invalid names, iterator deletion, duplicate names, repeated updates, tombstones, and header ordering.

Possibly related PRs

  • oven-sh/bun#35909: Both PRs rework CookieMap indexing, lookup, iteration, and deletion handling.

Suggested reviewers: jarred-sumner

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main CookieMap delete-validation and O(1) lookup changes.
Description check ✅ Passed The description covers what the PR does and how it was verified, matching the template's intent.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Comment @coderabbitai help to get the list of available commands.

@robobun

robobun commented Jul 26, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 9:04 AM PT - Jul 26th, 2026

❌ @robobun, your commit 26ed941 has 1 failures in Build #82385 (All Failures):

  • 📦 Binary size — 12 over 0.50 MB
  • targetthis build canary: main #79916
    sizeΔ
    ❌ bun-darwin-aarch6458.13 MB57.58 MB+564.9 KB
    ❌ bun-darwin-x6463.48 MB62.95 MB+544.5 KB
    ❌ bun-linux-aarch6470.98 MB70.42 MB+576.0 KB
    ❌ bun-linux-x6472.48 MB71.95 MB+544.0 KB
    ❌ bun-linux-aarch64-musl64.88 MB64.32 MB+576.0 KB
    ❌ bun-linux-x64-musl66.98 MB66.45 MB+544.0 KB
    ❌ bun-linux-aarch64-android78.47 MB77.97 MB+512.0 KB
    ❌ bun-linux-x64-android80.62 MB80.10 MB+529.2 KB
    ❌ bun-freebsd-x6483.07 MB82.56 MB+528.0 KB
    ❌ bun-freebsd-aarch6484.84 MB84.31 MB+544.0 KB
    ❌ bun-windows-x6480.26 MB79.70 MB+576.5 KB
    ❌ bun-windows-aarch6470.86 MB70.34 MB+539.5 KB

    Add [skip size check] to the commit message if this increase is intentional.


🧪   To try this PR locally:

bunx bun-pr 35918

That installs a local version of the PR into your bun-35918 executable, so you can run:

bun-35918 --bun

@github-actions

Copy link
Copy Markdown
Contributor

Found 1 issue this PR may fix:

  1. Bun.CookieMap & Bun.Cookie are 1.5x+ slower than pure js libraries #19216 - PR adds O(1) HashMap-based lookup for CookieMap's get()/has()/set()/delete(), directly addressing the reported performance gap vs pure JS cookie libraries

If this is helpful, copy the block below into the PR description to auto-close this issue on merge.

Fixes #19216

🤖 Generated with Claude Code

@robobun

robobun commented Jul 26, 2026

Copy link
Copy Markdown
Collaborator Author

Not linking #19216: that issue benchmarks parse cost on a 3-cookie header (where the C++/JS boundary and percent-decoding dominate). This PR changes lookup scaling at large N; on 3 entries the linear scan was already sub-microsecond.

@github-actions

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. Give Bun.CookieMap a name->index hash so per-key ops are O(1) #35909 - Also adds HashMap-based O(1) lookup for CookieMap per-key operations (get/has/set/delete)

🤖 Generated with Claude Code

@robobun

robobun commented Jul 26, 2026

Copy link
Copy Markdown
Collaborator Author

Overlaps with #35909 on the container change (face 3). Differences:

Happy to fold #35909's compaction in here if preferred.

@claude claude Bot left a comment

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.

Beyond the inline nit, I also checked: the ASSERT(!cookieOr.hasException()) in remove() is sound — Cookie::create(name, value, domain, path, ...) validates only name/path/domain, all three of which are pre-checked above it; getAllChanges() callers (CookieMap__write, toSetCookieHeaders) both just iterate the returned vector, so the switch from returning m_modifiedCookies by value to a filtered copy is safe; and the WTF HashMap<String, ...> null-key hazard is guarded (isNull() early-returns in get()/removeInternal(), and the Cookie-header parser skips empty names before they reach m_originalIndex.add).

Extended reasoning...

This PR bundles a data-structure rewrite (Vector scan → HashMap-indexed vectors with tombstoning, Ref<Cookie> → RefPtr<Cookie>), an iteration-semantics change (delete-in-loop now empties the map), and a user-visible API policy change (delete() on an invalid name now silently succeeds instead of throwing). Each is well-reasoned and well-tested, but together they warrant a human sign-off rather than bot approval. The inline nit about unbounded tombstone growth on repeated same-key writes is minor for the per-request use case but is a real regression relative to the pre-PR compacting behavior.

Comment thread src/jsc/bindings/CookieMap.cpp Resolved
Repeated set()/delete() on one name now overwrites the existing
m_modifiedCookies slot rather than nulling it and appending, so the
vector does not grow with the write count. Re-writing a name keeps its
first-write position in toSetCookieHeaders(); the two affected
snapshots are updated and a regression test covers the bounded case.
Comment thread src/jsc/bindings/CookieMap.cpp Resolved
Comment thread src/jsc/bindings/CookieMap.cpp Resolved
Comment thread src/jsc/bindings/CookieMap.cpp Resolved
Comment thread src/jsc/bindings/CookieMap.h Resolved
Comment thread src/jsc/bindings/CookieMap.h Resolved
Comment thread src/jsc/bindings/CookieMap.h Resolved

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/jsc/bindings/CookieMap.cpp`:
- Around line 136-142: Distinguish deleted-cookie tombstones from legitimate
empty values in CookieMap’s modified-cookie state, replacing value().isEmpty()
checks in get(), has(), size(), toJSON(), and Iterator::next() with the
removed-state predicate so set("x", "") remains readable and serialized. In
src/jsc/bindings/CookieMap.cpp#L136-142, implement the tombstone distinction; in
test/js/bun/cookie/cookie-map.test.ts#L544-553, add hashed-lookup coverage for
an empty-valued set, including when the name exists in parsed originals, and
assert get/has/size/toJSON/toSetCookieHeaders agree.
- Around line 202-218: Update the Cookie::create result handling in the
surrounding cookie mutation method to check hasException() at runtime and return
the contained exception before calling releaseReturnValue(). Keep the existing
ASSERT as optional debug validation, but ensure release builds never release a
value from an exception-holding ExceptionOr.

In `@test/js/bun/cookie/cookie-map.test.ts`:
- Around line 555-565: Update the many-key validation in the
“get()/set()/delete() stay correct over many keys” test to collect the keys
whose retrieved values do not match instead of collapsing comparisons through
the ok accumulator. Assert that the mismatch collection is empty so failures
identify the specific key(s) that regressed.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: b624e7d1-b420-4a91-8ebd-1960d6cb1c35

📥 Commits

Reviewing files that changed from the base of the PR and between 44f6469 and 06231f2.

📒 Files selected for processing (4)
  • src/jsc/bindings/CookieMap.cpp
  • src/jsc/bindings/CookieMap.h
  • test/js/bun/cookie/cookie-map.test.ts
  • test/js/bun/cookie/cookie.test.ts

Comment thread src/jsc/bindings/CookieMap.cpp Resolved
Comment thread src/jsc/bindings/CookieMap.cpp Resolved
Comment thread test/js/bun/cookie/cookie-map.test.ts Resolved
@robobun

robobun commented Jul 26, 2026

Copy link
Copy Markdown
Collaborator Author

The diff is ready. Both ASAN gate cells are green (15 fail without the fix, all pass with it). The release with fix cell is failing on the link step in the gate environment: ninja reports link bun-profile then env: '/workspace/bun/build/release/bun-profile': No such file or directory at the revision/strip steps, i.e. the linker produced no output. A clean local release build links and runs all 85 tests across the two cookie test files; the C++ changes compile in the gate's own cxx steps. This reproduces on two consecutive gate runs (9781189 and 26ed941).

@robobun

robobun commented Jul 26, 2026

Copy link
Copy Markdown
Collaborator Author

CI build #82385: no cookie-related failures. Remaining reds are the binary-size check (comparing against canary #79916; +544 KB is identical across all 12 targets and across both builds of this PR, so it is main's drift since that baseline, not this ~160-line C++ change), plus test/napi/napi.test.ts and test/js/bun/webview/webview-chrome.test.ts, both tagged flaky and unrelated to CookieMap. The cookie test suite is green on every lane that ran it.

@claude claude Bot left a comment

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.

No bugs found; deferring to a human because this is a data-structure refactor with three user-facing behavior changes (delete() no longer throws on unwritable names, toSetCookieHeaders() order for re-written keys, iterator delete-in-loop now empties the map) and it overlaps with #35909's competing design — a maintainer should pick between tombstones-in-place vs compaction.

Checked: the earlier same-key tombstone growth is fixed via setModified() in-place overwrite; m_modifiedIndex entries always point to non-null slots so size() can't null-deref; name reference in set() stays valid across WTF::move(cookie); removed getAll() and the Vector<Ref<Cookie>> constructor have no remaining callers; error messages match Cookie::create exactly.

Extended reasoning...

Overview

Rewrites CookieMap storage from linear-scanned vectors to vector + HashMap<String, ...> indices (originals may repeat a name → Vector<size_t>; modified is unique → size_t). Tombstones removed originals via null key so indices stay stable. remove() now validates path/domain and builds the deletion Cookie before mutating; unwritable names evict without queuing a Set-Cookie tombstone. Iterator gains separate cursors. getAll() and the unused Vector<Ref<Cookie>> constructor are deleted.

Security risks

None identified. The change is read/write bookkeeping over an in-process map; no new parsing of untrusted input, and the new name.isNull() guard in get() prevents the WTF::HashMap null-key crash. The pre-existing empty-value-as-deletion semantics are unchanged (tracked separately in #33431).

Level of scrutiny

Medium-high. CookieMap backs req.cookies in Bun.serve() so correctness affects every request handler that touches cookies, but the surface is small and well-covered by the new tests. The refactor is careful (validate-first, in-place slot reuse, clone copies both indices) and my earlier concern about unbounded tombstone growth on repeated same-key writes was addressed in c4739f6.

Other factors

Three observable behavior changes ship here beyond the bugfixes: (1) delete() on names the Set-Cookie grammar rejects now evicts silently instead of throwing — reasonable, but an API-design call; (2) re-set()ing a name keeps its first-write position in toSetCookieHeaders() (two snapshots updated); (3) delete-in-loop now reaches size 0 like Map/Set. There is also a competing open PR (#35909) with a different storage design (50%-hole compaction, next-index chains) that the author offered to fold in. A maintainer should decide which approach lands and whether the API changes are wanted.

@robobun

robobun commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as part of a cleanup of stale pull requests. This PR has had no new commits since 2026-07-26, it conflicts with main, and its last CI run failed. This is not a judgment on the fix itself. If the problem still reproduces on a current build, reopen this PR after a rebase or open a new one against main.

@robobun robobun closed this Sep 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants