Skip to content

test(jcode-app-core): fix 2 pre-existing --lib suite-state-pollution flakes (#46) - #48

Closed
KooshaPari wants to merge 1 commit into
fix/issue-44-17-broken-tests-v2from
fix/issue-46-pre-existing-flakes
Closed

KooshaPari wants to merge 1 commit into
fix/issue-44-17-broken-tests-v2from
fix/issue-46-pre-existing-flakes

Conversation

@KooshaPari

@KooshaPari KooshaPari commented Oct 12, 2026 •

Copy link
Copy Markdown
Owner

User description

Summary

Fixes the 2 remaining pre-existing flakes that survived the v2 branch (#45 + #44 + v2 commit 794f984da). The v2 commit message claimed "1272 passed; 1 failed" but the 1 failure was Flake 1 (not Flake 2 as the message implied), and the actual Flake 2 was also unfixed.

Two distinct parallel-test races, both in crates/jcode-app-core/src/server/.

Flake 1 — debug_tool_selfdev_reload_returns_promptly_for_direct_execution

Root cause: tokio::sync::watch::Receiver gotcha. A fresh clone's changed().await fires immediately for the unseen current slot value (the new receiver has no "last seen" version, so the existing value counts as a change). The test's ack_task was therefore acking the STALE value (left over in the slot from a prior test) instead of the next real send. The downstream wait_for_reload_ack(my_request_id) then saw an ack with a foreign request_id, failed the match, and waited indefinitely for the next ack — which never came, because no one re-acked the new signal that do_reload had just sent.

Fix: call borrow_and_update() once immediately after subscribe to mark the current value as seen (and ack any stale value, so a future wait_for_reload_ack doesn't trip on a leftover ack from a finished test). The loop now waits on changed() for a real new send. This mirrors the working pattern already in tool/selfdev/tests.rs::build_reload_waits_for_build_then_reloads (which had the same stale-slot problem and the same fix).

Verified empirically with a minimal tokio test:

  • Fresh receiver + prior tx.send + no borrow_and_update → first changed().await returns Ok(Ok(())) (BUG: fires immediately)
  • Same setup but call borrow_and_update() first → first changed().await returns Err(Elapsed) (CORRECT: waits for next send)

Flake 2 — background_task_wake_runs_live_session_immediately_when_idle

Root cause: v2 added invalidate_config_cache() to ScopedEnvVar::set/drop for config-driven keys. That handles the SEQUENTIAL case: by the time the read-side test starts after the write-side test drops, the cache fingerprint has been invalidated and a re-read returns the default WakeMode::Channel.

But the read-side test does NOT acquire storage::lock_test_env(). With --test-threads=2, the read-side test can start before the write-side test drops its ScopedEnvVar. At that point both the env var and the config cache still show WakeMode::External, emit_external_wake (in server/background_tasks.rs:23) short-circuits run_live_turn_if_idle, the asserted TextDelta never arrives, and the test times out at .expect("wake delivery should start streaming promptly").

Fix: add let _env_lock = crate::storage::lock_test_env(); as the first statement in the test. This serializes it with the write-side test (external_background_task_wake_emits_request_without_starting_turn) for the test's duration, so the read-side test cannot start while the write-side test still holds its ScopedEnvVar (which itself holds the mutex). v2's cache invalidation on drop then keeps things correct for subsequent sequential readers.

The v2 commit message's "1271 passed; 2 failed" → "1272 passed; 1 failed" claim was misleading: the 1 still-failing test was Flake 1, not Flake 2. Confirmed with debug prints at --test-threads=2 to reproduce the actual race.

Verification

  • Full jcode-app-core lib: 1273 passed; 0 failed; 28 ignored; 0 measured (single run, 63.6s)
  • Full server:: suite: 451 passed; 0 failed — confirmed across 4 consecutive runs
  • tool::selfdev suite: 34 passed; 0 failed (regression check on the selfdev reload path)
  • Both flakes still pass in isolation (regression check)

Files changed

  • crates/jcode-app-core/src/server/tests.rs — Flake 2 fix (10 lines added)
  • crates/jcode-app-core/src/server/debug_command_exec.rs — Flake 1 fix (35 lines added, 4 modified)
  • Total: 2 files, +45/-4

Ledger

tx-agent:     jcode
tx-task:      issue-46
tx-parent:    794f984da (v2)
tx-validated: test (4 consecutive full server:: runs + 1 full lib run)
tx-scope:     jcode-app-core/test
tx-intent:    fix two pre-existing --lib suite-state-pollution flakes rooted in stale global channels and missing parallel-test serialization

Out of scope (intentionally not touched)


CodeAnt-AI Description

Stabilize parallel server tests affected by shared state

What Changed

  • Reload tests skip and acknowledge stale signals so they wait for the signal created by the current test.
  • Wake tests serialize access to shared environment settings so parallel tests cannot change the wake mode mid-run.

Impact

✅ Fewer false reload-test timeouts
✅ Reliable wake tests during parallel runs
✅ More consistent server test results

💡 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.

…flakes (#46)

Two flakes in the full `server::` test suite that passed in isolation but
failed under parallel `--test-threads>1` execution were each rooted in a
distinct gap between the sequential assumption baked into the v2 commit
(`narrow config invalidation to JCODE_WAKE_MODE`, 794f984) and what
parallel test execution actually requires.

# Flake 1 — `debug_tool_selfdev_reload_returns_promptly_for_direct_execution`

The test subscribes to the process-global `RELOAD_SIGNAL` watch channel and
spawns a task that loops on `changed()` then acks whatever signal arrives.
The intent (per the existing comment) was to skip any pre-existing value in
the slot and only ack the *next* send, which is what `do_reload`
→ `send_reload_signal` will produce and what `wait_for_reload_ack` is
waiting for (matched on `request_id`).

In isolation the slot starts at `None` and the contract trivially holds. In
the full suite, a prior test leaves `Some(stale_signal)` in the slot. The
critical bug: `changed()` on a freshly-cloned `tokio::sync::watch::Receiver`
treats the unseen current value as a change and returns immediately (verified
empirically with a minimal `tokio` test). The ack_task therefore acks the
STALE signal, and `wait_for_reload_ack(my_request_id)` then sees an ack
with a foreign `request_id`, fails the match, and waits indefinitely for
the next ack — which never comes, because no one will re-ack the *new* signal
that `do_reload` just sent. The test's outer 2 s timeout fires.

Fix: mark the current value as seen via `borrow_and_update()` immediately
after subscribing (and ack any stale value so a future `wait_for_reload_ack`
match doesn't trip on a leftover ack from a finished test). The loop now
waits on `changed()` for a real new send. This is the same pattern already
used in `tool/selfdev/tests.rs::build_reload_waits_for_build_then_reloads`
(also held up by a stale `RELOAD_SIGNAL` slot, with the same fix).

# Flake 2 — `background_task_wake_runs_live_session_immediately_when_idle`

v2 already added `invalidate_config_cache()` to both `ScopedEnvVar::set`
and `ScopedEnvVar::drop` for config-driven keys. That handles the
*sequential* case: by the time the read-side test starts after the
write-side test drops, the cache fingerprint has been invalidated and a
re-read returns the default `WakeMode::Channel`.

But the read-side test does not acquire `storage::lock_test_env()`. With
`--test-threads=2`, the read-side test can start *before* the write-side
test drops its `ScopedEnvVar`. At that point both the env var and the
config cache still show `WakeMode::External`, `emit_external_wake` (in
`server/background_tasks.rs`) short-circuits `run_live_turn_if_idle`, the
asserted `TextDelta` never arrives, and the test times out at
`.expect("wake delivery should start streaming promptly")`.

v2's commit message claimed this fix took the suite from
`1271 passed; 2 failed` to `1272 passed; 1 failed`, but the failing
test reported there was Flake 1, not Flake 2. Re-validated with debug
prints at `--test-threads=2` to confirm the actual race.

Fix: add `let _env_lock = crate::storage::lock_test_env();` as the first
statement in the test. This serializes it with the write-side test for
the test's duration, so the read-side test cannot start while the
write-side test still holds its `ScopedEnvVar` (which itself holds the
mutex). The v2 cache invalidation on drop then keeps things correct for
subsequent sequential readers.

# Verification

Both flakes now pass consistently. Full `jcode-app-core` lib:
`1273 passed; 0 failed; 28 ignored; 0 measured` (single run).
Full `server::` suite: `451 passed; 0 failed` (4 consecutive runs).
`tool::selfdev` suite: `34 passed; 0 failed`.

tx-agent:     jcode
tx-task:      issue-46
tx-parent:    794f984
tx-validated: test
tx-scope:     jcode-app-core/test
tx-intent:    fix two pre-existing --lib suite-state-pollution flakes rooted in stale global channels and missing parallel-test serialization
Copilot AI balanced review requested due to automatic review settings October 12, 2026 04:43

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 12, 2026 •

Copy link
Copy Markdown

🤖 CodeAnt AI — Review Status

Status Commit Started (UTC) Finished (UTC)
✅ Reviewed your PR 51fe7f2 Oct 12, 2026 · 04:43 04:47

@codeant-ai

codeant-ai Bot commented Oct 12, 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 12, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 79ba3055-2d17-4821-bec9-91d2c3876f00

📥 Commits

Reviewing files that changed from the base of the PR and between 794f984 and 51fe7f2.


📒 Files selected for processing (2)
  • crates/jcode-app-core/src/server/debug_command_exec.rs
  • crates/jcode-app-core/src/server/tests.rs

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.


📜 Recent review details
⏰ Context from checks skipped due to timeout. (2)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Kilo Code Review

🔇 Additional comments (2)
crates/jcode-app-core/src/server/tests.rs (1)

354-363: LGTM!


crates/jcode-app-core/src/server/debug_command_exec.rs (1)

728-728: LGTM!

Also applies to: 756-763



📝 Summary

Summary

The PR fixes two test races in jcode-app-core. The reload test marks the current watch value as seen and acknowledges any stale signal before waiting for a new signal. The background-task wake test acquires the shared test-environment lock before running.

The PR author reports that the affected tests passed in isolation, the server:: suite passed four consecutive runs, and the jcode-app-core lib and tool::selfdev suites passed. The author also reports a separate timeout in viewer_attach_reuses_live_owner_without_tracking_placeholder, which is out of scope.

Must Fix

No blocking issues are established by the supplied evidence. Current review finding counts are unavailable.

Should Fix

No non-blocking review findings were supplied.

Consider

The reported test results are author-provided. This review did not independently run the tests.

Approve / Request Changes

Approve based on the inspected changes and supplied evidence.

Walkthrough

Two server tests now synchronize access to shared state. The reload test handles existing and subsequent watch signals. The background-task wake test holds the shared environment lock during its assertions.

Changes

Reload signal test

Layer / File(s) Summary
Reload watch handling
crates/jcode-app-core/src/server/debug_command_exec.rs
The test marks an existing watch value as seen and acknowledges it before reload. Its acknowledgement task waits for a later signal and exits if the sender closes.

Background-task wake test

Layer / File(s) Summary
Wake test environment lock
crates/jcode-app-core/src/server/tests.rs
The test acquires the shared environment lock while checking background-task wake behavior.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Other

Suggested reviewers: 1jehuang


Merge Risk: ⚪ Minimal · up to 51fe7

No actionable merge-blocking risk is identified in these test changes; they are ready for normal merge checks.

Architecture Summary

Architecture risk: 🔵 Low · up to 51fe7

The change affects 1 system.

Changed systems: crates

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — crates (service) was modified; 2 changed files map to changed impact.

Before / after behavior

  • observed — Modified behavior in crates/jcode-app-core/src/server/debug_command_exec.rs: Before the test’s reload, it now marks any existing watch value as seen and acknowledges it if present, preventing the stale value from being treated as the test’s signal.
  • observed — Modified behavior in crates/jcode-app-core/src/server/debug_command_exec.rs: The ack task now waits for a watch change before reading and acknowledging a signal, rather than checking the current value first. If the sender closes, the task returns instead of panicking.
  • observed — Modified behavior in crates/jcode-app-core/src/server/tests.rs: The test now holds the shared environment lock while running, preventing concurrent environment-mutating tests from changing JCODE_WAKE_MODE during its wake assertions.

Pre-merge checks | Passed 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description check Passed The description clearly explains both parallel-test races, their root causes, the fixes, verification results, and scope.
Title check Passed The title clearly identifies the test suite and the main change: fixing two pre-existing suite-state-pollution flakes.
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 2 files.
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.

✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR


🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

✨ Simplify code
  • Commit to this branch
  • Create a new PR

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

Some tools did not complete. Review the errors below.

🔧 Clippy (1.98.1)

Clippy execution timed out



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 12, 2026
@codeant-ai

codeant-ai Bot commented Oct 12, 2026

Copy link
Copy Markdown

CodeAnt Nitpicks

1 code suggestion

1. When another test sends a reload signal first, this watcher wakes and acknowledges it, then exits; this test's request receives no ack and times out.

Race condition · crates/jcode-app-core/src/server/debug_command_exec.rs:756-763

@codeant-ai

codeant-ai Bot commented Oct 12, 2026

Copy link
Copy Markdown

CodeAnt PR Risk: Low Risk

  • The PR appears safe to merge; the changes are limited to test synchronization.
  • The reload test skips and acknowledges stale signals, while the background-task test serializes access to environment settings.

Assessed commit: 51fe7f2fc5ca

// to the ack channel so `wait_for_reload_ack` (which `do_reload`
// awaits synchronously) returns promptly.
loop {
if reload_rx

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

WARNING: Latent race — the ack task returns after the first signal it observes, even if that signal belongs to another test's do_reload. If a foreign signal arrives between subscribe and this test's own send_reload_signal, the ack task acks it and exits, leaving this test's real signal unacked; wait_for_reload_ack then times out and the test fails. The sibling pattern in tool/selfdev/tests.rs::build_reload_waits_for_build_then_reloads (lines 886-890) loops on changed() and acks every signal instead of returning on the first — that is the correct shape for a process-global channel. The current lock_env() guard masks this under today's suite, but the code will flake again the moment a reload path is exercised outside that lock (or if the lock is ever relaxed). Consider mirroring the loop-forever pattern.


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

// `changed()` await wait for an actual new send. The mirror pattern
// lives in `tool/selfdev/tests.rs::build_reload_waits_for_build_then_reloads`
// (which pre-acks the current value then loops on `changed()`).
let stale_at_subscribe = reload_rx.borrow_and_update().clone();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

SUGGESTION: The stale-signal ack block (lines 728-736) is redundant: the spawned ack task already acks the current value at lines 764-767 before returning, so the pre-ack here can only fire for a signal that the loop would ack immediately afterward anyway. Acking twice is harmless (the ack channel is a watch slot), but the block adds dead-looking code and duplicates the explanation already carried by the loop comment. Consider removing lines 728-736 and relying solely on the loop, or (if kept) shorten the comment to avoid restating the loop's rationale.


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

// `run_live_turn_if_idle`, and the asserted `TextDelta` never arrives.
// The mutex is the existing process-wide serialization point for
// env-mutating tests in this crate, so we use it here too.
let _env_lock = crate::storage::lock_test_env();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

SUGGESTION: crate::storage::lock_test_env() is the crate-wide process mutex, so holding it for the full duration of this test serializes every env-mutating test in jcode-app-core behind it (e.g. external_background_task_wake_emits_request_without_starting_turn, the reload_recovery IsolatedHome tests, swarm.rs:1907, etc.). That is correct for correctness but will slow the parallel suite. The lock is justified and is the established pattern, but if the suite ever needs more parallelism, consider a finer-grained lock scoped to JCODE_WAKE_MODE mutation rather than the global env lock.


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

@kilo-code-bot

kilo-code-bot Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Code Review Summary

Status: 3 Issues Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 1
SUGGESTION 2
Issue Details (click to expand)

WARNING

File Line Issue
crates/jcode-app-core/src/server/debug_command_exec.rs 756 Ack task returns on the first observed signal; a foreign signal from another test's do_reload would be acked and this test's own signal left unacked, causing a timeout. The sibling pattern in tool/selfdev/tests.rs::build_reload_waits_for_build_then_reloads loops on changed() and acks every signal instead.

SUGGESTION

File Line Issue
crates/jcode-app-core/src/server/debug_command_exec.rs 728 The stale-signal pre-ack block (728-736) is redundant with the loop's ack at 764-767; the pre-ack can only fire for a value the loop would ack immediately afterward.
crates/jcode-app-core/src/server/tests.rs 363 Holding the crate-wide lock_test_env() for the full test serializes every env-mutating test in jcode-app-core behind it. Justified for correctness, but consider a finer-grained lock scoped to JCODE_WAKE_MODE if parallelism is ever needed.
Files Reviewed (2 files)
  • crates/jcode-app-core/src/server/debug_command_exec.rs - 2 issues (1 WARNING, 1 SUGGESTION)
  • crates/jcode-app-core/src/server/tests.rs - 1 issue (SUGGESTION)

Reviewed by free · Input: 769.4K · Output: 32.6K · Cached: 317.4K

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.

2 participants