search

package
v0.25.2 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: MIT Imports: 32 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 search provides the search service and embedding engine abstractions.

Package search provides the search service that combines full-text and vector (embedding-based) search over collected documents.

Index

Constants

View Source
const (
	// RecipeDocumentV1 은 문서 임베딩 = title + "\n\n" + content.
	RecipeDocumentV1 = "doc-v1"
	// RecipeChunkContextV1 은 청크 임베딩 = 문맥 헤더 + "\n\n" + 청크 본문.
	// 헤더 구성은 scheduler.BuildChunkContextHeader 가 정의한다.
	// (그 이전의 "청크 본문만" 방식에는 버전이 없었다 — 컬럼 NULL 이 곧
	//  레거시 표시다.)
	RecipeChunkContextV1 = "chunk-ctx-v1"
)

임베딩 "레시피" 식별자. 모델·차원이 같아도 임베딩에 넣는 텍스트를 어떻게 구성했는지가 다르면 벡터 공간이 달라지므로, 레시피도 버전 문자열에 포함한다.

값을 바꾸면 해당 레시피로 만들어진 모든 행이 "구버전"이 되어 재임베딩 대상으로 잡힌다. 그러니 임베딩 입력 구성을 실제로 바꿨을 때만 올릴 것.

View Source
const (
	LaneDocumentStore    = "document_store" // internal/store 의 5-lane 가중 RRF 결과
	LaneChunkVector      = "chunk_vector"
	LaneOpenSearch       = "opensearch"
	LaneChunkFTS         = "chunk_fts"           // 1차 경로가 비었을 때만 도는 폴백
	LaneChunkFTSFused    = "chunk_fts_fused"     // SEARCH_CHUNK_SPARSE=fuse: 결과 유무와 무관하게 RRF 융합(#270)
	LaneChunkFTSFusedCtx = "chunk_fts_fused_ctx" // SEARCH_CHUNK_SPARSE=fuse_ctx: 파생 문맥(migration 040) 우선 매칭(#270 phase B)
)

후보를 올려보낸 레인의 이름. 진단 출력에만 쓰이며, 값이 그대로 JSON 에 실리므로 영어 식별자로 고정한다.

View Source
const MaxQueryBytes = 1024

MaxQueryBytes 는 외부 진입점(REST /api/v1/search, GraphQL search, MCP search 도구, 그래프 엔티티 검색)이 받는 검색 질의 문자열의 상한이다(#282).

바이트 기준인 이유: 질의가 만드는 비용 — pg_bigm 2-gram 수, LIKE 패턴 길이, tsquery 항 수, 임베딩 API 입력 토큰, 리랭커 요청 본문 — 은 전부 룬 수가 아니라 바이트 수에 비례한다. 룬 기준으로 두면 4바이트 문자만으로 같은 상한의 네 배 입력이 통과한다. 또 바이트 길이는 UTF-8 디코딩 없이 O(1) 로 먼저 거를 수 있어서, 거대한 입력을 끝까지 훑기 전에 거부할 수 있다.

1024 인 이유: 한글 기준 약 341자, ASCII 기준 1024자다. 검색 질의는 키워드나 짧은 문장이라 실사용 질의보다 한 자릿수 이상 크다. /api/v1/ask 의 질문 상한(internal/api 의 askQuestionBytes, 4KB)은 대화형 질문을 받는 별도 예산이므로 이 상수를 쓰지 않고 자기 상한으로 같은 검증 함수를 호출한다.

Variables

View Source
var (
	// ErrInputTooLong 은 입력이 허용 바이트 수를 넘었다는 뜻이다.
	ErrInputTooLong = errors.New("too long")
	// ErrInputInvalidUTF8 은 입력이 올바른 UTF-8 이 아니라는 뜻이다.
	// PostgreSQL 은 이런 text 파라미터를 SQLSTATE 22021 로 거부한다.
	ErrInputInvalidUTF8 = errors.New("not valid UTF-8")
	// ErrInputContainsNUL 은 입력에 NUL(0x00) 바이트가 있다는 뜻이다.
	// PostgreSQL text 는 NUL 을 담을 수 없어 역시 SQLSTATE 22021 로 끝난다.
	ErrInputContainsNUL = errors.New("contains NUL character")
)

검증 실패 사유. 모두 ErrInvalidInput 과 함께 InputError 로 감싸 반환된다.

View Source
var ErrInvalidInput = errors.New("invalid search input")

ErrInvalidInput 은 검색 입력 검증 실패 전체를 묶는 상위 오류다. 호출자는 errors.Is(err, ErrInvalidInput) 하나로 "400 으로 돌려줄 입력 오류"를 판별한다.

Functions

func AggregateFPPenalty added in v0.20.0

func AggregateFPPenalty(results [][]string, irrelevant []map[string]bool, k int) float64

AggregateFPPenalty computes the macro-average FalsePositivePenalty over all queries in the eval set. results[i] and irrelevant[i] must have equal length. Returns 0 when the inputs are empty or when no irrelevant sets are provided.

func EmbeddingVersion added in v0.23.0

func EmbeddingVersion(model string, dimensions int, recipe string) string

EmbeddingVersion 은 벡터가 어떤 설정으로 만들어졌는지 식별하는 문자열을 만든다. 형식: "{model}:{dimensions}:{recipe}"

예) "text-embedding-3-small:1536:chunk-ctx-v1"

이 값을 documents.embedding_version / chunks.embedding_version 에 기록해 두면, 모델이나 레시피를 바꿨을 때 "아직 옛 설정으로 남아 있는 행"을 SQL 한 줄(IS DISTINCT FROM)로 찾아 재임베딩할 수 있다. 서로 다른 설정으로 만든 벡터가 같은 인덱스에 섞이면 거리 비교가 의미를 잃는데, 그 상태를 눈으로 확인할 수단이 지금까지 없었다.

model 이 비어 있으면 빈 문자열을 돌려준다 — 임베딩이 꺼진 배포에서 의미 없는 버전 문자열을 쓰지 않기 위함이다. dimensions 가 0 이면 모델 기본 차원을 뜻하는 "default" 로 표기한다.

func Expand

func Expand(ctx context.Context, client llm.Completer, query string) string

Expand returns a hypothetical document embedding query by asking the LLM to generate a plausible answer for the query. The generated answer is appended to the original query so that both the original keywords and the hypothetical document's vocabulary are used for retrieval.

It is safe to call with a nil client — the original query is returned unchanged. When the LLM call fails or returns an empty string, the original query is returned unchanged and no error is propagated.

func FalsePositivePenalty added in v0.20.0

func FalsePositivePenalty(results []string, irrelevant map[string]bool, k int) float64

FalsePositivePenalty computes the proportion of top-K results that are explicitly marked as irrelevant (thumbs=-1) for a single query.

A false positive (FP) is a document that appears in the top-K results but is in the irrelevant set. The penalty is the fraction of top-K slots that are FPs: penalty = |top-K ∩ irrelevant| / K.

Returns 0 when irrelevant is empty or k <= 0. A score of 0 means no false positives; 1.0 means all top-K results are FPs.

func MRRK

func MRRK(results []string, relevant map[string]bool, k int) float64

MRRK computes the Mean Reciprocal Rank for a single query within the top-K results. Returns 1/rank of the first relevant result, or 0 if no relevant result appears within the top-K. k <= 0 means no cutoff.

func NDCGK

func NDCGK(results []string, relevant map[string]bool, k int) float64

NDCGK computes Normalised Discounted Cumulative Gain at rank K for a single query. results contains document IDs in ranked order (position 0 = rank 1). relevant is the ground-truth set of relevant document IDs. k is the cutoff; k <= 0 means no cutoff. Missing results do not shrink the ideal ranking.

Returns 0 when relevant is empty or no relevant result appears in the top-K.

func ValidateInputText added in v0.25.1

func ValidateInputText(field, s string, maxBytes int) error

ValidateInputText 는 검색 경로로 들어가는 문자열 하나를 검사하는 공통 검증 함수다(#282). 모든 진입점이 이 함수 하나를 거친다.

검사 순서는 비용 순이다: 바이트 길이(O(1)) → UTF-8 유효성 → NUL 포함. maxBytes 가 0 이하이면 길이 검사를 건너뛴다 — 검색 서비스 내부의 방어선은 진입점마다 다른 길이 예산을 알 수 없어서 내용 검사만 한다.

이 함수는 입력을 고치지 않는다(NUL 제거·잘못된 바이트 치환 없음). 조용히 고쳐서 검색하면 사용자가 보낸 것과 다른 질의의 결과를 돌려주게 되므로, 거부하고 호출자에게 알리는 쪽을 택했다.

func ValidateQueryInput added in v0.25.1

func ValidateQueryInput(q model.SearchQuery, maxQueryBytes int) error

ValidateQueryInput 은 model.SearchQuery 에서 호출자가 채우는 문자열 필드 전부(질의 본문, 단수·복수 소스 필터, 제외 소스 목록, 정렬)를 ValidateInputText 로 검사한다. 소스 필터도 SQL 파라미터로 바인딩되므로 질의 본문과 똑같이 22021 을 일으킬 수 있다.

maxQueryBytes 는 질의 본문과 각 필터 값에 같이 적용된다. 필터 값은 수십 바이트짜리 식별자라 질의 상한보다 한참 짧으므로 따로 두지 않는다.

Types

type ActiveWeightsReader added in v0.23.0

type ActiveWeightsReader interface {
	Active(ctx context.Context) (*store.WeightsRecord, error)
}

ActiveWeightsReader returns the promoted search-weight configuration, or (nil, nil) when nothing has been promoted. It is satisfied by *store.WeightsHistoryStore.

This is the last link of the tuning loop (#214). cmd/tune measures candidates, gates them on a holdout set and writes the winner to search_weights_history as the single 'active' row — and until this interface existed, nothing read that row. Promotion changed a table and not one search.

type ChunkBatchLister added in v0.25.0

type ChunkBatchLister interface {
	ListByDocuments(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID][]store.Chunk, error)
}

ChunkBatchLister 는 여러 문서의 청크를 한 번에 돌려주는 선택 인터페이스다. *store.ChunkStore 가 만족한다. 청크가 없는 문서는 맵에 키가 없어도 되고, 문서별 슬라이스는 ListByDocument 와 같은 chunk_index 오름차순이어야 한다.

ChunkLister 에 메서드를 더하지 않고 따로 둔 이유: 기존 더블(askeval 가짜 코퍼스 등)을 건드리지 않기 위해서다. 이걸 만족하지 않으면 buildRerankDocs 는 예전처럼 문서마다 ListByDocument 를 부른다 — 결과 텍스트는 두 경로가 같다.

type ChunkLister added in v0.23.0

type ChunkLister interface {
	ListByDocument(ctx context.Context, documentID uuid.UUID) ([]store.Chunk, error)
}

ChunkLister 는 문서 하나의 청크를 순서대로 돌려준다. *store.ChunkStore 가 만족하며, RerankInputBestChunk 에서만 쓴다.

별도 인터페이스로 둔 이유: ChunkSearcher(코퍼스 전역 검색)와 목적이 다르고, 이걸 만족하지 않는 테스트 더블은 조용히 head 입력으로 되돌아가야 하기 때문이다. 인터페이스 단언 실패가 검색 실패가 되어서는 안 된다.

type ChunkSearcher

type ChunkSearcher interface {
	SearchFTS(ctx context.Context, query string, limit int) ([]store.ChunkSearchResult, error)
	SearchVector(ctx context.Context, queryVec []float32, limit int) ([]store.ChunkSearchResult, error)
}

ChunkSearcher is the subset of the chunk store used for chunk-based search. It is satisfied by *store.ChunkStore.

type DocCounter

type DocCounter interface {
	CountBySource(ctx context.Context) (map[string]int, error)
}

DocCounter is the subset of store.DocumentStore used by ReindexChecker. It is satisfied by *store.DocumentStore.

type DocumentSearcher

type DocumentSearcher interface {
	Search(ctx context.Context, query model.SearchQuery) ([]*model.SearchResult, error)
}

DocumentSearcher is the subset of the document store used by the search service.

type EmbedClient

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

EmbedClient calls an OpenAI-compatible /v1/embeddings endpoint to produce vector representations of text. When apiURL is empty all methods are no-ops and return nil, enabling full-text-only operation.

Token resolution at construction time:

  1. apiKey non-empty → static Bearer token
  2. authFilePath non-empty → CliProxyAPI OAuth token (auto-refreshed with 5-min TTL)
  3. both empty → no Authorization header sent

EmbedClient satisfies the EmbeddingEngine interface.

func NewEmbedClient

func NewEmbedClient(apiURL, apiKey, authFilePath, model string, dim int) *EmbedClient

NewEmbedClient returns an EmbedClient. When apiURL is empty the client is disabled — Embed and EmbedBatch return nil results without error.

Token priority: apiKey > authFilePath > no auth.

As a convenience, when neither apiKey nor authFilePath is set we force the client into the disabled state regardless of apiURL. This lets operators disable embeddings by clearing EMBEDDING_API_KEY/CLIPROXY_AUTH_FILE without also having to override the default EMBEDDING_API_URL.

dim is the advisory vector dimension (e.g. 1536 for text-embedding-3-small). Pass 0 when unknown.

func (*EmbedClient) Dimension

func (c *EmbedClient) Dimension() int

Dimension returns the advisory vector dimension configured for this client. A value of 0 indicates that the dimension is unknown.

func (*EmbedClient) Embed

func (c *EmbedClient) Embed(ctx context.Context, text string) (vec []float32, err error)

Embed returns the embedding vector for text, or nil if the client is disabled. text is silently truncated to maxEmbedTokens cl100k_base tokens before sending to the API (falls back to rune-based truncation when the offline encoder is unavailable).

Transient errors (5xx, network failures) and 429 rate-limit responses are retried up to embedMaxRetries times with exponential backoff (1s/2s/4s). When the server returns a Retry-After header with a longer delay, that delay is honoured instead of the default backoff interval. 4xx errors other than 429 are not retried.

Tracing: wrapped in a single "embedding.single" span. No span is created when the client is disabled (Enabled()==false) — that path is a configuration no-op, not an API call. err is a named return so the deferred finalizer can record whichever error value the retry loop's many return points ultimately produces, without repeating span.RecordError/SetStatus at each one.

func (*EmbedClient) EmbedBatch

func (c *EmbedClient) EmbedBatch(ctx context.Context, texts []string) (_ [][]float32, err error)

EmbedBatch generates embeddings for multiple texts. Each text is silently truncated to maxEmbedTokens tokens before processing.

When the total character count of all texts exceeds maxBatchChars the input is automatically split into sub-batches, each dispatched as a separate API call. The resulting vectors are concatenated in the original input order before being returned. This prevents 400 max_tokens_per_request errors that occur when a large backfill batch exceeds the per-request token limit.

A single item whose character count alone exceeds maxBatchChars is sent as its own sub-batch (the existing per-document rune truncation makes this case practically unreachable, but we handle it defensively).

Tracing: wrapped in a top-level "embedding.batch" span, with one child "embedding.batch.subbatch" span per API call dispatched by embedBatchOnce — so a slow or failing sub-batch is attributable within the overall batch operation rather than only visible as aggregate latency. No span is created when the client is disabled.

func (*EmbedClient) Enabled

func (c *EmbedClient) Enabled() bool

Enabled reports whether an embedding API is configured.

func (*EmbedClient) WithRequestDimensions added in v0.23.0

func (c *EmbedClient) WithRequestDimensions(n int) *EmbedClient

WithRequestDimensions 는 임베딩 요청에 실어 보낼 `dimensions` 값을 설정하고 같은 클라이언트를 돌려준다(체이닝용).

왜 생성자 파라미터가 아니라 별도 메서드인가: NewEmbedClient 의 호출 지점이 프로덕션 1곳 + 테스트 다수라, 파라미터를 하나 더 늘리면 임베딩과 무관한 테스트까지 전부 손봐야 한다. 기본 동작(필드 미전송)을 유지하는 선택적 설정 이므로 옵션 메서드가 더 알맞다.

n 이 0 이하이거나 모델이 dimensions 를 지원하지 않으면 무시한다.

type EmbeddingEngine

type EmbeddingEngine interface {
	// Embed returns the embedding vector for a single text, or nil if the
	// engine is disabled. text may be silently truncated by the implementation
	// before sending to the backend.
	Embed(ctx context.Context, text string) ([]float32, error)

	// EmbedBatch returns embedding vectors for multiple texts in the same
	// order as the input slice. When the engine is disabled every entry is nil.
	EmbedBatch(ctx context.Context, texts []string) ([][]float32, error)

	// Enabled reports whether the engine is configured and operational.
	// When false, Embed and EmbedBatch return nil results without error.
	Enabled() bool

	// Dimension returns the expected vector dimension produced by this engine.
	// The value comes from the configuration (EMBEDDING_DIM) and is advisory:
	// the actual dimension of returned vectors is determined by the backend.
	Dimension() int
}

EmbeddingEngine is the embedding backend abstraction used throughout the application. It is satisfied by *EmbedClient (OpenAI) and *LocalEmbedder (Ollama-compatible). A nil implementation should never be passed; use the disabled-state variants (Enabled()==false) instead.

Implementations must be safe for concurrent use from multiple goroutines.

func NewEmbeddingEngine

func NewEmbeddingEngine(cfg *config.Config) (EmbeddingEngine, error)

NewEmbeddingEngine constructs the appropriate EmbeddingEngine based on cfg.EmbeddingProvider:

  • "openai" (default) → *EmbedClient using the OpenAI-compatible API
  • "local" → *LocalEmbedder using an Ollama-compatible API
  • anything else → error

The returned engine may be in the disabled state (Enabled()==false) when the required configuration keys are not set; callers should check Enabled() before assuming vector search is available.

When the engine's Dimension() does not match cfg.EmbeddingDim a warning is logged but no error is returned — the mismatch is advisory only.

type EntityFetcher

type EntityFetcher interface {
	EntitiesForDocuments(ctx context.Context, docIDs []uuid.UUID) (map[uuid.UUID][]model.Entity, error)
}

EntityFetcher retrieves entities linked to a set of documents. It is satisfied by *store.EntityStore.

type EvalMetrics

type EvalMetrics struct {
	NDCG5  float64 // NDCG@5 macro-average
	NDCG10 float64 // NDCG@10 macro-average
	MRR10  float64 // MRR@10 macro-average
	Pairs  int     // number of query/relevance pairs evaluated
}

EvalMetrics aggregates evaluation metrics over an eval set. Each field is the macro-average over all query/relevance pairs.

func Aggregate

func Aggregate(results [][]string, relevant []map[string]bool) EvalMetrics

Aggregate computes EvalMetrics from parallel slices of results and relevance judgements. results[i] is the ranked result list for query i; relevant[i] is the ground-truth set for query i. The slices must have equal length.

Returns a zero EvalMetrics when the input is empty.

type EvalMetricsProvider

type EvalMetricsProvider interface {
	Latest(ctx context.Context) (*store.EvalMetricsRecord, error)
}

EvalMetricsProvider is the subset of store.EvalMetricsStore used by ReindexChecker. It is satisfied by *store.EvalMetricsStore.

type EvalSnapshot

type EvalSnapshot struct {
	NDCG5  float64
	NDCG10 float64
	MRR10  float64
}

EvalSnapshot holds a point-in-time snapshot of eval metrics for comparison.

type FilteredChunkSearcher added in v0.23.0

type FilteredChunkSearcher interface {
	SearchFTSFiltered(context.Context, model.SearchQuery, int) ([]store.ChunkSearchResult, error)
	SearchVectorFiltered(context.Context, model.SearchQuery, int) ([]store.ChunkSearchResult, error)
}

FilteredChunkSearcher applies source, occurred-time and retention predicates before its SQL LIMIT. Legacy adapters retain conservative post-filtering.

type HTTPReranker

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

HTTPReranker calls a Jina-compatible /rerank endpoint. When apiURL is empty, it acts as a no-op and returns the original order.

func NewHTTPReranker

func NewHTTPReranker(apiURL, apiKey, model string, _ int) *HTTPReranker

NewHTTPReranker creates a reranker backed by the given endpoint. Pass empty apiURL to get a disabled (no-op) reranker. The last argument is retained for constructor compatibility; top_n now follows the bounded input candidate pool so a legacy fixed value cannot silently shrink result pages.

func (*HTTPReranker) Enabled

func (r *HTTPReranker) Enabled() bool

Enabled reports whether a rerank API endpoint is configured.

func (*HTTPReranker) Rerank

func (r *HTTPReranker) Rerank(ctx context.Context, query string, docs []string) ([]RerankResult, error)

Rerank scores each document against the query and returns results ordered by descending relevance score. When the reranker is disabled (empty apiURL) it returns the original order with synthetic scores so callers need not branch.

type InputError added in v0.25.1

type InputError struct {
	// Field 는 요청 스키마 쪽 필드 이름이다(예: "query", "source_type").
	Field string
	// Reason 은 ErrInputTooLong / ErrInputInvalidUTF8 / ErrInputContainsNUL 중 하나다.
	Reason error
	// MaxBytes 는 Reason 이 ErrInputTooLong 일 때 적용된 상한이다.
	MaxBytes int
}

InputError 는 어느 입력 필드가 어떤 사유로 거부됐는지를 담는다.

Error() 는 필드 이름과 고정 사유 문구만 조합하고 입력값 자체는 절대 넣지 않는다. 그래서 이 오류는 그대로 HTTP/GraphQL/MCP 응답 본문에 실어도, 로그에 남겨도 질의 원문(개인정보가 섞일 수 있음)을 노출하지 않는다.

func (*InputError) Error added in v0.25.1

func (e *InputError) Error() string

func (*InputError) Unwrap added in v0.25.1

func (e *InputError) Unwrap() []error

Unwrap 은 상위 오류(ErrInvalidInput)와 구체 사유를 둘 다 노출해, 호출자가 어느 쪽으로든 errors.Is 판별을 할 수 있게 한다.

type LocalEmbedder

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

LocalEmbedder sends embedding requests to an Ollama-compatible local server. The expected API contract is:

POST {endpoint}/api/embeddings
Body: {"model": "<model>", "prompt": "<text>"}
Response: {"embedding": [<float32>, ...]}

When endpoint is empty the embedder is in the disabled state and all methods return nil results without error.

LocalEmbedder satisfies the EmbeddingEngine interface.

func NewLocalEmbedder

func NewLocalEmbedder(endpoint, model string, dim int) *LocalEmbedder

NewLocalEmbedder returns a LocalEmbedder targeting the given Ollama endpoint. endpoint should be the base URL, e.g. "http://localhost:11434". model is the Ollama model name, e.g. "bge-m3". dim is the advisory vector dimension from config (used by Dimension()).

func (*LocalEmbedder) Dimension

func (e *LocalEmbedder) Dimension() int

Dimension returns the advisory vector dimension for this embedder.

func (*LocalEmbedder) Embed

func (e *LocalEmbedder) Embed(ctx context.Context, text string) ([]float32, error)

Embed returns the embedding vector for a single text. Returns nil, nil when the embedder is disabled.

func (*LocalEmbedder) EmbedBatch

func (e *LocalEmbedder) EmbedBatch(ctx context.Context, texts []string) ([][]float32, error)

EmbedBatch returns embedding vectors for multiple texts in input order. Requests are issued sequentially; the loop honours ctx cancellation between iterations so that callers can cancel large batches promptly.

Returns a slice of nil vectors (not an error) when the embedder is disabled.

func (*LocalEmbedder) Enabled

func (e *LocalEmbedder) Enabled() bool

Enabled reports whether the local embedding endpoint is configured.

type OccurredRangeChecker added in v0.23.0

type OccurredRangeChecker interface {
	FilterIDsByOccurredRange(ctx context.Context, ids []uuid.UUID, from, to *time.Time) (map[uuid.UUID]struct{}, error)
}

OccurredRangeChecker verifies event-time membership for legacy chunk adapters which cannot accept SQL filters. Production ChunkStore instead implements FilteredChunkSearcher and narrows candidates before LIMIT.

type OpenSearchClient added in v0.23.0

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

OpenSearchClient queries an OpenSearch index of document chunks analyzed with a Korean morphological (nori) tokenizer, giving this lane a precision property the Postgres pg_bigm (bigram) FTS lane does not have: bigram has no notion of a morpheme boundary, so "회의" matches inside "사회의" and "기회의". Measured against ubuntu1 production data:

query "회의": pg_bigm 865 hits, nori exact-morpheme-match only 184 of them
query "계약": pg_bigm 1,356 hits, nori exact-morpheme-match only 368
query "예약": pg_bigm 1,273 hits, nori exact-morpheme-match only 497

The excess is substring noise that dilutes the candidate pool before a reranker ever sees it. This client does not replace pg_bigm — it is fused into the existing RRF pipeline as one more additive signal, exactly like the chunk vector/FTS lanes in search.go (see WithOpenSearch).

The index this client queries (default name "sb-chunks") is built and maintained OUTSIDE this codebase for now — see deploy/ubuntu1-stack/opensearch/ for the index settings and the bulk script that populates it from the `chunks`/`documents` tables. This client only reads it.

func NewOpenSearchClient added in v0.23.0

func NewOpenSearchClient(baseURL, index string, timeout time.Duration) *OpenSearchClient

NewOpenSearchClient returns a client for the given OpenSearch base URL and index. baseURL == "" produces a disabled client (Enabled() == false); it is still safe to call Search on it, which returns (nil, nil).

timeout <= 0 falls back to 5s. index == "" falls back to "sb-chunks" (the name used by deploy/ubuntu1-stack/opensearch/index-settings.json).

func (*OpenSearchClient) Enabled added in v0.23.0

func (c *OpenSearchClient) Enabled() bool

Enabled reports whether an OpenSearch endpoint is configured. A nil receiver is treated as disabled so that a zero-value *OpenSearchClient (e.g. an unwired field) never panics.

func (*OpenSearchClient) Search added in v0.23.0

func (c *OpenSearchClient) Search(ctx context.Context, q model.SearchQuery, limit int) ([]*model.SearchResult, error)

Search runs a BM25 multi_match query (content + title, title weighted 2x) against the OpenSearch index, applying the SAME include/exclude source-type and occurred_at-window semantics every other lane honours — see buildRequest. Results are chunk-level hits aggregated to the highest-scoring hit per document, sorted by descending score, and truncated to limit: the same shape searchChunksFTS/searchChunksVector return in search.go, ready to fuse via mergeRRF.

A nil/disabled client, an empty query, or limit <= 0 (normalised to the package default) are handled without a request. Every other failure — network error, non-2xx response, malformed JSON, an unparsable document_id — is returned to the caller. search.Service.Search treats an error here as a soft failure: log a warning and drop this lane's contribution, never fail the overall request. See the OpenSearch integration block in Search() for that behaviour; this method never swallows the error itself, so a caller that wants a different policy can still see the real error.

type OpenSearchSearcher added in v0.23.0

type OpenSearchSearcher interface {
	Enabled() bool
	Search(ctx context.Context, q model.SearchQuery, limit int) ([]*model.SearchResult, error)
}

OpenSearchSearcher is the subset of the OpenSearch client used for the BM25 (nori-analyzed) full-text lane. It is satisfied by *OpenSearchClient (see opensearch.go).

Unlike ChunkSearcher, its Search method takes the full model.SearchQuery rather than a bare query/vector — the client applies the window and source-type filters SERVER-SIDE (see buildOpenSearchRequest), which is why this lane needs neither chunkLanesEnabled's fail-closed skip nor verifyWindow's post-hoc check in Service.Search.

func NewOpenSearchLane added in v0.23.0

func NewOpenSearchLane(cfg *config.Config) OpenSearchSearcher

NewOpenSearchLane constructs the OpenSearch BM25 (nori) lane from cfg, or returns nil when cfg.OpensearchURL is empty — THE DEFAULT. A nil return is a true nil interface (not a typed-nil *OpenSearchClient wrapped in an interface), so Service.WithOpenSearch's "s.opensearch != nil" gate in search.go sees it as absent and runs the exact pre-existing code path.

See internal/search/opensearch.go for why this lane exists at all.

type ReindexChecker

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

ReindexChecker evaluates reindex thresholds against live data and returns a recommendation. It never initiates any mutation.

func NewReindexChecker

func NewReindexChecker(
	config ReindexConfig,
	metricsStore EvalMetricsProvider,
	docCounter DocCounter,
	stateStore ReindexStateProvider,
) *ReindexChecker

NewReindexChecker returns a ReindexChecker wired to the provided data sources.

func (*ReindexChecker) Check

Check evaluates all thresholds and returns a recommendation.

Three independent checks are performed:

  1. Eval regression: the latest eval metrics are compared against a regression threshold to detect quality degradation.
  2. New document growth: the total active document count is compared against the doc count recorded at the last reindex.
  3. Staleness: the last reindex timestamp is compared against the configured staleness window.

When no reindex event has been recorded (first run), the system recommends reindexing so that a baseline is established.

func (*ReindexChecker) CheckWithBaseline

func (c *ReindexChecker) CheckWithBaseline(
	ctx context.Context,
	current, baseline EvalSnapshot,
) (ReindexRecommendation, error)

CheckWithBaseline is a convenience method that adds eval regression detection when the caller already holds both the current and baseline metric snapshots. This is the typical path used by cmd/eval.

type ReindexConfig

type ReindexConfig struct {
	// EvalRegressionThreshold is the minimum relative metric drop that triggers
	// a reindex recommendation (e.g. 0.05 = 5%).
	EvalRegressionThreshold float64

	// NewDocThreshold is the minimum number of new documents since the last
	// reindex that triggers a recommendation.
	NewDocThreshold int

	// StalenessDays is the minimum number of days since the last reindex
	// before a staleness recommendation is generated.
	StalenessDays int
}

ReindexConfig holds the threshold configuration for reindex recommendations. All thresholds are evaluated independently; a recommendation is generated when ANY threshold is breached.

func DefaultReindexConfig

func DefaultReindexConfig() ReindexConfig

DefaultReindexConfig returns a ReindexConfig with conservative production defaults.

type ReindexRecommendation

type ReindexRecommendation struct {
	ShouldReindex bool     `json:"should_reindex"`
	Reasons       []string `json:"reasons"`
}

ReindexRecommendation is the output of the threshold check. ShouldReindex is true when at least one threshold has been breached. Reasons lists a human-readable description for each breached threshold.

IMPORTANT: This is a recommendation only. The system NEVER auto-executes reindexing; the operator must trigger it manually ("완전 자율 금지").

type ReindexStateProvider

type ReindexStateProvider interface {
	Latest(ctx context.Context) (*store.ReindexState, error)
}

ReindexStateProvider is the subset of store.ReindexStateStore used by ReindexChecker. It is satisfied by *store.ReindexStateStore.

type RerankResult

type RerankResult struct {
	Index int     `json:"index"`
	Score float64 `json:"relevance_score"`
}

RerankResult holds the reranked position and score for a document.

type Reranker

type Reranker interface {
	Enabled() bool
	Rerank(ctx context.Context, query string, docs []string) ([]RerankResult, error)
}

Reranker scores query-document pairs and returns results sorted by relevance.

type SearchTrace added in v0.23.0

type SearchTrace struct {
	// PoolIDs 는 페이지 크기(q.Limit)로 잘라내기 직전의 후보 풀 순서다.
	// 여기에 있는데 최종 결과에 없다면 "검색은 찾았지만 10위 밖" 이고,
	// 여기에도 없다면 "아예 회수되지 않음" 이다 — 전혀 다른 결함이다.
	PoolIDs []uuid.UUID
	// PreRerankIDs 는 리랭커에 넘기기 직전의 순서. 리랭크를 시도하지 않았으면 nil.
	PreRerankIDs []uuid.UUID
	// FusedIDs 는 융합·최신성 감쇠까지 끝나고 리랭크 합산이 개입하기 직전의
	// 순서다. PreRerankIDs 와 달리 리랭크를 하지 않은 실행에서도 채워진다 —
	// "리랭커가 순위를 올렸나 내렸나" 는 이 순서와의 차이로만 답할 수 있고,
	// 리랭크를 끈 실행과 켠 실행을 같은 기준으로 비교하려면 양쪽 모두에
	// 같은 기준선이 있어야 한다.
	FusedIDs []uuid.UUID
	// LaneHits 는 문서별로 그 문서를 후보로 올린 레인 이름 목록이다.
	LaneHits map[uuid.UUID][]string
	// RerankRequested 는 질의가 리랭크를 요청했는지, RerankAttempted 는
	// 리랭커가 실제로 호출됐는지(설정·정렬 조건을 모두 통과했는지),
	// RerankFailed 는 그 호출이 실패해 원래 순서로 되돌아갔는지를 뜻한다.
	RerankRequested bool
	RerankAttempted bool
	RerankFailed    bool
}

SearchTrace 는 Search 한 번에 대한 진단 기록이다. "왜 이 문서가 상위에 없었나"를 답하는 데 필요한 최소 증거만 담는다.

제목·본문·질의 텍스트는 의도적으로 담지 않는다. 이 구조체는 평가 도구가 파일로 떨구는 값이고, 그 파일에 개인정보가 섞이는 순간 진단 산출물 전체가 취급 곤란해진다. 식별자·순위·레인 이름까지만 남긴다.

type Service

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

Service performs hybrid search: it enriches queries with embeddings when available, then delegates to the document store. When chunks are available, chunk-based FTS is used as a fallback for full-document FTS. HyDE (Hypothetical Document Embeddings) can be enabled per-request to improve recall for short or ambiguous queries.

func AssembleService added in v0.23.0

func AssembleService(doc DocumentSearcher, embed EmbeddingEngine, chunks ChunkSearcher,
	reranker Reranker, entities EntityFetcher, openSearch OpenSearchSearcher,
	completer llm.Completer, weights ActiveWeightsReader, activeWeights bool) *Service

AssembleService is the common retrieval wiring for HTTP, MCP and offline evaluation. Query-level options (e.g. reranking) remain explicit per request.

func NewService

func NewService(store DocumentSearcher, embed EmbeddingEngine) *Service

NewService returns a search Service. Use WithChunkStore to enable chunk-based FTS search (issue #9).

func (*Service) RerankStats added in v0.23.0

func (s *Service) RerankStats() (attempts, failures int64)

RerankStats 는 이 서비스가 살아 있는 동안 실제로 리랭커를 호출한 횟수와 그중 실패한 횟수를 돌려준다. 요청 설정(UseRerank)만으로는 원격 리랭커가 동작했는지 알 수 없다는 평가 프로토콜의 지적에 대한 실측값이다.

func (*Service) Search

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

Search executes a search for the given query. If an embedding client is configured, the query text is embedded and the result is used for hybrid (RRF) search; otherwise only full-text search is performed.

Insight documents are excluded by default on every lane; see applyInsightExclusionDefault.

When q.UseHyDE is true and an LLM client is configured, the query is expanded via HyDE (Hypothetical Document Embeddings) before retrieval. HyDE adds ~1-3 s of latency due to an additional LLM round-trip; it is opt-in and disabled by default.

Chunk signals (vector + FTS) are fused into the RRF result set when a chunkStore is configured (issue #71). Full-document retrieval is always attempted first; chunk signals are additive and never replace it.

When the primary path returns no results AND a chunk store is configured, chunk-based FTS is attempted as a final fallback strategy.

func (*Service) SearchTraced added in v0.23.0

func (s *Service) SearchTraced(ctx context.Context, q model.SearchQuery) ([]*model.SearchResult, *SearchTrace, error)

SearchTraced 는 Search 와 완전히 같은 검색을 수행하면서 진단 기록을 함께 돌려준다. 결과 슬라이스는 Search 가 돌려주는 것과 동일하다 — 추적은 읽기만 할 뿐 순위·후보에 손대지 않는다. 평가 도구(cmd/eval --dump)용 경로다.

func (*Service) WithActiveWeights added in v0.23.0

func (s *Service) WithActiveWeights(r ActiveWeightsReader, enabled bool) *Service

WithActiveWeights makes the promoted row in search_weights_history the default RRF weighting for every request that does not carry its own.

enabled is passed in rather than inferred so that "off" means the table is never queried at all — not queried and ignored. Off is the default for the deployment (SEARCH_ACTIVE_WEIGHTS_ENABLED, see internal/config): an active row is a configuration that was validated against a holdout set SOMEWHERE, and a deployment that has not opted in should not start serving it because a row appeared. It is also the rollback of last resort — unset the variable, restart, and the compiled defaults are back regardless of the table's state.

Safe to call with a nil reader; the lookup is skipped exactly as if the flag were off.

func (*Service) WithChunkStore

func (s *Service) WithChunkStore(cs ChunkSearcher) *Service

WithChunkStore attaches a ChunkSearcher so that the service can perform chunk-based FTS and vector search.

Chunk signals are incorporated into the RRF fusion as additional retrieval sources alongside the full-document path (issue #71). The full-document path is preserved to avoid regression: chunk vector + chunk FTS are additive.

When the primary path (full-document FTS + vector) returns no results, chunk FTS is attempted as a secondary fallback strategy.

func (*Service) WithEntityFetcher

func (s *Service) WithEntityFetcher(ef EntityFetcher) *Service

WithEntityFetcher attaches an entity store so that named entities extracted from the returned documents are populated in SearchResult.Entities. This is ADDITIVE and omitempty — existing consumers are unaffected when the field is nil. Safe to call with nil — surfacing is silently skipped.

func (*Service) WithLLM

func (s *Service) WithLLM(client llm.Completer) *Service

WithLLM attaches an LLM client used for HyDE (Hypothetical Document Embeddings) query expansion. When set, callers may opt in to HyDE by setting UseHyDE in SearchOptions. Safe to call with a nil client.

func (*Service) WithOccurredRangeChecker added in v0.23.0

func (s *Service) WithOccurredRangeChecker(c OccurredRangeChecker) *Service

WithOccurredRangeChecker attaches the verifier used to keep the chunk lanes alive under an event-time window. Callers whose document store already implements OccurredRangeChecker — which *store.DocumentStore does — do not need to call this; occurredRangeChecker() discovers it. Safe to call with nil.

func (*Service) WithOpenSearch added in v0.23.0

func (s *Service) WithOpenSearch(c OpenSearchSearcher) *Service

WithOpenSearch attaches the BM25 (nori-analyzed) full-text lane. Safe to call with nil — the lane is then simply not run, and Search() behaves exactly as it did before this lane existed. Disabled by DEFAULT: nothing calls this unless OPENSEARCH_URL is set (see factory.NewOpenSearchLane and cmd/server/main.go).

func (*Service) WithReranker

func (s *Service) WithReranker(r Reranker) *Service

WithReranker attaches a cross-encoder reranker that post-processes search results when q.UseRerank is true. Safe to call with nil — reranking is silently skipped when the reranker is nil or disabled.

func (*Service) WithTuning added in v0.23.0

func (s *Service) WithTuning(t model.SearchTuning) *Service

WithTuning 은 이 서비스의 기본 노브를 덮어쓴다. 환경변수보다 우선하며, 개별 요청의 SearchQuery.Tuning 은 다시 이것보다 우선한다. 평가 도구 (cmd/eval)가 플래그로 실험 설정을 주입하는 경로다.

func (*Service) WithWeights

func (s *Service) WithWeights(w model.SearchWeights) *Service

WithWeights sets the RRF fusion weights applied to every search request issued through this service. Zero fields fall back to defaults (k=60, all signal weights = 1.0). Weights are applied per-request and do not affect the store configuration directly.

type SparseContextSearcher added in v0.24.0

type SparseContextSearcher interface {
	SearchSparseContextFiltered(ctx context.Context, q model.SearchQuery, limit int, version string) ([]store.ChunkSearchResult, error)
}

SparseContextSearcher is the subset of the chunk store the fuse_ctx lane needs (#270 phase B, migration 040). Implemented by *store.ChunkStore (chunk_sparse_search.go); a chunk store that does not implement it — legacy adapters, the askeval fake corpus — simply never contributes this lane (see fuseChunkSparseCtx's type assertion), the same graceful-skip pattern FilteredChunkSearcher already uses elsewhere in this package.

Jump to

Keyboard shortcuts

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