feat: persist sessions to SQLite and implement ACP session methods #3
No reviewers
Labels
No labels
code-review
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
sam/brainless!3
Loading…
Reference in a new issue
No description provided.
Delete branch "feat/on-disk-session-persistence"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary
Back the ADK runner with a shared on-disk SQLite session store instead of in-memory only, and implement the previously stubbed ACP session methods so sessions survive process restarts and can be listed/loaded/resumed/closed across instances.
Changes
internal/harness/sessionstore.go(new):NewSessionStore(dir)opens a SQLite-backed ADKsession.Serviceviasession/database, using the pure-Gogithub.com/glebarez/sqlitedriver (keepsCGO_ENABLED=0static cross-builds working). DSN usesjournal_mode(WAL)+busy_timeout(5000)so multiplebrainlessprocesses on the same host share the DB safely. RunsAutoMigrate.internal/harness/harness.go:Newusesrunner.Newwith the store whencfg.SessionDir != ""(else falls back to in-memory). ImplementsCloseSession(ends the active session, does not delete — sessions stay listable/loadable/resumable),ListSessions(enumerate →SessionInfo), andLoadSession/ResumeSession(activate by id, existence-checked via the store).InitializeadvertisesLoadSession: true.Prompthonors the session id carried in the request.activate()reports a missing session via wrappedsession.ErrNotFound.cmd/brainless/main.go: newSESSION_DIRenv var /-session-dirflag wired intoConfig.SessionDir.activatefor known/unknown sessions.SESSION_DIRand the new session capabilities.Scope notes
session/closeclears the active binding only; there is no delete path yet (sessions accumulate in the store and can be pruned externally). An explicit delete feature can be added later.session/forkis intentionally out of scope: it is an experimental/unstable ACP extension (UnstableForkSession), not part of the stable session lifecycle, and cloning session history is distinct behavior.CGO_ENABLED=0build,go test ./..., andgolangci-lint runall pass.Verified
go build ./...,go vet ./...,go test ./...— passCGO_ENABLED=0 go build— passgolangci-lint run— 0 issuesCode review: session persistence (PR #3)
Reviewed against head
cedd609. The change is well-structured and well-tested: the on-disk/store split, the WAL + busy-timeout DSN reasoning, the wrapped-error handling, and the race-detector test are all solid. I verified theglebarez/go-sqliteBUSY_TIMEOUT(5000)default claim — correct since v1.21.0, and this pins v1.21.2. No blocking issues found. Three comments below; one worth deciding on before merge. Overall high-quality work.cwd finding (🟠):
session/listreports a single cwd for every session and never sets it on load/resume, so cwd is misleading for the very persisted-session flows this PR adds. Decide whether cwd is meaningful or cosmetic; if meaningful, persist per session.@ -122,3 +181,4 @@return acp.NewSessionResponse{SessionId: acp.SessionId(sid)}, nil}// Prompt runs one ACP prompt turn through the ADK runner. It streams eachYELLOW SUGGESTION - Prompt can reach the runner with an empty session id. If a request carries no SessionId and h.session was cleared by CloseSession (or the single-shot path ran without a prior NewSession), sid resolves to empty and h.runner.Run(ctx, userID, "", ...) is invoked with an empty id. AutoCreateSession may salvage it by creating a fresh session, but the bind is then whatever the runner decided rather than the session the client asked for. Low practical impact - ACP clients (Paseo) always send a SessionId on prompt - but a cheap guard (like the activate empty-id check, or not clearing h.session at all in CloseSession) would make the empty fallback explicit. Optional.
@ -103,0 +140,4 @@h.mu.RLock()cwd := h.cwdh.mu.RUnlock()ORANGE IMPORTANT - session/list reports one cwd for every session, and it is often stale. h.cwd is read once and stamped onto every SessionInfo. But cwd is only ever written by NewSession - activate() (load/resume) sets h.session but never h.cwd. So (1) after session/load or session/resume of an existing persisted session, its cwd stays whatever the previous NewSession set, and (2) after a process restart + load, the restored session reports a cwd that no longer reflects where it was created. There is no per-session cwd stored, only the one active value. If cwd is meant to be meaningful per session, persist it alongside the session (it is derived from req.Cwd at NewSession time) or at minimum stop advertising the same value for all rows. If it is intentionally cosmetic, a comment to that effect would prevent a future reader from fixing it. Condition to observe: create session A with cwd /project/a, then session/load session B created earlier in /project/b - session/list shows B with /project/a.
@ -171,3 +242,4 @@return acp.ResumeSessionResponse{}, nil}// SetAgentConnection attaches the ACP connection used to stream updates.YELLOW SUGGESTION - h.conn is written without the mutex while Prompt reads it. NewSession/CloseSession/activate are documented as running from concurrent goroutines and are correctly guarded by mu, but h.conn is written in SetAgentConnection and read in Prompt with no guard. Benign today because SetAgentConnection is called once before serving (in main.run), so there is no actual concurrent access in normal operation - but the struct doc comment makes the concurrency contract explicit, and an unguarded sibling field invites a race the moment connection setup moves or repeats (e.g. hot reconnect). Minimal fix: take h.mu.Lock() in SetAgentConnection and RLock() around the read in Prompt. Optional; not blocking given current call order.
Resolved for cwd: decided it's cosmetic, and documented it as such.
SessionInforeports the working dir of the most recentNewSession, not a per-session value — the harness is one-session-at-a-time and doesn't track per-session cwds. Added a field comment inHarnessstating exactly that, so a reader won't mistake it for per-session data. Persisting cwd per-session would need wiring into the runner's lazy session creation and a state field; not worth it for the bare-minimum harness (and Paseo uses a single cwd). Flag if you'd rather I persist it.Resolved for conn: guarded under the existing RWMutex.
SetAgentConnectionnow takes the write lock;Promptcaptures the pointer underRLockbefore using it (releasing the lock before the streamingSessionUpdate, so a short-lived stream update doesn't block session writers).On the second-lock suggestion: I checked, and a dedicated
connLockwouldn't reduce contention here.connis written exactly once before serving (inmain.run) and only read after that, so it never overlaps with the per-requestsession/cwdtraffic in practice; splitting intosessionLock+connLockwould add a field and two call sites for zero contention benefit. One mutex is the proportionate fix.Resolved for the empty session id:
Promptnow rejects a request that resolves to no session id with a clear error (acp.PromptResponse{}, errors.New("prompt without a session id")) instead of invoking the ADK runner with an empty id and lettingAutoCreateSessionsilently bind to whatever it decided. This covers both the no-SessionId-after-CloseSessioncase and the single-shot path with no priorNewSession.Fixed: both error-log calls in Prompt (session update + write output) now use
slog.String("error", err.Error())instead ofslog.Any.erris nil-checked before the call, soerr.Error()is safe.