From 32e42773cdcb341f9896196ab8f4db95c8c517ee Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 2 Dec 2026 10:44:43 -0500 Subject: [PATCH 01/10] fix(app): mark a team start as live before its claim can be read A same-request caller that read the intent claim inside claims.create, before b.starting was set, was answered "uncertain" where the contract says "busy". Reproduced 21 times in 1500 runs of TestStartCrewConcurrentSameRequestSendsTheGoalOnce under load; 0 in 1500 with the mark raised first. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/appteamstart.go | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/cmd/codeaf/appteamstart.go b/cmd/codeaf/appteamstart.go index 6b1451e3c2..c8d48244d3 100644 --- a/cmd/codeaf/appteamstart.go +++ b/cmd/codeaf/appteamstart.go @@ -122,11 +122,18 @@ func (b *appBackend) CrewStart(ask appwire.CrewCreate) (appwire.CrewStartResult, ClientID: ask.ClientID, Goal: words, } claims := b.startClaims() + // THE MARK GOES UP BEFORE THE CLAIM CAN BE READ. A claim becomes visible to + // another caller inside create, a moment before create returns; a caller that + // reads an intent claim in that moment and finds no mark would call this live + // start a lost one and answer "uncertain" where the contract says "busy". We + // hold startMu, so no other start of this process touches the mark. + b.locked(func() { b.starting = ask.RequestID }) + defer b.locked(func() { b.starting = "" }) made, err := claims.create(claim) - if made { - // From the claim on, an intent claim of this request is this start. - b.locked(func() { b.starting = ask.RequestID }) - defer b.locked(func() { b.starting = "" }) + if !made { + // The claim is another process's, or the write failed: this start owns + // nothing, and the replay below must read the claim as somebody else's. + b.locked(func() { b.starting = "" }) } if err != nil || !made { b.takeBack(transcript) From 96a3db04cd609944739aea6b55236c98464925f0 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 2 Dec 2026 10:44:43 -0500 Subject: [PATCH 02/10] test(app): settle the day limit before the storage-failure test needs config.json Nothing in TestAppWireCustomStorageFailureCanRetryWithoutDuplicate created the profile file it renames; the start-up warm-up does, in the background. Delaying the warm-up 300ms makes the old test fail every time with the CI message. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/appprovider_journey_test.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/cmd/codeaf/appprovider_journey_test.go b/cmd/codeaf/appprovider_journey_test.go index 7c5ce30b7a..931d04db6a 100644 --- a/cmd/codeaf/appprovider_journey_test.go +++ b/cmd/codeaf/appprovider_journey_test.go @@ -153,6 +153,14 @@ func TestAppWireCustomStorageFailureCanRetryWithoutDuplicate(t *testing.T) { var check appwire.KeyCheck w.must("keys.check", params, &check) params["connection"] = check.Connection + // THE PROFILE FILE IS WRITTEN BY THE START-UP WARM-UP, which the hello starts + // in the background (appBackend.Warm settles the day limit, and settling + // writes config.json). The rename below needs that file, so the test settles + // it itself rather than racing the goroutine; settling is idempotent and + // holds the same lock Warm does, so whichever runs second finds it done. + if err := b.settleDayLimit(); err != nil { + t.Fatal(err) + } // A directory at the profile file makes the real profile writer fail. path := filepath.Join(profile, "config.json") if err := os.Rename(path, path+".backup"); err != nil { From d39f3a09b923e2d21d55927fade59adeba475303 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 2 Dec 2026 10:44:43 -0500 Subject: [PATCH 03/10] test(app): close the engine half after a provider test, as the app's exit does The warm-up opens the process-wide engine half once a key exists and its model discovery keeps writing into the profile; only closeEngineProcess joins it. Without it TempDir removal can race a late write (model-catalog.json was seen changing after the cleanups). Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/appproviders_test.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/cmd/codeaf/appproviders_test.go b/cmd/codeaf/appproviders_test.go index c989ea8d99..da6db1284a 100644 --- a/cmd/codeaf/appproviders_test.go +++ b/cmd/codeaf/appproviders_test.go @@ -80,6 +80,14 @@ func appProviderTest(t *testing.T) (*appBackend, *appRecorder, string) { t.Cleanup(restore) rec := newAppRecorder() backend := newFakeBackend(rec, nil) + // THE START-UP WARM-UP OPENS THE PROCESS-WIDE ENGINE HALF as soon as a + // provider key exists, and that half starts model discovery and stores of + // its own under the profile. Only closeEngineProcess joins them, as the app's + // exit does; without it they can still be writing when TempDir removes the + // profile ("directory not empty"). Registered BEFORE the backend's Close so + // it runs after it: Close waits for the warm-up, and only then is the half + // settled enough to close. + t.Cleanup(closeEngineProcess) t.Cleanup(func() { _ = backend.Close() }) return backend, rec, profile } From 673132d45155aef628547ec27053385c6bf46552 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 2 Dec 2026 10:44:43 -0500 Subject: [PATCH 04/10] test(app): drain the second seat in the storage-off gate test The another-computer branch seats the chat a second time and nothing closes that seat; its warm capture seals the first seat's unsaved call in the background. After the body returns the store's wal, pack, catalog and workspaces/t- were still being written (8 files, 5 of 5 runs); with the second seat drained only a daemon bookkeeping file changes. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/storage_off_gate_test.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/cmd/codeaf/storage_off_gate_test.go b/cmd/codeaf/storage_off_gate_test.go index d75135d240..d4cf9807cf 100644 --- a/cmd/codeaf/storage_off_gate_test.go +++ b/cmd/codeaf/storage_off_gate_test.go @@ -19,6 +19,7 @@ import ( cellstoretest "github.com/Agent-Field/codeaf/internal/cellstore/celltest" "github.com/Agent-Field/codeaf/internal/chatlist" "github.com/Agent-Field/codeaf/internal/directory" + "github.com/Agent-Field/codeaf/internal/executor" "github.com/Agent-Field/codeaf/internal/home" "github.com/Agent-Field/codeaf/internal/identity" "github.com/Agent-Field/codeaf/internal/reqsign" @@ -173,6 +174,14 @@ func TestStorageOffSeatedTurnStopsWhenAnotherComputerContinuesIt(t *testing.T) { t.Fatal(err) } cfg = v3Seated(cfg) + // THIS SECOND SEAT HAS NO SESSION TO CLOSE IT. Seating a chat starts a + // warm capture that seals whatever the first seat left unsaved, in the + // background, through furrow; the deferred agent.Close below drains only + // the first seat. Left alone, that seal can still be writing into the + // engine's store when the fixture's temp folder is removed ("directory + // not empty"), so the second seat is drained here, before any of the + // fixture's folders go. + defer func(seat executor.Seat) { _ = executor.Drain(context.Background(), seat) }(cfg.Seat) resumed := syncDrives.renewalsOf(c.ID) startupFinished(resumed) if err := resumed.Gate(); err != nil { From 927c70ba0c1e3491b0916e5f04060afb4189ea2a Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 2 Dec 2026 10:44:43 -0500 Subject: [PATCH 05/10] test(app): poll agents.entries for the moved chat's saved page The first read after the agent.changed event answered the local copy in 3 of 8 loaded runs. The contract is the saved page at the remote head, so that is what is waited for. 12 of 12 loaded runs pass. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/app_chat_preview_test.go | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/cmd/codeaf/app_chat_preview_test.go b/cmd/codeaf/app_chat_preview_test.go index d0a5e6ad46..6b2f74b5de 100644 --- a/cmd/codeaf/app_chat_preview_test.go +++ b/cmd/codeaf/app_chat_preview_test.go @@ -99,7 +99,21 @@ func TestAppPassThroughTitleAndPreview(t *testing.T) { l := changed.Agent.Location return l != nil && !l.Here && l.Cell == row.Cell && l.Seen != nil && l.Seen.Device == remote.Seen.Device }) - page := machineCall[appwire.EntriesResult](t, a.w, "agents.entries", appwire.EntriesParams{ID: created.ID}) + // THE EVENT AND THE READ ARE TWO DOORS ONTO ONE FACT, and the first read after + // the event is not always the verdict: on a loaded machine it answered the + // local copy (no remote head, no fallback) in three runs of eight. The likely + // reason is that an agent.changed is dressed from the chat list's cache, + // which is updated a step before the agent's own location that agents.entries + // reads. The contract is that once the other computer holds the chat the page + // is its saved one at that head, so that is what is polled for, with a + // ceiling long enough for a loaded runner. + var page appwire.EntriesResult + for until := time.Now().Add(30 * time.Second); ; time.Sleep(20 * time.Millisecond) { + page = machineCall[appwire.EntriesResult](t, a.w, "agents.entries", appwire.EntriesParams{ID: created.ID}) + if page.RemoteHead == remote.Seen.Head || time.Now().After(until) { + break + } + } if page.LocalFallback || page.RemoteHead != remote.Seen.Head || len(page.Entries) == 0 { t.Fatalf("the moved chat did not return a saved page at head %s: %+v", remote.Seen.Head, page) } From 3db89314e6cfb14d8f9a9fdb7b920785d3cdabc8 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 2 Dec 2026 10:44:43 -0500 Subject: [PATCH 06/10] test(app): say what the hosted startup was doing when its wait ran out The 2026-11-29 nightly timed out here with no state in the message. Report whether the start was attempted, may retry and how long its retry wait is, so the next occurrence explains itself. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/appsync_test.go | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/cmd/codeaf/appsync_test.go b/cmd/codeaf/appsync_test.go index ad7fd7a8f9..cf64505b49 100644 --- a/cmd/codeaf/appsync_test.go +++ b/cmd/codeaf/appsync_test.go @@ -70,6 +70,24 @@ func appSyncWait(t *testing.T, what string, check func() bool) { } } +// appSyncWaitStarted is appSyncWait for a drive's startup. When the wait runs +// out it says what the startup was doing, because "timed out" alone cannot tell +// a startup that failed and is waiting out its retry ladder (a transport +// failure retries after 5s, then 10s, then 20s) from one that was never woken. +func appSyncWaitStarted(t *testing.T, drive *liveDrive) { + t.Helper() + until := time.Now().Add(30 * time.Second) + for drive.started() == nil { + if time.Now().After(until) { + drive.mu.Lock() + attempted, waiting, wait, told := drive.attempted, drive.waiting, drive.retryWait, drive.told + drive.mu.Unlock() + t.Fatalf("timed out waiting for hosted background startup (attempted=%v, may retry=%v, retry wait=%v, refusal told=%v)", attempted, waiting, wait, told) + } + time.Sleep(10 * time.Millisecond) + } +} + func appSyncRelay(t *testing.T) *httptest.Server { t.Helper() svc := relayserve.New(relayserve.Config{Store: t.TempDir()}) @@ -543,7 +561,7 @@ func TestC3AppHostedDisclosureWaitsForAcknowledgement(t *testing.T) { if drive == nil { t.Fatal("hosted startup has no background drive") } - appSyncWait(t, "hosted background startup", func() bool { return drive.started() != nil }) + appSyncWaitStarted(t, drive) i := rec.waitFor(t, 30*time.Second, func(event string, data any) bool { changed, ok := data.(appwire.SyncChanged) return event == appwire.EventSyncChanged && ok && changed.Sync.Disclosure != nil From 10c97dcee900c90efb28f50cec36df24aa46d959 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 2 Dec 2026 10:44:43 -0500 Subject: [PATCH 07/10] test(session): let the background-after clock test's command wait on a gate The test bounded the foreground turn at four seconds against a two-second clock and the nightly measured 4.77s on a loaded runner. The command now waits for a file the test creates after the turn returns, so only the clock can have ended the foreground wait; the lower bound stays. Co-Authored-By: Claude Sonnet 5.5 --- internal/session/promote_test.go | 35 +++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/internal/session/promote_test.go b/internal/session/promote_test.go index ee66be92d9..305c772b1f 100644 --- a/internal/session/promote_test.go +++ b/internal/session/promote_test.go @@ -15,7 +15,9 @@ import ( "errors" "fmt" "os" + "path/filepath" "strings" + "sync/atomic" "testing" "time" @@ -139,9 +141,31 @@ func TestAForegroundCommandThatRunsOutOfTimeBecomesAJob(t *testing.T) { // M1: the background-after clock returns the existing promotion result and // roster row promptly, then carries the real exit into the next model boundary. func TestTheBackgroundAfterClockKeepsTheCommandAndTheConversationMovesOn(t *testing.T) { + // THE COMMAND FINISHES WHEN THE TEST SAYS, NOT WHEN A TIMER DOES. It used to + // be `sleep 5` against a two-second clock with a four-second ceiling on the + // foreground turn, so the verdict depended on a loaded runner scheduling the + // turn's return within two seconds of the clock: the nightly measured 4.77s. + // What the contract says is that the turn comes back WHILE THE COMMAND IS + // STILL RUNNING, and that is read directly: the command waits for a file the + // test creates after the turn has returned, so only the clock can have ended + // the foreground wait. The release timer is a backstop for a turn that never + // returns, and a return after it fired is a failure. + gate := filepath.Join(t.TempDir(), "release") + var released atomic.Bool + release := func() { + if released.CompareAndSwap(false, true) { + _ = os.WriteFile(gate, nil, 0o600) + } + } + backstop := time.AfterFunc(20*time.Second, release) + defer backstop.Stop() + command, err := json.Marshal(map[string]string{"command": "while [ ! -e " + gate + " ]; do sleep 0.05; done; echo late"}) + if err != nil { + t.Fatal(err) + } completer := &scriptedCompleter{steps: []step{ func(context.Context, []ai.Message) (*ai.Response, error) { - return toolResponse("clock-call", "bash", `{"command":"sleep 5; echo late"}`), nil + return toolResponse("clock-call", "bash", string(command)), nil }, func(context.Context, []ai.Message) (*ai.Response, error) { return textResponse("I moved on while it finishes."), nil @@ -164,9 +188,14 @@ func TestTheBackgroundAfterClockKeepsTheCommandAndTheConversationMovesOn(t *test job := awaitJob(t, lane, JobRunning) collect(t, turn) elapsed := time.Since(started) - if elapsed < 1500*time.Millisecond || elapsed > 4*time.Second { - t.Fatalf("the foreground turn returned after %v, want the two-second clock", elapsed) + if released.Load() { + t.Fatalf("the foreground turn waited for the command (returned after %v), want the two-second clock", elapsed) + } + if elapsed < 1500*time.Millisecond { + t.Fatalf("the foreground turn returned after %v, before the two-second clock", elapsed) } + // The turn is back and the command is still running: let it finish. + release() request := completer.request(1) result := roleText(request, "tool") From b354bfad7fe0611ce9265d1b9697b419b55ce63c Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 2 Dec 2026 10:44:43 -0500 Subject: [PATCH 08/10] test(tui3): the Spending tab test says how many calls went unpriced session.UnbilledCalls is a process-wide count that only grows, and TestExportAfterCompactKeepsAllJournalTurns2685 leaves 13 calls unpriced (its stream carries no usage), so every nightly shard that ran it first drew an unbilled row on the Spending tab. The count is now read through a variable the test sets, and a companion test pins when the row appears. Co-Authored-By: Claude Sonnet 5.5 --- internal/tui3/settingspend.go | 11 +++++++- internal/tui3/settingspend_test.go | 43 ++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/internal/tui3/settingspend.go b/internal/tui3/settingspend.go index dfa4c02d9b..8c953146e1 100644 --- a/internal/tui3/settingspend.go +++ b/internal/tui3/settingspend.go @@ -442,9 +442,18 @@ func unwrittenReading() *railReading { // without a usage block and no provider receipt could put a figure on it. It // says nothing at zero by the same emptiness law [unwrittenReading] keeps. func unbilledReading() *railReading { - return unbilledReadingFor(session.UnbilledCalls()) + return unbilledReadingFor(unbilledCount()) } +// unbilledCount is the process-wide count of calls the machine could not put a +// price on ([session.UnbilledCalls]), read through a variable so that a test can +// SAY how many calls this process has failed to price. The count is deliberately +// process-wide and only ever grows, so a test binary that ran any turn whose +// stream ended without a usage block earlier in the same process would otherwise +// hand every later test an "unbilled" row it never asked for (the nightly saw +// exactly that on the Spending tab for days). Nothing but a test assigns it. +var unbilledCount = session.UnbilledCalls + // unbilledReadingFor is the pure spelling half, separated so the two surfaces // can be tested against the same count without changing a process-wide fact. func unbilledReadingFor(count int64) *railReading { diff --git a/internal/tui3/settingspend_test.go b/internal/tui3/settingspend_test.go index 6558a48c53..4e77667013 100644 --- a/internal/tui3/settingspend_test.go +++ b/internal/tui3/settingspend_test.go @@ -3,6 +3,7 @@ package tui3 import ( "os" "path/filepath" + "slices" "strings" "testing" @@ -48,6 +49,10 @@ func spendingRows(a *app) []string { // and the rows are in the order a person worries about them — not alphabetical, // not registry order, not by key. func TestTheSpendingTabIsTheSevenRowsAndNothingElse(t *testing.T) { + // A MACHINE THAT PRICED EVERY CALL. The shortfall rows are facts about this + // process's past, and a process that ran other tests first has a past; this + // test is about the tab a person sees when nothing is short. + nothingWentUnpriced(t) a, _ := spendingSheet(t) // A day with something on it, so the receipt row is drawn at all. a.dayCost, a.dayCosted = 3.42, true @@ -68,6 +73,44 @@ func TestTheSpendingTabIsTheSevenRowsAndNothingElse(t *testing.T) { } } +// nothingWentUnpriced says, for one test, that this process has not failed to +// price a call. See [unbilledCount] for why the real count cannot be trusted to +// be zero in a binary that has run other tests. +func nothingWentUnpriced(t *testing.T) { t.Helper(); callsLeftUnpriced(t, 0) } + +// callsLeftUnpriced says, for one test, how many calls this process has failed +// to price. +func callsLeftUnpriced(t *testing.T, count int64) { + t.Helper() + was := unbilledCount + unbilledCount = func() int64 { return count } + t.Cleanup(func() { unbilledCount = was }) +} + +// TestTheSpendingTabNamesUnpricedCallsDirectlyUnderTheDayAndOnlyWhenThereAreSome +// is the other half of the seven-rows law: the one extra row the tab may draw is +// the shortfall row, directly under the day it makes short, and it appears if +// and only if calls went unpriced. +func TestTheSpendingTabNamesUnpricedCallsDirectlyUnderTheDayAndOnlyWhenThereAreSome(t *testing.T) { + callsLeftUnpriced(t, 2) + a, _ := spendingSheet(t) + a.dayCost, a.dayCosted = 3.42, true + a.sheet.today = a.todayReading() + a.sheet.build() + rows := spendingRows(a) + today, unbilled, limit := slices.Index(rows, spendTodayWord), slices.Index(rows, spendUnbilledWord), slices.Index(rows, "daily spending limit") + if today != 0 || unbilled <= today || unbilled >= limit { + t.Fatalf("with two unpriced calls the Spending tab reads %v, want %q first and %q before the first limit", rows, spendTodayWord, spendUnbilledWord) + } + callsLeftUnpriced(t, 0) + a.sheet.build() + for _, row := range spendingRows(a) { + if row == spendUnbilledWord { + t.Fatalf("the Spending tab still draws %q with nothing unpriced", spendUnbilledWord) + } + } +} + // TestSafetyAndTasksHoldWhatSpendingLetGoAndWorkspaceNamesNoMoney is the other // half of the split: twenty rows answering four questions became four sections, // and the tab a person opens for money holds money alone. From a5a586c0b78ed512b722fa605a606f62eea41b4e Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 2 Dec 2026 10:45:35 -0500 Subject: [PATCH 09/10] docs: change entry for the nightly Full check races (#3023) Co-Authored-By: Claude Sonnet 5.5 --- .../unreleased/3023-nightly-full-check-races.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 docs/changes/unreleased/3023-nightly-full-check-races.md diff --git a/docs/changes/unreleased/3023-nightly-full-check-races.md b/docs/changes/unreleased/3023-nightly-full-check-races.md new file mode 100644 index 0000000000..0f43e6d4bd --- /dev/null +++ b/docs/changes/unreleased/3023-nightly-full-check-races.md @@ -0,0 +1,15 @@ +--- +kind: fixed +title: A second start of one request is told busy, and the nightly's racing tests stop racing +pr: 3023 +surface: [app, chat] +invalidates: + - "Was true: a second caller of crews.create with start_manager and the same request_id could be answered uncertain while the first was still starting, because the start was marked live only after its claim was written. Is true now: the mark goes up before the claim can be read, so that caller is told busy and uncertain is kept for a claim another process holds or a start that stopped early." + - "Was true: the nightly Full check on dev was red because of a handful of known-flaky tests and nobody knew why. Is true now: each cause is named in the pull request, and only the hosted-disclosure startup wait is still unexplained (its failure message now says what the startup was doing)." +--- + +The rest of the change is tests: the Spending tab test no longer inherits the +process-wide count of unpriced calls that another test left behind, and the +storage-off, provider, pass-through, background-after and hosted-disclosure +tests no longer depend on a background goroutine, a store write or a stopwatch +finishing in time. From eabc825e3af60f4893ac99f25935567a057fcc9f Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 2 Dec 2026 10:45:44 -0500 Subject: [PATCH 10/10] docs: keep the change entry to the one claim that changed Co-Authored-By: Claude Sonnet 5.5 --- docs/changes/unreleased/3023-nightly-full-check-races.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/changes/unreleased/3023-nightly-full-check-races.md b/docs/changes/unreleased/3023-nightly-full-check-races.md index 0f43e6d4bd..f9fe13f392 100644 --- a/docs/changes/unreleased/3023-nightly-full-check-races.md +++ b/docs/changes/unreleased/3023-nightly-full-check-races.md @@ -5,7 +5,6 @@ pr: 3023 surface: [app, chat] invalidates: - "Was true: a second caller of crews.create with start_manager and the same request_id could be answered uncertain while the first was still starting, because the start was marked live only after its claim was written. Is true now: the mark goes up before the claim can be read, so that caller is told busy and uncertain is kept for a claim another process holds or a start that stopped early." - - "Was true: the nightly Full check on dev was red because of a handful of known-flaky tests and nobody knew why. Is true now: each cause is named in the pull request, and only the hosted-disclosure startup wait is still unexplained (its failure message now says what the startup was doing)." --- The rest of the change is tests: the Spending tab test no longer inherits the