scheduler

package
v0.25.1 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: MIT Imports: 17 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 scheduler periodically triggers collectors and persists the resulting documents.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrSlackCollectorNotFound = fmt.Errorf("slack collector not configured")
	ErrSlackChannelNotFound   = fmt.Errorf("channel not found in bot member list")
)

Sentinel errors for Slack channel operations.

Functions

This section is empty.

Types

type ActiveDocumentCounter added in v0.19.4

type ActiveDocumentCounter interface {
	CountActiveDocuments(ctx context.Context, sourceType model.SourceType) (int, error)
}

ActiveDocumentCounter is retained for backward compatibility and for use by external callers that only need the count method (e.g. collection_status store query). It is now also satisfied by any DocumentUpserter implementation since CountActiveDocuments is a required method on that interface (#148).

type DocumentUpserter

type DocumentUpserter interface {
	Upsert(ctx context.Context, doc *model.Document) error
	LastCollectedAt(ctx context.Context, instanceID string, src model.SourceType, fallback time.Time) time.Time
	UpdateCollectorState(ctx context.Context, instanceID string, src model.SourceType, lastCollectedAt time.Time) error
	RecordCollectionLog(ctx context.Context, src model.SourceType, started time.Time, count int, err error) error
	MarkDeleted(ctx context.Context, sourceType model.SourceType, activeIDs []string) (int, error)
	// CountActiveDocuments returns the number of active (non-deleted) documents for
	// the given source type. Required for the deletion-ratio sanity check (#148):
	// promoting this from an optional type-assertion to a required interface method
	// ensures the guard is always enforced at compile time — no store can silently
	// bypass the ratio check by omitting the method.
	CountActiveDocuments(ctx context.Context, sourceType model.SourceType) (int, error)
	// ListUnembedded returns up to limit active documents with a NULL embedding.
	ListUnembedded(ctx context.Context, limit int) ([]*model.Document, error)
	// ListDocumentsNeedingEmbedding 은 임베딩이 없거나 currentVersion 과 다른
	// 버전으로 만들어진 활성 문서를 돌려준다. currentVersion 이 빈 문자열이면
	// ListUnembedded 와 같다. 선택 메서드가 아니라 필수 메서드로 둔 이유는
	// CountActiveDocuments(#148) 와 같다 — 타입 어서션으로 두면 어떤 구현체가
	// 조용히 재임베딩을 건너뛰어도 컴파일 단계에서 드러나지 않는다.
	ListDocumentsNeedingEmbedding(ctx context.Context, limit int, currentVersion string) ([]*model.Document, error)
	// UpdateEmbedding persists the embedding vector for a single document.
	UpdateEmbedding(ctx context.Context, doc *model.Document) error
	// ActiveSourceIDSet returns the set of source_ids currently active in the
	// store for the given source type. Used by the filesystem collector to detect
	// files that are new (not yet indexed) regardless of their mtime.
	ActiveSourceIDSet(ctx context.Context, sourceType model.SourceType) (map[string]struct{}, error)
	// TranscribedSourceIDSet returns the set of source_ids the whisper pipeline
	// has already transcribed (transcription_ledger), regardless of whether the
	// resulting document was stored or rejected as a duplicate. Unioned with
	// ActiveSourceIDSet to build the authoritative "do NOT re-transcribe" set —
	// this fixes the infinite re-transcription loop for immutable audio.
	TranscribedSourceIDSet(ctx context.Context, sourceType model.SourceType) (map[string]struct{}, error)
	// RecordTranscribed durably records that the given source_ids were
	// transcribed for the source type. Idempotent (ON CONFLICT DO NOTHING),
	// no-op on empty input. Called per batch so duplicate-rejected files are
	// ledgered and never re-transcribed.
	RecordTranscribed(ctx context.Context, sourceType model.SourceType, sourceIDs []string) error
	// AttachTranscript merges a whisper transcript into an existing call
	// document (see model.SourceCall / store.AttachTranscript doc comments):
	// content/embedding are replaced, metadata is merged (not overwritten),
	// title/occurred_at are preserved when already set. Used instead of
	// Upsert whenever a batch document carries
	// metadata["transcript_source_id"] — WhisperCollector's signal that this
	// document should merge into the call-log document rather than become a
	// second, unlinked one. Returns contentChanged like UpsertTracked.
	AttachTranscript(ctx context.Context, doc *model.Document) (contentChanged bool, err error)
}

DocumentUpserter is the subset of the document store used by the scheduler.

type EntityExtractor

type EntityExtractor interface {
	UpsertAndLinkEntities(ctx context.Context, documentID uuid.UUID, entities []model.Entity) error
}

EntityExtractor is the subset of the entity store used by the scheduler to trigger best-effort entity extraction immediately after document ingestion. It is satisfied by *store.EntityStore.

type IntervalPreferrer added in v0.20.0

type IntervalPreferrer interface {
	PreferredInterval() time.Duration
}

IntervalPreferrer is an optional interface that a Collector may implement to advertise its preferred collection interval. When implemented, the scheduler uses this interval instead of the global COLLECT_INTERVAL for that collector.

This enables per-source freshness SLAs without changing the base Collector interface (#143): push-based sources (SMS, recording ingest) can use a longer interval, while high-frequency sources (Whisper) can use a shorter one. Collectors that do not implement this interface default to the global interval.

type Scheduler

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

Scheduler wraps robfig/cron and manages periodic collection runs.

func New

func New(store DocumentUpserter, embed search.EmbeddingEngine, collectors ...collector.Collector) *Scheduler

New returns a Scheduler with the given collectors and storage backend. Use WithChunkStore to enable chunk-based FTS indexing (issue #9).

func (*Scheduler) Collectors

func (s *Scheduler) Collectors() []collector.Collector

Collectors returns the list of registered collectors (for status reporting).

func (*Scheduler) ForceCollectSlackChannel

func (s *Scheduler) ForceCollectSlackChannel(ctx context.Context, channelID, channelName string) (int, error)

ForceCollectSlackChannel runs a full-history collection (since = zero time) for a single Slack channel and persists the resulting documents. It bypasses the source-level LastCollectedAt and is intended for manual POST /api/v1/collect/slack/channel calls.

If channelID is empty, channelName is used to resolve the ID via the Slack API (the bot must be a member of the channel).

Returns the number of upserted documents and any error.

func (*Scheduler) LookupSlackChannel

func (s *Scheduler) LookupSlackChannel(ctx context.Context, name string) (id, channelName string, err error)

LookupSlackChannel resolves a channel name (case-insensitive, "#" stripped) to its Slack channel ID by querying the channels the bot is a member of. Returns ErrSlackCollectorNotFound when no Slack collector is configured, ErrSlackChannelNotFound when the name does not match any member channel.

func (*Scheduler) Register

func (s *Scheduler) Register(interval time.Duration, perSource ...map[string]time.Duration) error

Register adds ONE cron job PER enabled collector.

The interval for each collector is resolved in this order:

  1. Per-source env var: COLLECT_INTERVAL_<NAME> (upper-cased collector name, hyphens and spaces replaced with underscores). E.g. COLLECT_INTERVAL_WHISPER.
  2. Collector implements IntervalPreferrer → uses PreferredInterval().
  3. Global interval (the interval argument).

Cron runs each job in its own goroutine, so distinct collectors execute concurrently. A given collector still skips its own overlapping tick via a per-collector try-lock (runningPerCollector). This eliminates the head-of-line blocking that occurred when a single global job ran all collectors sequentially: a slow gmail backfill (~60 min) no longer prevents calendar, whisper, or SMS collectors from running on their scheduled ticks.

The old single-job / single-lock design that fixed the starvation bug is preserved in runAll, which is still used by TriggerAll.

func (*Scheduler) Start

func (s *Scheduler) Start()

Start begins the cron scheduler. It is non-blocking.

func (*Scheduler) Stop

func (s *Scheduler) Stop()

Stop gracefully halts the scheduler and waits for running jobs to finish.

func (*Scheduler) TriggerAll

func (s *Scheduler) TriggerAll(ctx context.Context)

TriggerAll runs all enabled collectors immediately in the background, each in its own goroutine under its own per-collector lock. It is intended for manual /collect/trigger API calls. Collectors already running on their scheduled tick are skipped for the duration of that overlap; others proceed immediately.

func (*Scheduler) WithChunkStore

func (s *Scheduler) WithChunkStore(cs *store.ChunkStore) *Scheduler

WithChunkStore attaches a ChunkStore so that each collected document is split into overlapping text chunks and stored in the chunks table for FTS indexing. When not called, chunk storage is disabled and the scheduler behaves as before (full-document FTS via documents.tsv only).

func (*Scheduler) WithCutover added in v0.16.4

func (s *Scheduler) WithCutover(t time.Time) *Scheduler

WithCutover sets the cutover floor time that is propagated to every CutoverAwareCollector (SMS, Whisper) registered with this scheduler. When non-zero, those collectors will not emit records whose event time (OccurredAt for SMS/call-log, mtime for Whisper) is before t — even when the record was never indexed (IndexAware path).

Zero t (the default) disables the floor entirely (no behaviour change).

func (*Scheduler) WithDeletionRatioOverride added in v0.20.0

func (s *Scheduler) WithDeletionRatioOverride(enabled bool) *Scheduler

WithDeletionRatioOverride enables the escape hatch for the deletion-ratio guard. When enabled=true, the 50% ratio check is skipped for the current scheduler instance — MarkDeleted will run regardless of the deletion fraction.

Use this ONLY when you are certain that a legitimate large-scale deletion (>50% of a source's documents) needs to proceed. The guard exists to prevent accidental bulk data-loss caused by partially unmounted or glitching filesystems; bypassing it removes that protection.

A warning is always logged when the override is active so that the bypass is visible in production logs. This is an intentional audit trail.

Source: DELETION_RATIO_OVERRIDE=true in the environment (parsed in cmd/collector).

func (*Scheduler) WithEmbeddingVersion added in v0.23.0

func (s *Scheduler) WithEmbeddingVersion(modelName string, dimensions int) *Scheduler

WithEmbeddingVersion 은 이 스케줄러가 만드는 벡터에 찍을 버전 식별자를 설정한다. model/dimensions 는 설정값(EMBEDDING_MODEL / EMBEDDING_DIMENSIONS) 을 그대로 넘기면 된다.

설정하지 않으면(빈 model) 버전을 기록하지 않으므로 재임베딩 선별도 동작하지 않는다 — 배선 누락이 조용한 전량 재임베딩으로 번지지 않도록 한 안전 기본값이다.

func (*Scheduler) WithEntityExtraction

func (s *Scheduler) WithEntityExtraction(entities EntityExtractor, client llm.Completer) *Scheduler

WithEntityExtraction attaches the entity store and LLM client so that entity extraction is attempted inline after each document is persisted.

This method should only be called when entity extraction is explicitly enabled (ENTITY_EXTRACTION_ENABLED=true in cmd/collector/main.go). When not called, s.entities and s.llmClient remain nil and the extractEntities call in processBatch is skipped entirely — zero LLM calls are made.

Extraction is BEST-EFFORT: failures are logged as warnings and never block document ingestion. Safe to call with nil arguments — extraction is silently disabled in that case.

func (*Scheduler) WithInstance

func (s *Scheduler) WithInstance(id string) *Scheduler

WithInstance sets the collector instance identifier used to key per-instance watermark state. Defaults to "default" when not called.

func (*Scheduler) WithStaleReembedding added in v0.23.0

func (s *Scheduler) WithStaleReembedding(enabled bool) *Scheduler

WithStaleReembedding 은 "현재 버전과 다른 벡터를 다시 만들지" 여부를 정한다 (EMBEDDING_REEMBED_ENABLED). 기본은 false.

켜면 백필이 매 수집 사이클마다 구버전 문서·청크를 배치 단위로 다시 임베딩 한다. 전체 코퍼스를 한 번 훑는 동안은 새 벡터와 옛 벡터가 같은 인덱스에 섞여 있으므로(= 거리 비교가 부분적으로만 의미 있는 상태) 그 사실을 사이클 마다 경고 로그로 남긴다. 검색을 막지는 않는다 — 막으면 재임베딩이 끝날 때까지 서비스가 통째로 멈춘다.

Jump to

Keyboard shortcuts

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