postgres

package
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Overview

Package postgres is the optional Postgres implementation of brain.Store.

The host owns the connection pool: Configure sets what each connection needs on the host's pgxpool.Config (the search_path is the tacklr schema, then public, with a server-side statement_timeout), and Open takes the pool with the same Options. Inject the Store into brain.NewEngine. A transaction-mode pooler must support prepared statements and forward those startup parameters. Run Setup on each deploy: its schema script is idempotent, and concurrent runs wait for each other on an advisory lock. Tables live in Options.Schema (default "tacklr"): objects, objects_staging, object_kinds, session_messages, and audit_events. Store.Record is a brain.AuditFunc over audit_events (brain.WithAudit(store.Record)).

Lexical search uses a stored tsvector, search_tsv, on objects. Title is weight A, summary B, and body C. A partial GIN index covers live parts. Results order by ts_rank_cd with normalization 32. The query is websearch_to_tsquery (every term). When that page is shorter than requested, a second query ORs the same terms.

Tree writes (brain.Engine.PutTree) stage parts with one COPY per batch into objects_staging: an unlogged table with no vector or text index, so staged rows cost one cheap write and are lost on a crash, which only abandons uncommitted writes. Vectors go as binary real[]. CommitTree then sends its whole commit as one batch in one transaction: a per-tree advisory lock, the parent upsert, the objects.tree_rev check and increment (a stale revision is brain.ErrConflict), the staging checks, and the swap. The swap deletes replaced parts, inserts new parts with INSERT ... SELECT, and updates reused parts only when their position, properties, namespace or readers changed. Position is not indexed and the table keeps free space (fillfactor 85), so those updates are heap-only (HOT) and write no index entries. A failed check rolls the whole batch back. A session window is saved as one batch too: each row takes its key's generation or the next one.

Setup runs one script that creates whatever is missing, then checks the vector size. PurgeDeleted and Erase are single statements.

Other object indexes: namespace GIN (jsonb @>), parent btree (list children), a partial kind btree for live parents, and HNSW for vectors. Session messages are a small per-session set and are not indexed beyond their unique keys. Property, trigram, and created/updated indexes are not created: those queries do not use them. pg_trgm and pgvector are always created.

The Store's pool emits otelpgx spans under the caller context after export.Init (package telemetry/export). Package brain does not import this package. MemoryStore stays in brain for tests and offline hosts.

Index

Constants

View Source
const DefaultEmbeddingDim = 1536

DefaultEmbeddingDim is the pgvector column size when Options.EmbeddingDim is 0.

View Source
const DefaultSchema = "tacklr"

DefaultSchema is the Postgres schema for tacklr tables when Options.Schema is empty.

View Source
const DefaultStatementTimeout = 30 * time.Second

DefaultStatementTimeout caps one statement when Options.StatementTimeout is 0.

Variables

This section is empty.

Functions

func Configure added in v0.5.0

func Configure(cfg *pgxpool.Config, opts Options) error

Configure sets what every connection of the Store's pool needs: the search_path (opts.Schema, then public), the server-side statement timeout, statements prepared once per connection and cached, and an otelpgx tracer that emits a span per statement under the caller's context. Call it on the host's pool config before pgxpool.NewWithConfig, with the Options passed to Open. One pool configured this way also serves session/postgres, which qualifies its own tables.

A direct connection or a session-mode pooler works as is. A transaction-mode pooler (such as port 6543 on hosted Postgres) must support prepared statements (PgBouncer 1.21+ with max_prepared_statements, Supavisor) and must forward the search_path and statement_timeout startup parameters (or set them on the database role).

Types

type Options added in v0.5.0

type Options struct {
	// Schema holds the tacklr tables. Default DefaultSchema.
	Schema string
	// EmbeddingDim is the pgvector column size; it must match the embedder.
	// Default DefaultEmbeddingDim.
	EmbeddingDim int
	// StatementTimeout is the server-side statement_timeout, so a slow
	// statement is cancelled even when the client is gone (a frozen or
	// torn-down worker). Zero means DefaultStatementTimeout; negative turns
	// it off.
	StatementTimeout time.Duration
	// Embedding embeds objects, parts, session messages and queries; its
	// vectors must have EmbeddingDim values. No Embedder means search ranks
	// by the words alone.
	Embedding brain.Embedding
	// Ranking fuses the search channels.
	Ranking brain.Ranking
}

Options configures Open. Zero fields take the defaults.

type Store

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

Store is the Postgres brain.Store. Hosts open it with Open and inject it into brain.NewEngine. Run Setup before serving; it creates whatever schema is missing and is safe to run from many processes at once. It embeds with its own Options.Embedding and fuses its search channels with Options.Ranking.

func Open added in v0.5.0

func Open(pool *pgxpool.Pool, opts Options) (*Store, error)

Open returns a Store over pool, a pool the host built from a config that Configure set up with the same opts. It does no I/O. The host owns the pool and closes it.

func (*Store) DeleteSessionMessages added in v0.4.0

func (s *Store) DeleteSessionMessages(ctx context.Context, host brain.Namespace, sessionID string) error

DeleteSessionMessages implements brain.Store.

func (*Store) Erase added in v0.5.0

func (s *Store) Erase(ctx context.Context, scope brain.Scope) ([]uuid.UUID, error)

Erase implements brain.Store in one statement.

func (*Store) Get

func (s *Store) Get(ctx context.Context, scope brain.Scope, id uuid.UUID) (brain.Object, error)

Get implements brain.Store.

func (*Store) GetByProperty

func (s *Store) GetByProperty(ctx context.Context, scope brain.Scope, key, value string) (brain.Object, error)

GetByProperty implements brain.Store.

func (*Store) GetMany

func (s *Store) GetMany(ctx context.Context, scope brain.Scope, ids []uuid.UUID) ([]brain.Object, error)

GetMany implements brain.Store.

func (*Store) GetTree added in v0.5.0

func (s *Store) GetTree(ctx context.Context, scope brain.Scope, id uuid.UUID, limit int) (brain.Tree, error)

GetTree implements brain.Store in one query: the object, a part's record, and the record's parts. A saved session message (Scope.SessionID set) is read when no object has the id.

func (*Store) ListKinds

func (s *Store) ListKinds(ctx context.Context) ([]brain.ObjectKind, error)

ListKinds implements brain.Store.

func (*Store) PurgeDeleted added in v0.5.0

func (s *Store) PurgeDeleted(ctx context.Context, scope brain.Scope, before time.Time) (int, error)

PurgeDeleted implements brain.Store. It also drops parts staged by tree writes that never committed.

func (*Store) PurgeSessionMessages added in v0.5.0

func (s *Store) PurgeSessionMessages(ctx context.Context, host brain.Namespace, before time.Time) (int, error)

PurgeSessionMessages implements brain.Store.

func (*Store) Put

func (s *Store) Put(ctx context.Context, scope brain.Scope, in brain.Indexed) (brain.Object, error)

Put implements brain.Store: it embeds in.Text, then runs a full-column upsert that clears a soft delete and returns the stored row. The conflict update only applies to a row visible under scope, so an id held outside scope updates nothing (ErrNotFound).

func (*Store) PutKind

func (s *Store) PutKind(ctx context.Context, k brain.ObjectKind) error

PutKind implements brain.Store.

func (*Store) PutTree added in v0.5.0

func (s *Store) PutTree(ctx context.Context, scope brain.Scope, parent brain.Indexed, parts iter.Seq2[brain.Indexed, error]) (brain.Object, error)

PutTree implements brain.Store. It reads the tree's revision and the parts it can reuse, then runs Embedding.EmbedBatches: each finished batch is copied into the unlogged objects_staging table, so memory holds a few batches whatever the number of parts. One short commit then makes the staged parts the parent's only parts. Parts staged by a write that fails stay until PurgeDeleted drops them.

func (*Store) Record added in v0.5.0

func (s *Store) Record(ctx context.Context, ev brain.AuditEvent) error

Record is a brain.AuditFunc that appends ev to audit_events.

func (*Store) SaveSessionMessages added in v0.4.0

func (s *Store) SaveSessionMessages(ctx context.Context, host brain.Namespace, sessionID, generationKey string, messages []brain.SessionMessage) (int, error)

SaveSessionMessages implements brain.Store in one transaction. It embeds every message's SearchText in one call first; when that fails the window is saved without vectors, so it is still found by its words.

func (*Store) Search added in v0.5.0

func (s *Store) Search(ctx context.Context, scope brain.Scope, q brain.RecordSearch) ([]brain.ScoredID, error)

Search implements brain.Store in one round trip: every channel is one query of a batch, over the scope's records and parts and, when Scope.SessionID is set, the session's messages, and the store fuses the lists with its Ranking. Filters test the record a row belongs to: a part is joined to its parent only when there are filters. Search ranks by the words (full text; rows that hold every term first) and by meaning (the query's embedding, same model only; a query that does not embed is answered by its words). Exact search ranks by the words and by trigram similarity, and puts an exact title match first. Within keeps only that record's parts and leaves out session messages. An empty query lists the records the filters match, newest first, in one indexed query.

func (*Store) Setup

func (s *Store) Setup(ctx context.Context, kinds ...brain.KindSpec) error

Setup creates the schema, tables, indexes and functions the Store uses, then upserts kinds into object_kinds. Every statement is idempotent, so run it on each deploy; concurrent runs wait for each other on an advisory lock. Setup fails when the vector column has another size than Options.EmbeddingDim (changing it needs a re-embed, which Setup does not do).

func (*Store) SoftDelete

func (s *Store) SoftDelete(ctx context.Context, scope brain.Scope, id uuid.UUID) error

SoftDelete implements brain.Store: id and its parts.

Jump to

Keyboard shortcuts

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