Repository navigation
fix(cli): report Ctrl+C during reload readiness wait as canceled, not a shard failure - #1154
detail-app[bot] wants to merge 7 commits into
Conversation
smsunarto
left a comment
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · Argus PR review / Argus-Labs/world-engine
Architecture: keep the command-layer fix; tighten tests and finish cancellation presentation in the reload hotkeys. Checking the caller context before interpreting counts correctly separates Ctrl+C from the runtime's internal readiness timeout. The narrow interface follows the existing shardBuilder seam, and no new polling or concurrency is introduced.
The reviewers disagreed about widening WaitForShardsReady to return an error. I would keep this patch scoped: MCP callers have the same pre-existing classification problem, but changing their contract is a separate follow-up. The two context reads leave a very small presentation race; there is no reproduced operational failure warranting an API redesign here. NewSilent and the canceled row duplicate existing phasebox helpers; simplifying them is optional. Caller DeadlineExceeded is broader than phasebox's cancellation contract, but no current root caller supplies such a deadline, so this remains latent rather than a blocking defect. The author already documents start cleanup and exit code 1.
Findings: the new runtime test depends on real port 8081 and a 100 ms first-progress assumption; a typed-nil NotErrorIs assertion does not check error type; two comments describe guarantees the runtime does not provide. The reload hotkey callers also still print Reload failed: context canceled for the newly silent error. Details are inline.
Small cleanup nits:
reload_internal_test.go:22,32: remove unreadlabelstorage and make unusedFailan empty stub.reload_internal_test.go:62,245: the callback is always nonnil on these paths; drop those guards.reload_internal_test.go:18,238: only the final row is inspected; retaining the history is unnecessary. The two waiter fakes can share one implementation with an explicit progress-on-cancel option.reload_internal_test.go:140: this case cancels before progress; correct “after at least one progress tick.”runtime_internal_test.go:399: qualify the zero-count/no-progress claim as cancellation before the first completed probe round. Mid-wait cancellation returns the last completed count.reload.go:315,353:Box.Runalready silencescontext.Canceled, andsess.Failalready supplies the canceled row label.
Follow-up questions: should MCP cancellation parity be handled separately? Which healthy shard fixture can support repeatable end-to-end start/reload verification? The author explicitly could not exercise the healthy path; no success-path regression is established.
Verification: Claude reported focused readiness tests, go vet, and focused race tests PASS. Codex used source inspection. Full CLI lint/tests, Docker, and terminal rendering were not independently verified by this run. Author-reported end-to-end results remain author claims. No existing PR reviews or CI evidence were read; no code was edited.
Coverage: both independent Architecture assessments and all eleven lens reports per provider were collected. All 22 unique leaf IDs, providers, parents, lifecycle owners, and the shared environment were checked. No failed launches, recovery attempts, replacements, or gaps. Both reviewed base a94a9fc30a9860c62bc5badb8e131f8c7fc4b886 → head cd98e50e92048a516e7143100daae125f4c4ecdc.
Lens attestation
| Lens | Claude (parent thr_ybk4gf66s9) | Codex (parent thr_hwqmbyrtt7) |
|---|---|---|
| A | thr_4rgqkqejvt — complete | thr_9ycdgb242a — complete |
| B | thr_vcm4qsabew — complete | thr_bt897eeyi2 — complete |
| C | thr_isutbu2gwi — complete | thr_haxj8kiudk — complete |
| D | thr_8wdx6npaez — complete | thr_ky4usu7ckp — complete |
| E | thr_picb68n6jp — complete | thr_fmg25sn42u — complete |
| F | thr_mq59ssjy5d — complete | thr_da8s6szbg6 — complete |
| G | thr_y8t2efai4d — complete | thr_hn4mtnr9kc — complete |
| H | thr_hbxm53qwvu — complete | thr_zeaa3rpz35 — complete |
| J | thr_j6nspsac8k — complete | thr_68a339r45a — complete |
| K | thr_fq5srutteq — complete | thr_mwgjx9kzx7 — complete |
| I | thr_knzzhtqppj — complete | thr_w99pb8fpdr — complete |
| ready, expected = waiter.WaitForShardsReady(ctx, instanceIDs, onProgress) | ||
| }) | ||
| if ctx.Err() != nil { | ||
| return errorspkg.NewSilent(ctx.Err()) |
There was a problem hiding this comment.
[P2] The reload hotkeys still print this silent cancellation as a failure. handleReloadHotkey (logs.go:170-171) and the tail reload path (internal/logs/shard.go:75-76) print every nonnil error, so Ctrl+C during readiness still produces Reload failed: context canceled and resumes the picker/tail. Can those callers honor errorspkg.ShouldPrint as part of this fix?
There was a problem hiding this comment.
Not addressed in this PR — keeping it scoped as the review summary recommended. I checked the path: the hotkey/tail reload callers (handleReloadHotkey in cli/commands/root/logs.go:170 and the tail reload in cli/internal/logs/shard.go:75) route through reloadShards → deployShardImages → rollShards, which now returns a silent cancel, but those two callers print every non-nil error via printer.Errorf("Reload failed: %v", rerr). Making them honor errorspkg.ShouldPrint would touch cli/commands/root/logs.go and cli/internal/logs/shard.go, neither of which is in this PR's diff. That's a separate follow-up (the review summary also flagged MCP callers as the same pre-existing classification problem). This PR's scope is the rollShards readiness-wait misclassification, which is fixed.
| defer cancel() | ||
|
|
||
| var progressCalls int | ||
| ready, expected := r.WaitForShardsReady(ctx, nil, func(_, _ int) { progressCalls++ }) |
There was a problem hiding this comment.
[P2] Please control the readiness probe in this test. The fixture probes real 127.0.0.1:8081 regardless of its project name; any running world (or other HTTP server) makes ready=1 and fails the zero-ready assertion. A slow first response or scheduler pause can also consume the 100 ms caller deadline before progress is published, failing the callback assertion. Use a controlled endpoint/probe and synchronize cancellation with observed progress.
There was a problem hiding this comment.
Addressed in 5065c77 — the live-context test now binds the shard probe port and resets every connection, so it no longer depends on whether 127.0.0.1:8081 happens to be (un)occupied. It skips if the port can't be bound (environment holds it), and resetting makes the first probe round complete well before the caller deadline so progress is reliably published. Used a 1s caller deadline for scheduler tolerance; the cancel contract test already covers cancellation before any progress.
| assert.True(t, errorspkg.IsSilent(err), "a cancel must be silent, not a failure") | ||
| assert.ErrorIs(t, err, context.Canceled, "silent error must wrap context.Canceled") | ||
| var notReady *shardsNotReadyError | ||
| assert.NotErrorIs(t, err, notReady, "must not be a shardsNotReadyError") |
There was a problem hiding this comment.
[P3] notReady is a typed nil, so NotErrorIs does not exclude a nonnil *shardsNotReadyError. Use assert.False(t, errors.As(err, ¬Ready)) to check the error type.
There was a problem hiding this comment.
Addressed in 5065c77 — replaced the typed-nil NotErrorIs with assert.False(t, errors.As(err, ¬Ready)) so the type check actually runs.
| } | ||
|
|
||
| // WaitForShardsReady with a live context and no serving shards still | ||
| // terminates (via the 2-minute deadline) and reports the last known count. |
There was a problem hiding this comment.
[P3] This test expires the caller context after 100 ms; it does not exercise the internal two-minute readiness deadline with a live caller. At return, ctx.Err() is DeadlineExceeded, which the new command helper classifies as silent cancellation. Please describe this as caller-deadline coverage rather than proof of the genuine timeout path.
There was a problem hiding this comment.
Addressed in 5065c77 — reframed the test doc as caller-deadline coverage (the caller's context expires while ctx is otherwise live), explicitly noting it does not exercise the genuine internal 2-minute readiness deadline with a live caller.
| // protects a future waitForReady that could return without reporting anything. | ||
| // set Active on every tick, then closed to Done when ready >= expected, Failed | ||
| // ("canceled") when ctx was canceled, or Failed ("timed out …") otherwise. The | ||
| // progressed guard is defensive: WaitForShardsReady always ticks at least once |
There was a problem hiding this comment.
[P3] The runtime can already return before any progress callback when cancellation lands during the first probe round; the new tests explicitly cover that. Please replace the always-ticks guarantee with the actual reason for the guard: cancellation before the first completed probe round can produce no progress row.
There was a problem hiding this comment.
Addressed in 5065c77 — rewrote the comment to state the real reason (cancellation before the first completed probe round yields no progress callback) instead of the incorrect "always ticks at least once" claim.
|
Re: #1154 (review) Addressed in 5065c77 the substantive findings and doc nits:
Skipped as out of scope / optional, per the review summary's own scoping:
go build/vet/gofmt clean; full |
smsunarto
left a comment
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · Argus PR review / Argus-Labs/world-engine
Checking the caller context before interpreting incomplete counts fits the existing reload boundary and preserves genuine readiness failures.
The log picker and log tail still unconditionally print Reload failed: %v when their reload callback returns an error, including this silent cancellation. Could those callers honor the silent-error contract too, so interrupting readiness from either surface doesn't still announce a reload failure?
MCP reload/start also consume the counts-only API directly. Should cancellation handling cover those callers here, or should that be a follow-up?
| waitForShardsReadyRow(ctx, sess, func(onProgress func(ready, expected int)) { | ||
| ready, expected = waiter.WaitForShardsReady(ctx, instanceIDs, onProgress) | ||
| }) | ||
| if ctx.Err() != nil { |
There was a problem hiding this comment.
Do we want caller deadlines to be silent too? With a deadline-bearing context, this labels the row canceled, but phasebox recognizes only context.Canceled, so its summary says failed — see error below while the silent wrapper hides that error.
If silence is only for Ctrl+C, distinguish cancellation from deadline expiry and cover both outcomes.
There was a problem hiding this comment.
Addressed in a437833. waitForShardsReadyResult now silences only context.Canceled; a caller deadline (DeadlineExceeded) falls through to shardsNotReadyError and the row renders 'timed out', so a deadline-bearing context no longer labels the row 'canceled' while the silent wrapper hides the error. Added deadline tests for both the helper and the row renderer.
| ready, expected = waiter.WaitForShardsReady(ctx, instanceIDs, onProgress) | ||
| }) | ||
| if ctx.Err() != nil { | ||
| return errorspkg.NewSilent(ctx.Err()) |
There was a problem hiding this comment.
Optional nit: Box.Run already wraps context.Canceled as silent, and JoinFailures already recognizes bare cancellation. Could this return ctx.Err() and leave presentation to that existing owner? The focused test could assert the wrapped cancellation cause instead.
There was a problem hiding this comment.
Kept the explicit errorspkg.NewSilent in the helper so its unit tests assert the silent contract directly. Returning bare ctx.Err() would push silencing to Box.Run and require reworking the helper tests (CancelSurvivesJoinFailures asserts IsSilent on the helper's return) to assert the wrapped cause instead — a larger change for no functional gain, since Box.Run re-wrapping an already-silent Canceled is harmless. Left as-is.
| if lastReady < expected { | ||
| switch { | ||
| case ctx.Err() != nil: | ||
| state, detail = phasebox.Failed, "canceled" |
There was a problem hiding this comment.
Optional nit: for context.Canceled, could we use sess.Fail("ready", "Waiting for shards ready", ctx.Err())? Phasebox already owns the failed/canceled row formatting. Keep the custom timeout detail separate; Fail does not classify deadline expiry as cancellation.
There was a problem hiding this comment.
Kept the unified switch in waitForShardsReadyRow. sess.Fail only classifies the canceled/failed binary; the timeout detail ('timed out (n/m ready)') needs a custom UpsertRow, so using sess.Fail for cancel and a separate UpsertRow for timeout would split one classification into two paths. The current switch keeps canceled / timed-out / Done in one place.
| // shards-not-ready failure. This is the core bug: without the ctx.Err() check | ||
| // the cancel reappears as shardsNotReadyError and the phasebox contract never | ||
| // fires. | ||
| func TestWaitForShardsReadyResult_CanceledReturnsSilent(t *testing.T) { |
There was a problem hiding this comment.
Could we add a regression through a plain phasebox Shards section as well? These assertions pin the helper error, but the reported bug also involved the section summary and printed diagnostic. The existing phasebox.Start(ctx, phasebox.Plain) pattern in build_internal_test.go should let us assert that cancellation produces canceled without a shard-failure message.
There was a problem hiding this comment.
Addressed in a437833. Added TestWaitForShardsReadyResult_CancelThroughPlainSectionIsCanceled, which runs waitForShardsReadyResult through a real phasebox.Plain Shards section (the build_internal_test.go pattern) and asserts the returned error is silent and wraps context.Canceled, not a shardsNotReadyError — i.e. the section classifies cancel as 'canceled' (Box.Run silences Canceled) without a shard-failure diagnostic.
| } | ||
|
|
||
| type fakeRow struct { | ||
| id, label, detail string |
There was a problem hiding this comment.
nit: fakeRow.label has no readers. Could we drop it, along with the unused receiver name on UpsertProgress and the unused callback parameter name in the no-progress test?
There was a problem hiding this comment.
Addressed in a437833. Dropped fakeRow.label, the unused receiver on UpsertProgress, and the unused callback param name in the no-progress test.
| // progressAlwaysWaiter is a shardReadinessWaiter that always calls onProgress, | ||
| // even on a canceled context — simulating a cancel that landed after at least | ||
| // one progress tick, so the row renderer gets a chance to show "canceled". | ||
| type progressAlwaysWaiter struct { |
There was a problem hiding this comment.
nit: these two readiness fakes duplicate their fields, callback, and return values; only progress after cancellation differs. Could one fake with a progressOnCancel option cover both cases?
There was a problem hiding this comment.
Addressed in a437833. Merged fakeReadinessWaiter and progressAlwaysWaiter into one fake with a progressOnCancel option; the after-progress-cancel test now uses fakeReadinessWaiter{..., progressOnCancel: true}.
| t.Skipf("cannot control probe port %d: %v", service.ShardHostPort(0), err) | ||
| } | ||
| defer ln.Close() | ||
| go func() { |
There was a problem hiding this comment.
nit: this accept-and-close listener repeats the loop in probe_internal_test.go. Could a shared test helper accept the bind address?
Also, can this test use an isolated probe port without a broad runtime refactor? Binding the fixed shard port means a running world or concurrent test can make it skip coverage.
There was a problem hiding this comment.
A shared accept-and-close helper would require editing probe_internal_test.go, which is not in this PR's diff. An isolated probe port would require parameterizing the probe address in local.Runtime (the port is fixed via service.ShardHostPort), a broader refactor outside this PR's scope. The test binds the fixed port with skip-if-held, as the previous round requested.
| // protects a future waitForReady that could return without reporting anything. | ||
| // set Active on every tick, then closed to Done when ready >= expected, Failed | ||
| // ("canceled") when ctx was canceled, or Failed ("timed out …") otherwise. The | ||
| // progressed guard is defensive: cancellation before the first completed probe |
There was a problem hiding this comment.
The guard leaves the row absent when cancellation occurs before any progress; it doesn’t prevent a false cancellation claim, since ctx.Err() already establishes cancellation. Could the comment say that directly, and match the no-progress test comment?
Also, the callback fires when the ready count changes, rather than on every poll tick.
There was a problem hiding this comment.
Addressed in a437833. Rewrote the comment: the guard leaves the row absent (ctx.Err already establishes cancellation; the guard avoids rendering a terminal claim with no evidence) and onProgress fires when the ready count changes, not on every poll tick. The no-progress test comment matches.
| // WaitForShardsReady returns counts only (no error). A cancellation that lands | ||
| // before the first completed probe round collapses into a plain (0, expected) | ||
| // return without ever invoking onProgress; a mid-wait cancellation returns the | ||
| // last completed count. The no-progress case is what rollShards' ctx.Err() |
There was a problem hiding this comment.
nit: the context check now lives in waitForShardsReadyResult, rather than rollShards. Could we update this reference and the caller-deadline test’s comment to name the helper that owns classification?
There was a problem hiding this comment.
Addressed in a437833. Both comments now name waitForShardsReadyResult as the classification owner, and the caller-deadline test comment notes a DeadlineExceeded is classified as a real failure (only context.Canceled is silent).
|
|
||
| // Control the probe endpoint so the assertion does not depend on | ||
| // whatever happens to be (not) listening on the shard port in the | ||
| // environment. Bind the port the single shard resolves to and reset |
There was a problem hiding this comment.
nit: this listener accepts and closes connections; it doesn’t explicitly reset them. Could the comment say “close” so it describes the socket behavior the test actually sets up?
There was a problem hiding this comment.
Addressed in a437833. The comment now says 'close' (the listener does c.Close()), not 'reset'.
|
Re: #1154 (review) Out of scope for this PR, as the first review summary recommended keeping the patch scoped. The log picker / tail callers (cli/commands/root/logs.go, cli/internal/logs/shard.go) and the MCP reload/start callers are not in this PR's diff; honoring errorspkg.ShouldPrint there, and changing the MCP counts-only API contract, are separate follow-ups. This PR's scope is the rollShards readiness-wait misclassification, now fixed for both Ctrl+C (silent cancel) and caller deadlines (real failure). |
a437833 to
4a9fb46
Compare
smsunarto
left a comment
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · Argus PR review / Argus-Labs/world-engine
Keeping the cancellation check where readiness counts become a command error fits the existing design, and preserves the genuine timeout path.
I'd reuse phasebox's existing cancellation handling and tighten the regression assertions below.
| ready, expected = waiter.WaitForShardsReady(ctx, instanceIDs, onProgress) | ||
| }) | ||
| if errors.Is(ctx.Err(), context.Canceled) { | ||
| return errorspkg.NewSilent(ctx.Err()) |
There was a problem hiding this comment.
Nit: returning ctx.Err() is enough here. Box.Run already recognizes context.Canceled and wraps it as silent, so this adds a second wrapper. The helper tests can assert ErrorIs(err, context.Canceled) and leave the silent-error assertion at the phasebox boundary.
There was a problem hiding this comment.
Addressed in 8b119d9. waitForShardsReadyResult now returns bare ctx.Err() for context.Canceled; Box.Run silences Canceled at the section boundary. Helper tests assert ErrorIs(err, context.Canceled); the IsSilent assertion lives only at the phasebox section test.
| if lastReady < expected { | ||
| switch { | ||
| case errors.Is(ctx.Err(), context.Canceled): | ||
| state, detail = phasebox.Failed, "canceled" |
There was a problem hiding this comment.
Nit: could we use sess.Fail("ready", "Waiting for shards ready", ctx.Err()) for the canceled branch? Phasebox already owns the canceled label and Failed state. Keep the custom count-bearing detail for timeouts, and have the fake session record Fail calls.
There was a problem hiding this comment.
Addressed in 8b119d9. The canceled branch now calls sess.Fail("ready", "Waiting for shards ready", ctx.Err()) — phasebox owns the canceled label and Failed state. The timeout/Done branches keep their custom count-bearing UpsertRow. fakeSession.Fail records the row so the canceled-row test still asserts detail == "canceled".
| sess := &fakeSession{} | ||
| // Use a waiter that reports progress even on cancel (simulating a cancel | ||
| // that landed after a tick), to exercise the row + error path together. | ||
| err := waitForShardsReadyResult(ctx, sess, &fakeReadinessWaiter{ready: 0, expected: 2, progressOnCancel: true}, nil) |
There was a problem hiding this comment.
This starts with an already-canceled context, so it doesn't exercise the transition named by CanceledAfterProgress. Could we cancel from the progress callback after reporting a partial count, then assert both the canceled row and returned error? That would cover Ctrl+C arriving during the wait.
There was a problem hiding this comment.
Addressed in 8b119d9. The test now starts with a live context, reports a partial count (1/2), then cancels from the progress callback (onProgressHook: cancel), exercising the during-wait transition. Asserts the row renders "canceled" and the returned error wraps context.Canceled.
| }, | ||
| ) | ||
|
|
||
| require.Error(t, err) |
There was a problem hiding this comment.
A wrong Plain summary would still pass this test because it only checks the returned error. Could we capture the Plain output and assert that it contains canceled and omits the shard-failure diagnostic? That would verify the visible regression described above the test.
There was a problem hiding this comment.
Addressed in 8b119d9. Added errors.Is(ctx.Err(), context.DeadlineExceeded) after the wait, so a waiter that returned after its first failed probe would fail the assertion.
| // onProgress is called at least once (0/1 on the first tick) because the | ||
| // context is alive when the first round of probes completes. | ||
| if progressCalls == 0 { | ||
| t.Fatal("onProgress should be called at least once with a live context") |
There was a problem hiding this comment.
Could we also assert errors.Is(ctx.Err(), context.DeadlineExceeded) after the wait? These assertions would pass if the waiter returned immediately after its first failed probe. Checking the context would establish that this case actually waited for the caller deadline.
There was a problem hiding this comment.
Addressed in 8b119d9. The test now captures phasebox's Plain output (redirecting os.Stdout around Start, since d.plain is private to package root) and asserts it contains "canceled" and omits the shard-failure diagnostic ("instances are serving").
| t.Skipf("cannot control probe port %d: %v", service.ShardHostPort(0), err) | ||
| } | ||
| defer ln.Close() | ||
| go func() { |
There was a problem hiding this comment.
Nit: this accept-and-close loop also exists in probe_internal_test.go. Could we share a small helper that takes an already-bound listener, keeping each test’s port selection and failure handling at the call site?
There was a problem hiding this comment.
A shared accept-and-close helper would require editing probe_internal_test.go, which is not in this PR's diff. Left the inline listener as-is; the comment already says "close" (the listener does c.Close()).
| WaitForShardsReady(ctx context.Context, instanceIDs []string, onProgress func(ready, expected int)) (int, int) | ||
| } | ||
|
|
||
| // waitForShardsReadyResult waits for the targeted instances to serve and |
There was a problem hiding this comment.
Nit: this comment can just state the invariant: the waiter returns counts without an error, cancellation stays cancellation, and caller deadlines remain readiness failures. The branch-by-branch explanation below repeats the implementation.
There was a problem hiding this comment.
Addressed in 8b119d9. Trimmed the comment to the invariant: the waiter returns counts without an error, cancellation stays cancellation (passed through for phasebox to silence at the section boundary), and caller deadlines remain readiness failures.
|
|
||
| // The readiness row labels a caller deadline as "timed out", not "canceled" — | ||
| // only context.Canceled is a cancel; DeadlineExceeded is a real timeout. | ||
| func TestWaitForShardsReadyRow_DeadlineShowsTimedOut(t *testing.T) { |
There was a problem hiding this comment.
Nit: this and TimeoutShowsTimedOut have the same setup and row assertions apart from the caller context. A table with live and expired contexts would preserve both cases without duplicating the test body.
There was a problem hiding this comment.
Addressed in 8b119d9. TimeoutShowsTimedOut is now a table test over live and expired-deadline contexts; the separate DeadlineShowsTimedOut is gone.
| // --- waitForShardsReadyResult ----------------------------------------------- | ||
|
|
||
| // Ctrl+C before the first progress tick is a silent cancel, not a | ||
| // shards-not-ready failure. This is the core bug: without the ctx.Err() check |
There was a problem hiding this comment.
Nit: could we trim the comments that repeat the test names and assertions, and keep the ones explaining the no-progress contract? The PR-history narration here makes the regression cases harder to scan.
There was a problem hiding this comment.
Addressed in 8b119d9. Trimmed the PR-history narration on the readiness-wait tests; kept the no-progress contract comments.
| // is silent), so this does not exercise the silent-cancel path. It also does | ||
| // not exercise the genuine internal 2-minute readiness deadline with a live | ||
| // caller. | ||
| func TestWaitForShardsReady_LiveContextNoServersReturnsZero(t *testing.T) { |
There was a problem hiding this comment.
Nit: could we name this CallerDeadlineReturnsLastCount? It uses a listener and waits for a caller deadline, so LiveContextNoServersReturnsZero obscures what the test actually covers.
There was a problem hiding this comment.
Addressed in 8b119d9. Renamed to TestWaitForShardsReady_CallerDeadlineReturnsLastCount.
|
Re: #1154 (review) Addressed in 8b119d9. The reload hotkey canceled branch now reuses phasebox's sess.Fail for the canceled row, and waitForShardsReadyResult returns bare ctx.Err() so Box.Run silences it at the section boundary. The regression assertions are tightened: the after-progress test cancels from the progress callback, the Plain-section test captures the summary and asserts "canceled" with no shard-failure diagnostic, and the caller-deadline runtime test asserts the deadline actually expired. Details inline. |
smsunarto
left a comment
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · Argus PR review / Argus-Labs/world-engine
Passing cancellation back to phasebox fits the existing error handling and gives reload/start the intended canceled result. The new coverage also preserves genuine readiness failures.
There are a few concrete test and lint fixes below.
| orig := os.Stdout | ||
| r, w, err := os.Pipe() | ||
| require.NoError(t, err) | ||
| os.Stdout = w |
There was a problem hiding this comment.
The new stdout assignments trip reassign under the CLI lint configuration. Please use the documented test-only suppressions already used in printer_internal_test.go.
The added code also needs the long call in reload.go:359 wrapped, context.Background passed directly at line 110, and standard-library doc links such as [context.Canceled] in the new test comments.
There was a problem hiding this comment.
Addressed in c6ef3b8. Added //nolint:reassign on the stdout redirects (matching printer_internal_test.go), wrapped the long UpsertRow call in reload.go, simplified the live-context table case to context.Background, and added stdlib doc links ([context.Canceled]/[context.DeadlineExceeded]) in the test comments.
| cancel() | ||
|
|
||
| orig := os.Stdout | ||
| r, w, err := os.Pipe() |
There was a problem hiding this comment.
nit: defer r.Close() after creating the pipe too; closing the writer and reading EOF leaves the reader descriptor open.
There was a problem hiding this comment.
Addressed in c6ef3b8. Added defer r.Close() after the pipe so the reader descriptor is closed once io.Copy completes.
| var progressCalls int | ||
| ready, expected := r.WaitForShardsReady(ctx, nil, func(_, _ int) { progressCalls++ }) | ||
|
|
||
| if ready != 0 { |
There was a problem hiding this comment.
This last-count test would still pass if the waiter always returned zero on a deadline. Could we make one of two instances ready, observe partial progress, then expire the caller context and assert that the positive count survives?
There was a problem hiding this comment.
Addressed in c6ef3b8. The test now has two shards: one serves a real HTTP 200, the other stays down. onProgress observes 1/2, the caller deadline fires, and the returned count is 1 — the positive count survives.
|
|
||
| func (*fakeSession) UpsertProgress(string, string, int) {} | ||
|
|
||
| func (f *fakeSession) Fail(id, label string, err error) { |
There was a problem hiding this comment.
The canceled-row assertions currently check the label mapping implemented by this fake, so they would pass even if the real session stopped recognizing cancellation. Record the error passed to Fail and assert errors.Is(err, context.Canceled) at this boundary; leave label rendering to phasebox coverage.
If keeping the row recorder, nit: use f.UpsertRow for the append and pass label through rather than duplicating it.
There was a problem hiding this comment.
Addressed in c6ef3b8. fakeSession.Fail now records failID/failErr and delegates the row to f.UpsertRow (passing label through); the canceled-row tests assert errors.Is(failErr, context.Canceled) at that boundary, and the err→"canceled" label mapping is left to phasebox coverage.
| var notReady *shardsNotReadyError | ||
| assert.False(t, errors.As(runErr, ¬Ready), "must not be a shardsNotReadyError") | ||
| assert.Contains(t, out.String(), "canceled", "plain summary must say canceled") | ||
| assert.NotContains(t, out.String(), "instances are serving", "plain summary must omit the shard-failure diagnostic") |
There was a problem hiding this comment.
nit: this diagnostic assertion cannot catch the original failure: the plain phasebox summary never includes error text, even for shardsNotReadyError. The silent-error and cancellation assertions above are useful; remove this assertion or check the output at the ShouldPrint boundary.
There was a problem hiding this comment.
Addressed in c6ef3b8. Removed the NotContains("instances are serving") assertion — the plain phasebox summary never surfaces error text, so it could not catch the regression. The IsSilent/ErrorIs/not-shardsNotReadyError/Contains("canceled") assertions above cover the boundary.
| assert.False(t, errors.As(err, ¬Ready), "must not be a shardsNotReadyError") | ||
| } | ||
|
|
||
| // Ctrl+C arriving during the wait — after a partial count was reported — is |
There was a problem hiding this comment.
nit: this helper returns context.Canceled directly; it does not wrap it. Say “returns context.Canceled” here so the comment keeps wrapping ownership at the phasebox section boundary.
There was a problem hiding this comment.
Addressed in c6ef3b8. Reworded to say the helper returns [context.Canceled] (not wrapped), keeping wrapping ownership at the phasebox section boundary.
| // WaitForShardsReady with a live caller deadline (not the internal 2-minute | ||
| // readiness timeout) and no serving shards still terminates and reports the | ||
| // last known count. This is caller-deadline coverage — the caller's context | ||
| // expires while ctx is otherwise live. waitForShardsReadyResult's ctx.Err() |
There was a problem hiding this comment.
nit: ctx is the caller context here, so it does not stay live when the caller deadline expires. Describe this as preserving the last completed count on a caller deadline, and keep the distinction from the internal readiness timeout.
There was a problem hiding this comment.
Addressed in c6ef3b8. Reworded the comment to describe preserving the last completed count on a caller deadline, noting the caller context does not stay live after the deadline, distinct from the internal 2-minute readiness timeout.
|
|
||
| // shardReadinessWaiter is the subset of local.Runtime the readiness wait uses. | ||
| // Defined as an interface so the wait's cancel handling can be unit-tested | ||
| // without a running daemon; *local.Runtime satisfies it. |
There was a problem hiding this comment.
nit: say “without live shards” here. This waiter probes host ports and does not need a Docker daemon even without the interface seam.
There was a problem hiding this comment.
Addressed in c6ef3b8. Changed to "without live shards" — this waiter probes host ports and does not need a Docker daemon.
| switch { | ||
| case errors.Is(ctx.Err(), context.Canceled): | ||
| sess.Fail("ready", "Waiting for shards ready", ctx.Err()) | ||
| return |
There was a problem hiding this comment.
nit: this return is redundant; the switch is the last statement in the function.
There was a problem hiding this comment.
Addressed in c6ef3b8. Removed the redundant return — the switch is the last statement in the function.
| // always ticks at least once because its counter starts below zero, so it only | ||
| // protects a future waitForReady that could return without reporting anything. | ||
| // onProgress when the ready count changes (local.Runtime.WaitForShardsReady). | ||
| // The row is set Active on every progress callback, then closed to Done when |
There was a problem hiding this comment.
nit: this comment lists success before cancellation, but the switch gives cancellation precedence even when the counts are complete. Describe that order accurately and retain the useful explanation of the no-progress case.
There was a problem hiding this comment.
Addressed in c6ef3b8. Reordered the comment to list cancellation before success (cancellation takes precedence even when counts are complete) and kept the no-progress explanation.
|
Re: #1154 (review) Addressed in c6ef3b8. All ten inline nits from this review pass: reassign suppressions on the stdout redirects, the pipe reader Close, the partial-count caller-deadline test (one of two shards serves, 1/2 observed and survives the deadline), the fakeSession.Fail error-recording boundary, the dropped diagnostic assertion, the "returns" (not wraps) comment, the caller-deadline comment reword, "without live shards", the redundant return, and the row-state comment ordering. cli:lint (golangci-lint v2.14.0) and the full cli test suite pass locally. |
smsunarto
left a comment
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · Argus PR review / Argus-Labs/world-engine
Keeping the canceled label and silent wrapping in phasebox fits the existing design.
Are the MCP and log-picker reload paths intentionally deferred? The MCP readiness callers still turn cancellation into a shard shortfall, and both picker/tail reload callbacks still print Reload failed: context canceled without checking ShouldPrint. I'd either carry cancellation through those callers or make the follow-up scope explicit.
Could you also refresh the original “Fix” and test inventory in the description? They still say the helper returns NewSilent(ctx.Err()) and describe a live-context/no-server test; the code now returns the bare cancellation and the runtime test controls two endpoints with a caller deadline.
| // Report a partial count, then cancel from the progress callback so the | ||
| // row + error path exercises the during-wait transition the test name | ||
| // describes, not a pre-canceled context. | ||
| err := waitForShardsReadyResult(ctx, sess, &fakeReadinessWaiter{ |
There was a problem hiding this comment.
Could we also cancel after reporting 2/2 and assert both the returned cancellation and the canceled row?
The production comment explicitly makes cancellation win over complete counts, but the cancellation tests only exercise incomplete counts.
There was a problem hiding this comment.
Addressed in 318e645. Added TestWaitForShardsReadyResult_CanceledAfterCompleteReturnsCanceled: a fake waiter reports 2/2, cancels from the progress callback, and the test asserts the returned error is context.Canceled and the row is marked canceled through Fail.
| // accepted connection so shardReady reports false without relying on a | ||
| // real server's absence. Shard b (port 8082) serves a real HTTP 200 so | ||
| // shardReady reports true. Skip if either port is already held. | ||
| downLn, err := net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(service.ShardHostPort(0))) |
There was a problem hiding this comment.
This test skips whenever a local world owns 8081 or 8082, so the regression coverage disappears in a common development setup. It also claims those application ports from a parallel test.
Could we isolate the probe endpoints instead of relying on the world's fixed ports? The probe tests already use ephemeral listeners.
There was a problem hiding this comment.
Isolating the probe endpoints would require parameterizing the probe address in production code: cli/pkg/local/runtime.go WaitForShardsReady derives ports from service.ShardHostPort(i), which is index-based (ShardHostPortBase+i in cli/pkg/docker/service/cardinal.go), and that file is not in this PR's diff. The test skips when 8081/8082 are already held (t.Skipf on Listen error), so it does not interfere with a running dev world; no other parallel test in the local package binds those ports. Left as-is for this PR; a parameterized probe address is a follow-up.
| func TestWaitForShardsReady_CallerDeadlineReturnsLastCount(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| cfg := &service.Config{Project: "test", WorldToml: worldtoml.Config{ |
There was a problem hiding this comment.
nit: both new tests can reuse twoShardConfig above instead of repeating the two-shard slice. Neither assertion depends on the a/b names.
There was a problem hiding this comment.
Addressed in 318e645. Both new runtime tests now reuse twoShardConfig; the inline two-shard slices are gone. Comments refer to shards by index/port since the names changed to game/chat.
| t.Skipf("cannot control probe port %d: %v", service.ShardHostPort(0), err) | ||
| } | ||
| defer downLn.Close() | ||
| go func() { |
There was a problem hiding this comment.
nit: this accept-and-close loop duplicates TestShardReadyRejectsAcceptOnlyListener. A shared listener helper would keep the behavior in one place; the sibling HTTP-server fixture also sets ReadHeaderTimeout.
There was a problem hiding this comment.
Addressed in 318e645. Added ReadHeaderTimeout to the ready-shard HTTP server fixture. A shared accept-and-close helper would require editing probe_internal_test.go, which is not in this PR's diff; left the inline listener loop as-is.
| } | ||
|
|
||
| func (f *fakeSession) UpsertRow(id, _, detail string, state phasebox.RowState) { | ||
| f.rows = append(f.rows, fakeRow{id: id, detail: detail, state: state}) |
There was a problem hiding this comment.
nit: the tests only read the last row and whether any row was seen. A last-row field plus a seen flag would avoid storing the whole update history.
There was a problem hiding this comment.
Addressed in 318e645. fakeSession now stores only the last row and a seen flag instead of the whole history.
| } | ||
|
|
||
| // lastRow returns the last upserted row, or panics if none. | ||
| func (f *fakeSession) lastRow() fakeRow { |
There was a problem hiding this comment.
nit: pass t into lastRow, mark it as a helper, and fail the test when no row was recorded instead of panicking.
There was a problem hiding this comment.
Addressed in 318e645. lastRow now takes *testing.T, calls t.Helper(), and fails the test with t.Fatal when no row was recorded instead of panicking.
| WaitForShardsReady(ctx context.Context, instanceIDs []string, onProgress func(ready, expected int)) (int, int) | ||
| } | ||
|
|
||
| // waitForShardsReadyResult waits for the targeted instances to serve and |
There was a problem hiding this comment.
nit: keep the counts-only cancellation invariant, but trim the repeated explanation and the interface's testability narration. The row comment below can likewise keep cancellation precedence and the section-lifecycle constraint without walking through the switch.
Also, the no-progress guard now handles a documented cancellation path, so calling it defensive is misleading.
There was a problem hiding this comment.
Addressed in 318e645. Trimmed the waitForShardsReadyResult comment to the counts-only/cancellation-stays-cancellation/deadline-stays-failure invariant and dropped the interface testability narration. The row comment keeps cancellation precedence and the section-lifecycle constraint without walking the switch, and the no-progress guard comment no longer calls it "defensive" (it handles a documented cancellation path).
| assert.False(t, errors.As(err, ¬Ready), "must not be a shardsNotReadyError") | ||
| } | ||
|
|
||
| // Ctrl+C arriving during the wait — after a partial count was reported — is |
There was a problem hiding this comment.
nit: the row is marked canceled through Session.Fail before the section ends; Box.Run supplies the canceled summary and silent wrapper at the boundary. Could this comment distinguish those two steps?
There was a problem hiding this comment.
Addressed in 318e645. The comment now distinguishes the two steps: the row is marked canceled through sess.Fail before the section ends, and Box.Run supplies the canceled summary and silent wrapper at the boundary; the helper returns context.Canceled itself (not wrapped).
|
|
||
| // --- waitForShardsReadyResult ----------------------------------------------- | ||
|
|
||
| // Ctrl+C before the first progress tick is a cancel, not a shards-not-ready |
There was a problem hiding this comment.
nit: trim the comments that repeat the test names and assertions, including the before-progress and partial-progress setup narration. The runtime tests' introductory blocks can describe their own count/progress contracts without reaching into the command helper; keep the fixed-port and nonparallel stdout explanations.
There was a problem hiding this comment.
Addressed in 318e645. Trimmed the before-progress and partial-progress setup-narration comments on the readiness-wait tests, and dropped the waitForShardsReadyResult references from the runtime tests' introductory blocks (they now describe only their own count/progress contracts). Kept the no-progress contract comments, the fixed-port explanation, and the nonparallel-stdout explanation.
| // Defined as an interface so the wait's cancel handling can be unit-tested | ||
| // without live shards; *local.Runtime satisfies it. | ||
| type shardReadinessWaiter interface { | ||
| WaitForShardsReady(ctx context.Context, instanceIDs []string, onProgress func(ready, expected int)) (int, int) |
There was a problem hiding this comment.
nit: name the interface results (ready, expected int) so their order is visible at the contract.
There was a problem hiding this comment.
Addressed in 318e645. The interface is now WaitForShardsReady(...) (ready, expected int) so the result order is visible at the contract.
|
Re: #1154 (review) Refreshed the description: the "Fix" paragraph now says the helper returns the bare On the MCP and log-picker paths, from the code:
Whether to extend the fix to those callers is a scope decision outside what the repo can tell me; the PR's stated scope is |
smsunarto
left a comment
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · Argus PR review / Argus-Labs/world-engine
Returning context.Canceled through the existing phasebox contract fits this fix, and keeping the row label in sess.Fail avoids another cancellation-rendering path.
The picker reload handlers still print Reload failed: for a returned cancellation, and the MCP reload/start paths still interpret incomplete readiness counts as an error or warning. Should cancellation handling on those surfaces be a follow-up, or should the picker hotkeys share this behavior now?
|
|
||
| require.Error(t, err) | ||
| var notReady *shardsNotReadyError | ||
| require.ErrorAs(t, err, ¬Ready, "deadline with unready shards is a real failure") |
There was a problem hiding this comment.
The deadline test still passes if the readiness error is wrapped as silent, because ErrorAs unwraps it. Could we also assert errorspkg.ShouldPrint(err) so this covers the visibility promised by the test name?
There was a problem hiding this comment.
Addressed in 6919646. Added assert.True(t, errorspkg.ShouldPrint(err)) to the deadline test so a silent-wrapped readiness error would fail it.
| defer readySrv.Close() // closes the listener too. | ||
|
|
||
| // A short caller deadline so the test doesn't wait the full 2 minutes. | ||
| ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) |
There was a problem hiding this comment.
This parallel test can return zero if the first probe round takes longer than one second, even when the waiter is correct. Could we arrange for a completed progress callback before expiring the caller deadline, so the retained-count assertion doesn’t depend on scheduling speed?
There was a problem hiding this comment.
Addressed in 6919646. The caller context is now ended from the progress callback once 1/2 is observed, so the retained-count assertion no longer depends on the first probe round beating a fixed deadline.
| case errors.Is(ctx.Err(), context.Canceled): | ||
| sess.Fail("ready", "Waiting for shards ready", ctx.Err()) | ||
| case lastReady < expected: | ||
| sess.UpsertRow( |
There was a problem hiding this comment.
nit: return after sess.Fail for cancellation and keep the shared terminal UpsertRow for success and timeout; only the state and detail differ.
There was a problem hiding this comment.
Addressed in 6919646. The canceled branch returns after sess.Fail; success and timeout share a single terminal UpsertRow, differing only in state and detail.
| // the last probe round reports 2/2, then returns a cancel — not a silent | ||
| // success. The row is marked canceled through sess.Fail; the helper returns | ||
| // [context.Canceled] itself. | ||
| func TestWaitForShardsReadyResult_CanceledAfterCompleteReturnsCanceled(t *testing.T) { |
There was a problem hiding this comment.
nit: table-drive this with CanceledAfterProgressReturnsCanceled; the setup and assertions are identical, with only the ready count changing. Keep both named cases.
There was a problem hiding this comment.
Addressed in 6919646. Table-driven as CanceledAfterProgressReturnsCanceled with AfterPartialProgress (1/2) and AfterComplete (2/2) subtests; both named cases kept.
| t.Skipf("cannot control probe port %d: %v", service.ShardHostPort(0), err) | ||
| } | ||
| defer downLn.Close() | ||
| go func() { |
There was a problem hiding this comment.
nit: this accept-and-close loop also lives in probe_internal_test.go. Could we share a small listener fixture, leaving each caller’s port selection and skip policy local?
There was a problem hiding this comment.
Out of scope for this PR: a shared listener fixture would require editing probe_internal_test.go, which is not in this PR's diff (same reasoning as the earlier identical request). Left the inline listener as-is.
|
|
||
| // Ctrl+C during the wait must render the readiness row as "canceled", not | ||
| // "timed out" — the timeout never elapsed, the user did. | ||
| func TestWaitForShardsReadyRow_CanceledShowsCanceledNotTimedOut(t *testing.T) { |
There was a problem hiding this comment.
nit: rename this to CanceledRoutesThroughFail; the fake writes "failed", so this test checks the error passed to Fail, rather than the rendered "canceled" text.
There was a problem hiding this comment.
Addressed in 6919646. Renamed to TestWaitForShardsReadyRow_CanceledRoutesThroughFail; the comment now notes the canceled label rendering is phasebox's job, not duplicated by the fake.
|
|
||
| // waitForShardsReadyResult waits for the targeted instances to serve and | ||
| // classifies the outcome: the waiter returns counts without an error, | ||
| // cancellation stays cancellation, and caller deadlines remain readiness |
There was a problem hiding this comment.
nit: make the deadline wording conditional on incomplete counts: “Cancellation returns context.Canceled; otherwise, incomplete counts return shardsNotReadyError.” Complete counts can still succeed with an expired deadline.
There was a problem hiding this comment.
Addressed in 6919646. The comment now says cancellation returns [context.Canceled], incomplete counts return shardsNotReadyError, and complete counts still succeed with an expired deadline.
|
|
||
| cfg := &service.Config{Project: "test", WorldToml: worldtoml.Config{ | ||
| Project: "test", | ||
| Shards: twoShardConfig, |
There was a problem hiding this comment.
nit: update twoShardConfig’s comment too; it now serves readiness tests as well as CheckLayout tests.
There was a problem hiding this comment.
Addressed in 6919646. twoShardConfig's comment now notes it serves the CheckLayout and readiness wait tests.
|
Re: #1154 (review) Whether cancellation handling on the picker hotkeys and MCP reload/start surfaces should be a follow-up or carried in this PR is a scope decision outside what this repo can tell me; the PR's stated scope is |
6919646 to
6b2df3e
Compare
smsunarto
left a comment
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · Argus PR review / Argus-Labs/world-engine
Returning cancellation through the existing section error handling makes sense here.
Are the MCP reload/start callers intentionally left for a follow-up? They still translate canceled readiness counts into shard-failure diagnostics.
| return | ||
| } | ||
| if errors.Is(ctx.Err(), context.Canceled) { | ||
| sess.Fail("ready", "Waiting for shards ready", ctx.Err()) |
There was a problem hiding this comment.
Ctrl+C cancels the dashboard context and quits its Tea program before this update, so the new “canceled” row can be dropped; plain mode drops rows entirely.
Could we handle the terminal cancellation display before shutting down the dashboard, and cover the real TTY Ctrl+C path? The plain-section test cannot establish that this row is visible.
There was a problem hiding this comment.
Out of scope for this PR's diff. The dashboard Ctrl+C path lives in cli/internal/tui/component/phasebox (model.go:120 returns tea.Quit on ctrl+c, service.go:66-74). When Ctrl+C fires, cancel() and tea.Quit land together, so the canceled-row upsert from sess.Fail and the collapseMsg from Box.Run (service.go:136) race the program shutdown and can be dropped — fixing that requires changing how the Tea program drains in-flight section messages before quitting, which is a phasebox change in files not touched by this PR. The plain-section test covers the classification (the section returns a silent context.Canceled and the summary says "canceled"); it cannot establish TTY row visibility. A real TTY Ctrl+C integration test would also need a pty. Left for a separate PR; flagging for a human to decide whether to scope it in.
| } | ||
| // Scoped to this reload's instances: another instance the developer left down is | ||
| // not this reload's problem, and waiting for it would burn the whole timeout. | ||
| return waitForShardsReadyResult(ctx, sess, rt, targets.instanceIDs) |
There was a problem hiding this comment.
The log picker still prints “Reload failed: context canceled” when this path returns the new cancellation error: both handleReload and the shard tail loop print any reload error unconditionally.
Could we apply the existing ShouldPrint policy at those callers and cover canceling a picker-triggered reload too?
There was a problem hiding this comment.
Out of scope for this PR's diff. The log picker reload error printing is in cli/commands/root/logs.go (handleReload and the shard tail loop print any reload error unconditionally, without errorspkg.ShouldPrint), and logs.go is not in this PR's diff. This PR's stated scope is the rollShards readiness-wait misclassification shared by world reload and world start; the picker ShouldPrint policy is a separate follow-up in a file this PR does not touch.
| // zero. This is caller-context coverage — the caller's context is what ends; | ||
| // it does not stay live after. It also does not exercise the genuine internal | ||
| // 2-minute readiness deadline with a live caller. | ||
| func TestWaitForShardsReady_CallerDeadlineReturnsLastCount(t *testing.T) { |
There was a problem hiding this comment.
This exercises caller cancellation, not deadline expiry: it uses WithCancel and calls cancel() from the progress callback.
Please rename it to CallerCanceledReturnsLastCount and correct the deadline claim. If caller-deadline retention is intended coverage, it needs a separate test that actually expires a deadline.
There was a problem hiding this comment.
Addressed in 0d21203. Renamed to TestWaitForShardsReady_CallerCanceledReturnsLastCount (it uses WithCancel, not a deadline). Caller-deadline coverage stays in reload_internal_test.go's DeadlineExceededIsNotSilent, which asserts a real expired deadline yields shardsNotReadyError.
| // relying on a real server's absence. The second (port ShardHostPort(1)) | ||
| // serves a real HTTP 200 so shardReady reports true. Skip if either port | ||
| // is already held. | ||
| downLn, err := net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(service.ShardHostPort(0))) |
There was a problem hiding this comment.
This regression test silently skips whenever a running world owns either shard port, so coverage depends on what is running on the developer’s machine.
Could we make the probe ports controllable and bind ephemeral ports, as the existing probe tests do, so the test runs alongside a local world?
There was a problem hiding this comment.
Addressed in 0d21203. The test now uses withFreePorts (the probeHostPort seam from waitrepro_internal_test.go), so it binds ephemeral ports and a running local world can no longer collide and silently skip it.
| if lastReady != 1 || lastExpected != 2 { | ||
| t.Fatalf("onProgress did not observe partial progress: last = %d/%d, want 1/2", lastReady, lastExpected) | ||
| } | ||
| // The waiter must have waited past the first probe round (not returned |
There was a problem hiding this comment.
This assertion only confirms the callback called cancel(); it does not show that the waiter continued past the first probe round. The cancellation can return directly through deadline.Done() after that round.
Please remove the misleading comment, or drive a second probe round if that is the behavior this test should establish.
There was a problem hiding this comment.
Addressed in 0d21203. Removed the misleading ctx.Err() block; the onProgress assertions (lastReady/lastExpected == 1/N) already prove the waiter progressed past a probe round.
| t.Skipf("cannot control probe port %d: %v", service.ShardHostPort(0), err) | ||
| } | ||
| defer downLn.Close() | ||
| go func() { |
There was a problem hiding this comment.
nit: could we share the accept-and-close listener loop with probe_internal_test.go? It is the same fixture behavior in the same package.
There was a problem hiding this comment.
Addressed in 0d21203. The test now uses withFreePorts, which drives the shared startDeadListener from waitrepro_internal_test.go — the accept-and-close loop is no longer duplicated.
| if ready != 1 { | ||
| t.Fatalf("partial count must survive the caller context ending: ready = %d, want 1", ready) | ||
| } | ||
| if expected != 2 { |
There was a problem hiding this comment.
nit: use len(twoShardConfig) for the expected total here and in the canceled-before-progress test, so the assertions follow the fixture.
There was a problem hiding this comment.
Addressed in 0d21203. Both runtime tests now use len(twoShardConfig) for the expected total.
smsunarto
left a comment
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · Argus PR review / Argus-Labs/world-engine
Keeping cancellation in the existing phasebox path makes sense. The new test callback has a syntax error that prevents the root test package from compiling; the main follow-up is getting that coverage runnable.
The MCP reload/start tools still turn canceled readiness waits into shard-failure messages. Should we track cancellation handling for those callers as a follow-up?
| cancel() | ||
|
|
||
| sess := &fakeSession{} | ||
| waitForShardsReadyRow(ctx, sess, func(func(ready, expected int) { |
There was a problem hiding this comment.
This callback is missing a closing parenthesis, so the entire root test package fails to parse.
Use func(func(ready, expected int)) {, then rerun moon run cli:test and moon run cli:lint on the corrected head and update the verification results.
| // relying on a real server's absence. The second (port ShardHostPort(1)) | ||
| // serves a real HTTP 200 so shardReady reports true. Skip if either port | ||
| // is already held. | ||
| downLn, err := net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(service.ShardHostPort(0))) |
There was a problem hiding this comment.
This regression test skips whenever a running local world holds either shard port, so normal development can silently lose this coverage.
Use the existing withFreePorts(t, r, ...) helper and probeHostPort seam from waitrepro_internal_test.go; they already provide the dead and serving endpoints without production-port collisions.
There was a problem hiding this comment.
Addressed in 0d21203. The test now uses the existing withFreePorts(t, r, ...) helper and probeHostPort seam from waitrepro_internal_test.go, so it runs without production-port collisions.
|
|
||
| runErr := dash.Run("Shards", | ||
| func(ctx context.Context, sess phasebox.Session) error { | ||
| return waitForShardsReadyResult(ctx, sess, &fakeReadinessWaiter{expected: 2}, nil) |
There was a problem hiding this comment.
The new cancellation tests call the extracted helper directly, so restoring the old classification in rollShards would recreate the bug while leaving them green.
Could we add a canceled case to the existing TestRollShards table using its roller fake, so the production caller stays covered?
There was a problem hiding this comment.
Addressed in 0d21203. Added a CanceledReturnsCanceled case to the TestRollShards table (pre-canceled ctx via the roller fake, which now respects ctx.Err()); it asserts the section returns context.Canceled and not shardsNotReadyError, so a revert of the rollShards classification is caught at the production caller.
|
|
||
| // shardReadinessWaiter is the subset of local.Runtime the readiness wait uses; | ||
| // *local.Runtime satisfies it. | ||
| type shardReadinessWaiter interface { |
There was a problem hiding this comment.
Nit: embed shardReadinessWaiter in shardRoller so the identical WaitForShardsReady signature has one declaration to maintain.
There was a problem hiding this comment.
Addressed in 0d21203. shardRoller now embeds shardReadinessWaiter, so the WaitForShardsReady signature has one declaration.
| // zero. This is caller-context coverage — the caller's context is what ends; | ||
| // it does not stay live after. It also does not exercise the genuine internal | ||
| // 2-minute readiness deadline with a live caller. | ||
| func TestWaitForShardsReady_CallerDeadlineReturnsLastCount(t *testing.T) { |
There was a problem hiding this comment.
Nit: this uses WithCancel, so rename it TestWaitForShardsReady_CallerCancellationReturnsLastCount and correct the caller-deadline claim in the description. The comment at line 629 also overstates the test: cancellation can happen in the first probe round.
There was a problem hiding this comment.
Addressed in 0d21203. Renamed to TestWaitForShardsReady_CallerCanceledReturnsLastCount, removed the overstated line-629 comment, and corrected the description (caller cancellation, not a caller deadline).
| return ctx.Err() | ||
| } | ||
| if ready < expected { | ||
| // Returned, not just shown: the row is already Failed, but the summary and the |
There was a problem hiding this comment.
Nit: say 'the row, if any, is already Failed' here; the no-progress guard can leave the row absent.
There was a problem hiding this comment.
Addressed in 0d21203. The comment now says "the row, if any, is already Failed".
| return | ||
| } | ||
| if errors.Is(ctx.Err(), context.Canceled) { | ||
| sess.Fail("ready", "Waiting for shards ready", ctx.Err()) |
There was a problem hiding this comment.
Nit: use 'Waiting for shards to be ready' for the three readiness labels.
There was a problem hiding this comment.
Addressed in 0d21203. All three readiness labels now read "Waiting for shards to be ready".
smsunarto
left a comment
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · Argus PR review / Argus-Labs/world-engine
Returning cancellation through phasebox fits the existing design: it keeps the canceled label and silent error handling with their current owner. I'd keep that approach.
| // Ctrl+C before the first progress tick is a cancel, not a shards-not-ready | ||
| // failure: the helper passes [context.Canceled] through for phasebox to | ||
| // silence at the section boundary. | ||
| func TestWaitForShardsReadyResult_CanceledBeforeProgressReturnsCanceled(t *testing.T) { |
There was a problem hiding this comment.
Could we add a canceled-wait case to the existing TestRollShards using fakeShardRoller? These new tests call the extracted helper directly, so they wouldn't catch rollShards reverting to the old count-based classification.
That existing seam also lets us keep the cancellation check inline without a second waiter interface and fake.
There was a problem hiding this comment.
Addressed in 0d21203. Added a CanceledReturnsCanceled case to the TestRollShards table using fakeShardRoller (which now respects ctx.Err()), so a revert of the rollShards count-based classification is caught at the production caller. Kept the shardReadinessWaiter seam (now embedded in shardRoller per the earlier review), so cancellation is covered at both the helper level and the rollShards level; dropping the second interface/fake would conflict with that earlier request and is beyond the minimum change here.
| // relying on a real server's absence. The second (port ShardHostPort(1)) | ||
| // serves a real HTTP 200 so shardReady reports true. Skip if either port | ||
| // is already held. | ||
| downLn, err := net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(service.ShardHostPort(0))) |
There was a problem hiding this comment.
This regression test skips whenever a running world occupies either production shard port, so it loses coverage on those developer machines.
Could we use the existing withFreePorts(t, r, ...) fixture in waitrepro_internal_test.go? It already supplies dead and serving endpoints through probeHostPort, without the fixed-port binds or skips.
There was a problem hiding this comment.
Addressed in 0d21203. The test now uses withFreePorts (the probeHostPort seam from waitrepro_internal_test.go), so it binds ephemeral ports and no longer skips when a running world occupies the production shard ports.
| // zero. This is caller-context coverage — the caller's context is what ends; | ||
| // it does not stay live after. It also does not exercise the genuine internal | ||
| // 2-minute readiness deadline with a live caller. | ||
| func TestWaitForShardsReady_CallerDeadlineReturnsLastCount(t *testing.T) { |
There was a problem hiding this comment.
nit: could we rename this to CallerCanceledReturnsLastCount? It uses WithCancel and asserts context.Canceled, so it doesn't exercise a caller deadline.
There was a problem hiding this comment.
Addressed in 0d21203. Renamed to TestWaitForShardsReady_CallerCanceledReturnsLastCount (it uses WithCancel and asserts context.Canceled, not a caller deadline).
| if lastReady != 1 || lastExpected != 2 { | ||
| t.Fatalf("onProgress did not observe partial progress: last = %d/%d, want 1/2", lastReady, lastExpected) | ||
| } | ||
| // The waiter must have waited past the first probe round (not returned |
There was a problem hiding this comment.
nit: ctx.Err() only establishes cancellation; it doesn't prove the waiter went past the first probe round. Could we remove that claim and the redundant assertion?
There was a problem hiding this comment.
Addressed in 0d21203. Removed the ctx.Err() claim and the redundant assertion; the onProgress assertions (lastReady/lastExpected == 1/N) already prove the waiter progressed past a probe round.
|
Re: #1154 (review) Yes — the MCP reload/start callers are intentionally left for a follow-up. They call rt.WaitForShardsReady directly and convert incomplete counts into a shard-failure diagnostic without checking ctx.Err() (cli/commands/mcp/tool_reload.go:165 and the start path), and that package is not in this PR's diff. This PR's stated scope is the rollShards readiness-wait misclassification shared by world reload and world start; the MCP counts-only contract is a separate follow-up. |
|
Re: #1154 (review) The syntax error (missing closing paren in the NoProgress test callback) was fixed in dd2a45d; the root test package compiles and the full cli test suite passes on the current head (0d21203). moon run cli:test and moon run cli:lint are clean on the changed files (the only cli:lint finding is a pre-existing testpackage issue in cli/commands/root/tui/setup_model_test.go, which is outside this PR's diff and present on the prior head). On the MCP reload/start callers: intentionally left for a follow-up — they translate canceled readiness waits into shard-failure messages and live in cli/commands/mcp/, which is not in this PR's diff. This PR's scope is the rollShards path shared by world reload and world start. |
smsunarto
left a comment
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · Argus PR review / Argus-Labs/world-engine
Keeping cancellation in the command layer and letting phasebox own the canceled label fits the existing design.
| if tt.preCanceled { | ||
| cctx, cancel := context.WithCancel(ctx) | ||
| cancel() | ||
| defer cancel() |
There was a problem hiding this comment.
nit: cancel() already ran on the previous line, so the deferred call can go.
| func (f *fakeReadinessWaiter) WaitForShardsReady( | ||
| ctx context.Context, _ []string, onProgress func(ready, expected int), | ||
| ) (int, int) { | ||
| if ctx.Err() != nil { |
There was a problem hiding this comment.
nit: this repeats the cancellation/count handling in fakeShardRoller. Could we share that small branch while keeping the roller’s ID recording and this waiter’s progress hook?
| func TestWaitForShardsReady_CallerCanceledReturnsLastCount(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| cfg := &service.Config{Project: "test", WorldToml: worldtoml.Config{ |
There was a problem hiding this comment.
nit: this config/runtime setup is identical to the cancellation-before-progress test above. Could we share the setup and keep the two cancellation scenarios separate?
| // out of scope. The AllReadyReturnsNil case is the happy path: every waited | ||
| // instance comes back, so rollShards returns nil. The CanceledReturnsCanceled | ||
| // case drives the production caller with a pre-canceled context so a future | ||
| // revert of the ctx.Err() classification in rollShards (the bug this PR fixes) |
There was a problem hiding this comment.
nit: the table already names these cases, so we can drop the case-by-case narration and “the bug this PR fixes.” Keep the wait-scope explanation above; that captures the useful invariant.
smsunarto
left a comment
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · Argus PR review / Argus-Labs/world-engine
Checking cancellation before interpreting the readiness counts fixes the misleading shard failure and lets world start reach its existing cleanup path.
The log-picker reload callbacks still print Reload failed: context canceled when this shared path returns a cancellation (cli/commands/root/logs.go:170 and cli/internal/logs/shard.go:75). Could those callbacks honor the existing silent-error policy too?
The MCP reload/start callers also interpret incomplete counts without checking cancellation. Is that intentionally deferred from this fix?
One description correction: cancellation before the first completed probe round returns zero without progress; later cancellation preserves the last completed count, as the new runtime test demonstrates.
| return | ||
| } | ||
| if errors.Is(ctx.Err(), context.Canceled) { | ||
| sess.Fail("ready", "Waiting for shards to be ready", ctx.Err()) |
There was a problem hiding this comment.
The canceled readiness row may never reach the terminal: phasebox gives Bubble Tea this same context, and Program.Send can discard messages once it's canceled. Plain mode also drops rows.
Could we attach TTY output showing this row changing to canceled? The fake-session test proves dispatch, but can't establish that the update renders.
There was a problem hiding this comment.
Re: the row reaching the terminal in dashboard mode — the PR body's "How did you verify?" section already documents the end-to-end dashboard capture (Ctrl+C during world reload readiness wait: box shows "canceled", no "0/N instances are serving" message). At the unit level, TestWaitForShardsReadyResult_CancelThroughPlainSectionIsCanceled drives a real phasebox.Plain section and asserts the captured stdout contains "canceled" (reload_internal_test.go:495). The sess.Fail upsert happens inside dash.Run's section callback, before the section ends (reload.go:349-351), so phasebox's finished-section guard does not drop it. A fresh TTY recording can't be attached from this environment without a live Docker world; the dashboard-mode Program.Send-while-canceled race is phasebox's contract (cli/internal/tui/component/phasebox), outside this PR's diff.
| // waitForShardsReadyResult waits for the targeted instances to serve and | ||
| // classifies the outcome: the waiter returns counts without an error, | ||
| // cancellation returns [context.Canceled], and incomplete counts return | ||
| // shardsNotReadyError (complete counts still succeed with an expired |
There was a problem hiding this comment.
Could we add a case with complete counts and an expired caller deadline? This comment promises success for that combination, but the current deadline test only covers incomplete counts. It would catch a future blanket ctx.Err() check that changes this distinction.
| // readiness cancellation tests. WaitForShardsReady only reads | ||
| // cfg.WorldToml.Shards — no Docker is involved — so both cancellation | ||
| // scenarios share this setup while keeping their own contexts and assertions. | ||
| func newTwoShardRuntime() *Runtime { |
There was a problem hiding this comment.
nit: can we reuse New(nil, poolShardConfig()) here? The existing readiness fixture already supplies two instances and works with withFreePorts; derive the expected totals from that fixture if we consolidate.
| // failure, not a cancel: waitForShardsReadyResult classifies it as a | ||
| // shardsNotReadyError so the failure is reported, not hidden — only | ||
| // [context.Canceled] is silent. | ||
| func TestWaitForShardsReadyResult_DeadlineExceededIsNotSilent(t *testing.T) { |
There was a problem hiding this comment.
nit: could we table the live-context and expired-deadline result cases, as the row timeout test does? Keep both the count assertions and the printability assertion.
| var out bytes.Buffer | ||
| copyDone := make(chan struct{}) | ||
| go func() { | ||
| _, _ = io.Copy(&out, r) |
There was a problem hiding this comment.
nit: could the channel carry the io.Copy error so the test can assert it after joining the reader? Right now capture errors are discarded.
| } | ||
|
|
||
| // WaitForShardsReady preserves the last completed count when the caller | ||
| // context is canceled mid-wait (not the internal 2-minute readiness |
There was a problem hiding this comment.
nit: reference shardReadyTimeout instead of repeating its current two-minute value here and below, so this explanation stays accurate when the timeout changes.
| defer cancel() | ||
|
|
||
| var lastReady, lastExpected int | ||
| ready, expected := r.WaitForShardsReady(ctx, nil, func(r, e int) { |
There was a problem hiding this comment.
nit: use ready, expected for the callback parameters; r currently shadows the *Runtime in the enclosing test.
| waiter := &fakeReadinessWaiter{expected: 2} | ||
| err := waitForShardsReadyResult(ctx, &fakeSession{}, waiter, nil) | ||
|
|
||
| require.Error(t, err) |
There was a problem hiding this comment.
nit: the exact context.Canceled equality assertion already establishes a non-nil error and excludes shardsNotReadyError. We can drop the surrounding require.Error and errors.As assertions here.
| {"liveContext", context.Background}, | ||
| {"expiredDeadline", func() context.Context { | ||
| ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Hour)) | ||
| t.Cleanup(cancel) |
There was a problem hiding this comment.
nit: this closure captures the parent t, so the subtest registers cleanup on its parent. Pass the subtest's t into the context factory to keep cleanup with the case that owns it.
| // --- waitForShardsReadyRow --------------------------------------------------- | ||
|
|
||
| // Ctrl+C during the wait routes through sess.Fail (not the timed-out | ||
| // UpsertRow): the timeout never elapsed, the user did. The canceled label |
There was a problem hiding this comment.
nit: replace “the timeout never elapsed, the user did” with “the user canceled before the timeout elapsed.”
|
Re: #1154 (review) The log-picker and MCP scope questions were answered in earlier replies (#1154 (comment) and #1154 (comment)): those callers are not in this PR's diff and are intentional follow-ups; this PR's scope is the rollShards path shared by Applied the description correction: the Root cause sentence now says |
1e10f00 to
de99746
Compare
- embed shardReadinessWaiter in shardRoller so the WaitForShardsReady signature has one declaration - add a CanceledReturnsCanceled case to TestRollShards so the production rollShards caller stays covered against a revert of the ctx.Err() classification (not just the helper-level tests) - rename TestWaitForShardsReady_CallerDeadlineReturnsLastCount to CallerCanceledReturnsLastCount (it uses WithCancel, not a deadline) and rewrite it to use the existing withFreePorts/probeHostPort seam so a running local world's shard ports cannot collide and silently skip it; drop the misleading ctx.Err() assertion (the onProgress assertions already prove the waiter progressed) - use len(twoShardConfig) for the expected total in both runtime tests - comment/label nits: 'row, if any, is already Failed' and 'Waiting for shards to be ready'
- drop redundant defer cancel() (cancel() already ran) - share the canceled-readiness branch between fakeShardRoller and fakeReadinessWaiter via canceledShardCounts - share the two-shard config/runtime setup via newTwoShardRuntime - trim case-by-case narration in TestRollShards comment
- table live-context and expired-deadline result cases (count + printability) - add complete-counts + expired-deadline success case - channel the io.Copy error so the plain-section test asserts it - pass the subtest's t into the row timeout context factory - drop redundant assertions around the exact context.Canceled equality - consolidate readiness runtime tests on poolShardConfig; move the waiter-contract paragraph beside the cancellation tests - reference shardReadyTimeout instead of repeating 2-minute - use ready/expected for the callback params (avoid shadowing *Runtime) - wording nit on the cancel-before-timeout comment
de99746 to
1c7b866
Compare
Detail bug report: View on Detail
Closes https://linear.app/smsunarto-work/issue/PER-542/detail-bug-cli-reload-ctrlc-during-shard-readiness-wait-is-reported-as
Screenshot / Recordings
No screenshot or recording attached: the change is in terminal output text (box summary label and error message), verified via before/after terminal captures described in "How did you verify?" below.
What changed
Ctrl+C during
world reload's shard readiness wait was reported as a hard shard failure — the box showed"failed", the CLI printed"0/N instances are serving; check world logs", and the process exited 1 — indistinguishable from a genuine crash-loop. A developer who deliberately aborted a slow reload was told their shards failed to come up.Root cause:
WaitForShardsReadyreturns counts only (no error). Onctx.Err() != nilit returns the last completed count (zero before the first completed probe round) without callingonProgress.rollShardsthen unconditionally convertedready < expectedintoshardsNotReadyErrorwithout checkingctx.Err(), so a cancel reappeared as a real failure. The phasebox row also showed"timed out (k/N ready)"even though the 2-minute timeout never elapsed.Fix: After the readiness wait in
rollShards, checkctx.Err()and return the barectx.Err()oncontext.Canceled— before converting counts intoshardsNotReadyError.Box.Runsilencescontext.Canceledat the section boundary (the box summary shows"canceled") andJoinFailuresclassifies it as a cancel, not a failure. Onlycontext.Canceledis silent — a callerDeadlineExceededfalls through toshardsNotReadyError. The readiness row is marked canceled throughsess.Failso phasebox owns the"canceled"label, instead of"timed out". Cancellation wins even when the counts are complete.The readiness wait + error classification was extracted into
waitForShardsReadyResultwith ashardReadinessWaiterinterface seam for unit testing, mirroring the existingshardBuilderpattern. The same fix coversworld start, which shares thedeployShardImages→rollShardspath.How did you verify?
Unit tests (new): 12 tests in
cli/commands/root/reload_internal_test.gocovering the threewaitForShardsReadyRowterminal states (canceled, timed out, ready), the no-progress edge case, and thewaitForShardsReadyResultoutcomes (cancel before progress, cancel after progress, cancel after complete counts, timeout→shardsNotReadyError, deadline→shardsNotReadyError, ready→nil), theJoinFailuresinteraction (a cancel alone stays silent), and a real plain-phasebox section regression. 2 tests incli/pkg/local/runtime_internal_test.gocoveringWaitForShardsReady's contract on cancel (returns(0, N)withoutonProgress) and on a caller cancellation with two controlled endpoints (one serving, one accept-and-close via the shared withFreePorts seam) asserting the partial count survives.Unit tests (existing): All existing tests in
cli/commands/root/(build, logs, endpoints),cli/internal/errors/(silent error,JoinFailures), andcli/internal/tui/component/phasebox/(cancel contract) pass unchanged.Static checks:
go build ./cli/...,go vet, andgofmtall clean. Fullgo test -count=1 ./cli/...(34 packages) passes.End-to-end (Docker): Built the CLI and ran it against a live Docker world using the
bare-bone-templatefixture (whose shard crashes on startup, so the readiness wait is always in progress when interrupted):world reloadreadiness wait: box shows"canceled", no"0/N instances are serving"message. Before the fix (old binary): box shows"failed", prints"0/1 instances are serving; check world logs".world startreadiness wait: box shows"canceled", world stops cleanly, no standalone"0/N instances are serving"error. Before the fix: box shows"failed".world reload --purgereadiness wait: purge succeeds, box shows"canceled", no failure message.world reloadwaits the full 2 minutes, shows"failed (2m0s)", prints"0/1 instances are serving; check world logs", exits 1 — no regression.TestWaitForShardsReadyResult_ReadyReturnsNil,TestWaitForShardsReadyRow_ReadyShowsDone).Caveats
The exit code on Ctrl+C is still 1 (not 0) because
main.gosetsexitCode=1for any non-nil error, including silent ones — this is the existing behavior for all commands and not a regression. The bug was about the misleading failure message and box label, both of which are fixed: the message is no longer printed (silent error), and the box shows "canceled" instead of "failed".AI Usage
Created with detail-zai/glm-5.2 in opencode. Fully autonomous: the bug report, fix, tests, and verification were all produced by the agent.
Automatic Fixes PRs can be configured here.
Summary by cubic
Fixes
world reloadandworld startreporting Ctrl+C during the shard readiness wait as a shard failure (box shows"failed", the CLI prints"0/N instances are serving", exit 1) instead of a cancel.WaitForShardsReadyreturns counts only, so a canceled context collapsed into(0, expected)and was misread as not-ready. The wait and error classification moved intowaitForShardsReadyResultthrough ashardReadinessWaiterseam (embedded inshardRoller), which returnscontext.Canceledbefore the count check soBox.Runtreats it as a cancel. The readiness row is marked canceled throughsess.Fail. Onlycontext.Canceledis silent — a caller deadline still reports as"timed out"— and cancellation wins even when counts are complete.Adds unit tests covering the row terminal states, result outcomes (cancel before/after progress, cancel-after-complete, timeout, deadline, ready, complete counts succeeding with an expired caller deadline), the
rollShardscancel path,JoinFailuresinterplay, a real plain-phasebox section, andWaitForShardsReady's cancellation contract.Written for commit 1c7b866. Summary will update on new commits.