store

package
v0.25.4 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: MIT Imports: 26 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

View Source
const (
	// WeightsStatusProposed is a candidate that was measured but not promoted.
	// Refused candidates are recorded too — otherwise there is no way to ask
	// later why the weights did not change.
	WeightsStatusProposed = "proposed"
	// WeightsStatusActive is the live configuration. At most one row may hold
	// this status; a partial unique index enforces it.
	WeightsStatusActive = "active"
	// WeightsStatusRolledBack is a configuration that was live and was undone.
	WeightsStatusRolledBack = "rolled_back"
	// WeightsStatusSuperseded is a configuration that was live and was replaced
	// by a newer promotion. Rollback restores the most recent of these.
	WeightsStatusSuperseded = "superseded"
)

Lifecycle of a candidate in search_weights_history.

proposed ──promote──> active ──promote(other)──> superseded ──rollback──> active
                         └────────rollback────────> rolled_back
View Source
const SourceAskEvidence = "ask_evidence"

SourceAskEvidence is the feedback.source value reserved for per-evidence votes cast on /ask answer cards.

It is a constant rather than a caller-supplied string because the uniqueness index that makes UpsertEvidence idempotent is PARTIAL on this exact value (migrations/025_feedback_evidence.sql). A caller passing anything else would silently fall outside the index and start inserting duplicate labels.

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.

View Source
var ErrWeightsRecordNotFound = errors.New("weights history: record not found")

ErrWeightsRecordNotFound is returned when a promotion targets a row that does not exist.

Functions

func DuplicateArrivalGuardHits added in v0.23.0

func DuplicateArrivalGuardHits() int64

DuplicateArrivalGuardHits returns the number of times checkDuplicateArrival has flagged a possible cross-source duplicate since process start.

func SourceTypeGuardStats added in v0.23.0

func SourceTypeGuardStats() (containerHits, deprecatedHits, unknownHits int64)

SourceTypeGuardStats returns the number of times checkSourceTypeGuard has flagged a container source_type, a deprecated source_type, or an unrecognized source_type, respectively, since process start. Exported for tests and for any future /metrics or ops endpoint that wants to surface these counters.

Types

type ActionFilter added in v0.23.0

type ActionFilter struct {
	// Kinds restricts to the given action kinds. Empty means all kinds.
	Kinds []model.ActionKind
	// Counterpart is a case-insensitive substring match against the joined
	// entity's normalized_name. Empty disables the filter.
	Counterpart string
	// DueBefore keeps only actions with a non-NULL due_at at or before it.
	DueBefore *time.Time
	// MinConfidence is an inclusive lower bound on actions.confidence (0–1).
	// Zero (the default) applies no bound — production's confidence
	// distribution is not yet known, and a non-zero default could silently
	// hide every LLM-detected action.
	MinConfidence float64
	// IncludeArchived disables the 90-day observed_at window.
	IncludeArchived bool
	// Sort is "recent", "due", or "confidence". Anything else falls back to
	// "recent".
	Sort string
	// Limit is clamped to [1, 200]; <= 0 means the 50-row default.
	Limit int
}

ActionFilter narrows ListOpenActions. The zero value is valid and means "open actions observed in the last 90 days, newest-detected first, at most 50".

type ActionListItem added in v0.23.0

type ActionListItem struct {
	model.Action
	State           model.ActionState
	CounterpartName string
}

ActionListItem is one row of ListOpenActions: the action itself plus the two values that only exist after the joins (its effective state and a display name for the counterpart entity).

type ActionQueryStore added in v0.23.0

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

ActionQueryStore holds the read path and the user-driven state transition for actions. It is deliberately separate from ActionStore (the extraction worker's write path) so the two can be edited independently.

func NewActionQueryStore added in v0.23.0

func NewActionQueryStore(pg *Postgres) *ActionQueryStore

NewActionQueryStore returns an ActionQueryStore backed by pg.

func (*ActionQueryStore) ListOpenActions added in v0.23.0

func (s *ActionQueryStore) ListOpenActions(ctx context.Context, f ActionFilter) ([]ActionListItem, error)

ListOpenActions returns the open actions matching f.

"Open" is COALESCE(action_status.state, 'open'): the join to action_status is a LEFT JOIN because an action row can exist without a status row (the extraction worker writes the two in separate statements), and an INNER JOIN would make such an action permanently invisible. The same reasoning applies to the entities join — counterpart_entity_id is nullable.

When f.Kinds is empty, awaitingMyReplyKind is excluded regardless of the migration having already flipped its rows to action_status.state='ignored' — this is a second, independent line of defence, not a duplicate of that state filter: it also covers any row a future caller resurrects with state left at 'open' (e.g. a stray EnsureOpenStatus call this migration cannot see in advance). An explicit f.Kinds request for it is still honoured — a caller that names it on purpose (auditing, admin tooling) is not second-guessed.

func (*ActionQueryStore) SetActionState added in v0.23.0

func (s *ActionQueryStore) SetActionState(ctx context.Context, identityKey string, state model.ActionState, note string) (bool, error)

SetActionState records the user's decision about identityKey.

It is idempotent in the strict sense: replaying the same request leaves the row unchanged, including resolved_at. The obvious "DO UPDATE SET resolved_at = now()" is not — it rewrites the timestamp on every duplicate delivery, and resolved_at is the only column that can isolate a batch of actions resolved during a given incident window. resolved_at therefore advances only when the state actually changes.

The write targets action_status.identity_key, never actions.id: identity_key is the handle that survives re-extraction, which is what makes a user's done/ignored decision outlive the row that prompted it (spec §5.5).

found=false with a nil error means "no such action". That case arrives as a foreign-key violation, which would otherwise reach the user as a 500.

type ActionStore added in v0.23.0

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

ActionStore provides persistence for actions + action_status (migration 022).

func NewActionStore added in v0.23.0

func NewActionStore(pg *Postgres) *ActionStore

NewActionStore returns an ActionStore backed by the given Postgres instance.

func (*ActionStore) EnsureOpenStatus added in v0.23.0

func (s *ActionStore) EnsureOpenStatus(ctx context.Context, identityKey string) error

EnsureOpenStatus inserts an 'open' action_status row for identityKey if none exists yet. ON CONFLICT DO NOTHING is the entire point (spec §5.5): a user's prior 'done'/'ignored' decision must survive re-extraction — this method is only ever called AFTER UpsertAction succeeds for the same identityKey (satisfying the FK), and never overwrites an existing state.

func (*ActionStore) UpsertAction added in v0.23.0

func (s *ActionStore) UpsertAction(ctx context.Context, a model.Action) error

UpsertAction inserts or updates an action row keyed by identity_key (spec §5.5/§7.2). On conflict, detected_by is merged rather than overwritten: a structural candidate followed later by an LLM candidate for the SAME identity_key (or vice versa) becomes "both"; the same source re-asserting the same identity_key is a no-op on detected_by. Every other field is refreshed from the latest observation (EXCLUDED) — this is NOT a RETURNING clause, so referencing EXCLUDED here is safe (this project's feedback_postgres_returning_excluded lesson is specifically about RETURNING, not SET).

Caller MUST call this before EnsureOpenStatus for the same identity_key — action_status.identity_key has an FK to actions.identity_key.

counterpart_entity_id is resolved here rather than by the caller: the structural signal worker holds no entity store, so before this it wrote every awaiting_my_reply action with a NULL counterpart and the /actions screen had no name to render. A caller states the label (model.Action.CounterpartName) and the store canonicalises it through the same (normalized_name, type) dedup every other entity goes through. On conflict the column is COALESCEd, never overwritten: a re-assertion that carries no label must not blank a resolved counterpart, and — the reason the existing NULL rows repair themselves — a row written before this change picks the id up on the worker's next tick.

type AskCitationVerification added in v0.23.0

type AskCitationVerification struct {
	CitationStatus    string   `json:"citation_status"`
	CitedIDs          []string `json:"cited_ids"`
	UnknownIDs        []string `json:"unknown_ids"`
	MalformedLinks    int      `json:"malformed_links"`
	InferredCitedIDs  []string `json:"inferred_cited_ids"`
	PromptEvidenceIDs []string `json:"prompt_evidence_ids"`
	ClaimSupport      string   `json:"claim_support"`
}

AskCitationVerification mirrors internal/api.askVerificationPayload's wire shape exactly (all ID fields are already the string form, matching that package's newAskVerificationPayload — see AskSource's doc comment above for why the shape is duplicated here rather than imported: store must not depend on api). Keep field names/JSON tags in sync if either changes.

This is migration 039's citation_verification JSONB column (issue #268): the deterministic citation-validation result for one turn's generated answer, persisted so (a) a page reload can show the same verdict without re-deriving it, and (b) recentAskHistory (ask_history.go) can filter out "invalid"/"unverified" turns before replaying them into a later prompt without re-parsing stored answer text.

type AskSession added in v0.23.0

type AskSession struct {
	ID             uuid.UUID
	ConversationID uuid.UUID
	TurnIndex      int
	Question       string
	Answer         string
	FinishReason   string // "stop" | "error" | "no_evidence"
	Sources        []AskSource
	// Verification is migration 039's citation_verification column: nil for
	// every row written before that migration, and for rows where
	// synthesize (internal/api) never produced a report at all (see
	// AskCitationVerification's doc comment) — never fabricated.
	Verification *AskCitationVerification
	CreatedAt    time.Time
}

AskSession represents one row in ask_sessions (migration 024): a single turn (one question/answer exchange) within a multi-turn conversation, persisted so a page refresh does not lose the answer. TurnIndex is 0-based and unique within ConversationID (see migration 024's UNIQUE constraint). There is deliberately no separate "conversations" table — the first turn's Question doubles as the conversation's title (YAGNI; add one later if conversation-level metadata becomes necessary).

type AskSessionStore added in v0.23.0

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

AskSessionStore provides persistence for ask_sessions (migration 024).

func NewAskSessionStore added in v0.23.0

func NewAskSessionStore(pg *Postgres) *AskSessionStore

NewAskSessionStore returns an AskSessionStore backed by the given Postgres instance.

func (*AskSessionStore) Get added in v0.23.0

func (s *AskSessionStore) Get(ctx context.Context, id uuid.UUID) (*AskSession, error)

Get retrieves a single ask session turn by id. Returns nil, nil when no row matches — this is not an error condition (mirrors EvalMetricsStore.Latest), leaving 404-vs-500 handling to the caller.

func (*AskSessionStore) Insert added in v0.23.0

func (s *AskSessionStore) Insert(ctx context.Context, session AskSession) (AskSession, error)

Insert records one conversation turn and returns the persisted row with id/created_at filled in from the database (id is DB-generated via gen_random_uuid() when session.ID is uuid.Nil; a caller-supplied ID is honored otherwise). The caller is responsible for supplying ConversationID and TurnIndex — Insert does not compute the next turn index itself, since the caller (the /ask handler) already knows the conversation's current length from the request context.

The UNIQUE(conversation_id, turn_index) constraint (migration 024) surfaces as a plain error here if the caller races two writers for the same turn; it is not treated as a special "ok, already inserted" case because, unlike UpsertAction/UpsertEntityRelations, a turn collision means a real logic error upstream (two answers claiming the same turn), not a harmless re-observation.

Sources defaults to an empty slice (never nil) before marshaling so the stored JSONB is always a valid array, matching the column's NOT NULL DEFAULT '[]'::jsonb.

session.Verification, unlike Sources, is allowed to stay nil — migration 039's citation_verification column is JSONB NULL (not NOT NULL DEFAULT), because unlike "which documents backed this answer" (always knowable), "was this answer's citations checked" genuinely has no value for a no_evidence turn or a pre-migration-039 row, and NULL is the honest way to say that (mirrors AskSource.OccurredAt's pre-#218-row reasoning above). A nil Verification is passed through as a Go nil interface{} parameter, which pgx encodes as SQL NULL regardless of the $8::jsonb cast.

func (*AskSessionStore) ListConversationTurns added in v0.23.0

func (s *AskSessionStore) ListConversationTurns(ctx context.Context, conversationID uuid.UUID) ([]AskSession, error)

ListConversationTurns returns every turn of one conversation ordered by turn_index ASC — used both to rebuild multi-turn LLM context (question 1, answer 1, question 2, answer 2, ...) and to restore the /ask screen after a page refresh.

func (*AskSessionStore) ListRecentConversations added in v0.23.0

func (s *AskSessionStore) ListRecentConversations(ctx context.Context, limit int) ([]AskSession, error)

ListRecentConversations returns the latest turn of each conversation, ordered by that turn's created_at DESC — the /ask screen's conversation list view (one row per conversation, most recently active first).

Implemented with DISTINCT ON (conversation_id) rather than a ROW_NUMBER() window function: verified via EXPLAIN ANALYZE on real Postgres (Mac mini prod, rolled back afterward) against migration 024's indexes, with synthetic data (500 conversations x 10 turns = 5,003 rows). Both plans do the same Seq Scan + Sort on (conversation_id, created_at DESC) underneath; DISTINCT ON's planner cost was lower (475.12..475.24 vs 596.61..596.67) because Unique is a single pass over the sorted rows with no per-row window-function bookkeeping, while WindowAgg materializes a rn column before the outer filter discards all but rn=1. At this data size actual execution time was statistically indistinguishable (1.96ms DISTINCT ON vs 1.87ms window — within noise); DISTINCT ON was chosen for its lower, more predictable cost estimate as conversation volume grows, not for a measured speed win at this scale.

type AskSource added in v0.23.0

type AskSource struct {
	ID         string     `json:"id"`
	Title      string     `json:"title"`
	SourceType string     `json:"source_type"`
	Score      float64    `json:"score"`
	OccurredAt *time.Time `json:"occurred_at"`
}

AskSource mirrors internal/api.AskSourceItem's wire shape (id, title, source_type, score, occurred_at) — that struct lives in internal/api, which this package must not depend on (store is a lower layer than api), so the shape is duplicated here rather than imported. Keep field names/JSON tags in sync with internal/api/ask.go's AskSourceItem if either changes.

OccurredAt was added after ask_sessions rows already existed (issue #218); no migration was needed because this struct is marshaled straight into the sources JSONB column (migration 024) rather than its own SQL columns. Rows written before this change have no "occurred_at" key at all, so json.Unmarshal leaves OccurredAt as its zero value, nil — the same value a row written after this change uses for "no known event time". A pre-existing row therefore silently reads back as "no event time" rather than erroring, which is the correct degradation: no backfill can recover a value that was never captured.

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 CalendarAutomationStore added in v0.23.0

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

func NewCalendarAutomationStore added in v0.23.0

func NewCalendarAutomationStore(pg *Postgres) *CalendarAutomationStore

func (*CalendarAutomationStore) AcquireLock added in v0.23.0

func (s *CalendarAutomationStore) AcquireLock(ctx context.Context) (func(), bool, error)

A session lock needs a dedicated connection. If unlocking fails, destroy that connection rather than returning a possibly locked session to the pool.

func (*CalendarAutomationStore) Finish added in v0.23.0

func (s *CalendarAutomationStore) Finish(ctx context.Context, id uuid.UUID, status, eventID string) error

func (*CalendarAutomationStore) Initialize added in v0.23.0

func (s *CalendarAutomationStore) Initialize(ctx context.Context) (time.Time, error)

func (*CalendarAutomationStore) ListJobs added in v0.23.0

func (s *CalendarAutomationStore) ListJobs(ctx context.Context, cutoff time.Time, limit int) ([]calendarauto.Job, error)

func (*CalendarAutomationStore) Retry added in v0.23.0

func (s *CalendarAutomationStore) Retry(ctx context.Context, id uuid.UUID, reason string) error

Only fixed stage codes are retained; upstream errors may contain personal data.

func (*CalendarAutomationStore) SaveDecision added in v0.23.0

func (*CalendarAutomationStore) SaveEvent added in v0.23.0

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
	// Version 은 이 벡터를 만든 설정 식별자다(internal/search.EmbeddingVersion).
	// 빈 문자열이면 chunks.embedding_version 을 건드리지 않는다 — 버전 배선이
	// 없는 호출자의 동작을 그대로 두기 위해서다. 마이그레이션 037 참고.
	Version string
}

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

	// DocumentOccurredAt / DocumentCollectedAt are the parent document's event
	// and ingest times. They are selected here — rather than left to a second
	// fetch — because internal/search orders a merged result set in Go, and a
	// document reachable ONLY through a chunk lane never passes through the
	// document store's ORDER BY.
	//
	// Without them such a document has no usable timestamp at all, and
	// search.recencyKey ranks it LAST in both directions. For a forward-looking
	// window that is the exact inversion of what Sort="recent" means: the most
	// imminent entry is shown as the furthest away (#215).
	//
	// DocumentOccurredAt stays a pointer, and NULL stays nil: "no event-time
	// concept" and "the epoch" are different facts, and the COALESCE onto
	// collected_at belongs to the ordering rule, not to this row.
	DocumentOccurredAt  *time.Time
	DocumentCollectedAt time.Time

	// DocumentMetadata is the parent document's metadata jsonb, decoded to a
	// map. Selected for the same reason as DocumentOccurredAt above: a
	// document reachable ONLY through a chunk lane never passes through
	// hybridSearch's WHERE predicates, so internal/search's
	// applyRetentionExclusion and applyLowRetentionPenalty have nothing to
	// read unless the chunk row carries it directly.
	// nil (not an empty map) when the source column was NULL or failed to
	// decode — model.Document.RetentionTag treats nil the same as "no tag".
	DocumentMetadata map[string]any
}

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) CountChunksNeedingEmbedding added in v0.23.0

func (s *ChunkStore) CountChunksNeedingEmbedding(ctx context.Context, currentVersion string) (int, error)

CountChunksNeedingEmbedding 은 재임베딩 대상 청크 수를 센다. 진행 상황 로그용이며 검색 경로에서는 호출하지 않는다.

func (*ChunkStore) FetchSparseContextCandidates added in v0.24.0

func (s *ChunkStore) FetchSparseContextCandidates(ctx context.Context, version string, sweep bool, afterChunkID int64, batchSize int) ([]SparseContextCandidate, error)

FetchSparseContextCandidates returns up to batchSize chunks that still need a chunk_sparse_context row for version, ordered by c.id, each joined to its parent document's header-relevant fields and current fingerprint. The caller (internal/sparsectx) builds sparse_text from these via internal/chunkctx.BuildSparseText and writes them back with UpsertSparseContextBatch — in a SEPARATE call, deliberately: building sparse_text needs no database access, and keeping it out of this method keeps store free of internal/chunkctx (search/store -> chunkctx is fine; this file just does not need to import it).

"Still needs a row" is an anti-join against chunk_sparse_context, NOT a c.id > checkpoint filter (#270 deep-verify HIGH): a chunk whose INSERT commits with a LOWER id than one already scanned by an earlier batch — a real race, since chunks.id (BIGSERIAL) is assigned in statement-call order, not commit order, so two concurrent inserters can commit out-of-order — must still be found by the NEXT call. A checkpoint (`WHERE c.id > $checkpoint`) can permanently skip that chunk once the checkpoint has advanced past its id; the anti-join cannot, because it asks "does chunk_sparse_context already have what I need for THIS chunk", never "have I already looked past this id".

  • sweep=false (a plain pass): a chunk qualifies if it has NO row at all for version — the common case, picking up newly chunked documents. A chunk whose row exists but has gone stale (title/metadata edit) is NOT re-queued here; SearchSparseContextFiltered already falls back to raw content matching for it in the meantime (chunk_sparse_search.go).
  • sweep=true: a chunk also qualifies if its row's fingerprint no longer matches the document's CURRENT fingerprint (chunkSparseFingerprintSQL, evaluated fresh here) — i.e. it exists but is stale. This is how --sweep "catches up" documents edited since the last full pass, without needing to re-verify every already-fresh row on every call.

This makes the method naturally idempotent and safe to call repeatedly with no coordination: rows already written (and still fresh, for the sweep=false case) simply stop matching the anti-join and are never returned again — resumability falls out of that property for free, with no checkpoint read required before the first call of a pass.

afterChunkID is an OPTIONAL pagination hint (`AND c.id > afterChunkID`), NOT a correctness mechanism — pass 0 to consider every chunk. It exists for exactly one caller: internal/sparsectx.Run's --dry-run path, which never writes anything, so nothing else can advance the anti-join between its batches; Run tracks a local, in-memory cursor there purely to page through a read-only preview. The real (writing) path in Run always passes 0 — using a non-zero afterChunkID there would reintroduce exactly the skip bug the anti-join fixes (#270 deep-verify HIGH): a chunk whose commit lands, out of id order, behind a cursor a PRIOR real batch already advanced past would never be looked at again. A dry-run "skipping" such a chunk in its preview has no such consequence — it writes nothing, so the very next (real or dry-run) invocation recomputes candidates from scratch via the anti-join with a fresh cursor of its own.

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) ListByDocuments added in v0.25.0

func (s *ChunkStore) ListByDocuments(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID][]Chunk, error)

ListByDocuments 는 여러 문서의 청크를 한 번의 왕복으로 읽는다. 반환 컬럼과 문서 내 정렬(chunk_index 오름차순)은 ListByDocument 와 같다 — 리랭크 입력 선택(search.bestChunkText)이 동점일 때 인덱스가 작은 청크를 고르는 규칙이 이 순서에 기대므로, 두 경로의 순서가 달라지면 같은 질의의 순위가 바뀐다.

청크가 하나도 없는 문서는 맵에 키 자체가 없다(빈 슬라이스로 채우지 않는다). ids 가 비어 있으면 DB 를 건드리지 않고 빈 맵을 돌려준다. 중복 ID 는 ANY 가 알아서 한 번만 매칭하므로 호출자가 미리 걸러 둘 필요는 없다.

func (*ChunkStore) ListChunksNeedingEmbedding added in v0.23.0

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

ListChunksNeedingEmbedding 은 "임베딩을 (다시) 만들어야 하는" 청크를 최대 limit 건 돌려준다. 대상은 두 부류다:

  1. embedding IS NULL — 아직 임베딩되지 않은 청크.
  2. embedding_version 이 currentVersion 과 다른 청크 — 다른 모델/차원/입력 구성으로 만들어진 옛 벡터. NULL(마이그레이션 037 이전 레거시, 즉 문맥 헤더 없이 청크 본문만 임베딩한 벡터)도 여기 포함된다.

currentVersion 이 빈 문자열이면 2번 조건을 적용하지 않는다 — 버전 배선이 없거나 재임베딩이 꺼진 배포에서 기존 동작을 그대로 두기 위한 기본값이다.

잠금·정렬 규약은 ListUnembeddedChunks 문서 주석과 동일하다 (id ASC + FOR UPDATE OF c SKIP LOCKED).

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 id ASC (primary key order) so backfill progresses in a stable direction that matches the lock-acquisition order used by updateEmbeddingsBatch (#157).

FOR UPDATE SKIP LOCKED: rows that are currently locked by another writer (e.g. the persistChunks → embedChunks path racing on the same chunks) are skipped rather than waited on. Skipped rows will be picked up by the next backfill cycle, which is correct because backfill runs repeatedly. This eliminates the primary source of 40P01 deadlock cycles: the backfill reader no longer queues behind the inline writer on the same row locks.

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) ResetSparseBackfillCheckpoint added in v0.24.0

func (s *ChunkStore) ResetSparseBackfillCheckpoint(ctx context.Context, version string) error

ResetSparseBackfillCheckpoint restarts version's checkpoint marker at 0. --sweep (cmd/sparsectx) no longer needs this to force a full re-scan — FetchSparseContextCandidates(ctx, version, sweep=true, ...) already re-examines stale rows regardless of this value — kept only so the informational checkpoint does not read as "already past everything" after an operator explicitly asks for a sweep.

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) SearchFTSFiltered added in v0.23.0

func (s *ChunkStore) SearchFTSFiltered(ctx context.Context, filter model.SearchQuery, limit int) ([]ChunkSearchResult, error)

SearchFTSFiltered applies document eligibility before the chunk candidate LIMIT.

func (*ChunkStore) SearchSparseContextFiltered added in v0.24.0

func (s *ChunkStore) SearchSparseContextFiltered(ctx context.Context, filter model.SearchQuery, limit int, version string) ([]ChunkSearchResult, error)

SearchSparseContextFiltered is the fuse_ctx lane's SQL (#270 phase B, SEARCH_CHUNK_SPARSE=fuse_ctx). It reads chunk_sparse_context (migration 040) for a specific context_version, and — for chunks that have no FRESH row there — falls back to raw chunk content, the exact same predicate SearchFTSFiltered above uses. "Fresh" means chunk_sparse_context.fingerprint still equals the document's CURRENT fingerprint (chunkSparseFingerprintSQL, evaluated fresh on d in this query) — a title rename, a metadata merge, or a PII-redaction rewrite invalidates the fingerprint immediately, so a stale (pre-edit) header can never be the thing that matches a query; the chunk just falls back to its own raw content until the backfill worker recomputes it.

It ALWAYS returns c.content (never sparse_text) — sparse_text exists only to be matched against, exactly like SearchFTSFiltered's use of content_tsv/content.

filters applies the SAME document eligibility (source/window/retention) chunkEligibilitySQL already defines for every other chunk lane, applied identically inside BOTH branches below (both alias documents as `d`).

LIMIT is applied INSIDE each CTE (#270 deep-verify MEDIUM), not once on the UNION ALL of both — fresh.rank (over sparse_tsv, header+body) and raw.rank (over content_tsv, body only) come from two different tsvector populations and are not calibrated against each other; a raw-content lane with many high-frequency matches can outnumber and outrank every fresh match, and a single post-union LIMIT would then drop fresh rows entirely — even though a fresh match (a name findable only via the header) is exactly the result this lane exists to surface. Limiting each branch independently first guarantees up to `limit` of EACH kind survive into the combined result; the caller (fuseChunkSparseCtx, internal/search/chunk_sparse_lane.go) already over-fetches (limit*3) and does its own per-document aggregation/truncation in Go, so returning up to 2*limit rows here (rather than a single hard cap) is intentional, not a leak.

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) SearchVectorFiltered added in v0.23.0

func (s *ChunkStore) SearchVectorFiltered(ctx context.Context, filter model.SearchQuery, limit int) ([]ChunkSearchResult, error)

SearchVectorFiltered applies document eligibility before the ANN candidate LIMIT.

func (*ChunkStore) SparseBackfillCheckpoint added in v0.24.0

func (s *ChunkStore) SparseBackfillCheckpoint(ctx context.Context, version string) (int64, error)

SparseBackfillCheckpoint returns the last chunk_id processed for version, or 0 if no pass has ever run (or completed a batch) for it. Informational only (see UpsertSparseContextBatch's doc comment) — internal/sparsectx.Run no longer reads this before deciding what to fetch next; FetchSparseContextCandidates' anti-join answers that from the data directly. Exposed for operators who want to check backfill progress.

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.

func (*ChunkStore) UpsertSparseContextBatch added in v0.24.0

func (s *ChunkStore) UpsertSparseContextBatch(ctx context.Context, version string, rows []SparseContextRow, checkpoint int64) (written int64, err error)

UpsertSparseContextBatch writes rows for context_version in ONE transaction and records the batch's highest chunk_id in chunk_sparse_backfill_state in the SAME transaction, purely as an observability/progress marker for operators (e.g. "how far has any pass ever written up to") — correctness no longer depends on this value. FetchSparseContextCandidates' anti-join (chunk_sparse_context.go) decides what still needs work from the data itself, not from this checkpoint, so a process killed mid-batch (leaving the checkpoint behind, ahead of, or exactly at what committed) can never cause the NEXT call to skip a chunk.

The upsert is idempotent by design: ON CONFLICT only writes when the fingerprint or sparse_text actually differs from what is already stored, so re-running a batch whose documents have not changed reports 0 rows written (see the WHERE clause below) even though the checkpoint UPDATE still runs.

checkpoint is the highest chunk_id in rows — the caller (internal/sparsectx) is responsible for passing candidates in ascending c.id order (FetchSparseContextCandidates already returns them that way).

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 DocumentFreshnessProvider added in v0.21.0

type DocumentFreshnessProvider interface {
	DocumentFreshness(ctx context.Context) ([]SourceDocumentFreshness, error)
}

DocumentFreshnessProvider is the interface implemented by DocumentStore to expose per-source document freshness data. Defined separately from CollectionStatusReader so the FreshnessChecker can be tested with a minimal mock.

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) AttachTranscript added in v0.23.0

func (s *DocumentStore) AttachTranscript(ctx context.Context, doc *model.Document) (contentChanged bool, err error)

AttachTranscript merges a whisper transcript into the call document at (doc.SourceType, doc.SourceID) — normally the call-log-formula SourceID computed by internal/collector/whisper.go's callLogMergeSourceID, so the transcript lands on the SAME document ingest_recording.go created rather than a second, unlinked one (model.SourceCall's doc comment: "통화 1건 = 문서 1건").

Unlike Upsert/UpsertTracked, on conflict this method:

  • REPLACES content and embedding — the transcript supersedes the short call-log summary as the document's substantive content.
  • MERGES metadata via `documents.metadata || EXCLUDED.metadata` rather than replacing it wholesale: doc.Metadata is treated as a PATCH (transcription, transcript_source_id, model, language, diarization, speaker_count, ...), so call-log-only keys the transcript never knows about (contact_name/direction/duration_seconds from smsmap.MapCall, any later retention tag) survive the merge. On key collision the patch's value wins (jsonb `||` is right-biased). This full merge is safe here specifically because doc.Metadata is always a small, deliberate patch — it is NOT the same shape as Upsert/UpsertTracked's merge (upsertMetadataMergeSQL), whose incoming metadata is the collector's FULL replacement snapshot; a full `||` merge there would leave every collector-owned key the collector no longer reports (a removed label, a corrected sender) stuck at its stale value forever, so those two protect only the classification-owned key set instead of merging the whole object.
  • Does NOT touch title on conflict — the call-log title ("incoming 통화 상대") stays more useful than the transcript's raw filename-stem title. collected_at IS still refreshed to EXCLUDED, matching Upsert's "last time this document was touched" semantics.
  • COALESCEs occurred_at onto the EXISTING value first, not the incoming one — the call-log's dateMs-derived timestamp is authoritative; WhisperCollector's filename-parsed occurredAt only matters for the INSERT branch below (no existing call document to merge into).

When no document exists yet at (source_type, source_id) — e.g. a recording was transcribed before its call-log document was ever created — this INSERTs a new one using doc's own Title/OccurredAt/Metadata, identical in shape to what Upsert would have produced for a standalone transcript.

The same call-content dedup guard as Upsert/UpsertTracked applies (issue #134, see callDupCheckQuery's doc comment): if an active call document with byte-identical content already exists under a DIFFERENT source_id, this returns (false, ErrDuplicateTranscript) without writing — this is the guard that protects against the SAME audio being merged under two different SourceIDs (e.g. a duplicate or renamed recording file).

Returns contentChanged exactly like UpsertTracked, for callers (the scheduler) that skip chunk/embedding regeneration when content did not actually change — rare here (a successful transcription produces new content by definition), but it keeps a re-run against the same audio idempotent rather than repeatedly re-chunking.

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) CountDocumentsNeedingEmbedding added in v0.23.0

func (s *DocumentStore) CountDocumentsNeedingEmbedding(ctx context.Context, currentVersion string) (int, error)

CountDocumentsNeedingEmbedding 은 재임베딩 대상 활성 문서 수를 센다. 진행 상황 로그용이며, 검색 경로에서는 호출하지 않는다.

func (*DocumentStore) CountPendingTranscription added in v0.23.0

func (s *DocumentStore) CountPendingTranscription(ctx context.Context) (int, error)

CountPendingTranscription returns the number of active call documents (source_type='call') whose metadata.transcription is still "pending" — i.e. a recording was captured (ingest_recording.go) but WhisperCollector has not yet merged the transcript in via AttachTranscript. Surfaced on GET /api/v1/stats so a stuck whisper pipeline (offline server, exhausted disk, etc.) is visible without querying the database directly.

func (*DocumentStore) DocumentFreshness added in v0.21.0

func (s *DocumentStore) DocumentFreshness(ctx context.Context) ([]SourceDocumentFreshness, error)

DocumentFreshness returns per-source-type MAX(created_at) and active document count from the documents table. Only active (non-deleted) documents are considered, using the same status='active' filter as CountActiveDocuments.

Results are ordered by source_type ASC. Sources with zero active documents are not included (they have no rows to aggregate).

This is used by FreshnessChecker to detect silent push-ingest failures that do not write collection_log rows (e.g. SMS via Android push app / /ingest).

func (*DocumentStore) FilterIDsByOccurredRange added in v0.23.0

func (s *DocumentStore) FilterIDsByOccurredRange(ctx context.Context, ids []uuid.UUID, from, to *time.Time) (map[uuid.UUID]struct{}, error)

FilterIDsByOccurredRange returns the subset of ids whose documents.occurred_at falls inside the half-open window [from, to). Rows with a NULL occurred_at never survive a window — the SQL comparison gives that for free, and it is the same rule every retrieval lane applies.

This exists so that the search service's chunk lanes can honour an event-time window. Chunk rows carry no occurred_at, so before this the only safe behaviour was to switch those lanes off whenever a window was set, which deleted chunk-level recall from every temporal query. Verifying the candidate IDs against the documents table costs one primary-key lookup per windowed request (at most `limit` ids after per-document deduplication) and keeps both properties: chunk recall and a window the result provably satisfies.

An empty ids slice short-circuits without touching the database.

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) HasOutboundTo added in v0.23.0

func (s *DocumentStore) HasOutboundTo(ctx context.Context, sender string) (bool, error)

HasOutboundTo reports whether an active outbound SMS to sender exists — the SenderLookup dependency of internal/classify.Evaluator's SMS PersonSignal check (spec: "발신 010 대역이면서 같은 sender에 direction=outbound 문서 존재"). sender is matched against both the "sender" and "number" metadata keys since collectors have historically used either.

func (*DocumentStore) IncrementClassificationAttempts added in v0.23.0

func (s *DocumentStore) IncrementClassificationAttempts(ctx context.Context, documentID uuid.UUID, attempts int) error

IncrementClassificationAttempts records a failed classification attempt (Jev call error or unusable answer) by setting classifier_attempts to attempts. Once attempts reaches 3, ListUnclassified/ListLegacyForRecheck's classifier_attempts < 3 predicate stops returning the document, mirroring MarkExtractionAttemptFailed's 3-attempt cap in document.go.

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) ListDocumentsNeedingEmbedding added in v0.23.0

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

ListDocumentsNeedingEmbedding 은 "임베딩을 (다시) 만들어야 하는" 활성 문서를 최대 limit 건 돌려준다. 대상은 두 부류다:

  1. embedding IS NULL — 아직 임베딩되지 않은 문서(ListUnembedded 와 동일).
  2. embedding_version 이 currentVersion 과 다른 문서 — 다른 모델/차원/입력 구성으로 만들어진 옛 벡터. NULL(마이그레이션 037 이전 레거시)도 포함된다.

currentVersion 이 빈 문자열이면 2번 조건을 적용하지 않는다(= ListUnembedded 와 같은 동작). 임베딩 버전이 배선되지 않았거나 재임베딩이 꺼져 있을 때 기존 동작을 한 치도 바꾸지 않기 위한 안전 기본값이다.

정렬은 collected_at ASC — 오래된 문서부터 앞으로 진행한다.

func (*DocumentStore) ListLegacyForRecheck added in v0.23.0

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

func (*DocumentStore) ListPendingForExtraction added in v0.23.0

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

ListPendingForExtraction returns up to limit active documents from the 4 active sources (gmail, sms, call-log, call-transcript) whose occurred_at falls within the last 30 days AND whose relations_extracted_at is NULL AND whose extraction backoff (if any) has elapsed (spec §5.1, migration 023). The 30-day bound is evaluated live at every call — NOT a one-time snapshot — so newly collected documents (which always have recent occurred_at) are naturally picked up on later ticks without any extra state, satisfying spec §5.1's "이후에는 신규 유입 문서를 증분 처리한다".

Deliberately keyed on relations_extracted_at, NOT entities_processed_at: that column belongs to the pre-existing, currently-active EntityWorker (ENTITY_EXTRACTION_ENABLED=true in production), which extracts a different artifact via a different LLM call. See migration 023's header comment for the full rationale.

func (*DocumentStore) ListPendingNotes added in v0.23.0

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

ListPendingNotes returns up to limit active model.SourceNote documents whose Metadata.enrichment_status is "pending" and whose enrichment_next_retry_at backoff (if any) has elapsed. Used by NoteEnrichmentWorker (spec §6.3). insight documents are never returned — source_type is hard-scoped to 'note', enforcing spec §3.2 gate 1 (insight-of-insight is structurally impossible via this query).

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) ListUnclassified added in v0.23.0

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

ListUnclassified returns up to limit active SMS/Gmail/call documents that have never been tagged with a retention value, ordered by collected_at DESC (newest first) so that the background worker's steady-state Jev spend tracks newly-collected volume rather than being starved by an ever-growing historical backlog.

transcription='pending' call documents (a recording exists but WhisperCollector has not transcribed it yet — see model.SourceCall's doc comment) are excluded: their content is still the short call-log summary, which store.AttachTranscript will wholesale replace once transcription completes. Classifying now would tag against content the document will no longer have moments later; deferring until transcription='done' means the eventual tag actually reflects the transcript.

backfillDays, when > 0, additionally restricts the result to documents collected within the last backfillDays days — CLASSIFIER_BACKFILL_DAYS in internal/worker.ClassificationWorkerConfig. 0 (the default) means "no limit": classify the entire history, not just recent arrivals.

classifier_attempts is checked so a document that has failed classification 3 times (ClassificationWorker's retry cap) stops being re-listed — see MergeClassificationMetadata / IncrementClassificationAttempts.

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. Insight documents are excluded too; see listUnsummarizedQuery.

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.

Insight documents are excluded too; see listWithoutEntitiesQuery.

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) MarkExtractionAttemptFailed added in v0.23.0

func (s *DocumentStore) MarkExtractionAttemptFailed(ctx context.Context, documentID uuid.UUID, attempts int, reason string, nextRetryAt time.Time) error

MarkExtractionAttemptFailed records a non-terminal extraction failure (attempts 1-2 of a 3-attempt cap — mirrors NoteEnrichmentWorker's retry model, adopted deliberately over EntityWorker's unbounded-retry model; see plan Global Constraints). relations_extracted_at is left NULL so the document is retried once nextRetryAt elapses.

func (*DocumentStore) MarkExtractionTerminal added in v0.23.0

func (s *DocumentStore) MarkExtractionTerminal(ctx context.Context, documentID uuid.UUID, reason string) error

MarkExtractionTerminal records the 3rd (terminal) extraction failure: relations_extracted_at is set so ListPendingForExtraction stops returning the document (a permanently malformed LLM output must not retry forever — this is the exact failure mode this plan's JSON-decoder defense and retry cap both exist to bound). There is currently no manual-retry endpoint for extraction (unlike POST /api/v1/notes/{id}/retry-enrichment) — out of scope for Part A; add one in Part C if operational need arises.

func (*DocumentStore) MarkNoteEnriched added in v0.23.0

func (s *DocumentStore) MarkNoteEnriched(ctx context.Context, documentID uuid.UUID, title string, metadata map[string]any) error

MarkNoteEnriched merges the Organized-layer fields (spec §3) into a note's Metadata and marks enrichment_status "done". title, when non-empty, overwrites the document's Title column — this is how POST /api/v1/notes' server-left-empty title (spec §6.1) gets filled in. Content is never touched by this method or any caller of it (spec §3.1 write-once guarantee) — there is no content parameter to accidentally pass one.

func (*DocumentStore) MarkNoteEnrichmentAttemptFailed added in v0.23.0

func (s *DocumentStore) MarkNoteEnrichmentAttemptFailed(ctx context.Context, documentID uuid.UUID, attempts int, reason string, nextRetryAt time.Time) error

MarkNoteEnrichmentAttemptFailed records a non-terminal enrichment failure (attempts 1-2 of the 3-attempt cap, spec §6.3): increments the attempt counter, records the failure reason, and schedules the next eligible retry time. enrichment_status is left "pending" so ListPendingNotes will pick the note back up once nextRetryAt elapses.

func (*DocumentStore) MarkNoteEnrichmentTerminal added in v0.23.0

func (s *DocumentStore) MarkNoteEnrichmentTerminal(ctx context.Context, documentID uuid.UUID, reason string) error

MarkNoteEnrichmentTerminal records the 3rd (terminal) enrichment failure (spec §6.3): sets enrichment_status "failed" so ListPendingNotes stops returning the note. Only POST /api/v1/notes/{id}/retry-enrichment (ResetNoteEnrichment) can revive it.

func (*DocumentStore) MarkRelationsExtracted added in v0.23.0

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

MarkRelationsExtracted sets relations_extracted_at to now() on successful extraction. After this call the document is never returned by ListPendingForExtraction again (migration 023's partial index scopes on this column being NULL).

func (*DocumentStore) MergeClassificationMetadata added in v0.23.0

func (s *DocumentStore) MergeClassificationMetadata(ctx context.Context, documentID uuid.UUID, updates map[string]any) error

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) RecordTranscribed added in v0.21.2

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

RecordTranscribed records that each source_id in sourceIDs has been transcribed for the given source type. Existing rows are left untouched (ON CONFLICT DO NOTHING), so re-recording an already-ledgered source_id is a no-op and the original transcribed_at timestamp is preserved.

The insert is a single round-trip: source_ids are passed as an array and expanded with unnest, avoiding one query per id. An empty slice is a no-op.

func (*DocumentStore) ResetNoteEnrichment added in v0.23.0

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

ResetNoteEnrichment reverts a terminal "failed" note back to "pending" with a zeroed attempt counter, for manual retry via POST /api/v1/notes/{id}/retry-enrichment (spec §6.3, §9.2). Returns found=false (no error) when documentID does not exist, is not a note, or is not currently in the terminal "failed" state — the caller (Task 7 retryEnrichmentHandler) maps found=false to 409 Conflict.

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) SoftDeleteByID added in v0.23.0

func (s *DocumentStore) SoftDeleteByID(ctx context.Context, id uuid.UUID) error

SoftDeleteByID soft-deletes a single model.SourceNote document (spec §6.5 delete path). Scoped to source_type='note' so this method cannot be used to soft-delete arbitrary documents of other source types. Returns nil without effect when the id does not exist or the document is not an active note — callers that need to distinguish "not found" from "not a note" should GetByID first (Task 7 deleteNoteHandler does this).

func (*DocumentStore) SoftDeleteBySourceID added in v0.23.0

func (s *DocumentStore) SoftDeleteBySourceID(ctx context.Context, sourceType model.SourceType, sourceID string) (bool, error)

SoftDeleteBySourceID soft-deletes the active document identified by (source_type, source_id), if one exists, and reports whether a row was affected.

Unlike Upsert/UpsertTracked, this method NEVER inserts: when no row with the given (source_type, source_id) exists, it is a pure no-op (false, nil). This is deliberate — it lets a collector that only observes a partial event stream (e.g. a calendar collector that receives a cancellation for an event it may never have fetched while active) signal a deletion without ever manufacturing a new document out of a tombstone event. It is idempotent: calling it again for an already-deleted or never-existing document is a harmless no-op (0 rows affected, no error).

func (*DocumentStore) SoftDeleteInsightsByNoteID added in v0.23.0

func (s *DocumentStore) SoftDeleteInsightsByNoteID(ctx context.Context, noteID uuid.UUID) (int, error)

SoftDeleteInsightsByNoteID cascades a note's soft-delete to every model.SourceInsight document derived from it (spec §6.5 permanent policy): "근거가 사라진 추론은 반증 불가능하고 감사 불가능하다". Matches on the JSONB path Metadata.provenance.source_note_id, which is how insight documents record their origin note (Task 6 EnrichNote). Returns the number of insight documents soft-deleted.

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) TranscribedSourceIDSet added in v0.21.2

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

TranscribedSourceIDSet returns the set of source_ids that the whisper pipeline has already transcribed for the given source type — the UNION of:

  1. transcription_ledger rows for sourceType — a source_id lands here as soon as it has been successfully transcribed, regardless of whether the resulting document was stored or rejected as a duplicate (ErrDuplicateTranscript).
  2. active documents' metadata->>'transcript_source_id' for sourceType — migration 033's call-log/call-transcript unification (model.SourceCall doc comment) means a transcribed recording's own raw identity ("transcript:{relPath}") is often NOT the document's SourceID: when WhisperCollector merges a transcript into an existing call-log document via AttachTranscript, the DOCUMENT is keyed by the call-log-formula SourceID, and the raw identity survives only in this metadata field. Without this second source, a merged recording's raw "transcript:..." id would never appear in the union, and the file would be re-transcribed forever — the exact bug this ledger exists to prevent (see package background below), just reintroduced through the merge path.

The whisper collector unions this set with the active document index (ActiveSourceIDSet) to decide which immutable audio files must NOT be re-transcribed, eliminating the infinite re-transcription loop.

The returned map is keyed by source_id and is safe for O(1) membership tests. On no rows an empty (non-nil) set is returned.

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 content guard: for source_type='call' 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.

metadata on conflict is EXCLUDED.metadata with classificationProtectedMetadataKeys overlaid back from the existing row (see upsertMetadataMergeSQL's doc comment) — every other metadata key is replaced wholesale by the incoming collector snapshot, same as before this protection was added.

통화 전사 보호(#292)도 UpsertTracked 와 똑같이 적용된다(녹음 재업로드가 이 경로다) — callTranscriptKeptSQL 주석 참고.

func (*DocumentStore) UpsertTracked added in v0.21.2

func (s *DocumentStore) UpsertTracked(ctx context.Context, doc *model.Document) (contentChanged bool, err error)

UpsertTracked is identical to Upsert but additionally returns a bool that indicates whether the document's content actually changed. Callers that perform post-upsert work (chunking, embedding) can use this to skip expensive operations when a document arrives unchanged.

Change detection uses a WITH CTE that captures the pre-update content in the same MVCC snapshot as the INSERT … ON CONFLICT statement, then compares it against the incoming value in RETURNING. This avoids two PostgreSQL pitfalls:

  1. EXCLUDED cannot be referenced in the RETURNING clause (only valid inside ON CONFLICT DO UPDATE SET/WHERE).
  2. `documents.col` in RETURNING reflects the post-update value, so a naive `documents.content IS DISTINCT FROM EXCLUDED.content` would always be false after the UPDATE overwrites the column.

metadata on conflict is EXCLUDED.metadata with classificationProtectedMetadataKeys overlaid back from the existing row — see upsertMetadataMergeSQL's doc comment for why a bare `metadata = EXCLUDED.metadata` used to silently erase a golden-set "user" retention judgment on the document's next re-collection.

통화 전사 보호(#292): 전사가 붙은 통화 문서에 같은 source_id 의 통화 로그· 녹음 요약이 다시 오면 content·전사 metadata·임베딩을 남기고 contentChanged=false 를 돌려준다 — callTranscriptKeptSQL 주석 참고.

*DocumentStore satisfies the api.IngestMessagesUpserter interface via this method.

func (*DocumentStore) UpsertTrackedWithChunks added in v0.25.3

func (s *DocumentStore) UpsertTrackedWithChunks(
	ctx context.Context,
	doc *model.Document,
	buildChunks func(*model.Document) []Chunk,
) (contentChanged bool, err error)

UpsertTrackedWithChunks 는 UpsertTracked 와 같은 upsert 를 하되, 내용이 바뀌었으면(contentChanged) 그 문서의 청크 교체까지 **한 트랜잭션**에서 한다 (#290). buildChunks 는 upsert 가 doc.ID 를 채운 뒤, 내용이 바뀐 경우에만 호출된다. 돌려받은 청크의 DocumentID 는 무시하고 doc.ID 를 쓴다.

왜 한 트랜잭션인가: upsert(autocommit)와 청크 교체(별도 트랜잭션)를 따로 하면, 청크 교체만 실패했을 때 문서 행은 새 내용으로 이미 커밋돼 있다. 호출자가 일시 오류로 보고 같은 레코드를 다시 보내면 upsert 는 "내용이 같다" (contentChanged=false)를 돌려주고 청크 교체를 건너뛴다 — 그 문서는 청크 없이 (또는 옛 내용의 청크로) 영구히 남는다. 청크 백필은 embedding IS NULL 인 청크만 채우고, 청크가 아예 없는 문서는 되살리지 않는다. 한 트랜잭션으로 묶으면 "문서 행이 새 내용이다" 이면 "청크도 새 내용이다" 가 항상 성립하므로, 실패 뒤 재전송은 언제나 처음부터 다시 한다.

내용이 바뀌었는데 buildChunks 가 빈 슬라이스를 돌려주면(빈 본문) 옛 청크를 지우기만 한다 — 옛 내용의 청크가 새 내용의 문서에 매달려 있으면 안 된다.

동시성: upsert 가 문서 행에 FOR NO KEY UPDATE 잠금을 잡은 뒤에 청크를 교체하고, ChunkStore.ReplaceDocument 는 청크를 지우기 전에 같은 행을 FOR UPDATE 로 잠근다. 그래서 같은 문서의 청크 교체 둘이 겹치지 않는다 (겹치면 늦은 쪽이 chunk_index 유일 제약 23505 로 실패했다). 잠금 순서는 양쪽 모두 "문서 행 → 청크 행" 이다(ReplaceDocument 주석의 교착 분석).

사전 점검(checkDuplicateArrival, 통화 중복 전사 확인)은 읽기 전용이라 트랜잭션 밖에서 풀로 한다. ErrDuplicateTranscript 는 UpsertTracked 처럼 감싸지 않고 돌려준다. 그 밖의 오류는 %w 로 감싸므로 *pgconn.PgError·context 오류를 errors.As/Is 로 꺼낼 수 있다.

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 EvalExclusionReasons added in v0.23.0

type EvalExclusionReasons struct {
	// Missing 은 documents 에 행 자체가 없는 경우다. 라벨은 남았는데 문서가
	// 물리적으로 지워졌다는 뜻이므로 가장 먼저 본다.
	Missing int `json:"missing"`
	// StatusNotActive 는 status<>'active' 인 경우다.
	StatusNotActive int `json:"status_not_active"`
	// Deleted 는 status 는 active 인데 deleted_at 이 채워진 경우다.
	Deleted int `json:"deleted_at"`
	// Insight 는 source_type='insight' 인 모델 생성 문서다.
	Insight int `json:"insight"`
	// Disposable 은 retention 태그가 disposable 인 문서다.
	Disposable int `json:"disposable"`
}

EvalExclusionReasons 는 라벨이 평가 스냅샷에서 빠진 사유별 집계다.

한 문서가 여러 사유에 동시에 해당할 수 있으므로(예: 삭제되면서 상태도 바뀐 문서) 아래 필드 선언 순서를 그대로 판정 우선순위로 쓴다. 우선순위를 고정해 두지 않으면 같은 코퍼스에서도 집계가 흔들린다.

func (EvalExclusionReasons) Total added in v0.23.0

func (r EvalExclusionReasons) Total() int

Total 은 사유별 집계의 합이다.

type EvalExclusions added in v0.23.0

type EvalExclusions struct {
	Relevant   int `json:"relevant_labels"`
	Irrelevant int `json:"irrelevant_labels"`
	Queries    int `json:"queries"`

	// Reasons 는 제외된 라벨 수를 사유별로 나눈 것이다. 합계는
	// Relevant+Irrelevant 와 항상 같다 — 한 라벨은 정확히 하나의 사유로만
	// 센다(EvalExclusionReasons 의 우선순위 참고).
	//
	// 총계만으로는 "라벨이 가리키는 문서가 사라졌다"(missing)와 "코퍼스
	// 정책상 검색 대상이 아니다"(disposable/insight)를 구분할 수 없는데,
	// 앞의 것은 데이터 결함이고 뒤의 것은 의도된 제외다.
	Reasons EvalExclusionReasons `json:"reasons"`
}

EvalExclusions describes labels outside the default production retrieval corpus. Filtering affects this evaluation snapshot only, never stored labels.

type EvalLabelFact added in v0.23.0

type EvalLabelFact struct {
	Found      bool
	Status     string
	Deleted    bool
	SourceType string
	Retention  string
	OccurredAt *time.Time
}

EvalLabelFact 은 라벨이 가리키는 문서 한 건의 적격성 판정 근거다.

제목·본문은 의도적으로 담지 않는다. 이 구조체는 평가 진단 파일로 흘러가고, 거기에 원문이 섞이면 산출물 전체가 개인정보가 된다.

func (EvalLabelFact) Eligible added in v0.23.0

func (f EvalLabelFact) Eligible() bool

Eligible 은 이 문서가 기본 운영 검색 코퍼스에 속하는지를 돌려준다. 판정 규칙은 FilterSearchEligible 이 쓰던 SQL WHERE 절과 같다.

type EvalMetricsRecord

type EvalMetricsRecord struct {
	ConfigHash   string
	LabelHash    string
	CodeRevision string
	RunConfig    json.RawMessage
	Attempted    int
	Failed       int
	FPPenalty10  float64
	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) LatestMatching added in v0.23.0

func (s *EvalMetricsStore) LatestMatching(ctx context.Context, configHash, labelHash string) (*EvalMetricsRecord, error)

LatestMatching excludes legacy/incomplete runs and unlike label/configuration snapshots. Code revision is recorded, but intentionally not matched so a regression can be detected across revisions of the same scoring protocol.

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"`

	// GoldenQueryID / GoldenQuerySource 는 골든셋에서 뽑은 쌍에만 채워진다
	// (GoldenStore.ExportEvalPairs). 각각 golden_queries.id 와 그 행의
	// source("seed" | "ask_history" | "manual" | "hermes" | "document")로,
	// 질의 문구를 드러내지 않고도 진단 출력에서 질의를 지목하고 출처별로
	// 나눠 볼 수 있게 한다. 피드백 기반 쌍에서는 빈 문자열이다.
	GoldenQueryID     string `json:"golden_query_id,omitempty"`
	GoldenQuerySource string `json:"golden_query_source,omitempty"`

	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 rows obey the same positive/negative vote semantics. Conflicting historical votes resolve to negative, never both labels.

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

func (*EvalStore) EvalPairsBySplit added in v0.23.0

func (s *EvalStore) EvalPairsBySplit(ctx context.Context, split string) ([]EvalPair, error)

EvalPairsBySplit returns the eval pairs belonging to one train/holdout split (see migrations/025_feedback_evidence.sql and internal/dataset).

It exists so that internal/dataset can read the two halves with two separate queries. There is deliberately no "read everything and partition afterwards" path: a variable holding both halves is exactly what must not exist outside the dataset package, or the weight optimiser can be handed its own validation set by accident.

split must be "train" or "holdout"; anything else is rejected rather than silently widened to "all", because a typo that returns the whole labelled set would be indistinguishable from success right up until the holdout metric stops meaning anything.

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.

func (*EvalStore) FilterSearchEligible added in v0.23.0

func (s *EvalStore) FilterSearchEligible(ctx context.Context, pairs []EvalPair) ([]EvalPair, EvalExclusions, error)

FilterSearchEligible 은 기본 운영 검색 코퍼스에 없는 라벨을 이번 평가 스냅샷에서만 걷어내고, 걷어낸 수를 사유별로 집계해 함께 돌려준다. 저장된 판정 자체는 절대 고쳐 쓰지 않는다.

func (*EvalStore) LabelFacts added in v0.23.0

func (s *EvalStore) LabelFacts(ctx context.Context, ids []string) (map[string]EvalLabelFact, error)

LabelFacts 는 주어진 문서 ID 들의 적격성 판정 근거를 한 번의 쿼리로 읽는다. 존재하지 않는 ID 는 Found=false 인 항목으로 채워 돌려주므로, 호출자는 "행이 없다"와 "조회를 안 했다"를 구분할 수 있다.

type EvidenceVote added in v0.23.0

type EvidenceVote struct {
	// SessionID is the conversation the card was shown in. It is part of the
	// idempotency key: the same question asked in a different conversation is
	// an independent signal, not a re-vote.
	SessionID string
	// Query is the question that produced the card — the turn's question, not
	// whatever is currently typed.
	Query string
	// DocumentID is the evidence document (UUID).
	DocumentID string
	// Thumbs is +1, -1 or 0.
	Thumbs int16
	// UserID is optional and normally nil: this is a single-user system and a
	// label does not need an identity attached to it.
	UserID *string
	// Metadata carries presentation context such as {"rank": 0, "layer": "observed"}.
	// The query text is NOT duplicated here — it already has its own column.
	Metadata map[string]any
}

EvidenceVote is one thumbs judgement on one evidence card of one /ask answer.

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.

func (*FeedbackStore) UpsertEvidence added in v0.23.0

func (s *FeedbackStore) UpsertEvidence(ctx context.Context, v EvidenceVote) (int64, int16, error)

UpsertEvidence records or updates one per-evidence vote and returns the row ID together with the thumbs value the database settled on.

It is idempotent per (session, normalised query, document): a repeat call updates the existing row instead of adding one.

Re-sending the same value toggles the vote off (to 0) rather than leaving it set, so a user can un-vote by clicking the same button again. The decision is made inside the UPDATE so it is atomic and needs no read-modify-write round trip. The resolved value is returned because the server, not the client, is the authority on what the vote now is.

Rows with thumbs = 0 are kept. "Looked at it and had no opinion" and "never saw it" are different facts, and EvalStore.BuildFromFeedback only reads thumbs >= 1 and thumbs = -1, so a zero row is inert for evaluation anyway.

This deliberately does NOT reuse FeedbackStore.Upsert: that function deletes every row for a (user, session, source) tuple before inserting, which is right for a Discord reaction toggle and catastrophic here — it would wipe every other label already collected in the same conversation.

type GoldenGeneratedQuery added in v0.23.0

type GoldenGeneratedQuery struct {
	Text       string
	DocumentID uuid.UUID
}

type GoldenGenerationDocument added in v0.23.0

type GoldenGenerationDocument struct {
	ID         uuid.UUID
	Source     model.SourceType
	Title      string
	Content    string
	OccurredAt *time.Time
}

GoldenGenerationDocument is evidence for a new question, never an automatic relevance judgment. A human still judges the generated question's results.

type GoldenJudgmentInput added in v0.23.0

type GoldenJudgmentInput struct {
	DocumentID uuid.UUID
	Judgment   string // "relevant" | "irrelevant" | "noise"
	Rank       int
	// Judge distinguishes a human review-UI label ("user") from an
	// unreviewed LLM auto-judgment made by hermes during a live conversation
	// ("llm"). This is not cosmetic: only "user" judgments are allowed to
	// rewrite a document's retention tag (UpsertJudgments) or be exported as
	// eval ground truth (ExportEvalPairs' default) — an unreviewed model
	// opinion must never silently become the answer key it is being
	// evaluated against. Empty defaults to "user" for callers written before
	// this field existed.
	Judge string
}

GoldenJudgmentInput is one document judgment submitted via POST /api/v1/golden/judgments or POST /api/v1/golden/feedback.

type GoldenProgress added in v0.23.0

type GoldenProgress struct {
	JudgedQueries  int
	OpenQueries    int
	TotalJudgments int
}

GoldenProgress summarizes labelling progress across the whole golden set. Returned alongside GET /api/v1/golden/next's candidate list so the caller can render a progress indicator without a second round trip.

type GoldenQuery added in v0.23.0

type GoldenQuery struct {
	ID     uuid.UUID
	Text   string
	Source string // "ask_history" | "seed" | "manual" | "hermes" | "document"
	Status string // "open" | "done" | "skipped"
	// AskedAt is the instant golden_queries row was created
	// (migrations/032_golden_asked_at.sql), for every source including
	// ask_history — it is NO LONGER the original ask_sessions moment the
	// question was actually asked. GET /api/v1/golden/next does not read this
	// field to resolve a query's period expression ("지난주", "오늘", ...);
	// that resolution is anchored at REVIEW TIME (the request handler's
	// s.nowFunc()) instead, so a stale generation timestamp here can never
	// silently reinterpret what "지난주" means for a reviewer. Feedback never
	// changes this provenance; GenerateQueries sets it only when creating a row.
	AskedAt   time.Time
	CreatedAt time.Time
}

GoldenQuery is a single candidate query awaiting (or having received) human relevance judgments (migrations/031_golden_set.sql).

type GoldenStore added in v0.23.0

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

GoldenStore persists golden-set queries and judgments.

func NewGoldenStore added in v0.23.0

func NewGoldenStore(pg *Postgres) *GoldenStore

NewGoldenStore returns a GoldenStore backed by the given Postgres instance.

func (*GoldenStore) CandidateGenerationDocuments added in v0.23.0

func (s *GoldenStore) CandidateGenerationDocuments(ctx context.Context, limit int) ([]GoldenGenerationDocument, error)

CandidateGenerationDocuments interleaves random eligible samples per source. This balances high-volume mail against other sources and lets a later explicit request move beyond documents whose generated questions were all duplicates.

func (*GoldenStore) ExistingGenerationQuestions added in v0.23.0

func (s *GoldenStore) ExistingGenerationQuestions(ctx context.Context, limit int) ([]string, error)

ExistingGenerationQuestions gives the generator a bounded exclusion list; insertion still checks every existing normalized text transactionally.

func (*GoldenStore) ExportEvalPairs added in v0.23.0

func (s *GoldenStore) ExportEvalPairs(ctx context.Context, judge string) ([]EvalPair, error)

ExportEvalPairs returns one EvalPair per golden query that has at least one relevant or negative judgment FROM THE GIVEN judge, in the exact shape internal/dataset.Source and cmd/eval expect (see EvalStore.BuildFromFeedback for the sibling feedback-derived version in eval.go). Source is "golden" so a downstream metric or log can tell which half of the eval set a pair came from. Used by both GET /api/v1/golden/export and cmd/eval's --golden flag.

Callers building an actual evaluation set (cmd/eval --golden; the default GET .../export) MUST pass "user": an unreviewed "llm" judgment becoming the answer key it is later scored against would make the metric measure hermes agreeing with itself, not correctness.

func (*GoldenStore) FindQueryByText added in v0.23.0

func (s *GoldenStore) FindQueryByText(ctx context.Context, text string) (uuid.UUID, bool, error)

FindQueryByText resolves an existing query without creating or updating it. Feedback can judge only questions explicitly generated by the user.

func (*GoldenStore) GenerateQueries added in v0.23.0

func (s *GoldenStore) GenerateQueries(ctx context.Context) (created int, totalOpen int, err error)

GenerateQueries inserts new candidate queries from two sources — recent ask_sessions questions (source="ask_history") and the fixed seed list above (source="seed") — and returns how many were newly created plus the resulting total count of status='open' queries.

Every inserted row's asked_at is left to the column's DEFAULT now() (migrations/032_golden_asked_at.sql) — i.e. the moment THIS call runs — for both sources uniformly. ask_history candidates used to be inserted with the EARLIEST ask_sessions.created_at recorded for that question text instead (the moment it was actually asked), to anchor GET /api/v1/golden/next's period-phrase resolution against the asker's original intent. That anchor point moved to review time (the handler's s.nowFunc()) instead, so carrying the original ask moment through this column would now be dead data with no reader — it is discarded rather than stored. The underlying ask_sessions row (and its created_at) is not deleted; only this copy of it is no longer taken.

Deduplication happens in two layers: an exact match on `text` is rejected by the table's UNIQUE constraint (ON CONFLICT DO NOTHING, so a repeat call is a no-op), and a normalized-form match (internal/dataset.Normalize — the same rule the feedback train/holdout split already uses) is checked in Go before each insert, so "질문" and "질문 " are not both admitted.

func (*GoldenStore) JudgedDocumentIDs added in v0.23.0

func (s *GoldenStore) JudgedDocumentIDs(ctx context.Context, queryID uuid.UUID, judge string) (map[uuid.UUID]struct{}, error)

JudgedDocumentIDs returns the set of document IDs already judged for queryID BY THE GIVEN judge, so GET /api/v1/golden/next can exclude them from a fresh candidate list — a document judged once by a given judge should not compete for another judgment slot from that same judge on the same query. A document already judged by "llm" is still a valid candidate for "user" review, and vice versa.

func (*GoldenStore) NewGeneratedQueries added in v0.23.0

func (s *GoldenStore) NewGeneratedQueries(ctx context.Context, candidates []GoldenGeneratedQuery) (created, totalOpen int, err error)

NewGeneratedQueries persists only still-eligible evidence and new normalized question text. The same transaction lock used by seed/history generation protects near-duplicate checks across concurrent explicit requests.

func (*GoldenStore) NextQuery added in v0.23.0

func (s *GoldenStore) NextQuery(ctx context.Context, judge string) (*GoldenQuery, error)

NextQuery returns the status='open' query with the fewest existing judgments FROM THE GIVEN judge ("user" or "llm") — ties broken by oldest created_at first, so a freshly generated batch is worked through roughly in order — or nil with no error if no open query remains.

judge is part of the ranking, not just a filter on the result: a query that already has 10 "llm" judgments but zero "user" ones must still look completely fresh to the human-review queue (judge="user"), and vice versa — the two judge tracks are independent progress counters over the same query set.

func (*GoldenStore) Progress added in v0.23.0

func (s *GoldenStore) Progress(ctx context.Context) (GoldenProgress, error)

Progress returns the labelling-progress summary for GET /api/v1/golden/next.

func (*GoldenStore) SkipQuery added in v0.23.0

func (s *GoldenStore) SkipQuery(ctx context.Context, queryID uuid.UUID) (bool, error)

SkipQuery marks a query 'skipped' so GET /api/v1/golden/next never surfaces it again. Returns found=false (no error) when queryID does not exist or is not currently 'open' — a query already 'done' must not be silently reopened-then-skipped by a stale client request.

func (*GoldenStore) UpsertJudgments added in v0.23.0

func (s *GoldenStore) UpsertJudgments(ctx context.Context, queryID uuid.UUID, judgments []GoldenJudgmentInput, finishQuery bool) (saved int, feedbackApplied int, err error)

UpsertJudgments records each judgment (upsert on the (query_id, document_id, judge) unique key — a re-judgment BY THE SAME JUDGE overwrites the prior label rather than erroring; "user" and "llm" judgments on the same document coexist as separate rows) and, for judge="user" ONLY, feeds the result back into the retention pipeline: a "noise" judgment tags the document retention=disposable, a "relevant" judgment tags it retention=keep (see internal/model/retention.go), both with classifier="user" so a later audit can tell a human label apart from the automated gmail segmentation pass. "irrelevant" means "not an answer to THIS query" — it says nothing about the document's general retention value, so it leaves the tag untouched regardless of judge.

"keep" wins across queries: a document a human has EVER judged "relevant" (judge="user", any query) must never be downgraded to disposable by a later "noise" judgment on the same document FROM A DIFFERENT QUERY — a document can legitimately be the right answer to one query and unrelated noise for another, and last-write-wins would let whichever query happens to be reviewed last silently erase the earlier "this document matters" signal. hasUserRelevantJudgment checks golden_judgments (not the document's current metadata) as the source of truth for this, since a collector re-sync can wipe classifier="user" out of a document's metadata wholesale (internal/store.Upsert/UpsertTracked's `metadata = EXCLUDED.metadata` ON CONFLICT clause replaces the whole jsonb blob rather than merging it — see this package's operator-facing report for the out-of-scope follow-up this implies for document.go). The judgment row itself is still upserted either way — only the retention-tag side effect is skipped — so the review history stays accurate even when the retention write is suppressed.

judge="llm" judgments (hermes's own in-conversation relevance calls, POST /api/v1/golden/feedback) are recorded ONLY — never applied to retention. An unreviewed model opinion silently retagging a document (or contaminating the eval holdout via ExportEvalPairs' default judge="user" filter) would defeat the entire point of having a human-judged golden set.

finishQuery, when true, additionally marks the query status='done'. All writes happen in one transaction: a caller that submits judgments with finishQuery=true must not end up with judgments saved but the query left open (or vice versa) if the connection drops mid-request.

Returns saved (judgment rows upserted) and feedbackApplied (of those, how many carried a retention-tag update — always 0 for an all-"llm" batch, and excludes a "noise" judgment suppressed by the keep-wins rule above).

type GraphSource added in v0.23.0

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

GraphSource is the read-only PostgreSQL side of the Neo4j projection. It is a separate type (not a method set bolted onto an existing store) so that the projection pipeline owns its own queries and cannot accidentally acquire write methods.

func NewGraphSource added in v0.23.0

func NewGraphSource(pg *Postgres) *GraphSource

NewGraphSource returns a GraphSource backed by the given Postgres instance.

func (*GraphSource) ListMentionsAfter added in v0.23.0

func (s *GraphSource) ListMentionsAfter(ctx context.Context, afterDocumentID string, afterEntityID int64, limit int) ([]model.ProjectionMention, error)

ListMentionsAfter returns document_entities rows (joined to their document and entity) after the given keyset cursor, ordered by (document_id, entity_id).

document_entities has no monotonic key — its primary key is composite and document ids are random UUIDs — so a keyset cursor can only paginate one sweep; it cannot be used as an incremental watermark across cycles, because a newly inserted row can land "below" a saved cursor. The worker therefore restarts each cycle from an empty cursor and sweeps the whole table. That is cheap at the current table size and is flagged in the plan's open risks for revisiting past ~100k rows.

func (*GraphSource) ListRelationsAfter added in v0.23.0

func (s *GraphSource) ListRelationsAfter(ctx context.Context, afterID int64, limit int) ([]model.ProjectionRelation, error)

ListRelationsAfter returns relations with id greater than afterID, oldest first, together with both endpoint entities.

entity_relations is append-only (inserted with ON CONFLICT DO NOTHING and never updated), which is what makes an id watermark correct here. The one gap is that BIGSERIAL ids are handed out before commit, so a transaction holding id 100 can commit after one holding 101 — a strictly increasing watermark can step over it. That is handled by the worker re-reading an overlap window each cycle, which is only safe because the projection is idempotent.

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 NewReadOnlyPostgres added in v0.23.0

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

NewReadOnlyPostgres opens an existing migrated database without installing extensions. Every pooled connection enforces read-only transactions.

func (*Postgres) Close

func (pg *Postgres) Close()

Close releases all pool connections.

func (*Postgres) MaxConns added in v0.25.2

func (pg *Postgres) MaxConns() int32

MaxConns 는 풀의 최대 연결 수다. DSN 의 pool_max_conns 가 없으면 pgx 기본값 max(4, runtime.NumCPU()) 이다. 동시 검색 상한(SEARCH_MAX_CONCURRENCY, #286)을 정하는 입력이고 시작 로그에 남긴다(DSN 자체는 로그에 남기지 않는다).

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

Concurrent-startup serialisation: before executing any migration file, RunMigrations acquires a PostgreSQL session-level advisory lock (pg_advisory_lock) on migrationAdvisoryLockKey. When multiple service instances (server, collector, eval-runner) start simultaneously each one blocks on pg_advisory_lock until the holder finishes and releases via pg_advisory_unlock. This prevents the 40P01 deadlock that previously occurred when concurrent instances raced on DDL statements in the same migration file.

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 documents (source_type='call', or
	// the deprecated pre-migration-033 'call-log') that have an audio_file
	// entry in their metadata JSON (i.e. a recording was captured).
	RecentKindCallRecording RecentKind = "call-recording"

	// RecentKindVoiceMemo returns call documents (source_type='call', or the
	// deprecated pre-migration-033 'call-log') 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 RelationStore added in v0.23.0

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

RelationStore provides persistence for entity_relations (migration 021).

func NewRelationStore added in v0.23.0

func NewRelationStore(pg *Postgres) *RelationStore

NewRelationStore returns a RelationStore backed by the given Postgres instance.

func (*RelationStore) UpsertEntityRelations added in v0.23.0

func (s *RelationStore) UpsertEntityRelations(ctx context.Context, relations []model.EntityRelation) error

UpsertEntityRelations inserts relations, relying on the UNIQUE(from, to, type, evidence_document_id) constraint (migration 021) to silently skip a relation already observed from the SAME evidence document — that is not new information (spec §5.4). A DIFFERENT evidence document observing the same (from, to, type) pair is a separate row by design (spec §5.4: "김대표" and "박부장" observed communicated_with across 3 emails → 3 rows).

Individual failures are accumulated so partial success is still persisted, mirroring EntityStore.UpsertAndLinkEntities.

type SourceDocumentFreshness added in v0.21.0

type SourceDocumentFreshness struct {
	SourceType  model.SourceType `json:"source_type"`
	LastCreated *time.Time       `json:"last_created"` // MAX(created_at); nil when no active docs exist
	ActiveCount int              `json:"active_count"`
}

SourceDocumentFreshness holds the per-source-type document freshness snapshot derived from the documents table (not the collection_log). This is used by the FreshnessChecker to detect silent push-ingest failures where no collection_log row is written (e.g. SMS documents from the Android push app via /ingest).

type SparseContextCandidate added in v0.24.0

type SparseContextCandidate struct {
	ChunkID     int64
	Content     string
	Fingerprint string
	Doc         model.Document // SourceType, Title, OccurredAt, Metadata only
}

SparseContextCandidate is one chunk's raw materials for computing a chunk_sparse_context row, fetched by FetchSparseContextCandidates. Fingerprint comes from chunkSparseFingerprintSQL evaluated on the SAME row Doc was read from (same SELECT, same MVCC snapshot) — see that constant's doc comment for why this matters.

type SparseContextRow added in v0.24.0

type SparseContextRow struct {
	ChunkID     int64
	Fingerprint string
	SparseText  string
}

SparseContextRow is one computed sparse_text ready for UpsertSparseContextBatch.

type UnembeddedChunk added in v0.20.0

type UnembeddedChunk struct {
	ID         int64
	Content    string
	DocumentID uuid.UUID
	SourceType model.SourceType
	Title      string
	OccurredAt *time.Time
	Metadata   map[string]any
}

UnembeddedChunk is a minimal chunk record used for embedding backfill.

청크 본문(Content) 외에 소속 문서의 메타(SourceType/Title/OccurredAt/ Metadata)도 함께 싣는다. 청크 임베딩 입력 앞에 붙일 문맥 헤더 (scheduler.BuildChunkContextHeader)를 만들려면 "누가·언제·무슨 제목" 이 필요한데, 그 정보는 청크 행이 아니라 문서 행에 있기 때문이다. 어차피 활성 문서인지 보려고 documents 와 조인하고 있으므로 추가 쿼리 비용은 없다.

type WeightsHistoryStore added in v0.23.0

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

WeightsHistoryStore persists search weight candidates and their promotion state.

func NewWeightsHistoryStore added in v0.23.0

func NewWeightsHistoryStore(pg *Postgres) *WeightsHistoryStore

NewWeightsHistoryStore returns a WeightsHistoryStore backed by Postgres.

func (*WeightsHistoryStore) Active added in v0.23.0

Active returns the live configuration, or (nil, nil) when nothing has been promoted. A nil result is not an error: it is the normal state before the first promotion and after a rollback with nothing to restore, and it means "use the compiled-in defaults".

func (*WeightsHistoryStore) Insert added in v0.23.0

Insert records a candidate and returns its ID.

Insert never writes status 'active' on its own: becoming live is what Promote does, in a transaction that first stands the previous holder down. Allowing a direct active insert here would give a caller a way to create the second active row that the whole design exists to prevent.

func (*WeightsHistoryStore) Promote added in v0.23.0

func (s *WeightsHistoryStore) Promote(ctx context.Context, id int64) error

Promote makes one record live in a single transaction.

The order matters and is not interchangeable: the incumbent is stood down to 'superseded' first, then the target is raised to 'active'. Doing it the other way round puts two active rows in the table for the duration of a statement, and the partial unique index rejects that — the transaction would fail even though the end state is legal.

func (*WeightsHistoryStore) Rollback added in v0.23.0

func (s *WeightsHistoryStore) Rollback(ctx context.Context) (*WeightsRecord, error)

Rollback stands the current configuration down and restores the one it replaced. It returns the restored record, or (nil, nil) when there was nothing to restore — in which case the system falls back to the compiled-in defaults, which is itself a safe state.

Runs in one transaction for the same reason as Promote: between the two statements the table would otherwise be readable with zero or two active rows.

type WeightsRecord added in v0.23.0

type WeightsRecord struct {
	ID             int64
	Weights        model.SearchWeights
	Status         string
	TrainObjective *float64
	HoldoutNDCG10  *float64
	HoldoutFP10    *float64
	BaselineNDCG10 *float64
	BaselineFP10   *float64
	HoldoutQueries int
	// GateReason is written for a human: "holdout distinct queries 12 < 30".
	GateReason *string
	// Metadata carries run context such as
	// {"rerank": false, "train_holdout_gap": 0.04, "sweeps": 2}.
	// train_holdout_gap is the overfitting tell-tale.
	Metadata   map[string]any
	CreatedAt  time.Time
	PromotedAt *time.Time
}

WeightsRecord is one row of search_weights_history.

The metric fields are pointers because "not measured" and "measured as zero" are different facts: a proposed candidate that never reached the holdout evaluation has no holdout score, and recording 0.0 would make it look like a catastrophically bad configuration in any later review.

No query text and no document IDs appear here by design — see migration 026.

Jump to

Keyboard shortcuts

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