feat: persist sessions to SQLite and implement ACP session methods #3

Merged
sam merged 6 commits from feat/on-disk-session-persistence into main 2026-09-22 07:07:37 +00:00
Collaborator

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 ADK session.Service via session/database, using the pure-Go github.com/glebarez/sqlite driver (keeps CGO_ENABLED=0 static cross-builds working). DSN uses journal_mode(WAL) + busy_timeout(5000) so multiple brainless processes on the same host share the DB safely. Runs AutoMigrate.
  • internal/harness/harness.go: New uses runner.New with the store when cfg.SessionDir != "" (else falls back to in-memory). Implements CloseSession (ends the active session, does not delete — sessions stay listable/loadable/resumable), ListSessions (enumerate → SessionInfo), and LoadSession/ResumeSession (activate by id, existence-checked via the store). Initialize advertises LoadSession: true. Prompt honors the session id carried in the request. activate() reports a missing session via wrapped session.ErrNotFound.
  • cmd/brainless/main.go: new SESSION_DIR env var / -session-dir flag wired into Config.SessionDir.
  • Tests: session store round-trip across a simulated restart, plus activate for known/unknown sessions.
  • README: document SESSION_DIR and the new session capabilities.

Scope notes

  • session/close clears 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/fork is 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=0 build, go test ./..., and golangci-lint run all pass.

Verified

  • go build ./..., go vet ./..., go test ./... — pass
  • CGO_ENABLED=0 go build — pass
  • golangci-lint run — 0 issues
## 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 ADK `session.Service` via `session/database`, using the pure-Go `github.com/glebarez/sqlite` driver (keeps `CGO_ENABLED=0` static cross-builds working). DSN uses `journal_mode(WAL)` + `busy_timeout(5000)` so multiple `brainless` processes on the same host share the DB safely. Runs `AutoMigrate`. - **`internal/harness/harness.go`**: `New` uses `runner.New` with the store when `cfg.SessionDir != ""` (else falls back to in-memory). Implements `CloseSession` (ends the active session, **does not delete** — sessions stay listable/loadable/resumable), `ListSessions` (enumerate → `SessionInfo`), and `LoadSession`/`ResumeSession` (activate by id, existence-checked via the store). `Initialize` advertises `LoadSession: true`. `Prompt` honors the session id carried in the request. `activate()` reports a missing session via wrapped `session.ErrNotFound`. - **`cmd/brainless/main.go`**: new `SESSION_DIR` env var / `-session-dir` flag wired into `Config.SessionDir`. - **Tests**: session store round-trip across a simulated restart, plus `activate` for known/unknown sessions. - **README**: document `SESSION_DIR` and the new session capabilities. ## Scope notes - `session/close` clears 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/fork` is 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=0` build, `go test ./...`, and `golangci-lint run` all pass. ## Verified - `go build ./...`, `go vet ./...`, `go test ./...` — pass - `CGO_ENABLED=0 go build` — pass - `golangci-lint run` — 0 issues
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 reused across instances.

- internal/harness/sessionstore.go: NewSessionStore opens a SQLite-backed
  session.Service (glebarez/sqlite, pure-Go for CGO_ENABLED=0 builds) with
  WAL + busy_timeout so concurrent processes share it safely.
- harness.New uses runner.New with the store when cfg.SessionDir is set,
  falling back to the in-memory service otherwise.
- Implement CloseSession (delete), ListSessions (enumerate), LoadSession
  and ResumeSession (activate by id, verified against the store); set the
  loadSession capability in Initialize. activate() reports a missing
  session via wrapped session.ErrNotFound.
- cmd/brainless: new SESSION_DIR env / -session-dir flag.
- Tests: session store round-trip across reopen, and harness activate.
- README: document SESSION_DIR and the new session capabilities.
Address Paseo review #3 comments:
- session/close now only clears the active in-memory session binding; it no
  longer deletes from the store, so a closed session stays listable,
  loadable, and resumable (persistence is the point).
- NewSessionStore keeps returning session.Service; justify the ireturn nolint
  (ADK's concrete databaseService is unexported).
- Build the SQLite DSN with plain string concat instead of fmt.Sprintf.
The ACP SDK dispatches each inbound request in its own goroutine, so
NewSession, CloseSession, activate, and ListSessions can run concurrently and
previously mutated/read h.session and h.cwd without synchronization (a data
race on the active-session fallback id).

- Protect session/cwd with a sync.RWMutex; reads in Prompt and ListSessions
  take RLock, writes in NewSession/activate/CloseSession take Lock.
- Add TestHarnessConcurrentSessionAccess hammering the four paths from
  parallel goroutines; passes under the race detector.
style: streamline docs and simplify the SQLite DSN, per review
All checks were successful
code-review / Agent review (pull_request) Successful in 11s
cedd609998
- Drop the redundant busy_timeout pragma: glebarez/go-sqlite sets a 5s
  BUSY_TIMEOUT by default and its _pragma= DSN parameter is the documented
  way to set pragmas, so only journal_mode(WAL) is needed.
- Shorten the RWMutex and cwd field comments and the Config.SessionDir doc.
pi-agent left a comment

Code 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 the glebarez/go-sqlite BUSY_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/list reports 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.

## Code 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 the `glebarez/go-sqlite` `BUSY_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/list` reports 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 each
Author
Collaborator

YELLOW 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.

YELLOW 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.
sam marked this conversation as resolved
@ -103,0 +140,4 @@
h.mu.RLock()
cwd := h.cwd
h.mu.RUnlock()
Author
Collaborator

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.

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.
sam marked this conversation as resolved
@ -171,3 +242,4 @@
return acp.ResumeSessionResponse{}, nil
}
// SetAgentConnection attaches the ACP connection used to stream updates.
Author
Collaborator

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.

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.
sam marked this conversation as resolved
- Guard h.conn under the same RWMutex: SetAgentConnection takes the write
  lock, Prompt captures the pointer under RLock before using it, closing the
  unguarded read flagged in review. A single lock suffices - conn is written
  once before serving, so it never contends with session/cwd; a second lock
  would split on a non-contended field.
- Prompt now rejects an empty session id with a clear error instead of
  invoking the runner with one (review).
- Document that SessionInfo cwd is intentionally the most recent NewSession's
  working dir, not a per-session value (review).
- Extend the concurrency test with a SetAgentConnection writer goroutine.
Author
Collaborator

Resolved for cwd: decided it's cosmetic, and documented it as such. SessionInfo reports the working dir of the most recent NewSession, not a per-session value — the harness is one-session-at-a-time and doesn't track per-session cwds. Added a field comment in Harness stating 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 **cwd**: decided it's **cosmetic**, and documented it as such. `SessionInfo` reports the working dir of the most recent `NewSession`, not a per-session value — the harness is one-session-at-a-time and doesn't track per-session cwds. Added a field comment in `Harness` stating 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.
Author
Collaborator

Resolved for conn: guarded under the existing RWMutex. SetAgentConnection now takes the write lock; Prompt captures the pointer under RLock before using it (releasing the lock before the streaming SessionUpdate, so a short-lived stream update doesn't block session writers).

On the second-lock suggestion: I checked, and a dedicated connLock wouldn't reduce contention here. conn is written exactly once before serving (in main.run) and only read after that, so it never overlaps with the per-request session/cwd traffic in practice; splitting into sessionLock + connLock would add a field and two call sites for zero contention benefit. One mutex is the proportionate fix.

Resolved for **conn**: guarded under the existing RWMutex. `SetAgentConnection` now takes the write lock; `Prompt` captures the pointer under `RLock` before using it (releasing the lock before the streaming `SessionUpdate`, so a short-lived stream update doesn't block session writers). On the second-lock suggestion: I checked, and a dedicated `connLock` wouldn't reduce contention here. `conn` is written exactly once before serving (in `main.run`) and only read after that, so it never overlaps with the per-request `session`/`cwd` traffic in practice; splitting into `sessionLock` + `connLock` would add a field and two call sites for zero contention benefit. One mutex is the proportionate fix.
Author
Collaborator

Resolved for the empty session id: Prompt now 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 letting AutoCreateSession silently bind to whatever it decided. This covers both the no-SessionId-after-CloseSession case and the single-shot path with no prior NewSession.

Resolved for the **empty session id**: `Prompt` now 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 letting `AutoCreateSession` silently bind to whatever it decided. This covers both the no-`SessionId`-after-`CloseSession` case and the single-shot path with no prior `NewSession`.
Author
Collaborator

Fixed: both error-log calls in Prompt (session update + write output) now use slog.String("error", err.Error()) instead of slog.Any. err is nil-checked before the call, so err.Error() is safe.

Fixed: both error-log calls in Prompt (session update + write output) now use `slog.String("error", err.Error())` instead of `slog.Any`. `err` is nil-checked before the call, so `err.Error()` is safe.
sam merged commit b6c71d5444 into main 2026-09-22 07:07:37 +00:00
sam deleted branch feat/on-disk-session-persistence 2026-09-22 07:07:37 +00:00
Sign in to join this conversation.
No reviewers
No labels
code-review
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
sam/brainless!3
No description provided.