fix(sdk): reject sharedcontext maxentries below 1 (#4743)

## Description

`SharedContext` in the TypeScript SDK has an infinite loop when
`maxEntries` is 0 (or negative). `evictIfFull`
(`sdk/typescript/src/shared-context.ts:182` on `1da8930a`) is `while
(this.entries.size >= this.maxEntries)` and only deletes when the map
has a key. With `maxEntries <= 0` and an empty map the condition stays
true, nothing is deleted, and the loop never exits. It is synchronous,
so the whole Node event loop stops. The constructor keeps `0` because it
uses `??` (`shared-context.ts:47`).

With this PR the constructor throws a `RangeError` when `maxEntries` is
not at least 1 (this also covers `NaN`), and `evictIfFull` stops when
there is nothing left to delete, so the loop cannot spin even if the
field is changed later.

This is one of three eviction defects in `SharedContext` described in
#4740. This PR fixes only the infinite loop; the other two (updating an
existing key at capacity evicts an unrelated entry, and the bound is not
held under concurrent `put`) are not touched.

Part of #4740

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `sdk/typescript/src/shared-context.ts`: the constructor throws
`RangeError("SharedContext maxEntries must be at least 1, got N")` when
`!(maxEntries >= 1)`; `evictIfFull` breaks when `keys().next().value` is
`undefined`.
- `sdk/typescript/test/shared-context.test.ts`: new `SharedContext
maxEntries validation` block: `0`, `-1` and `NaN` are rejected; `1` is
accepted and keeps only the last key; `evictIfFull` returns on an empty
map even when the field is forced to 0 (guards the loop on its own).

## Testing

- [ ] Unit tests pass (`pytest`)
- [ ] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

This is a TypeScript-only change, so the Python checks above do not
apply; the SDK equivalents were run (Node v24.22.2, vitest 5.1.0, `npm
ci --ignore-scripts` from the committed lockfile, Ubuntu on WSL2).

### Test Output

```text
vitest run test/shared-context.test.ts (origin/main src, original tests)
Tests  15 passed (15)

vitest run (this branch, whole sdk/typescript suite)
Test Files  19 passed | 5 skipped (24)
Tests  454 passed | 33 skipped (487)

tsc --noEmit -> exit 0
```

Fail before (`shared-context.ts` from `1da8930a`, new tests kept):

```text
vitest run test/shared-context.test.ts -t "rejects|accepts"
 × rejects maxEntries 0
 × rejects maxEntries -1
 × rejects maxEntries NaN
AssertionError: expected function to throw an error, but it didn't
Tests  3 failed | 1 passed | 16 skipped (20)

timeout 20 vitest run test/shared-context.test.ts -t "returns on an empty map"
(no result; killed by timeout, rc=124, the test never returns)
```

The last test hangs on `1da8930a` by design (it is the loop); I ran it
alone under `timeout 20` so it cannot stall the run.

Pass after:

```text
vitest run test/shared-context.test.ts
Tests  20 passed (20)
```

## Real Behavior Proof

- Environment: Node v24.22.2 on Ubuntu (WSL2), `node
--experimental-transform-types` on the real SDK source, no network.
- Exact command / steps: `new SharedContext({ maxEntries: 0, baseUrl:
"http://127.0.0.1:9", retries: 0, timeout: 500 })`, then `await
ctx.put("k", "v")`.
- Observed result: on `1da8930a` it prints `constructed; calling put`,
then never returns and is killed by `timeout 10` (rc=124). On this
branch it prints `threw RangeError: SharedContext maxEntries must be at
least 1, got 0` and exits 0.
- Not tested: a Python-side change (none made).

## Runtime Rollout Safety

- Rollout-managed feature(s): none.
- Minimum rollout channel: n/a (no new feature)
- Stable/default behavior changed: yes, narrowly: `maxEntries` of 0, a
negative number or `NaN` now throws at construction instead of freezing
on the first `put`. The default (100) and every valid value are
unchanged.
- Kill switch / disable path: none; not needed.
- Unsafe override required: no
- Qualification impact: none expected.
- Rollback path: revert this commit.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes (see
Testing)
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Additional Notes

- The Python twin (`headroom/shared_context.py`) does not validate
`max_entries` either; with `max_entries=0` its `min()` over an empty
dict would raise `ValueError` (read, not run: the module's package
imports need `opentelemetry`, which is not installed here). This PR does
not touch Python.
- `RangeError` was chosen as the standard JS error for an out-of-range
number; a maintainer may prefer clamping to 1 instead.

Produced with AI assistance (Claude Code) operated by me (HetCreep); the
tests and proof above were run on my machine against a clone of the
repository.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4743"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
HetCreep
2026-11-10 09:04:17 -06:00
committed by GitHub
co-authored by Claude Sonnet 5.5
parent 318e8e0808
commit 4b6529fc14
2 changed files with 32 additions and 1 deletions
+8 -1
View File
@@ -45,6 +45,12 @@ export class SharedContext {
this.model = model ?? "claude-sonnet-4-5-20250929";
this.ttl = ttl ?? 3600;
this.maxEntries = maxEntries ?? 100;
// A bound below 1 can never be met: evictIfFull would spin forever.
if (!(this.maxEntries >= 1)) {
throw new RangeError(
`SharedContext maxEntries must be at least 1, got ${this.maxEntries}`,
);
}
}
/**
@@ -182,7 +188,8 @@ export class SharedContext {
private evictIfFull(): void {
while (this.entries.size >= this.maxEntries) {
const oldest = this.entries.keys().next().value;
if (oldest !== undefined) this.entries.delete(oldest);
if (oldest === undefined) break; // nothing left to evict
this.entries.delete(oldest);
}
}
}
@@ -208,6 +208,30 @@ describe("SharedContext eviction", () => {
});
});
describe("SharedContext maxEntries validation", () => {
it.each([0, -1, Number.NaN])("rejects maxEntries %s", (maxEntries) => {
expect(
() => new SharedContext({ baseUrl: "http://test:8787", maxEntries }),
).toThrow(RangeError);
});
it("accepts maxEntries 1", async () => {
mockFetch.mockResolvedValue(mockCompressResponse("data"));
const ctx = new SharedContext({ baseUrl: "http://test:8787", maxEntries: 1 });
await ctx.put("a", "data");
await ctx.put("b", "data");
expect(ctx.keys()).toEqual(["b"]);
});
it("evictIfFull returns on an empty map even if the bound is 0", () => {
const ctx = new SharedContext({ baseUrl: "http://test:8787" });
// Bypass the constructor check to prove the loop itself terminates.
(ctx as unknown as { maxEntries: number }).maxEntries = 0;
(ctx as unknown as { evictIfFull(): void }).evictIfFull();
expect(ctx.keys()).toEqual([]);
});
});
describe("SharedContext clear", () => {
beforeEach(() => {
vi.clearAllMocks();