package semantic import ( "context" "errors" "fmt" "regexp" "strconv" "time" "github.com/google/uuid" "lincodex/backend/internal/port/outbound" ) // BackfillPageSize is the number of subjects one backfill transaction // schedules. const BackfillPageSize = 200 var backfillRunPattern = regexp.MustCompile(`^[a-z0-9-]{1,32}$`) // BackfillScope selects what a backfill schedules. type BackfillScope string const ( BackfillCandidates BackfillScope = "candidates" BackfillNeeds BackfillScope = "needs" ) // BackfillProgress reports one finished page: how many jobs it scheduled // and the cursor to resume after. type BackfillProgress struct { Scope BackfillScope Scheduled int After uuid.UUID Done bool } // Backfill schedules vector jobs for every candidate with a saved profile or // every need, page by page in identifier order. The job of a candidate who is // not published removes any stored vectors, so the backfill also cleans up. // A run label makes the job keys, so repeating a run schedules nothing twice, // and a new label recomputes again; a job whose texts did not change costs no // ML call. The cursor of the last page resumes an interrupted run. type Backfill struct { transactor outbound.Transactor clock func() time.Time } // NewBackfill returns the backfill. func NewBackfill(transactor outbound.Transactor, clock func() time.Time) (*Backfill, error) { if transactor == nil || clock == nil { return nil, errors.New("semantic.NewBackfill - transactor and clock must be set") } return &Backfill{transactor: transactor, clock: clock}, nil } // Run schedules pages until the scope is exhausted and reports each page. func (backfill *Backfill) Run( ctx context.Context, scope BackfillScope, run string, after uuid.UUID, report func(BackfillProgress) error, ) error { const location = "semantic.Backfill.Run" if !backfillRunPattern.MatchString(run) { return errors.New(location + " - run label must be 1 to 32 lower-case letters, digits, or hyphens") } if scope != BackfillCandidates && scope != BackfillNeeds { return errors.New(location + " - scope must be candidates or needs") } cursor := after for { progress, err := backfill.page(ctx, scope, run, cursor) if err != nil { return fmt.Errorf("%s - schedule page: %w", location, err) } if report != nil { if err := report(progress); err != nil { return err } } if progress.Done { return nil } cursor = progress.After } } func (backfill *Backfill) page(ctx context.Context, scope BackfillScope, run string, after uuid.UUID) (BackfillProgress, error) { progress := BackfillProgress{Scope: scope, After: after} err := backfill.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { at := backfill.clock().UTC() if scope == BackfillCandidates { ids, err := unit.SemanticVectors().CandidatesAfter(ctx, after, BackfillPageSize) if err != nil { return err } for _, id := range ids { if err := schedule(ctx, unit, CandidateJobKind, id.String()+":backfill-"+run, at, map[string]string{"candidate_id": id.String()}, vectorJobAttempts); err != nil { return err } progress.After = id } progress.Scheduled, progress.Done = len(ids), len(ids) < BackfillPageSize return nil } needs, err := unit.SemanticVectors().NeedsAfter(ctx, after, BackfillPageSize) if err != nil { return err } for _, need := range needs { key := need.NeedID.String() + ":" + strconv.FormatInt(need.RequirementsVersion, 10) + ":backfill-" + run if err := schedule(ctx, unit, NeedJobKind, key, at, map[string]any{ "organization_id": need.OrganizationID.String(), "need_id": need.NeedID.String(), "requirements_version": need.RequirementsVersion, }, vectorJobAttempts); err != nil { return err } progress.After = need.NeedID } progress.Scheduled, progress.Done = len(needs), len(needs) < BackfillPageSize return nil }) return progress, err }