Repository navigation
Add SQLite-backed persistent session storage - #64
Conversation
Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
Display session ID when chat exits so users can reconnect with --session-id to resume a persistent conversation. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
|
Warning Rate limit exceeded
You’ve run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Enterprise Run ID: 📒 Files selected for processing (3)
📝 WalkthroughWalkthroughThis PR implements persistent session storage with a new ChangesSession Storage Layer
Sequence DiagramsequenceDiagram
actor User
participant CLI as docsclaw chat
participant Model as Chat Model
participant Store as Session Store<br/>(Memory/SQLite)
participant Executor as Agent Executor
participant LLM as LLM Backend
User->>CLI: --session-id=abc123
CLI->>Model: NewModel(..., sessionID="abc123")
Model->>Store: GetOrCreate(sessionID, systemPrompt)
alt Session Exists
Store-->>Model: return existing session & messages
else New Session
Store->>Store: create session, insert system message
Store-->>Model: return new session
end
Model-->>CLI: model ready with session
User->>CLI: send message
CLI->>Model: handle user input
Model->>Executor: call with session context
Executor->>LLM: process request
LLM-->>Executor: assistant response
Executor->>Store: Append(sessionID, assistantMessage)
Store->>Store: compute seq, JSON-marshal tool fields, insert, update last_active
Store-->>Executor: ack
Executor-->>Model: result
Model-->>CLI: display response
User->>CLI: exit
CLI->>Model: return
User->>User: note session ID for next time
User->>CLI: --session-id=abc123 (later)
CLI->>Model: NewModel(..., sessionID="abc123")
Model->>Store: GetOrCreate(sessionID, systemPrompt)
Store-->>Model: return session with full message history
Note over Model,Store: Conversation resumes with all prior context restored
Estimated code review effort🎯 4 (Complex) | ⏱️ ~55 minutes 🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (2 warnings, 1 inconclusive)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/bridge/executor.go (1)
97-99:⚠️ Potential issue | 🟠 Major | ⚡ Quick winReject oversized session IDs instead of truncating them.
Silently slicing the client-provided ID can merge two distinct sessions that share the same 64-byte prefix, which is especially risky now that history is persisted across requests. Fail the request for invalid IDs, or map them to a fixed-length derived key.
Suggested fix
- if len(sessionID) > 64 { - sessionID = sessionID[:64] - } + if len(sessionID) > 64 { + yield(e.failedEvent(execCtx, "Invalid session ID"), nil) + return + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/bridge/executor.go` around lines 97 - 99, Replace the silent truncation of sessionID in executor.go with explicit validation and handling: in the function/method that currently contains the sessionID truncation (look for the sessionID variable near the block with "if len(sessionID) > 64 { sessionID = sessionID[:64] }"), either return a clear error response when the client-provided sessionID length exceeds 64 bytes (e.g., reject the request with a validation error) or deterministically map the long ID to a fixed-length derived key (e.g., compute a stable hash and use that as the stored session key) and document which approach you choose; ensure the error path sets an appropriate status/error message and that any derived-key approach uses a collision-resistant method and records both original and derived IDs where needed for traceability.
🧹 Nitpick comments (7)
internal/session/sqlite_store_test.go (1)
11-326: 💤 Low valueComprehensive test coverage; the timing-based reaper test is the only fragile spot.
TestSQLiteStoreReaperrelies ontime.Sleep(20 * time.Millisecond)being long enough for the 10ms TTL. TheAppend("keep-me", ...)call on line 198 refresheslast_activeso the "keep" path is robust, but if you ever see flakes on slow CI runners, consider an injectable clock or anowFuncfield inSQLiteStoreso the test can advance time deterministically. Not blocking — the suite as written exercises the right behaviors (TTL expiry, cascade cleanup of messages, JSON roundtrip, persistence across reopen).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/session/sqlite_store_test.go` around lines 11 - 326, TestSQLiteStoreReaper is timing-flaky because it relies on real time; modify SQLiteStore to accept an injectable clock (e.g., add a nowFunc field or clock interface used by NewSQLiteStore and by reap()/TTL checks) and update the test TestSQLiteStoreReaper to use a deterministic nowFunc that you can advance instead of time.Sleep, ensuring calls to store.GetOrCreate, store.Append and store.reap use the injected nowFunc so the test can simulate expiry reliably.internal/session/sqlite_store.go (5)
134-134: ⚡ Quick winUse
errors.Is(err, sql.ErrNoRows)instead of direct comparison.Direct equality with
sql.ErrNoRowsbreaks if the error gets wrapped anywhere in the future and is not the idiomatic Go 1.13+ pattern. Cheap to fix today.♻️ Proposed fix
- if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { return nil, nil }(Add
"errors"to imports.)Also applies to: 219-219
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/session/sqlite_store.go` at line 134, Replace direct equality checks against sql.ErrNoRows with errors.Is(err, sql.ErrNoRows) to correctly handle wrapped errors: update the conditional(s) that currently use "if err == sql.ErrNoRows" (seen in the function(s) handling query results in sqlite_store.go) to use errors.Is, and add "errors" to the import list; apply the same change to the second occurrence around the code that currently compares err == sql.ErrNoRows (the one referenced at the other occurrence).
216-232: ⚖️ Poor tradeoffRace window between existence check and seq computation.
The session existence check (line 218),
MAX(seq)query (line 227), and the actualINSERT(line 258) are three separate operations againsts.db. The instance-levels.mumutex makes this safe within a single process, but if the same SQLite file is ever opened by a secondSQLiteStore(or another process — e.g., during a rolling pod restart with shared PVC), two concurrentappendMessagecalls could compute the sameseqand one would fail theUNIQUE(session_id, seq)constraint. Folding the existence check and seq computation into the same transaction (and relying on the unique constraint as the safety net) would make this multi-writer-safe.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/session/sqlite_store.go` around lines 216 - 232, The appendMessage function has a race between checking session existence, computing seq, and inserting; fix it by running the existence check, seq computation, and INSERT inside a single DB transaction using s.db.BeginTx (or Begin) so those reads/writes are atomic; in appendMessage, start a transaction, perform SELECT 1 FROM sessions WHERE id = ? and SELECT COALESCE(MAX(seq), -1) + 1 FROM messages WHERE session_id = ? within that same tx, then perform the INSERT and commit; also handle UNIQUE(session_id, seq) constraint errors from the INSERT (return or retry as appropriate) instead of relying on s.mu so multi-process writers are safe.
217-218: 💤 Low valueVerify
Scan(&exists)works with abooldestination onmodernc.org/sqlite.
SELECT 1 FROM sessions WHERE id = ?returns an integer column, anddatabase/sql.convertAssignis conservative about integer→bool conversions on some drivers. The PR description says all 21 tests pass (which includesTestSQLiteStoreAppend), so this likely works with the modernc driver, but it's worth a quick sanity check. If you ever swap drivers, switchingvar exists booltovar exists int(orvar dummy intsince the value isn't actually used) avoids the dependency on driver-specific conversion behavior.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/session/sqlite_store.go` around lines 217 - 218, The current QueryRow call uses Scan(&exists) with exists declared as a bool which can be driver-dependent; change the destination to an integer (e.g., declare var dummy int and call Scan(&dummy)) and keep the same error handling (treat sql.ErrNoRows as "not found" and any other error as a failure). Locate the s.db.QueryRow("SELECT 1 FROM sessions WHERE id = ?", id) call in sqlite_store.go and replace the bool target with an int/dummy variable to avoid relying on driver-specific int→bool conversion behavior.
22-61: ⚡ Quick winConsider limiting the SQLite connection pool to 1 writer.
database/sqlopens a pool of connections, but SQLite serializes writers at the file level. Under concurrent writes (multiple sessions appending in parallel) you can hitSQLITE_BUSY/ "database is locked" errors despite WAL mode. A common, simple mitigation isdb.SetMaxOpenConns(1)for write-heavy SQLite, or use a separate read pool. Given eachAppenddoesBEGIN ... COMMIT, andappendMessagealready serializes vias.mu, the practical effect today is small — but once any caller bypassess.mu(e.g., a future read path) the issue surfaces.♻️ Suggested addition in `NewSQLiteStore` after schema init
if _, err := db.Exec(schema); err != nil { _ = db.Close() return nil, fmt.Errorf("create schema: %w", err) } + // SQLite serializes writers at the file level; cap the pool to avoid + // SQLITE_BUSY under concurrent writes. + db.SetMaxOpenConns(1) return &SQLiteStore{db: db, ttl: ttl}, nil🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/session/sqlite_store.go` around lines 22 - 61, The SQLite store should limit concurrent open connections to avoid SQLITE_BUSY under concurrent writers: in NewSQLiteStore, after the schema is created and before returning the SQLiteStore, call db.SetMaxOpenConns(1) so the database uses a single writer connection; reference NewSQLiteStore and SQLiteStore to locate where to add this, and note Append and appendMessage / s.mu currently serialize writes but this db.SetMaxOpenConns(1) provides a safety net if future callers bypass s.mu.
67-71: ⚡ Quick win
Len()silently swallows query errors.
_ = s.db.QueryRow(...).Scan(&count)discards any error and returns0, which is indistinguishable from an empty store. Either return(int, error)(interface change) or at minimum log the error so a corrupted/locked DB doesn't go unnoticed.♻️ Minimal fix without changing the interface
func (s *SQLiteStore) Len() int { var count int - _ = s.db.QueryRow("SELECT COUNT(*) FROM sessions").Scan(&count) + if err := s.db.QueryRowContext(context.Background(), + "SELECT COUNT(*) FROM sessions").Scan(&count); err != nil { + slog.Error("session count query failed", "error", err) + } return count }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/session/sqlite_store.go` around lines 67 - 71, Len() currently ignores errors from s.db.QueryRow(...).Scan(&count) causing silent failures; update SQLiteStore.Len() to check the error returned by Scan, log the error (using SQLiteStore's logger field if present, otherwise a package logger like log.Printf) and still return the count (or 0) to avoid changing the function signature, e.g., capture err := s.db.QueryRow(...).Scan(&count) and if err != nil log the error with context ("SQLiteStore.Len: failed to count sessions") before returning count; keep the function name SQLiteStore.Len() and signature unchanged.internal/cmd/chat.go (1)
67-71: 💤 Low valueOptional: also surface session ID when
p.Runerrors.If
p.Runreturns a non-nil error (e.g., terminal issue mid-conversation) the user loses the session ID and cannot resume. Consider attempting the type-assert/print before returning the error, so the resume hint is always available when achat.Modelwas produced.♻️ Proposed tweak
result, err := p.Run() + if finalModel, ok := result.(chat.Model); ok && finalModel.SessionID() != "" { + _, _ = fmt.Fprintf(cmd.ErrOrStderr(), + "\nSession ID: %s\nTo resume: docsclaw chat --agent-url %s --session-id %s\n", + finalModel.SessionID(), agentURL, finalModel.SessionID()) + } if err != nil { return err } - if finalModel, ok := result.(chat.Model); ok { - _, _ = fmt.Fprintf(cmd.ErrOrStderr(), - "\nSession ID: %s\nTo resume: docsclaw chat --agent-url %s --session-id %s\n", - finalModel.SessionID(), agentURL, finalModel.SessionID()) - } return nil🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/cmd/chat.go` around lines 67 - 71, When p.Run returns an error, the resume hint is currently only printed when result is a chat.Model and no error is returned; change the flow so you attempt the type assertion on result (e.g., if finalModel, ok := result.(chat.Model)) and print the SessionID/resume hint to cmd.ErrOrStderr() using finalModel.SessionID() and agentURL before returning the error from p.Run, ensuring the session ID is surfaced even when p.Run fails.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/bridge/executor.go`:
- Around line 135-140: The Append call on e.Sessions
(e.Sessions.Append(sessionID, llm.Message{Role: "assistant", Content: result}))
can fail but the code currently only logs and lets the caller proceed; change
this so that when Append returns an error you both log it (retain e.Log.Error)
and propagate it to the caller by returning/wrapping the error from the
surrounding function (or otherwise signaling failure) so the caller does not
treat the turn as successfully persisted; ensure no subsequent success path
(sending/acknowledging the assistant response) runs if Append fails.
In `@internal/cmd/serve.go`:
- Around line 465-474: The directory for the persistent session DB is created
with overly permissive 0755; change the os.MkdirAll call to use 0700 to restrict
traversal to the user, and after creating/opening the database with
session.NewSQLiteStore (symbol sqliteStore), explicitly set the file permissions
to 0600 (e.g., os.Chmod(sessionDB, 0600)) and handle any error (returning a
wrapped fmt.Errorf) before deferring sqliteStore.Close(); keep assignments to
sessions and the log.Info call as-is.
In `@internal/session/sqlite_store.go`:
- Line 32: Update the SQLite store to use context-aware DB calls: replace
db.Exec, db.QueryRow, db.Begin and tx.Exec usages with their context-aware
counterparts (ExecContext, QueryRowContext, BeginTx/Tx.ExecContext) and thread a
context.Context through all affected methods; specifically change the
SessionStore interface method signatures for GetOrCreate, Get, Append,
AppendAndSnapshot, Len and the internal reap method to accept ctx, update
MemoryStore and any executor callers to pass the incoming ctx, and use
db.BeginTx with a context when starting transactions so long-running DB ops can
be cancelled by the request context.
---
Outside diff comments:
In `@internal/bridge/executor.go`:
- Around line 97-99: Replace the silent truncation of sessionID in executor.go
with explicit validation and handling: in the function/method that currently
contains the sessionID truncation (look for the sessionID variable near the
block with "if len(sessionID) > 64 { sessionID = sessionID[:64] }"), either
return a clear error response when the client-provided sessionID length exceeds
64 bytes (e.g., reject the request with a validation error) or deterministically
map the long ID to a fixed-length derived key (e.g., compute a stable hash and
use that as the stored session key) and document which approach you choose;
ensure the error path sets an appropriate status/error message and that any
derived-key approach uses a collision-resistant method and records both original
and derived IDs where needed for traceability.
---
Nitpick comments:
In `@internal/cmd/chat.go`:
- Around line 67-71: When p.Run returns an error, the resume hint is currently
only printed when result is a chat.Model and no error is returned; change the
flow so you attempt the type assertion on result (e.g., if finalModel, ok :=
result.(chat.Model)) and print the SessionID/resume hint to cmd.ErrOrStderr()
using finalModel.SessionID() and agentURL before returning the error from p.Run,
ensuring the session ID is surfaced even when p.Run fails.
In `@internal/session/sqlite_store_test.go`:
- Around line 11-326: TestSQLiteStoreReaper is timing-flaky because it relies on
real time; modify SQLiteStore to accept an injectable clock (e.g., add a nowFunc
field or clock interface used by NewSQLiteStore and by reap()/TTL checks) and
update the test TestSQLiteStoreReaper to use a deterministic nowFunc that you
can advance instead of time.Sleep, ensuring calls to store.GetOrCreate,
store.Append and store.reap use the injected nowFunc so the test can simulate
expiry reliably.
In `@internal/session/sqlite_store.go`:
- Line 134: Replace direct equality checks against sql.ErrNoRows with
errors.Is(err, sql.ErrNoRows) to correctly handle wrapped errors: update the
conditional(s) that currently use "if err == sql.ErrNoRows" (seen in the
function(s) handling query results in sqlite_store.go) to use errors.Is, and add
"errors" to the import list; apply the same change to the second occurrence
around the code that currently compares err == sql.ErrNoRows (the one referenced
at the other occurrence).
- Around line 216-232: The appendMessage function has a race between checking
session existence, computing seq, and inserting; fix it by running the existence
check, seq computation, and INSERT inside a single DB transaction using
s.db.BeginTx (or Begin) so those reads/writes are atomic; in appendMessage,
start a transaction, perform SELECT 1 FROM sessions WHERE id = ? and SELECT
COALESCE(MAX(seq), -1) + 1 FROM messages WHERE session_id = ? within that same
tx, then perform the INSERT and commit; also handle UNIQUE(session_id, seq)
constraint errors from the INSERT (return or retry as appropriate) instead of
relying on s.mu so multi-process writers are safe.
- Around line 217-218: The current QueryRow call uses Scan(&exists) with exists
declared as a bool which can be driver-dependent; change the destination to an
integer (e.g., declare var dummy int and call Scan(&dummy)) and keep the same
error handling (treat sql.ErrNoRows as "not found" and any other error as a
failure). Locate the s.db.QueryRow("SELECT 1 FROM sessions WHERE id = ?", id)
call in sqlite_store.go and replace the bool target with an int/dummy variable
to avoid relying on driver-specific int→bool conversion behavior.
- Around line 22-61: The SQLite store should limit concurrent open connections
to avoid SQLITE_BUSY under concurrent writers: in NewSQLiteStore, after the
schema is created and before returning the SQLiteStore, call
db.SetMaxOpenConns(1) so the database uses a single writer connection; reference
NewSQLiteStore and SQLiteStore to locate where to add this, and note Append and
appendMessage / s.mu currently serialize writes but this db.SetMaxOpenConns(1)
provides a safety net if future callers bypass s.mu.
- Around line 67-71: Len() currently ignores errors from
s.db.QueryRow(...).Scan(&count) causing silent failures; update
SQLiteStore.Len() to check the error returned by Scan, log the error (using
SQLiteStore's logger field if present, otherwise a package logger like
log.Printf) and still return the count (or 0) to avoid changing the function
signature, e.g., capture err := s.db.QueryRow(...).Scan(&count) and if err !=
nil log the error with context ("SQLiteStore.Len: failed to count sessions")
before returning count; keep the function name SQLiteStore.Len() and signature
unchanged.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Enterprise
Run ID: c01d146d-87dd-47df-a22f-b4fb8aff0025
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (12)
CLAUDE.mddocs/superpowers/plans/2026-05-08-sqlite-session-persistence.mddocs/superpowers/specs/2026-05-08-sqlite-session-persistence-design.mdgo.modinternal/bridge/executor.gointernal/chat/model.gointernal/cmd/chat.gointernal/cmd/serve.gointernal/session/sqlite_store.gointernal/session/sqlite_store_test.gointernal/session/store.gointernal/session/store_test.go
| if e.Sessions != nil && sessionID != "" { | ||
| e.Sessions.Append(sessionID, | ||
| llm.Message{Role: "assistant", Content: result}) | ||
| if err := e.Sessions.Append(sessionID, | ||
| llm.Message{Role: "assistant", Content: result}); err != nil { | ||
| e.Log.Error("Failed to save assistant response to session", | ||
| "session_id", sessionID, "error", err) | ||
| } |
There was a problem hiding this comment.
Don't complete the task after the assistant turn fails to persist.
If this append fails, the caller still gets a successful response, but the stored conversation is now missing the assistant reply. The next resumed turn will run against corrupted history.
Suggested fix
if e.Sessions != nil && sessionID != "" {
if err := e.Sessions.Append(sessionID,
llm.Message{Role: "assistant", Content: result}); err != nil {
e.Log.Error("Failed to save assistant response to session",
"session_id", sessionID, "error", err)
+ yield(e.failedEvent(execCtx, "Session error: "+err.Error()), nil)
+ return
}
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if e.Sessions != nil && sessionID != "" { | |
| e.Sessions.Append(sessionID, | |
| llm.Message{Role: "assistant", Content: result}) | |
| if err := e.Sessions.Append(sessionID, | |
| llm.Message{Role: "assistant", Content: result}); err != nil { | |
| e.Log.Error("Failed to save assistant response to session", | |
| "session_id", sessionID, "error", err) | |
| } | |
| if e.Sessions != nil && sessionID != "" { | |
| if err := e.Sessions.Append(sessionID, | |
| llm.Message{Role: "assistant", Content: result}); err != nil { | |
| e.Log.Error("Failed to save assistant response to session", | |
| "session_id", sessionID, "error", err) | |
| yield(e.failedEvent(execCtx, "Session error: "+err.Error()), nil) | |
| return | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/bridge/executor.go` around lines 135 - 140, The Append call on
e.Sessions (e.Sessions.Append(sessionID, llm.Message{Role: "assistant", Content:
result})) can fail but the code currently only logs and lets the caller proceed;
change this so that when Append returns an error you both log it (retain
e.Log.Error) and propagate it to the caller by returning/wrapping the error from
the surrounding function (or otherwise signaling failure) so the caller does not
treat the turn as successfully persisted; ensure no subsequent success path
(sending/acknowledging the assistant response) runs if Append fails.
| "PRAGMA journal_mode=WAL", | ||
| "PRAGMA foreign_keys=ON", | ||
| } { | ||
| if _, err := db.Exec(pragma); err != nil { |
There was a problem hiding this comment.
noctx lint failures will block make lint.
Static analysis flags six call sites that use the non-context variants of database/sql operations: db.Exec (lines 32, 55), db.QueryRow (lines 69, 218, 227), and db.Begin/tx.Exec (lines 88, 94, 102, 252, 258, 266). Per the project's lint policy these need to use the *Context variants. Plumbing a context.Context through GetOrCreate, Get, Append, AppendAndSnapshot, Len, and reap would also let the executor cancel long-running DB ops along with the request.
♻️ Sketch of the change
-func (s *SQLiteStore) GetOrCreate(id, systemPrompt string) (*Session, error) {
+func (s *SQLiteStore) GetOrCreate(ctx context.Context, id, systemPrompt string) (*Session, error) {
s.mu.Lock()
defer s.mu.Unlock()
- sess, err := s.loadSession(id)
+ sess, err := s.loadSession(ctx, id)
...
- tx, err := s.db.Begin()
+ tx, err := s.db.BeginTx(ctx, nil)
...
- _, err = tx.Exec(
+ _, err = tx.ExecContext(ctx,
"INSERT INTO sessions ...",
...,
)The SessionStore interface in store.go would also need its method signatures updated, and MemoryStore + the executor callers would need to thread through ctx.
As per coding guidelines: "Focus on major issues impacting performance, readability, maintainability and security."
Also applies to: 55-55, 69-69, 88-88, 94-94, 102-102
🧰 Tools
🪛 golangci-lint (2.12.1)
[error] 32-32: (*database/sql.DB).Exec must not be called. use (*database/sql.DB).ExecContext
(noctx)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/session/sqlite_store.go` at line 32, Update the SQLite store to use
context-aware DB calls: replace db.Exec, db.QueryRow, db.Begin and tx.Exec
usages with their context-aware counterparts (ExecContext, QueryRowContext,
BeginTx/Tx.ExecContext) and thread a context.Context through all affected
methods; specifically change the SessionStore interface method signatures for
GetOrCreate, Get, Append, AppendAndSnapshot, Len and the internal reap method to
accept ctx, update MemoryStore and any executor callers to pass the incoming
ctx, and use db.BeginTx with a context when starting transactions so
long-running DB ops can be cancelled by the request context.
- Use errors.Is for sql.ErrNoRows checks - Move exists check and seq query into transaction in appendMessage - Use int instead of bool for EXISTS scan target - Set db.SetMaxOpenConns(1) for SQLite safety - Log errors in Len() instead of silently ignoring - Tighten directory (0700) and file (0600) permissions for session DB - Print session ID on chat exit even when p.Run returns error Skipped (with reasons): - Append error propagation: response already computed, log+continue is correct UX - Context-aware DB calls: significant interface refactor, follow-up - Session ID truncation: pre-existing code outside this PR - Injectable clock for tests: over-engineering for 20ms sleep Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
Summary
SessionStoreinterface from concrete in-memory store, enabling pluggable backendsSQLiteStoreimplementation usingmodernc.org/sqlite(pure Go, no CGo)--session-dbflag andDOCSCLAW_SESSION_DBenv var for store selection$XDG_DATA_HOME/docsclaw/sessions.db), works with K8s PVCs--session-idflag to chat command for resuming previous sessions--session-db memoryto preserve previous in-memory behaviorTest plan
--session-id— agent remembers contextCloses #5 (Phase 2)
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
--session-idflag, allowing users to resume previous chat sessions--session-dbflag to configure session storage backend (memory or SQLite database path)Documentation