sessions

package module
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package sessions provides SQL-backed session.Storage implementations (SQLite and PostgreSQL) on uptrace/bun, as a separate module so the drivers never reach the core SDK's dependency graph. Entries are stored one row per entry, the whole entry serialized as JSON in one column: entry kinds and payloads are an open set, so a column per field would make every new kind a schema migration, and a build meeting an unknown kind must still read the row back.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateSchema

func CreateSchema(ctx context.Context, db *bun.DB) error

CreateSchema creates the agent_entries table and its lookup indexes if they do not already exist. It is safe to call repeatedly. The entry indexes are UNIQUE, and that is load-bearing: sequence numbers and entry ids are never handed out twice (spec §2.5e2), so a duplicate becomes a failed write. This project ships no migrations — rebuild the database on a schema change.

func CreateTaskSchema

func CreateTaskSchema(ctx context.Context, db *bun.DB) error

CreateTaskSchema creates the task table and its indexes.

It also ensures the session table exists, because a task row names sessions by (id, generation) and every read resolves the generation against it — a task store built without it would fail at the first query rather than at setup, depending on the order the two schema calls happened to be made in. Both creations are IfNotExists, so calling this and CreateSchema in either order (or both) is the same.

Types

type Repo

type Repo struct {
	// contains filtered or unexported fields
}

Repo is a SQL-backed session.Repo: it owns which sessions exist, separately from what each one holds.

func NewRepo

func NewRepo(db *bun.DB) *Repo

NewRepo wraps a *bun.DB as a session repository; on SQLite the pool is capped at one connection (spec §2.5e2). Call CreateSchema once before first use.

func (*Repo) Create

func (r *Repo) Create(ctx context.Context, opts session.CreateOptions) (*session.Session, error)

Create records a new session and returns it.

func (*Repo) Delete

func (r *Repo) Delete(ctx context.Context, id string) error

Delete removes a session, its entries, its task rows and the hidden sessions its tasks ran in — the whole tree, in one transaction, so a failure cannot leave orphans pointing at a session that is gone (spec §2.13).

func (*Repo) List

func (r *Repo) List(ctx context.Context, opts session.ListOptions) ([]session.Metadata, error)

List returns session metadata, newest first.

func (*Repo) Open

func (r *Repo) Open(ctx context.Context, id string) (*session.Session, error)

Open returns an existing session, or an error when there is none — a typo in a session id must not look like an empty conversation.

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session is a bun-backed session.Storage scoped to one session ID. Multiple Sessions may share a *bun.DB with different IDs.

func New

func New(db *bun.DB, sessionID string) *Session

New wraps an existing *bun.DB as a Session for the given session ID. The caller owns the db's lifecycle (and dialect); on SQLite the pool is capped at one connection (spec §2.5e2). Use NewSQLite or NewPostgres for the common cases. Call CreateSchema once before first use.

func NewPostgres

func NewPostgres(sqldb *sql.DB, sessionID string) (*Session, *bun.DB)

NewPostgres wraps an existing PostgreSQL *sql.DB as a Session, returning the *bun.DB for further use. The caller owns the underlying connection pool.

func NewSQLite

func NewSQLite(dsn, sessionID string) (*Session, *bun.DB, error)

NewSQLite opens a SQLite database at dsn (e.g. "file:agents.db?cache=shared", or "file::memory:?cache=shared") using the pure-Go modernc driver — no CGO — and returns a Session plus the *bun.DB so the caller can Close it. It does not create the schema; call CreateSchema.

func (*Session) Append

func (s *Session) Append(ctx context.Context, entries ...session.Entry) error

Append implements session.Storage. The append point is read inside the same transaction as the insert — see lockForWrite for why.

func (*Session) Clear

func (s *Session) Clear(ctx context.Context) error

Clear implements session.Storage, removing every entry for this session ID under the same write lock every other entry write holds — an unlocked clear could land between an append's tip-read and its insert.

func (*Session) Entries

func (s *Session) Entries(ctx context.Context, cur session.Cursor) ([]session.Entry, error)

Entries implements session.Storage, paginating by cursor.

func (*Session) Entry

func (s *Session) Entry(ctx context.Context, id string) (*session.Entry, error)

Entry implements session.Storage with an indexed lookup rather than a scan of the session.

func (*Session) Metadata

func (s *Session) Metadata(ctx context.Context) (session.Metadata, error)

Metadata implements session.Storage. It counts rather than loading, and merges in the session row when one exists (a session created through a repo).

func (*Session) ReplaceEntries

func (s *Session) ReplaceEntries(ctx context.Context, entries ...session.Entry) error

ReplaceEntries implements session.AtomicReplacer: the delete of the old history and the insert of the new one run in a single transaction, so a failure mid-rewrite rolls back to the previous history instead of leaving the session empty. Only this session ID's rows are touched. The high-water mark is read inside the same transaction — see lockForWrite.

type TaskStore

type TaskStore struct {
	// contains filtered or unexported fields
}

TaskStore is a SQL-backed tasks.Store.

The SQL is what makes it usable: Finalize is one conditional UPDATE, so the database arbitrates between racing finalizers rather than the process. That is why tasks require a transactional store and why there is no file-backed one — a read-modify-write over JSON cannot offer the same guarantee across processes.

func NewTaskStore

func NewTaskStore(db *bun.DB) *TaskStore

NewTaskStore wraps a *bun.DB as a task store. Call CreateTaskSchema once before first use.

func (*TaskStore) Advance

func (s *TaskStore) Advance(ctx context.Context, id, runID, nextRunID string, state json.RawMessage) (bool, error)

Advance implements tasks.Store as one conditional UPDATE: the run moves and the state lands together, only while runID is the current attempt and the row is working. The generation predicates are RetryClaim's, for the same reason — a row whose sessions are gone must not start a run.

func (*TaskStore) ByChildSession

func (s *TaskStore) ByChildSession(ctx context.Context, sessionID string) (*tasks.Task, error)

ByChildSession implements tasks.Store.

func (*TaskStore) Create

func (s *TaskStore) Create(ctx context.Context, t *tasks.Task) error

Create implements tasks.Store.

func (*TaskStore) Delete

func (s *TaskStore) Delete(ctx context.Context, id string) error

Delete implements tasks.Store.

func (*TaskStore) FailOrphans

func (s *TaskStore) FailOrphans(ctx context.Context) ([]tasks.Task, error)

FailOrphans implements tasks.Store, as ONE statement so the rows reported are exactly the rows failed — a select-then-update pair could fail a row the select never saw, or report one that finalized in between. Scoped by liveParent: a row bound to a dead generation matches nothing (§2.13 — it lists nowhere and owes nothing), so the sweep neither fails nor reports it.

input_required rows are kept: their pending approval persists and resumes the run, so they are not orphans.

func (*TaskStore) Finalize

func (s *TaskStore) Finalize(ctx context.Context, id, runID string, st tasks.Status, summary, result string, state json.RawMessage) (bool, error)

Finalize implements tasks.Store as one conditional UPDATE: status and result land together, only while the row is still non-terminal, so no reader sees a terminal task without its result. The run_id predicate says WHICH attempt was finalized, since RetryClaim lets a task leave a terminal state.

func (*TaskStore) Get

func (s *TaskStore) Get(ctx context.Context, id string) (*tasks.Task, error)

Get implements tasks.Store.

func (*TaskStore) ListByParent

func (s *TaskStore) ListByParent(ctx context.Context, parentSessionID string) ([]tasks.Task, error)

ListByParent implements tasks.Store, newest first.

func (*TaskStore) ListNonTerminal

func (s *TaskStore) ListNonTerminal(ctx context.Context, parentSessionID string) ([]tasks.Task, error)

ListNonTerminal implements tasks.Store.

func (*TaskStore) MarkInputRequired

func (s *TaskStore) MarkInputRequired(ctx context.Context, id, runID string) error

MarkInputRequired implements tasks.Store, bound to the current attempt like Finalize — an approval can outlive the attempt that opened it, and it must not pause the one that replaced it. Best-effort CAS: a concurrent terminal transition (or newer attempt) wins.

func (*TaskStore) ReclaimWorking

func (s *TaskStore) ReclaimWorking(ctx context.Context, id, runID string) (bool, error)

ReclaimWorking implements tasks.Store, with the same attempt bound: a stale approval (its attempt retried past) must lose the claim, not resume over the newer run.

func (*TaskStore) ReleaseRetryClaim

func (s *TaskStore) ReleaseRetryClaim(ctx context.Context, id, runID, summary, result string) (bool, error)

ReleaseRetryClaim implements tasks.Store as one conditional UPDATE bound to the claimed run id, like Finalize: only the claim's owner can release it. The attempt rolls back because the claimed run never launched — attempt counts runs the task has HAD — with the same floor AttemptNo() applies.

func (*TaskStore) RetryClaim

func (s *TaskStore) RetryClaim(ctx context.Context, id, newRunID string, maxAttempts int) (bool, error)

RetryClaim implements tasks.Store as one conditional UPDATE, so the attempt ceiling holds across processes rather than only within the Manager that checked it.

The generation predicate is the same one every by-session read carries: a row whose sessions were deleted must not come back to life and launch a run onto an id that now answers to a different session.

Directories

Path Synopsis
Command example persists an agent's conversation in SQLite via the sessions module, so a follow-up question sees the previous turn.
Command example persists an agent's conversation in SQLite via the sessions module, so a follow-up question sees the previous turn.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址