Skip to content

fix(worker): propagate concurrency override via claim-sim response - #173

Merged
TytaniumDev merged 2 commits into
mainfrom
fix-worker-override-propagation
Apr 22, 2026
Merged

TytaniumDev merged 2 commits into
mainfrom
fix-worker-override-propagation

Conversation

@TytaniumDev

Copy link
Copy Markdown
Owner

Summary

  • Setting a worker's multithreaded instance count from the UI persisted in Firestore but had no effect on the running worker. Root cause: since fix(worker,api): slow heartbeat to 60s and drop per-beat Firestore read #150 dropped per-heartbeat override reads, runtime changes only reach a worker via push to its /config endpoint — which requires WORKER_API_URL to be set and reachable from Cloud Run. setup-worker.sh never configures WORKER_API_URL, and user-hosted workers are typically behind NAT anyway, so push silently fails (pushResult: 'no_url') and the worker keeps its startup value until restart.
  • Piggyback the current override on the existing /api/jobs/claim-sim poll response as the X-Max-Concurrent-Override header (value: positive integer, or none). The worker applies it via the existing applyOverride path on every poll, so changes propagate within one poll interval (~3s) without requiring externally-reachable worker APIs.
  • Override read is best-effort (.catch(() => undefined)) — a transient Firestore hiccup omits the header rather than orphaning a successful claim. Push /config path is untouched and still works when available.

Test plan

  • npm run lint --prefix api passes
  • npx tsc --noEmit in worker/ passes
  • npx tsx lib/claim-sim.test.ts — 6/6 pass
  • Manual: deploy, change worker concurrency 1→4 in UI, confirm worker picks up additional sims within a poll cycle (~3s)
  • Manual: change 4→1 while busy, confirm excess sims are preempted via existing killExcessSimulations path

🤖 Generated with Claude Code

Runtime override changes didn't reach workers that don't have
WORKER_API_URL reachable from the API (push /config path fails), and
since #150 dropped per-heartbeat reads, the worker would keep its
startup-loaded value until restart.

Piggyback the current override on the existing claim-sim poll as the
X-Max-Concurrent-Override header. Worker applies it on every poll, so
changes propagate within one poll interval (~3s) without requiring
externally-reachable worker APIs.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@TytaniumDev

Copy link
Copy Markdown
Owner Author

@claude do a code review

@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses an issue where worker concurrency settings were not being applied to running workers due to network reachability constraints. By piggybacking the concurrency override onto the existing simulation polling mechanism, the system now ensures that configuration changes are picked up by workers within a single poll interval, regardless of their network environment.

Highlights

  • Concurrency Override Propagation: Implemented a fallback mechanism to propagate worker concurrency overrides via the X-Max-Concurrent-Override header in the claim-sim poll response.
  • Improved Reliability: Ensures runtime changes reach workers even when they are behind NAT or lack a reachable WORKER_API_URL, avoiding reliance on the push-based /config endpoint.
  • Best-Effort Implementation: The override read is now performed as a best-effort operation, ensuring that transient Firestore issues do not prevent workers from claiming simulations.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@claude

claude Bot commented Apr 22, 2026 •

Copy link
Copy Markdown

Claude finished @TytaniumDev's task in 1m 52s —— View job


Code Review

  • Gather context
  • Read changed files
  • Analyze changes
  • Post review feedback

Overall this is a clean, pragmatic fix. The approach is solid — piggybacking on a frequent, already-authenticated poll rather than requiring externally-reachable worker APIs. A few observations below, ordered by severity.


worker/src/worker.ts — applyOverrideFromHeader

Minor: magic number 20 creates subtle asymmetry with the push path

applyOverrideFromHeader caps the header value at 1–20 (worker.ts:533), but the push-based path (worker.ts:613) calls applyOverride(data.maxConcurrentOverride ?? null) directly with no such cap. The API enforces 1–20 at write time so this can't trigger in practice today, but if the cap ever changes it would need to be updated in three places (API PATCH route, applyOverrideFromHeader, and the push receiver). A named constant shared between the cap check and the validation comment would make this more robust. Not a blocker.

Minor: parseInt without isNaN guard (mitigated)

parseInt("1abc", 10) returns 1, which passes Number.isInteger(1) && 1 >= 1 && 1 <= 20. The stored value is always a clean integer (API validates at write), so this is theoretical, but worth knowing. Using Number.isInteger(n) && !isNaN(n) is redundant here — Number.isInteger already implies a non-NaN finite number — so the current check is fine as written.


api/app/api/jobs/claim-sim/route.ts

Nitpick: == vs === on line 51

overrideHeader['X-Max-Concurrent-Override'] = overrideResult == null ? 'none' : String(overrideResult);

== null correctly catches both null (no override stored) and undefined (returned by .catch(() => undefined) on error, which must be excluded from the header). The two cases are semantically different though: null means "override was explicitly cleared", undefined means "we couldn't even read it". The current code collapses them — if the store call throws, the worker receives 'none' and clears its override. But wait — no. The if (overrideResult !== undefined) guard on line 50 already filters out the error case (where overrideResult is undefined), so the == null on line 51 only fires when overrideResult === null (legitimate no-override state). The logic is correct, just non-obvious at a glance. A comment // null means override is cleared above line 51 would help future readers. Fix this →

Observation: header applied before status check in worker

In worker.ts:864, applyOverrideFromHeader fires before the status code is checked. For error responses (non-200, non-204), the API error path doesn't add the header, so res.headers.get('X-Max-Concurrent-Override') returns null → applyOverrideFromHeader(null) is a no-op. Correct, but worth confirming explicitly if the error response helper is ever changed to forward headers.


Test coverage

The existing claim-sim.test.ts exercises the SQLite store claim logic, but there's no test for the HTTP route verifying that the X-Max-Concurrent-Override header is actually emitted (on both 200 and 204), or that applyOverrideFromHeader handles the valid/invalid/none cases. Not a requirement for this fix to land, but a gap worth tracking. Fix this →


DATA_FLOW.md

Update is accurate and appropriately scoped. No issues.


Summary: The implementation is correct, well-documented, and handles the failure modes cleanly. The best-effort .catch(() => undefined) + undefined-guard pattern for the override read is exactly right. The 204-also-carries-the-header behavior means a worker gets override updates even when the queue is empty, which is the right call. The issues above are all minor/nitpick — nothing blocking merge.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request implements a fallback mechanism for propagating concurrency overrides to workers using the X-Max-Concurrent-Override header in the claim-sim response. This ensures that workers behind NAT or without a reachable API URL can still receive runtime configuration changes. The changes include documentation updates, server-side header injection, and client-side header parsing. Feedback was provided regarding an inconsistency in the worker's parsing logic, where a hardcoded maximum value of 20 was applied to the override, potentially restricting valid configurations on high-performance machines.

Comment thread worker/src/worker.ts Outdated
return;
}
const n = parseInt(header, 10);
if (Number.isInteger(n) && n >= 1 && n <= 20) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The concurrency override is hardcoded to a maximum of 20 here, but the applyOverride function (line 490) does not have this restriction and only enforces a minimum of 1. This creates an inconsistency between the push-based /config path and this new header-based path. On high-core machines, a user might legitimately want to set concurrency higher than 20. Consider removing this upper bound to match the behavior of applyOverride.

Suggested change
if (Number.isInteger(n) && n >= 1 && n <= 20) {
if (Number.isInteger(n) && n >= 1) {
References
  1. Address valid code quality suggestions immediately within the current pull request, even if it expands the scope. Do not defer them to a follow-up task.

@github-actions github-actions 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.

All CI checks passed.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review - Changes Requested

The implementation is logically correct and the design is sound — the best-effort .catch(() => undefined) properly isolates store failures from claim failures, the 'none'/integer encoding is consistent between emitter and parser, the 1–20 range check in applyOverrideFromHeader matches the write-time validation in api/app/api/workers/[id]/route.ts, and DATA_FLOW.md is updated.

Issue: Missing test coverage for new behavior (CLAUDE.md requirement)

CLAUDE.md states: "Ensure test coverage exists for the part of the flow you changed — see the test files listed in DATA_FLOW.md." DATA_FLOW.md was updated in this PR to document the X-Max-Concurrent-Override header as part of the claim-sim flow, which triggers this requirement.

The PR lists claim-sim.test.ts (6/6 pass) as evidence of coverage, but those 6 tests only exercise claimNextSim — the SQLite DB function — and were written before this change. They do not touch the route handler at all. The two new code paths have no test coverage:

  1. Route handler header emission (api/app/api/jobs/claim-sim/route.ts): the logic that reads overrideResult and builds the X-Max-Concurrent-Override header (including the overrideResult == null ? 'none' : String(overrideResult) encoding). Specifically untested: the 204 path with header, the 200 path with header, and the best-effort omission when the store call throws.

  2. applyOverrideFromHeader (worker/src/worker.ts, line 526): the parsing logic for 'none' → clear override, valid integer string → apply, and malformed/out-of-range → ignore.

Please add tests covering these paths. The route handler behavior could be covered by extending claim-sim.test.ts (or a new route-level test), and applyOverrideFromHeader is a pure function that is straightforward to unit-test.

- Extract header encode/parse into pure modules (api/lib/override-header.ts
  and worker/src/override.ts) with unit tests covering null/'none'/valid
  integer/malformed cases
- Drop the 1-20 upper bound from the worker parser per Gemini review;
  the value is already validated on write by PATCH /api/workers/:id and
  the /config endpoint, so the parser trusts any positive integer from
  the API (matches applyOverride's contract)
- Wire the new worker tests into scripts/test.sh and api/package.json so
  they run in CI

Co-Authored-By: Claude Opus 4.7 <[email protected]>

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review - Approved

No issues found. Checked for bugs, security issues, and CLAUDE.md compliance.

The fallback override-via-poll-header feature is implemented correctly:

  • Encode/decode separation: api/lib/override-header.ts and worker/src/override.ts are independent packages with matching wire formats; duplication is intentional and correct.
  • Type safety: overrideResult is number | null | undefined; the !== undefined guard correctly narrows to number | null before calling encodeOverrideHeader, matching its signature.
  • Best-effort header: .catch(() => undefined) ensures a store failure never orphans a successful claim — the worker simply keeps its last-known override.
  • Header applied on 200 and 204: Correct — override propagates even when there is no work to claim.
  • Parse strictness: String(n) === header round-trip check in parseOverrideHeader correctly rejects trailing garbage and non-integer inputs.
  • Test coverage: Both encoder and parser have unit tests; new tests are wired into api/package.json, worker/package.json, and scripts/test.sh.
  • tsx dependency: Already present in worker/package.json (^4.7.0); new test:unit script works.
  • DATA_FLOW.md updated: Per CLAUDE.md requirement, step 3 documents the new header behavior.

@TytaniumDev
TytaniumDev merged commit c06d5bd into main Apr 22, 2026
8 checks passed
@TytaniumDev
TytaniumDev deleted the fix-worker-override-propagation branch April 22, 2026 07:27
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.

1 participant