store

package
v0.20.0 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2026 License: MIT Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package store provides PostgreSQL-backed persistence for documents and chunks.

Index

Constants

This section is empty.

Variables

View Source
var ErrDuplicateTranscript = fmt.Errorf("store: call-transcript with identical content already exists (different source_id)")

ErrDuplicateTranscript is returned by Upsert when a call-transcript document with identical content already exists under a different source_id. Callers in the collector pipeline should log and skip this document; they MUST NOT treat it as a fatal error that aborts the entire collection cycle.

Functions

This section is empty.

Types

type BaselineChunkStats

type BaselineChunkStats struct {
	Total                int64   `json:"total"`
	AvgChunksPerDocument float64 `json:"avg_chunks_per_document"`
	AvgChunkSizeBytes    float64 `json:"avg_chunk_size_bytes"`
}

BaselineChunkStats aggregates chunk-level baseline metrics.

type BaselineCollectionStats

type BaselineCollectionStats struct {
	MostRecentCollectedAt *time.Time            `json:"most_recent_collected_at"`
	BySource              map[string]*time.Time `json:"by_source_type"`
}

BaselineCollectionStats holds the most recent collection timestamps per source.

type BaselineDocumentStats

type BaselineDocumentStats struct {
	Total    int                            `json:"total"`
	BySource map[string]DocumentSourceStats `json:"by_source_type"`
}

BaselineDocumentStats aggregates document-level baseline metrics.

type BaselineFailureStats

type BaselineFailureStats struct {
	Open       int64          `json:"open"`
	DeadLetter int64          `json:"dead_letter"`
	BySource   map[string]int `json:"by_source_type"`
}

BaselineFailureStats aggregates extraction failure metrics.

type BaselineStats

type BaselineStats struct {
	Documents          BaselineDocumentStats   `json:"documents"`
	Chunks             BaselineChunkStats      `json:"chunks"`
	ExtractionFailures BaselineFailureStats    `json:"extraction_failures"`
	Collection         BaselineCollectionStats `json:"collection"`
}

BaselineStats is the top-level structure returned by the baseline stats query.

type Chunk

type Chunk struct {
	ID         int64
	DocumentID uuid.UUID
	ChunkIndex int
	Content    string
	ByteSize   int
	CreatedAt  time.Time
}

Chunk represents one text segment of a document stored in the chunks table.

type ChunkEmbedding

type ChunkEmbedding struct {
	ChunkID   int64
	Embedding []float32
}

ChunkEmbedding pairs a chunk ID with its embedding vector. Used by UpdateChunkEmbeddings for batch persistence.

type ChunkSearchResult

type ChunkSearchResult struct {
	Chunk

	// Rank is the ts_rank value from PostgreSQL for FTS results.
	Rank float64

	// Score is the cosine similarity for vector search results (1 - distance).
	// Zero when the result comes from FTS. Use whichever is non-zero, or fuse
	// both via RRF in the search layer.
	Score float64

	// Document metadata joined from the documents table.
	DocumentTitle  string
	DocumentSource string // source_type value (e.g. "slack", "github")
	DocumentStatus string
}

ChunkSearchResult extends Chunk with rank/score and parent document metadata. Only the fields needed for API responses are included; the full document is not re-fetched to keep the query fast.

type ChunkStore

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

ChunkStore provides chunk persistence and FTS search operations.

func NewChunkStore

func NewChunkStore(pg *Postgres) *ChunkStore

NewChunkStore returns a ChunkStore backed by the given Postgres instance.

func (*ChunkStore) ListByDocument

func (s *ChunkStore) ListByDocument(ctx context.Context, documentID uuid.UUID) ([]Chunk, error)

ListByDocument returns all chunks for the given document ordered by chunk_index ascending. It is used by the scheduler to fetch chunk IDs after a ReplaceDocument call (CopyFrom does not return inserted IDs).

func (*ChunkStore) ListUnembeddedChunks added in v0.20.0

func (s *ChunkStore) ListUnembeddedChunks(ctx context.Context, limit int) ([]UnembeddedChunk, error)

ListUnembeddedChunks returns up to limit chunks whose embedding column is NULL, ordered by created_at ASC (oldest first) so backfill progresses forward in time.

Only chunks belonging to active documents are included. Chunks for soft-deleted documents are excluded — re-embedding them would waste quota.

This is the per-chunk analogue of DocumentStore.ListUnembedded (#141).

func (*ChunkStore) ReplaceDocument

func (s *ChunkStore) ReplaceDocument(ctx context.Context, documentID uuid.UUID, chunks []Chunk) error

ReplaceDocument atomically replaces all chunks for documentID. It first deletes existing chunks for the document, then batch-inserts the provided chunks in a single transaction. If chunks is empty, only the delete is executed (effectively clearing chunks for the document).

func (*ChunkStore) SearchFTS

func (s *ChunkStore) SearchFTS(ctx context.Context, query string, limit int) ([]ChunkSearchResult, error)

SearchFTS performs full-text search across chunks using the 'simple' dictionary (matching the generated content_tsv column in the chunks table).

Results are ordered by ts_rank DESC. Each row includes chunk content and parent document metadata joined from the documents table.

Query plan notes:

  • content_tsv @@ plainto_tsquery uses the GIN index idx_chunks_tsv.
  • ts_rank is computed only for matching rows (post-filter).
  • The JOIN on documents uses the primary key (idx scan).

func (*ChunkStore) SearchVector

func (s *ChunkStore) SearchVector(ctx context.Context, queryVec []float32, limit int) ([]ChunkSearchResult, error)

SearchVector performs approximate nearest-neighbour (ANN) vector search over chunks using the HNSW index on chunks.embedding. Results are ordered by cosine similarity (highest first). Only active documents are included.

queryVec must have the same dimension as the stored vectors; mismatches result in a pgvector error. The caller is responsible for truncating/padding if needed.

func (*ChunkStore) UpdateChunkEmbeddings

func (s *ChunkStore) UpdateChunkEmbeddings(ctx context.Context, embeddings []ChunkEmbedding) error

UpdateChunkEmbeddings persists embedding vectors for a batch of chunks. When the batch exceeds updateEmbeddingsBatchSize entries, it is split into multiple transactions of at most updateEmbeddingsBatchSize UPDATEs each. Each sub-transaction commits independently; a failure in one sub-batch returns an error but does not roll back already-committed sub-batches.

Chunks with an empty embedding slice are silently skipped so that partial batch failures in the scheduler do not block the rest of the batch.

This is the per-chunk analogue of DocumentStore.UpdateEmbedding.

type CollectionSourceStatus added in v0.20.0

type CollectionSourceStatus struct {
	SourceType          model.SourceType `json:"source_type"`
	LastSuccessAt       *time.Time       `json:"last_success_at"`      // nil if never succeeded
	LastAttemptAt       *time.Time       `json:"last_attempt_at"`      // nil if never attempted
	ConsecutiveFailures int              `json:"consecutive_failures"` // failures since last success
	TotalRuns           int              `json:"total_runs"`
	StaleSeconds        *float64         `json:"stale_seconds,omitempty"` // seconds since last success; nil when never succeeded
}

CollectionSourceStatus describes the freshness state of a single collector source computed from the collection_log table.

type CollectionStatusReader added in v0.20.0

type CollectionStatusReader interface {
	// CollectionStatus returns the current freshness state per source type.
	// It reads from the collection_log table and computes last-success time
	// and consecutive failure count per source.
	CollectionStatus(ctx context.Context) ([]CollectionSourceStatus, error)
}

CollectionStatusReader is the interface implemented by DocumentStore to support the /api/v1/collect/status endpoint (#137). Defined as a separate interface so the API handler can be tested independently.

type ContentLengthStats

type ContentLengthStats struct {
	Mean float64 `json:"mean"`
	P50  float64 `json:"p50"`
	P95  float64 `json:"p95"`
	Max  int64   `json:"max"`
}

ContentLengthStats holds percentile and aggregate statistics for content length.

type DocumentSourceStats

type DocumentSourceStats struct {
	Count         int                `json:"count"`
	ContentLength ContentLengthStats `json:"content_length"`
}

DocumentSourceStats holds per-source aggregate document metrics.

type DocumentStore

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

DocumentStore provides document persistence and search operations.

func NewDocumentStore

func NewDocumentStore(pg *Postgres) *DocumentStore

NewDocumentStore returns a DocumentStore backed by the given Postgres instance.

func (*DocumentStore) ActiveSourceIDSet

func (s *DocumentStore) ActiveSourceIDSet(ctx context.Context, sourceType model.SourceType) (map[string]struct{}, error)

ActiveSourceIDSet returns a set of all source_ids that are currently active for the given source type. The returned map is keyed by source_id and is safe to use for O(1) membership tests. It is used by the filesystem collector to detect files that are new (not yet indexed) regardless of their mtime.

func (*DocumentStore) CollectionStatus added in v0.20.0

func (s *DocumentStore) CollectionStatus(ctx context.Context) ([]CollectionSourceStatus, error)

CollectionStatus reads collection_log and computes per-source freshness metrics: last successful run time, last attempt time, and consecutive failures (runs with a non-NULL error since the last success).

This is used by GET /api/v1/collect/status and the freshness checker (#137).

func (*DocumentStore) CountActiveDocuments added in v0.19.4

func (s *DocumentStore) CountActiveDocuments(ctx context.Context, sourceType model.SourceType) (int, error)

CountActiveDocuments returns the total number of active (non-deleted) documents for the given source type. It is used by the scheduler's deletion-ratio sanity check (issue #135) to detect a suspicious bulk-deletion before calling MarkDeleted. Implements scheduler.ActiveDocumentCounter.

func (*DocumentStore) CountByKind added in v0.19.0

func (s *DocumentStore) CountByKind(ctx context.Context, kind RecentKind) (int, error)

CountByKind returns the total number of active documents matching the given kind filter, regardless of any pagination limit.

The WHERE predicates are identical to those used by ListRecentByKind so both methods always agree on which rows belong to each kind. This count is used by the dashboard API to report the true total (e.g. "500 SMS messages collected") rather than the capped page size.

func (*DocumentStore) CountBySource

func (s *DocumentStore) CountBySource(ctx context.Context) (map[string]int, error)

CountBySource returns the number of active documents grouped by logical source. Deleted documents are excluded. The returned map is keyed by logical source string.

Legacy documents stored under source_type='secretary' are re-bucketed by their metadata 'kind' field (e.g. "sms", "gmail", "call-log", "call-transcript", "calendar"). This means historical SMS documents count toward the "sms" bucket alongside post-cutover documents — there is no double-counting because the two sets are date-disjoint. All other source_type values are reported as-is.

func (*DocumentStore) GetByID

func (s *DocumentStore) GetByID(ctx context.Context, id uuid.UUID) (*model.Document, error)

GetByID retrieves a single document by primary key.

func (*DocumentStore) LastCollectedAt

func (s *DocumentStore) LastCollectedAt(ctx context.Context, instanceID string, src model.SourceType, fallback time.Time) time.Time

LastCollectedAt returns the last collection watermark for the given (instance_id, source_type) pair, or the fallback when no row exists yet.

Per-instance state decouples collectors that share a source_type (e.g., filesystem scans on laptop, host1, host2) so one instance's recent scan cannot suppress older files seen by another instance.

func (*DocumentStore) ListActiveSourceIDs

func (s *DocumentStore) ListActiveSourceIDs(ctx context.Context, sourceType model.SourceType) ([]string, error)

ListActiveSourceIDs returns all source_ids for active documents of a given source type.

func (*DocumentStore) ListBySource

func (s *DocumentStore) ListBySource(ctx context.Context, src model.SourceType, limit, offset int) ([]*model.Document, error)

ListBySource returns active documents of a given source type, ordered by the original event time (occurred_at) when available, falling back to collected_at for rows that have no event-time concept. NULLS LAST ensures untagged rows appear after all event-timestamped rows. When src is empty, all active documents are returned regardless of source type.

func (*DocumentStore) ListRecent

func (s *DocumentStore) ListRecent(ctx context.Context, includeSrc model.SourceType, excludeSrcs []model.SourceType, limit, offset int) ([]*model.Document, error)

ListRecent returns active documents ordered by the original event time (occurred_at) when available, falling back to collected_at for rows that have no event-time concept. This ensures "most recent" reflects when the underlying event actually happened (email sent, call placed, etc.) rather than when second-brain ingested the document.

When includeSrc is non-empty, only documents of that source type are returned. excludeSrcs lists source types to omit from results; it is applied after includeSrc and may be empty.

func (*DocumentStore) ListRecentByKind added in v0.19.0

func (s *DocumentStore) ListRecentByKind(ctx context.Context, kind RecentKind, limit int) ([]RecentItem, error)

ListRecentByKind returns the most recent active documents for the given kind, ordered by occurred_at DESC NULLS LAST, then collected_at DESC. limit is already validated and capped by the caller.

func (*DocumentStore) ListUnembedded

func (s *DocumentStore) ListUnembedded(ctx context.Context, limit int) ([]*model.Document, error)

ListUnembedded returns up to limit active documents whose embedding column is NULL, ordered by collected_at ASC (oldest first) so backfill progresses forward in time.

Soft-deleted documents are excluded because they are never served in search results and re-embedding them would waste API quota.

func (*DocumentStore) ListUnsummarized

func (s *DocumentStore) ListUnsummarized(ctx context.Context, limit int) ([]*model.Document, error)

ListUnsummarized returns up to limit active documents whose title_summary column is NULL, ordered by collected_at ASC (oldest first) so backfill progresses forward in time.

Soft-deleted documents are excluded; there is no value in summarizing them.

func (*DocumentStore) ListWithoutEntities

func (s *DocumentStore) ListWithoutEntities(ctx context.Context, limit int) ([]*model.Document, error)

ListWithoutEntities returns up to limit active documents whose entities_processed_at column is NULL, ordered by collected_at ASC (oldest first) so that entity-extraction backfill progresses forward in time.

Once the EntityWorker attempts extraction for a document — whether or not any entities are found — it calls MarkEntitiesProcessed to set the column, preventing the document from being re-queued on subsequent ticks.

Soft-deleted documents are excluded — there is no value in extracting entities from documents that are not served in search results.

func (*DocumentStore) MarkDeleted

func (s *DocumentStore) MarkDeleted(ctx context.Context, sourceType model.SourceType, activeIDs []string) (int, error)

MarkDeleted marks documents as deleted for source IDs not present in activeIDs. Only documents with status 'active' are updated. Returns the number of rows updated.

Belt-and-suspenders: if activeIDs is empty, this function returns (0, nil) immediately without touching the database. An empty slice fed to the Postgres expression `source_id != ALL('{}')` is vacuously TRUE — it would delete every active document for the source type. The legitimate callers that intend a full wipe (if any ever exist) must use a dedicated, explicitly-named method rather than relying on an empty-slice side-effect.

func (*DocumentStore) MarkEntitiesProcessed

func (s *DocumentStore) MarkEntitiesProcessed(ctx context.Context, documentID uuid.UUID) error

MarkEntitiesProcessed sets entities_processed_at to now() for the given document. After this call the document will no longer be returned by ListWithoutEntities, preventing the EntityWorker from re-queuing it on every tick when entity extraction consistently returns zero results.

func (*DocumentStore) QueryBaselineStats

func (s *DocumentStore) QueryBaselineStats(ctx context.Context) (*BaselineStats, error)

QueryBaselineStats executes four independent queries and assembles BaselineStats. Each query is kept separate for readability and to avoid a single monstrous CTE.

func (*DocumentStore) RecordCollectionLog

func (s *DocumentStore) RecordCollectionLog(ctx context.Context, sourceType model.SourceType, started time.Time, count int, collErr error) error

RecordCollectionLog writes a collection event to the collection_log table.

func (*DocumentStore) Search

func (s *DocumentStore) Search(ctx context.Context, query model.SearchQuery) ([]*model.SearchResult, error)

Search performs hybrid search using full-text and, when an embedding is provided, vector cosine similarity. Results are combined via Reciprocal Rank Fusion (RRF).

func (*DocumentStore) SummaryCoverageRatio

func (s *DocumentStore) SummaryCoverageRatio(ctx context.Context) (float64, error)

SummaryCoverageRatio returns the fraction of active documents that have a summary_embedding (non-NULL). The result is cached for summaryCoverageTTL (60 s) to avoid a per-search COUNT(*) on large tables.

Used by hybridSearch to gate the SummaryVec signal (#63): when coverage is below model.SummaryVecCoverageThreshold() the weight is set to 0 so that un-summarised documents are not systematically demoted during backfill.

func (*DocumentStore) UpdateCollectorState

func (s *DocumentStore) UpdateCollectorState(ctx context.Context, instanceID string, src model.SourceType, lastCollectedAt time.Time) error

UpdateCollectorState upserts the watermark for (instance_id, source_type). Callers should only invoke this on a successful collection cycle so that failed runs are retried from the previous watermark on the next tick.

func (*DocumentStore) UpdateEmbedding

func (s *DocumentStore) UpdateEmbedding(ctx context.Context, doc *model.Document) error

UpdateEmbedding writes the given embedding vector for a single document identified by its primary key. Only the embedding column is touched so that other fields (title, content, collected_at …) remain unchanged.

func (*DocumentStore) UpdateSummary

func (s *DocumentStore) UpdateSummary(ctx context.Context, id uuid.UUID, titleSummary, bulletSummary string, summaryEmbedding []float32) error

UpdateSummary writes the LLM-generated summary fields for a single document identified by its primary key. Only title_summary, bullet_summary, and summary_embedding are touched; other fields remain unchanged.

summaryEmbedding may be nil when the embedder is disabled or failed — in that case the column is set to NULL, leaving the document out of summary-vector search until a subsequent run embeds it.

Idempotency guard: the UPDATE is a no-op when title_summary is already set (WHERE title_summary IS NULL). This prevents a racing concurrent instance from overwriting a completed summary with its own version (#64).

func (*DocumentStore) Upsert

func (s *DocumentStore) Upsert(ctx context.Context, doc *model.Document) error

Upsert inserts a document or updates it when (source_type, source_id) already exists. On conflict the status is reset to 'active' (handles re-appearance of previously deleted files).

Duplicate call-transcript guard: for source_type='call-transcript' only, a cheap pre-insert existence check is performed. When an active document with identical content but a DIFFERENT source_id already exists, the upsert is skipped and ErrDuplicateTranscript is returned (the caller may safely ignore or log it). A same-source_id re-upsert is NOT affected: the ON CONFLICT path handles it normally even when the content is identical.

type EntityStore

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

EntityStore provides persistence for named entities and their document links. It is backed by the entities and document_entities tables added in migration 017.

func NewEntityStore

func NewEntityStore(pg *Postgres) *EntityStore

NewEntityStore returns an EntityStore backed by the given Postgres instance.

func (*EntityStore) EntitiesForDocuments

func (s *EntityStore) EntitiesForDocuments(ctx context.Context, docIDs []uuid.UUID) (map[uuid.UUID][]model.Entity, error)

EntitiesForDocuments fetches the entities linked to the given document IDs. The result map is keyed by document UUID; missing entries mean no entities were extracted for that document. Returns an empty map (not nil) on success.

func (*EntityStore) LinkDocumentEntity

func (s *EntityStore) LinkDocumentEntity(ctx context.Context, documentID uuid.UUID, entityID int64) error

LinkDocumentEntity creates a join between a document and an entity. It is idempotent: conflicting rows are silently ignored via ON CONFLICT DO NOTHING.

func (*EntityStore) UpsertAndLinkEntities

func (s *EntityStore) UpsertAndLinkEntities(ctx context.Context, documentID uuid.UUID, entities []model.Entity) error

UpsertAndLinkEntities upserts each entity and links it to the given document in a single call. It is the primary entry-point used by the entity extraction worker. Failures for individual entities are accumulated and returned as a combined error so that partial success is still persisted.

func (*EntityStore) UpsertEntity

func (s *EntityStore) UpsertEntity(ctx context.Context, name string, entityType model.EntityType) (int64, error)

UpsertEntity inserts a canonical entity or returns the existing one when (normalized_name, type) already exists. The normalized_name is derived from the entity name: lower-cased and trimmed. Returns the entity ID.

type EvalMetricsRecord

type EvalMetricsRecord struct {
	ID     int64
	NDCG5  float64
	NDCG10 float64
	MRR10  float64
	Pairs  int
	RunAt  time.Time

	// Read-path (search) latency profiling (nullable — zero when not measured).
	// Added by migration 016.
	SearchLatencyP50Ms  float64
	SearchLatencyP95Ms  float64
	SearchLatencyMeanMs float64
}

EvalMetricsRecord represents a single eval run stored in the eval_metrics table.

type EvalMetricsStore

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

EvalMetricsStore persists and retrieves eval run metrics.

func NewEvalMetricsStore

func NewEvalMetricsStore(pg *Postgres) *EvalMetricsStore

NewEvalMetricsStore returns an EvalMetricsStore backed by the given Postgres instance.

func (*EvalMetricsStore) Latest

Latest returns the most recent eval metrics record. Returns nil, nil when the table is empty — this is not an error condition.

func (*EvalMetricsStore) List

func (s *EvalMetricsStore) List(ctx context.Context, limit int) ([]EvalMetricsRecord, error)

List returns the most recent eval metrics records ordered by run_at DESC. limit controls the maximum number of records returned; pass 0 to use the default of 20 and values above 100 are capped at 100.

func (*EvalMetricsStore) Save

Save inserts a new eval metrics record. The RunAt field is set by the database DEFAULT (NOW()) so callers do not need to populate it.

type EvalPair

type EvalPair struct {
	ID               int64          `json:"id"`
	Query            string         `json:"query"`
	RelevantDocIDs   []string       `json:"relevant_doc_ids"`
	IrrelevantDocIDs []string       `json:"irrelevant_doc_ids,omitempty"` // thumbs=-1 docs for this query
	Source           string         `json:"source"`                       // "feedback", "manual"
	CreatedAt        time.Time      `json:"created_at"`
	Metadata         map[string]any `json:"metadata,omitempty"`
}

EvalPair is a single (query, relevant_document) evaluation pair derived from positive feedback or explicit ratings.

type EvalStore

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

EvalStore derives evaluation pairs from feedback data.

func NewEvalStore

func NewEvalStore(pg *Postgres) *EvalStore

NewEvalStore returns an EvalStore backed by the given Postgres instance.

func (*EvalStore) BuildFromFeedback

func (s *EvalStore) BuildFromFeedback(ctx context.Context) ([]EvalPair, error)

BuildFromFeedback derives eval pairs from positive feedback rows, enriched with negative signals (thumbs=-1) and manual source pairs.

Positive pairs: queries where thumbs >= 1 and at least one document_id is present. Queries are grouped so that multiple positive votes are merged into a single EvalPair with all relevant document IDs collected.

Negative signals: for each query that has positive pairs, documents rated thumbs = -1 are added as IrrelevantDocIDs. These are used to compute FalsePositivePenalty in the eval pipeline.

Manual source: rows with source = 'manual' are always included regardless of thumbs value. This expands the eval pool beyond already-shown documents, addressing self-confirming bias.

Results are ordered by the earliest positive feedback creation time (DESC) and capped at 5 000 pairs to bound memory usage.

func (*EvalStore) ExportJSONL

func (s *EvalStore) ExportJSONL(ctx context.Context, w io.Writer) (int, error)

ExportJSONL writes eval pairs as newline-delimited JSON (JSONL) to w. It returns the number of pairs written and any write error. Each line is a self-contained JSON object that can be streamed directly to an HTTP response without buffering the entire result set in memory.

type ExtractionFailure

type ExtractionFailure struct {
	ID           int64
	SourceType   string
	SourceID     string
	FilePath     string
	ErrorMessage string
	Attempts     int
	NextRetryAt  time.Time
	DeadLetter   bool
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

ExtractionFailure represents a single row in the extraction_failures table.

type ExtractionFailureStore

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

ExtractionFailureStore provides persistence for extraction failure records.

func NewExtractionFailureStore

func NewExtractionFailureStore(pg *Postgres) *ExtractionFailureStore

NewExtractionFailureStore returns an ExtractionFailureStore backed by the given Postgres instance.

func (*ExtractionFailureStore) DueForRetry

func (s *ExtractionFailureStore) DueForRetry(ctx context.Context, limit int) ([]ExtractionFailure, error)

DueForRetry returns up to limit rows whose next_retry_at has elapsed and are not yet dead-lettered, ordered by next_retry_at ascending (oldest-first).

func (*ExtractionFailureStore) Record

Record inserts a new failure row, or increments attempts on an existing one.

Back-off and dead-letter logic is delegated to durable.ExtractionBackoff so that the policy can be unit-tested without a running Postgres instance. The SQL upsert now receives explicit nextRetryAt and deadLetter values computed in Go, keeping the database as a dumb store.

Back-off schedule (matches the previous inline SQL formula):

attempt 0 (first insert): +5 minutes
attempt n (ON CONFLICT):  +LEAST(60, 2^n) minutes

Dead-letter threshold: 10 attempts (i.e. currentAttempts+1 >= 10).

func (*ExtractionFailureStore) Resolve

func (s *ExtractionFailureStore) Resolve(ctx context.Context, sourceType, sourceID string) error

Resolve deletes the failure record for (sourceType, sourceID) after a successful re-extraction. A no-op when the record does not exist.

type Feedback

type Feedback struct {
	ID         int64
	Query      *string        // nullable — absent for direct doc/chunk rating
	DocumentID *string        // nullable FK → documents.id (UUID)
	ChunkID    *int64         // nullable FK → chunks.id
	Source     string         // "search" | "discord_bot" | "api"
	SessionID  *string        // optional conversation grouping
	UserID     *string        // opaque identifier (Discord user ID in bot context)
	Thumbs     int16          // -1, 0, +1
	Comment    *string        // optional free-text
	Metadata   map[string]any // arbitrary extra context
	CreatedAt  time.Time
}

Feedback represents one user feedback row in the feedback table.

type FeedbackSourceStats

type FeedbackSourceStats struct {
	Positive int64 `json:"positive"`
	Negative int64 `json:"negative"`
}

FeedbackSourceStats holds positive/negative counts for one source value.

type FeedbackStats

type FeedbackStats struct {
	BySource map[string]FeedbackSourceStats `json:"by_source"`
}

FeedbackStats holds aggregate thumbs counts grouped by source.

type FeedbackStore

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

FeedbackStore provides feedback persistence operations backed by Postgres.

func NewFeedbackStore

func NewFeedbackStore(pg *Postgres) *FeedbackStore

NewFeedbackStore returns a FeedbackStore backed by the given Postgres instance.

func (*FeedbackStore) ListRecent

func (s *FeedbackStore) ListRecent(ctx context.Context, limit int) ([]Feedback, error)

ListRecent returns the most recent feedback rows ordered by created_at DESC. Intended for eval-set construction (issue #18).

func (*FeedbackStore) Record

func (s *FeedbackStore) Record(ctx context.Context, f Feedback) (int64, error)

Record inserts a new feedback row and returns the generated ID.

func (*FeedbackStore) Stats

func (s *FeedbackStore) Stats(ctx context.Context) (FeedbackStats, error)

Stats returns aggregate thumbs counts grouped by source. Useful for monitoring dashboard and eval set quality signals.

func (*FeedbackStore) Upsert

func (s *FeedbackStore) Upsert(ctx context.Context, f Feedback) (int64, error)

Upsert replaces existing feedback for the same (user_id, session_id, source) tuple by deleting the prior rows and inserting a fresh one. This supports the thumbs-toggle pattern (e.g. Discord reaction add/remove).

When either user_id or session_id is nil the call falls through to Record, since there is no meaningful identity to de-duplicate on.

type Postgres

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

Postgres wraps a pgx connection pool with store operations.

func NewPostgres

func NewPostgres(ctx context.Context, databaseURL string) (*Postgres, error)

NewPostgres opens a pgx pool, registers pgvector types, and enables the pgvector extension. The caller must call Close when done.

func (*Postgres) Close

func (pg *Postgres) Close()

Close releases all pool connections.

func (*Postgres) Pool

func (pg *Postgres) Pool() *pgxpool.Pool

Pool returns the underlying pgx pool for use by store implementations.

func (*Postgres) RunMigrations

func (pg *Postgres) RunMigrations(ctx context.Context, migrationsDir string, embeddingDim int) error

RunMigrations executes all *.sql files inside the given directory in lexicographic order. Files already applied are safe to re-run because each migration is idempotent (CREATE TABLE IF NOT EXISTS, etc.).

embeddingDim is the configured vector dimension (from EMBEDDING_DIM env var, default 1536). When a migration file is named "011_configurable_embedding_dim.sql", RunMigrations acquires a dedicated connection, opens a transaction, and runs

SET LOCAL app.embedding_dim = <embeddingDim>

immediately before executing that file's SQL — all on the same connection and within the same transaction. SET LOCAL ensures the GUC is visible only to that transaction, which is exactly what migration 011 reads via current_setting(). Any other migration file is executed via the pool as before.

type RecentItem added in v0.19.0

type RecentItem struct {
	ID          uuid.UUID  `json:"id"`
	Title       string     `json:"title"`
	OccurredAt  *time.Time `json:"occurred_at"`
	CollectedAt time.Time  `json:"collected_at"`
}

RecentItem is a lightweight projection of a document used by the dashboard recent-items API. Large fields (content, embedding) are intentionally omitted.

type RecentKind added in v0.19.0

type RecentKind string

RecentKind identifies the dashboard card kind for recent-item queries.

const (
	// RecentKindSMS returns documents with source_type = 'sms'.
	RecentKindSMS RecentKind = "sms"

	// RecentKindCallRecording returns call-log documents that have an
	// audio_file entry in their metadata JSON (i.e. a recording was captured).
	RecentKindCallRecording RecentKind = "call-recording"

	// RecentKindVoiceMemo returns call-log documents whose metadata field
	// recording_type equals 'voice-memo'.
	RecentKindVoiceMemo RecentKind = "voice-memo"
)

type ReindexState

type ReindexState struct {
	ID                int64
	LastReindexAt     time.Time
	DocCountAtReindex int
	TriggerReason     string
}

ReindexState represents a single reindex event persisted in the reindex_state table.

type ReindexStateStore

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

ReindexStateStore persists and retrieves reindex events.

func NewReindexStateStore

func NewReindexStateStore(pg *Postgres) *ReindexStateStore

NewReindexStateStore returns a ReindexStateStore backed by the given Postgres instance.

func (*ReindexStateStore) Latest

func (s *ReindexStateStore) Latest(ctx context.Context) (*ReindexState, error)

Latest returns the most recent reindex event. Returns nil, nil when the table is empty — this is not an error condition.

func (*ReindexStateStore) Save

func (s *ReindexStateStore) Save(ctx context.Context, state ReindexState) error

Save inserts a new reindex event. The last_reindex_at field is set by the database DEFAULT (NOW()) so callers do not need to populate it.

type UnembeddedChunk added in v0.20.0

type UnembeddedChunk struct {
	ID      int64
	Content string
}

UnembeddedChunk is a minimal chunk record used for embedding backfill. Only the fields necessary for embedding (ID and Content) are included.

Jump to

Keyboard shortcuts

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