Skip to content

test(portal): stop the offline stub test flaking on a cold npx cache - #172

Merged
KooshaPari merged 2 commits into
masterfrom
fix/xj03-offline-test-cold-npx-timeout
Oct 21, 2026
Merged

KooshaPari merged 2 commits into
masterfrom
fix/xj03-offline-test-cold-npx-timeout

Conversation

@KooshaPari

@KooshaPari KooshaPari commented Oct 21, 2026 •

Copy link
Copy Markdown
Owner

User description

Closes #171

Problem

scripts/test-portal-bridge.sh (merged in #138) can fail spuriously on a cold npx cache. The bridge step was hard-coded to timeout 30, but npx -y [email protected] can spend longer than that resolving the package and writes nothing to stderr while it does. The bridge log ends up 0 bytes and the assertion reports:

FAIL: mcp-remote never logged that it accepted the client metadata document.

i.e. exit 2 — "the bridge did not prove the client-metadata / callback configuration". That is a false verdict: the harness never gave the bridge a chance to prove anything. Exit 2 is reserved for the exact regression this test guards, so conflating "we never observed" with "we observed a rejection" defeats the guard.

Evidence

Clean git archive extraction of merged master (2aea04dd8), 2026-10-21:

Run Result Duration
1, cold after a long idle gap exit 2, 0-byte bridge.log ~36s (bridge hit the 30s cap)
2, warm exit 0 PASS 28s
3, warm exit 0 PASS 19s
4, warm exit 0 PASS 15s

A bare npx -y [email protected] ... --debug against an unreachable URL emits ~12.7 KB of stderr within a second, so npx itself is healthy; the empty log is specific to the cold-resolve window. 30s sat right on the boundary.

Change

  • BRIDGE_TIMEOUT is configurable, default 120s.
  • An empty bridge log is classified as an infrastructure failure (exit 1), matching the script's own documented exit-code contract, with an actionable hint (BRIDGE_TIMEOUT=300 ...).

No assertion semantics change: the three confirmations (client metadata document accepted, callback hostname is 127.0.0.1, callback port derived) still decide PASS.

Validation

Check Result
bash -n clean
shellcheck -S warning, before vs after 3 vs 3, no new warnings
BRIDGE_TIMEOUT=1 (forces the empty-log path) exit 1 with the infrastructure message
Normal run exit 0, all three confirmations intact, 15s

Scope

Script-only. No Rust or build files touched, so build outcomes are unaffected. Sibling CI work continues in #156 / #164 / #166 / #168 / #169.


CodeAnt-AI Description

Prevent cold-cache timeouts from appearing as client-metadata failures

What Changed

  • The bridge test allows up to 120 seconds for a cold package download, with an option to set a longer timeout.
  • If the bridge produces no output before timing out, the test reports an infrastructure failure with retry guidance instead of a misleading client-metadata failure.

Impact

✅ Fewer cold-cache test failures
✅ Clearer timeout failure reports
✅ Adjustable wait for package downloads

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

Closes #171.

The bridge step was hard-coded to `timeout 30`. `npx -y [email protected]`
can spend longer than that resolving the package, and it writes nothing to
stderr while it does, so the bridge log ended up 0 bytes and the assertion
reported exit 2 ("the bridge did not prove the client-metadata / callback
configuration"). That verdict is false: the harness never gave the bridge a
chance to prove anything. Exit 2 is reserved for the exact regression this
test guards, so conflating "we never observed" with "we observed a
rejection" defeats it.

Observed 2026-10-21 against a clean extraction of merged master (2aea04d):
one cold run exited 2 with a 0-byte bridge.log, then three warm runs passed
in 28s / 19s / 15s. A bare npx mcp-remote produces ~12.7 KB of stderr in
under a second, so npx is healthy; 30s simply sat on the cold-start boundary.

Changes:
- BRIDGE_TIMEOUT is configurable, default 120s
- an empty bridge log is classified as an infrastructure failure (exit 1),
  matching the script's own exit-code contract, with an actionable hint

Validation: bash -n clean; shellcheck -S warning yields no new warnings
versus master (3 pre-existing, 3 after); BRIDGE_TIMEOUT=1 yields exit 1 with
the infrastructure message; a normal run still yields exit 0 with all three
confirmations (client metadata document accepted, callback hostname
127.0.0.1, callback port derived).

tx-agent:     jcode
tx-task:      #171
tx-validated: test
tx-scope:     scripts/test-portal-bridge.sh
tx-intent:    Remove the false-failure mode from the merged XJ-03 offline stub test
Copilot AI balanced review requested due to automatic review settings October 21, 2026 22:19
@codeant-ai

codeant-ai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

🤖 CodeAnt AI — Review Status

Status Commit Started (UTC) Finished (UTC)
✅ Reviewed your PR cfc3b31 Oct 21, 2026 · 22:20 22:25

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@codeant-ai

codeant-ai Bot commented Oct 21, 2026

Copy link
Copy Markdown

Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

@coderabbitai

coderabbitai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 2 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: fe547252-f3f0-4045-828d-19134ed3d39b
📥 Commits

Reviewing files that changed from the base of the PR and between 2aea04d and ce856c1.

📒 Files selected for processing: 1
  • scripts/test-portal-bridge.sh
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@codeant-ai codeant-ai Bot added the size:M This PR changes 30-99 lines, ignoring generated files label Oct 21, 2026
Comment thread scripts/test-portal-bridge.sh Resolved
@codeant-ai

codeant-ai Bot commented Oct 21, 2026

Copy link
Copy Markdown

CodeAnt Nitpicks

1 code suggestion

1. Setting BRIDGE_TIMEOUT=0 passes zero to GNU timeout, which disables the deadline; a hung npx process can then leave the test running indefinitely.

Possible bug · scripts/test-portal-bridge.sh:68

@codeant-ai

codeant-ai Bot commented Oct 21, 2026

Copy link
Copy Markdown

CodeAnt PR Risk: Medium Risk

  • The PR needs attention before merging.
  • The bridge timeout status is discarded, so partial stderr can let a timed-out run continue and report a CIMD failure instead of an infrastructure failure.

Assessed commit: cfc3b31aed77

… status

Address both findings from the CodeAnt review of #172.

1. `BRIDGE_TIMEOUT=0` was passed straight to GNU timeout, which treats 0 as
   "no deadline", so a hung npx would have run indefinitely. Any non-integer
   was a usage error. The value is now validated as a positive integer and
   falls back to 120s with a visible warning.

2. The bridge exit status was discarded with `|| true`. A timed-out bridge can
   still have written partial stderr, so the empty-log guard did not fire and
   the assertions could report a CIMD rejection (exit 2) from a truncated log.
   The status is now captured and GNU timeout's 124 is classified as an
   infrastructure failure (exit 1) before any assertion runs.

Validation: bash -n clean; shellcheck -S warning still 3, matching master's
baseline. BRIDGE_TIMEOUT=0 warns and passes in 5s instead of hanging;
BRIDGE_TIMEOUT=abc warns and passes; BRIDGE_TIMEOUT=1 exits 1 with the exit-124
message and produces zero "never logged that it accepted" lines; a normal run
still exits 0 with all three confirmations.

tx-agent:     jcode
tx-task:      #171
tx-validated: test
tx-scope:     scripts/test-portal-bridge.sh
tx-intent:    Close the two robustness gaps CodeAnt found in the timeout handling
@KooshaPari

Copy link
Copy Markdown
Owner Author

Both CodeAnt findings were valid and are fixed in ce856c16f.

1. BRIDGE_TIMEOUT=0 disables the deadline

Correct. GNU timeout treats 0 as "no deadline", so a hung npx would have run indefinitely, and a non-integer was a usage error. The value is now validated as a positive integer and falls back to 120s with a visible warning:

WARNING: BRIDGE_TIMEOUT='0' is not a positive integer; using 120s.

2. The timeout status was discarded

Correct, and this was the more serious of the two. || true swallowed everything, so a bridge that timed out after writing partial stderr would leave a non-empty log, the empty-log guard would not fire, and the assertions could report a CIMD rejection (exit 2) from a truncated log. Exit 2 is exactly the regression this test exists to detect.

The status is now captured and GNU timeout's 124 is classified as an infrastructure failure (exit 1) before any assertion runs.

Verification

Case Result
BRIDGE_TIMEOUT=0 warns, falls back to 120s, PASS in 5s (no hang)
BRIDGE_TIMEOUT=abc warns, falls back, PASS
BRIDGE_TIMEOUT=1 exit 1, FAIL: the bridge hit the 1s timeout (exit 124)
old false verdict on that run 0 occurrences of "never logged that it accepted"
normal run exit 0, all three confirmations intact
bash -n clean
shellcheck -S warning 3, matching master's pre-existing baseline (no new warnings)

The empty-log guard is retained as a backstop for the case where the bridge dies before writing anything at all without tripping the deadline.

Note on the two failing checks: Kilo Code Review failed with Review failed: Assistant request was rate limited, and CodeRabbit reported Review limit reached with the next slot in 10 minutes. Neither is a code finding.

@KooshaPari

Copy link
Copy Markdown
Owner Author

Root-cause correction, plus direct A/B proof of the fix

My original attribution was wrong and I'm correcting it here.

The cold-npx hypothesis is disproven

I claimed a cold npx cache could exceed 30s. Tested it properly with a genuinely empty cache (npm_config_cache pointed at a fresh dir, 0 bytes, so npx had to download [email protected]):

Condition Script Result
Cold npm cache (0 B, 18 MB downloaded) old (timeout 30) exit 0, PASS in 13s

A cold resolve took 13s, not >30s. So cold npx is not the cause. The flake came from some other adverse condition (system load, registry latency, or TLS stub slowness at that moment). The durable statement is the weaker, correct one: the bridge step can exceed a 30s budget under adverse conditions, and a cold cache is one of several candidates rather than the demonstrated one.

The failure mode is reproduced exactly, and the fix resolves it

To test the mechanism instead of guessing, I injected a deterministic 45s delay into npx via a PATH shim, which makes the bridge step exceed the old budget while writing nothing to stderr:

Condition Script Exit Verdict
45s bridge delay old (timeout 30) 2 FAIL: mcp-remote never logged that it accepted the client metadata document. — the exact false verdict from the original failure
45s bridge delay new (default 120s) 0 PASS with all three confirmations intact
45s bridge delay, BRIDGE_TIMEOUT=20 new 1 FAIL: the bridge hit the 20s timeout (exit 124). — and 0 occurrences of the old false verdict

The third row is the important one: when the budget genuinely is too small, the new script reports an infrastructure failure (exit 1) instead of falsely asserting a CIMD rejection (exit 2). Exit 2 stays reserved for the regression this test actually guards.

What this changes

  • The diagnosis in test(portal): offline stub test flakes on a cold npx cache (30s bridge timeout) #171 and the PR body said "cold npx cache". That specific claim is retracted; the general claim (budget too tight, empty log misclassified) is confirmed by direct reproduction.
  • No code change needed: the fix is correct for the real mechanism, and the reproduction shows it working on both the pass-through and the too-small-budget paths.

@KooshaPari
KooshaPari merged commit 0d95c41 into master Oct 21, 2026
9 of 16 checks passed
@KooshaPari
KooshaPari deleted the fix/xj03-offline-test-cold-npx-timeout branch October 21, 2026 22:50
KooshaPari added a commit that referenced this pull request Oct 27, 2026
* fix(portal): serialise token refresh under a lock and add conditional refresh

Closes #199.

The helper read the cache, exchanged the refresh token, and wrote the result
with no mutual exclusion. Portal refresh tokens are single-use and rotating and
mcp-remote also refreshes on launch, so two callers racing on one cache meant
the loser got HTTP 400 invalid_grant and printed "the cached refresh token was
already spent; re-run the consent flow" -- instructing the operator to
re-consent for what is really a local concurrency bug. A process that read the
pair before another rotated it could also leave a spent refresh token on disk
paired with a still-valid access token, which is the exact cache state found at
the start of the 2026-10-19 session.

Changes:
- advisory exclusive flock on <token-path>.lock around the whole
  read/exchange/write cycle; released in a finally block
- re-read the cache INSIDE the lock, because another process may have rotated
  the pair between the first read and lock acquisition
- --refresh-if-expiring SECONDS: no-op unless the access token expires within
  the threshold. Every refresh consumes a rotation, so an unconditional
  refresh from a scheduled caller needlessly widens the race window.
- reject a negative --refresh-if-expiring with exit 2
- lock file is created 0600 and never unlinked, since removing it while another
  process holds it reopens the race the lock exists to close
- platforms without fcntl skip the lock; the atomic write remains the only
  protection there

Validation against a mock endpoint implementing single-use rotation with a
200ms window, seeded with an expired access token, 4 concurrent callers:
- before: 2 of 4 failed with the misleading invalid_grant message
- after, --refresh-if-expiring 600: 1 rotation, 3 no-ops, 0 failures
- after, unconditional: 4 sequential rotations, 0 failures
- lock file mode 0600, no temp residue, raced cache still authenticates
- ruff check/format clean, py_compile clean, --check and argument validation
  exit codes as documented

tx-agent:     jcode
tx-task:      #199
tx-validated: test
tx-scope:     scripts/refresh-portal-token.py
tx-intent:    Remove the spurious invalid_grant and spent-token races from token refresh

* ci(scripts): lint changed shell scripts at error severity

Closes #200.

scripts/ holds 73 bash files and no CI job linted them, so shellcheck findings
could only ever arrive from third-party review bots. On PR #172 exactly that
happened: bots reported shellcheck issues while every native gate ignored the
file.

Added as a step in the existing `quality` job rather than a new job, because
hosted runners are capped at $0 (the macOS leg was already removed for that
reason) and the single self-hosted runner already serialises every job with all
open PRs queued behind it.

Design:
- lint only the scripts CHANGED in the current change set. A full scan costs
  roughly 5s per file, which is minutes on that runner.
- gate at -S error only. The tree has 0 error-level findings and 50
  pre-existing warning-level ones, so error-only is green today and still
  catches real breakage; warnings are reported informationally.
- if shellcheck is missing, attempt install, then degrade to a ::warning::
  annotation instead of blocking every PR on runner provisioning.

Validation: bad probe (missing `then`) exits 1 with SC1049/SC1073/SC1050/
SC1072; clean probe and the merged scripts/test-portal-bridge.sh exit 0;
workflow YAML parses and the step lands in the quality job.

tx-agent:     jcode
tx-task:      #200
tx-validated: lint
tx-scope:     .github/workflows/ci.yml
tx-intent:    Give shell scripts a native CI gate instead of relying on review bots
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:M This PR changes 30-99 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

test(portal): offline stub test flakes on a cold npx cache (30s bridge timeout)

2 participants