package thin import ( "context" "database/sql" "encoding/json" "os" "path/filepath" "testing" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/wire" "golang.org/x/sys/unix" ) const connPerson = "p@example.com" // connectorRig is a runner state, a bindings file with one Codex // connection of the person's (codex-1, its home under the accounts // root) and a connector over them that a test can restart. type connectorRig struct { t *testing.T state *State bindings, root string home string conns *Conns cfg runner.Config } func newConnectorRig(t *testing.T) *connectorRig { dir := t.TempDir() r := &connectorRig{t: t, root: filepath.Join(dir, "accounts"), bindings: filepath.Join(dir, "config", "bindings.json")} for _, d := range []string{r.root, filepath.Dir(r.bindings), filepath.Join(dir, "state")} { if err := os.MkdirAll(d, 0700); err != nil { t.Fatal(err) } } var err error if r.state, err = OpenState(context.Background(), filepath.Join(dir, "state")); err != nil { t.Fatal(err) } t.Cleanup(func() { r.state.Close() }) r.cfg = runner.Config{AccountBindingsPath: r.bindings, CodexPath: "/bin/true", ClaudePath: "/bin/true"} r.conns = &Conns{Runner: r.cfg, State: r.state} r.add() return r } // add (again) binds codex-1 in a fresh home. func (r *connectorRig) add() { r.home = filepath.Join(r.root, "codex-1") if err := os.MkdirAll(r.home, 0700); err != nil { r.t.Fatal(err) } identity := map[string]string{"account_id": "a@example.com", "home_id": "h-" + time.Now().Format("150405.000000000"), "provider_version": "1"} b := []map[string]any{{"id": "codex-1", "local_id": "codex-1", "label": "codex-1", "person_id": connPerson, "provider": "codex", "family": "gpt", "model": "gpt-6-astra", "account_id": "a@example.com", "provider_home": r.home, "kind": "subscription", "expected_identity": identity}} raw, _ := json.Marshal(b) if err := os.WriteFile(r.bindings, raw, 0600); err != nil { r.t.Fatal(err) } } // connector is the runner's connector; crashed: its background cleanups // never run, as if the process stopped right after the frame. func (r *connectorRig) connector(crashed bool) *Connector { c := &Connector{Runner: r.cfg, State: r.state, Conns: r.conns, Root: r.root, Owners: []string{connPerson}} c.spawn = func(f func()) { f() } if crashed { c.spawn = func(func()) {} } if err := c.Start(context.Background()); err != nil { r.t.Fatal(err) } return c } func (r *connectorRig) bound() bool { _, ok := r.conns.Binding("codex-1") return ok } func (r *connectorRig) signedOut() int { frames, _, err := r.state.Unacked(context.Background(), 0) if err != nil { r.t.Fatal(err) } n := 0 for _, f := range frames { var v wire.ConnectionReport if f.Type == wire.FrameConnection && json.Unmarshal(f.Data, &v) == nil && v.State == wire.ConnSignedOut { n++ } } return n } func (r *connectorRig) attempt(id, state string, cancelled int) { if _, err := r.state.db.Exec("INSERT INTO connect_attempts(id, person, provider, state, local_id, cancelled, created_at) VALUES(?,?,?,?,?,?,?)", id, connPerson, "codex", state, "codex-1", cancelled, now()); err != nil { r.t.Fatal(err) } } // Astra round 1, finding 4: a sign-out whose frame was consumed is done // even when the runner stops before the cleanup ran: the restarted // connector owes it, does it once, and reports signed_out. func TestConnectorSignOutSurvivesACrash(t *testing.T) { r := newConnectorRig(t) c := r.connector(true) if err := c.Disconnect(context.Background(), "f1", wire.DisconnectCommand{Connection: "cn_1", Person: connPerson, LocalID: "codex-1"}); err != nil { t.Fatal(err) } if !r.bound() { t.Fatal("the crashed connector signed out anyway") } r.connector(false) if r.bound() || r.signedOut() != 1 { t.Fatalf("after the restart: bound %v, %d signed_out reports", r.bound(), r.signedOut()) } if _, err := os.Stat(r.home); !os.IsNotExist(err) { t.Fatalf("the home stayed: %v", err) } // The same frame again changes nothing; a later start owes nothing. again := r.connector(false) if err := again.Disconnect(context.Background(), "f1", wire.DisconnectCommand{Connection: "cn_1", Person: connPerson, LocalID: "codex-1"}); err != nil { t.Fatal(err) } if r.signedOut() != 1 { t.Fatalf("%d signed_out reports", r.signedOut()) } } // Finding 4, cancel: a cancel that finds the attempt's connection saved // owes its sign-out from the transaction that consumes the frame; a // connection saved and then found cancelled is owed at startup. Once // done, the attempt's local id, reused by a later connection, is never // signed out again. func TestConnectorCancelSurvivesACrash(t *testing.T) { r := newConnectorRig(t) r.attempt("cn_2", "done", 0) c := r.connector(true) if err := c.Cancel(context.Background(), "f2", wire.CancelConnectCommand{Connection: "cn_2", Person: connPerson}); err != nil { t.Fatal(err) } if !r.bound() { t.Fatal("the crashed connector signed out anyway") } r.connector(false) if r.bound() { t.Fatal("the cancelled connection stood after the restart") } // Saved, then the cancel seen, then the stop: owed at startup. r.add() r.attempt("cn_3", "done", 1) r.connector(false) if r.bound() { t.Fatal("a connection cancelled as it was saved stood after the restart") } // codex-1 again, a new connection: no restart signs it out. r.add() r.connector(false) if !r.bound() { t.Fatal("a later connection with the same local id was signed out") } } // Finding 3: the attempt holds its home's lock while it signs in; a // cancel that lands as the connection is saved signs it out without // waiting on that lock. func TestConnectorLateCancelLetsGoOfTheLock(t *testing.T) { r := newConnectorRig(t) r.attempt("cn_4", "done", 1) c := r.connector(true) lock, err := os.Open(r.home) if err != nil { t.Fatal(err) } if err = unix.Flock(int(lock.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { t.Fatal(err) } done := make(chan struct{}) go func() { c.standOrGo(wire.ConnectCommand{Connection: "cn_4", Person: connPerson, Provider: "codex"}, "codex-1", lock) close(done) }() select { case <-done: case <-time.After(10 * time.Second): t.Fatal("the late cancel waits on the attempt's own lock") } if r.bound() { t.Fatal("the cancelled connection stood") } } // Astra round 2: a stop after the binding went and before the home did // leaves the home in the cleanup's record; the restarted connector // deletes it and only then reports signed_out. func TestConnectorSignOutFinishesTheHomeAfterACrash(t *testing.T) { r := newConnectorRig(t) if err := r.state.tx(context.Background(), func(tx *sql.Tx) error { return owe(tx, cleanup{connection: "cn_5", person: connPerson, local: "codex-1", report: true}) }); err != nil { t.Fatal(err) } if _, err := r.state.db.Exec("UPDATE connect_cleanups SET home=?, provider='codex' WHERE connection='cn_5'", r.home); err != nil { t.Fatal(err) } if err := os.WriteFile(r.bindings, []byte("[]"), 0600); err != nil { t.Fatal(err) } r.connector(false) if _, err := os.Stat(r.home); !os.IsNotExist(err) || r.signedOut() != 1 { t.Fatalf("home left %v, %d signed_out reports", err, r.signedOut()) } } // Round 2: a home that cannot be deleted is never reported signed out; // the cleanup stays owed and finishes once it can. func TestConnectorNeverReportsSignedOutWhileTheHomeExists(t *testing.T) { r := newConnectorRig(t) c := r.connector(true) if err := c.Disconnect(context.Background(), "f6", wire.DisconnectCommand{Connection: "cn_6", Person: connPerson, LocalID: "codex-1"}); err != nil { t.Fatal(err) } if err := os.Chmod(r.root, 0500); err != nil { t.Fatal(err) } r.connector(false) if err := os.Chmod(r.root, 0700); err != nil { t.Fatal(err) } if _, err := os.Stat(r.home); err != nil || r.signedOut() != 0 { t.Fatalf("home %v, %d signed_out reports while it exists", err, r.signedOut()) } r.connector(false) if _, err := os.Stat(r.home); !os.IsNotExist(err) || r.signedOut() != 1 || r.bound() { t.Fatalf("home %v, %d reports, bound %v", err, r.signedOut(), r.bound()) } }