Repository navigation
Conversation
…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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (2)
WalkthroughChangesCookieMap 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
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Updated 9:04 AM PT - Jul 26th, 2026
❌ @robobun, your commit 26ed941 has 1 failures in
Add 🧪 To try this PR locally: bunx bun-pr 35918That installs a local version of the PR into your bun-35918 --bun |
||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Found 1 issue this PR may fix:
🤖 Generated with Claude Code |
|
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. |
|
This PR may be a duplicate of:
🤖 Generated with Claude Code |
|
Overlaps with #35909 on the container change (face 3). Differences:
Happy to fold #35909's compaction in here if preferred. |
There was a problem hiding this comment.
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.
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.
There was a problem hiding this comment.
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
📒 Files selected for processing (4)
src/jsc/bindings/CookieMap.cppsrc/jsc/bindings/CookieMap.htest/js/bun/cookie/cookie-map.test.tstest/js/bun/cookie/cookie.test.ts
|
The diff is ready. Both ASAN gate cells are green (15 fail without the fix, all pass with it). The |
|
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 |
There was a problem hiding this comment.
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.
|
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. |
Three related
Bun.CookieMapfixes.delete() mutated before it validated
CookieMap::remove()calledremoveInternal(name)beforeCookie::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 onlydelete()was torn.remove()now validatespathanddomainup front and returns the exception before any mutation.delete() rejected names the Cookie-header parser accepted
The Cookie-header parser accepts names (spaces, CTLs, DEL, 0x80-0xFF) that
isValidCookieName(the Set-Cookie emission grammar) rejects. Such cookies were readable viaget()/has()but could never be deleted, and the throwingdelete()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()andnew Bun.Cookie()keep the strict name validator unchanged. No parser change.O(n) get/has/set/delete
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 aHashMap<String, ...>keyed on the cookie name. Originals are tombstoned in place (null key) so indices stay valid;set()/remove()reuse an existingm_modifiedCookiesslot for the same name rather than appending, so repeated writes to one key do not grow the vector. Them_originalCookiesindex maps to aVector<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 twoiterator > delete in a looptests now end atsize === 0(matchingMap/Set), as the test comment had already asked for. Re-writing a name keeps its first-write position intoSetCookieHeaders()instead of moving to the end; two snapshots are updated accordingly.Dead
CookieMap::getAll()and the unusedVector<Ref<Cookie>>constructor are removed.Supersedes #35908.
Verification
New tests in
test/js/bun/cookie/cookie-map.test.tscover each face (invalid path/domain on both parsed andset()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.tsis updated for the new delete-by-name policy and header order.Without
src/changes the new/updated tests fail; with them the fulltest/js/bun/cookie/suite (178 tests) and theBun.serve/bake cookie tests pass.