Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion cmd/codeaf/app_chat_preview_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
8 changes: 8 additions & 0 deletions cmd/codeaf/appprovider_journey_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
8 changes: 8 additions & 0 deletions cmd/codeaf/appproviders_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
20 changes: 19 additions & 1 deletion cmd/codeaf/appsync_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()})
Expand Down Expand Up @@ -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
Expand Down
15 changes: 11 additions & 4 deletions cmd/codeaf/appteamstart.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
9 changes: 9 additions & 0 deletions cmd/codeaf/storage_off_gate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 {
Expand Down
14 changes: 14 additions & 0 deletions docs/changes/unreleased/3023-nightly-full-check-races.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
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."
---

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.
35 changes: 32 additions & 3 deletions internal/session/promote_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"

Expand Down Expand Up @@ -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
Expand All @@ -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")
Expand Down
11 changes: 10 additions & 1 deletion internal/tui3/settingspend.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
43 changes: 43 additions & 0 deletions internal/tui3/settingspend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package tui3
import (
"os"
"path/filepath"
"slices"
"strings"
"testing"

Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down
Loading