diff --git a/backend/README.md b/backend/README.md index 4c886a8..2acfd68 100644 --- a/backend/README.md +++ b/backend/README.md @@ -290,12 +290,18 @@ throughout (`graph/schema/job_lead.graphql`, all `@admin`) with the work in for the backlog a first poll of several boards leaves behind, or leads that arrived before the profile was written. A lead that fails is tried once per press. It stops after an hour; pressing again continues. +- **Rescoring.** The `rescoreJobLeads` mutation (`RescoreAll`, "Rescore all" + on the page) scores every matched inbox lead again, for after the profile + or `CLAUDE_MODEL` has changed. It does not wipe scores first: a lead keeps + its old score until the new one is saved, and `scored_at` is what marks a + lead as done by this job. A job that fails partway leaves a mix of old and + new scores, and pressing again starts over. - **When it runs.** `JOB_LEADS_ENABLED=true` starts a timer (`JOB_LEADS_INTERVAL`, default `6h`); it does not run at start-up, so a deploy spends nothing. The `runJobLeadSync` mutation starts a run in a goroutine and returns at once, whether or not the timer is on, and - `jobLeadSyncStatus` reports on it (and on `scoreJobLeads`; only one of - the two jobs runs at a time) — a run can take minutes, so unlike + `jobLeadSyncStatus` reports on it (and on `scoreJobLeads` and + `rescoreJobLeads`; only one of the three jobs runs at a time) — a run can take minutes, so unlike `POST /email/sync` it does not hold the request open. The status is in memory and resets on restart. - **Promotion** (`promoteJobLead`) is the only way a lead reaches the tracker. diff --git a/backend/graph/generated.go b/backend/graph/generated.go index ba31697..b56ff4c 100644 --- a/backend/graph/generated.go +++ b/backend/graph/generated.go @@ -121,6 +121,7 @@ type ComplexityRoot struct { PostedAt func(childComplexity int) int Score func(childComplexity int) int ScoreReasons func(childComplexity int) int + ScoredAt func(childComplexity int) int SourceKind func(childComplexity int) int State func(childComplexity int) int URL func(childComplexity int) int @@ -187,6 +188,7 @@ type ComplexityRoot struct { Logout func(childComplexity int) int PromoteJobLead func(childComplexity int, id int) int RefreshToken func(childComplexity int) int + RescoreJobLeads func(childComplexity int) int RestoreJobLead func(childComplexity int, id int) int RunJobLeadSync func(childComplexity int) int ScoreJobLeads func(childComplexity int) int @@ -340,6 +342,7 @@ type MutationResolver interface { UpdateJobSearchProfile(ctx context.Context, input model.UpdateJobSearchProfileInput) (*models.JobSearchProfile, error) RunJobLeadSync(ctx context.Context) (bool, error) ScoreJobLeads(ctx context.Context) (bool, error) + RescoreJobLeads(ctx context.Context) (bool, error) CreatePlace(ctx context.Context, input model.CreatePlaceInput) (*models.Place, error) UpdatePlace(ctx context.Context, id int, input model.UpdatePlaceInput) (*models.Place, error) DeletePlace(ctx context.Context, id int) (*models.Place, error) @@ -736,6 +739,12 @@ func (e *executableSchema) Complexity(ctx context.Context, typeName, field strin } return e.ComplexityRoot.JobLead.ScoreReasons(childComplexity), true + case "JobLead.scoredAt": + if e.ComplexityRoot.JobLead.ScoredAt == nil { + break + } + + return e.ComplexityRoot.JobLead.ScoredAt(childComplexity), true case "JobLead.sourceKind": if e.ComplexityRoot.JobLead.SourceKind == nil { break @@ -1142,6 +1151,12 @@ func (e *executableSchema) Complexity(ctx context.Context, typeName, field strin } return e.ComplexityRoot.Mutation.RefreshToken(childComplexity), true + case "Mutation.rescoreJobLeads": + if e.ComplexityRoot.Mutation.RescoreJobLeads == nil { + break + } + + return e.ComplexityRoot.Mutation.RescoreJobLeads(childComplexity), true case "Mutation.restoreJobLead": if e.ComplexityRoot.Mutation.RestoreJobLead == nil { break @@ -1999,6 +2014,8 @@ func (ec *executionContext) childFields_JobLead(ctx context.Context, field graph return ec.fieldContext_JobLead_score(ctx, field) case "scoreReasons": return ec.fieldContext_JobLead_scoreReasons(ctx, field) + case "scoredAt": + return ec.fieldContext_JobLead_scoredAt(ctx, field) case "jobAppId": return ec.fieldContext_JobLead_jobAppId(ctx, field) } @@ -4263,6 +4280,29 @@ func (ec *executionContext) fieldContext_JobLead_scoreReasons(_ context.Context, return graphql.NewScalarFieldContext("JobLead", field, false, false, errors.New("field of type String does not have child fields")) } +func (ec *executionContext) _JobLead_scoredAt(ctx context.Context, field graphql.CollectedField, obj *models.JobLead) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return ec.fieldContext_JobLead_scoredAt(ctx, field) + }, + func(ctx context.Context) (any, error) { + return obj.ScoredAt, nil + }, + nil, + func(ctx context.Context, selections ast.SelectionSet, v *time.Time) graphql.Marshaler { + return ec.marshalOTime2ᚖtimeᚐTime(ctx, selections, v) + }, + true, + false, + ) +} +func (ec *executionContext) fieldContext_JobLead_scoredAt(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + return graphql.NewScalarFieldContext("JobLead", field, false, false, errors.New("field of type Time does not have child fields")) +} + func (ec *executionContext) _JobLead_jobAppId(ctx context.Context, field graphql.CollectedField, obj *models.JobLead) (ret graphql.Marshaler) { return graphql.ResolveField( ctx, @@ -6047,6 +6087,42 @@ func (ec *executionContext) fieldContext_Mutation_scoreJobLeads(_ context.Contex return graphql.NewScalarFieldContext("Mutation", field, true, true, errors.New("field of type Boolean does not have child fields")) } +func (ec *executionContext) _Mutation_rescoreJobLeads(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return ec.fieldContext_Mutation_rescoreJobLeads(ctx, field) + }, + func(ctx context.Context) (any, error) { + return ec.Resolvers.Mutation().RescoreJobLeads(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + if ec.Directives.Admin == nil { + var zeroVal bool + return zeroVal, errors.New("directive admin is not implemented") + } + return ec.Directives.Admin(ctx, nil, directive0) + } + + next = directive1 + return next + }, + func(ctx context.Context, selections ast.SelectionSet, v bool) graphql.Marshaler { + return ec.marshalNBoolean2bool(ctx, selections, v) + }, + true, + true, + ) +} +func (ec *executionContext) fieldContext_Mutation_rescoreJobLeads(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + return graphql.NewScalarFieldContext("Mutation", field, true, true, errors.New("field of type Boolean does not have child fields")) +} + func (ec *executionContext) _Mutation_createPlace(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { return graphql.ResolveField( ctx, @@ -11223,6 +11299,11 @@ func (ec *executionContext) _JobLead(ctx context.Context, sel ast.SelectionSet, if out.Values[i] == graphql.RequiredNull { out.Invalids++ } + case "scoredAt": + out.Values[i] = ec._JobLead_scoredAt(ctx, field, obj) + if out.Values[i] == graphql.RequiredNull { + out.Invalids++ + } case "jobAppId": out.Values[i] = ec._JobLead_jobAppId(ctx, field, obj) if out.Values[i] == graphql.RequiredNull { @@ -11723,6 +11804,13 @@ func (ec *executionContext) _Mutation(ctx context.Context, sel ast.SelectionSet) if out.Values[i] == graphql.Null { out.Invalids++ } + case "rescoreJobLeads": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_rescoreJobLeads(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } case "createPlace": out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_createPlace(ctx, field) diff --git a/backend/graph/job_lead.resolvers.go b/backend/graph/job_lead.resolvers.go index b9866b0..2adba73 100644 --- a/backend/graph/job_lead.resolvers.go +++ b/backend/graph/job_lead.resolvers.go @@ -144,7 +144,7 @@ func (r *mutationResolver) RunJobLeadSync(ctx context.Context) (bool, error) { if r.Store.JobLeads == nil { return false, fmt.Errorf("job leads are not configured") } - return r.Store.JobLeads.RunInBackground(false), nil + return r.Store.JobLeads.RunInBackground(services.LeadJobSync), nil } // ScoreJobLeads is the resolver for the scoreJobLeads field. @@ -152,7 +152,15 @@ func (r *mutationResolver) ScoreJobLeads(ctx context.Context) (bool, error) { if r.Store.JobLeads == nil { return false, fmt.Errorf("job leads are not configured") } - return r.Store.JobLeads.RunInBackground(true), nil + return r.Store.JobLeads.RunInBackground(services.LeadJobScore), nil +} + +// RescoreJobLeads is the resolver for the rescoreJobLeads field. +func (r *mutationResolver) RescoreJobLeads(ctx context.Context) (bool, error) { + if r.Store.JobLeads == nil { + return false, fmt.Errorf("job leads are not configured") + } + return r.Store.JobLeads.RunInBackground(services.LeadJobRescore), nil } // JobSources is the resolver for the jobSources field. @@ -176,7 +184,7 @@ func (r *queryResolver) JobLeads(ctx context.Context, state *string, includeUnma if includeUnmatched == nil || !*includeUnmatched { // A promoted or dismissed lead is shown whatever the filter now says // about it; `matched` only decides what the inbox offers. - query = query.Where("matched = ? OR state <> ?", true, services.LeadNew) + query = query.Where("(matched = ? OR state <> ?)", true, services.LeadNew) } var leads []*models.JobLead // Best first, unscored after scored, newest first within a score. The diff --git a/backend/graph/schema/job_lead.graphql b/backend/graph/schema/job_lead.graphql index 76ddff7..9e129dd 100644 --- a/backend/graph/schema/job_lead.graphql +++ b/backend/graph/schema/job_lead.graphql @@ -67,6 +67,7 @@ type JobLead { state: String! score: Int scoreReasons: String + scoredAt: Time jobAppId: ID } @@ -135,4 +136,10 @@ extend type Mutation { # source. Background and polled like runJobLeadSync, and refused (false) # while either is running. scoreJobLeads: Boolean! @admin + + # Scores every matched inbox lead again, scored or not, for after the + # profile or the model has changed. A lead keeps its old score until its + # new one arrives. Background and polled like the two above, and refused + # (false) while any of the three is running. + rescoreJobLeads: Boolean! @admin } diff --git a/backend/models/models.go b/backend/models/models.go index 74274ed..5a1d47d 100644 --- a/backend/models/models.go +++ b/backend/models/models.go @@ -291,8 +291,10 @@ type JobSource struct { // Matched says whether the lead passed the keyword pre-filter the last time // the fetcher ran; only matched leads are shown by default and only they are // scored. Score (0-100) and ScoreReasons are Claude's, and nil until scored. -// ScoreAttempts counts failed tries, so a posting Claude can never score -// stops costing a call per run. +// ScoredAt is when that score was given, which is how a rescore tells the +// leads it has redone from the ones it has yet to reach; it is nil on a lead +// scored before the column existed. ScoreAttempts counts failed tries, so a +// posting Claude can never score stops costing a call per run. type JobLead struct { ID uint `gorm:"primarykey" json:"id"` CreatedAt time.Time `json:"createdAt"` @@ -311,6 +313,7 @@ type JobLead struct { State string `gorm:"not null;default:new;index" json:"state"` Score *int `json:"score"` ScoreReasons *string `json:"scoreReasons"` + ScoredAt *time.Time `json:"scoredAt"` ScoreAttempts int `gorm:"not null;default:0" json:"scoreAttempts"` JobAppID *uint `json:"jobAppId"` } diff --git a/backend/services/job_leads.go b/backend/services/job_leads.go index b818933..f29999d 100644 --- a/backend/services/job_leads.go +++ b/backend/services/job_leads.go @@ -162,18 +162,32 @@ func (s *JobLeadService) StartScheduler(ctx context.Context) { } } -// RunInBackground starts a run and returns at once, reporting false when one -// was already going. It backs the page's two buttons — "Check now" (Run) and -// "Score unscored" (ScoreAll, when scoreOnly is set). Either can take minutes, -// far longer than a request should be held open, so the page polls Status -// instead of waiting. -func (s *JobLeadService) RunInBackground(scoreOnly bool) bool { +// LeadJob names one of the pipeline's three jobs, for RunInBackground. +type LeadJob int + +const ( + // LeadJobSync is Run: poll the sources, then score up to a cap. + LeadJobSync LeadJob = iota + // LeadJobScore is ScoreAll: score every unscored lead, polling nothing. + LeadJobScore + // LeadJobRescore is RescoreAll: score every inbox lead again. + LeadJobRescore +) + +// RunInBackground starts a job and returns at once, reporting false when one +// was already going. It backs the page's buttons — "Check now", "Score +// unscored" and "Rescore all". Any of them can take minutes, far longer than +// a request should be held open, so the page polls Status instead of waiting. +func (s *JobLeadService) RunInBackground(job LeadJob) bool { if s.Status().Running { return false } run := s.Run - if scoreOnly { + switch job { + case LeadJobScore: run = s.ScoreAll + case LeadJobRescore: + run = s.RescoreAll } go func() { // Not the request's context: the request is over long before this is. @@ -199,6 +213,28 @@ func (s *JobLeadService) Run(ctx context.Context) error { // decide what gets scored. There is no cap on the count — the person pressed a // button that says "all" — only maxScoreAllDuration on the time. func (s *JobLeadService) ScoreAll(ctx context.Context) error { + return s.scoreAll(ctx, false) +} + +// RescoreAll scores every matched lead in the inbox again, including the +// ones that already have a score. It is for when what a score means has +// changed: the profile was rewritten, or CLAUDE_MODEL was switched. +// +// Old scores are not wiped first. Each lead keeps the score it has until its +// new one arrives, so the inbox stays sorted and readable while the job runs, +// and a job that dies halfway (no API key, a restart) leaves every lead with +// a score, some new and some old, rather than half of them blank. What is +// left to do is told apart by ScoredAt: anything scored before this job +// started is still due. Pressing the button again after a failure therefore +// starts over rather than resuming, which costs calls but is never wrong. +// +// Leads that had used up their attempts get them back: a posting the old +// model could not score may be fine on the new one. +func (s *JobLeadService) RescoreAll(ctx context.Context) error { + return s.scoreAll(ctx, true) +} + +func (s *JobLeadService) scoreAll(ctx context.Context, rescore bool) error { return s.exclusive(ctx, maxScoreAllDuration, func(ctx context.Context) error { profile, err := LoadJobSearchProfile(s.DB) if err != nil { @@ -211,7 +247,19 @@ func (s *JobLeadService) ScoreAll(ctx context.Context) error { return fmt.Errorf("re-applying the filter: %w", err) } - log.Println("[JobLeads] Scoring all unscored leads") + var due *time.Time + if rescore { + started := time.Now() + due = &started + if err := s.DB.Model(&models.JobLead{}). + Where("state = ? AND matched = ? AND score_attempts > 0", LeadNew, true). + UpdateColumn("score_attempts", 0).Error; err != nil { + return fmt.Errorf("resetting score attempts: %w", err) + } + log.Println("[JobLeads] Rescoring every inbox lead") + } else { + log.Println("[JobLeads] Scoring all unscored leads") + } total := 0 var failed []uint for { @@ -220,7 +268,7 @@ func (s *JobLeadService) ScoreAll(ctx context.Context) error { // it, not all three — a passing Claude hiccup should not write a // lead off for good. That is also why the loop terminates: every // lead a pass looks at is either scored or added to `failed`. - scored, tried, nowFailed, err := s.scoreLeads(ctx, profile, failed) + scored, tried, nowFailed, err := s.scoreLeads(ctx, profile, failed, due) total += scored failed = append(failed, nowFailed...) if err != nil || tried == 0 { @@ -302,7 +350,7 @@ func (s *JobLeadService) fetchAndScore(ctx context.Context) error { if err := s.refilter(filter); err != nil { return fmt.Errorf("re-applying the filter: %w", err) } - scored, _, _, err := s.scoreLeads(ctx, profile, nil) + scored, _, _, err := s.scoreLeads(ctx, profile, nil, nil) log.Printf("[JobLeads] Run finished: %d new leads, %d scored", added, scored) return err } @@ -678,13 +726,22 @@ type scoreRequest struct { // tried is zero once nothing is left to score, which is what ScoreAll loops // on. // +// rescoreBefore, when set, widens "has no score yet" to "has no score from +// this job": a lead whose score is older than that time is due again. Its old +// score stays in place until the new one is saved, and through a failure. +// // With no profile text there is nothing to score against, so it does nothing // — leads still arrive and can be read, they just carry no score. -func (s *JobLeadService) scoreLeads(ctx context.Context, profile *models.JobSearchProfile, skip []uint) (scored, tried int, failed []uint, err error) { +func (s *JobLeadService) scoreLeads(ctx context.Context, profile *models.JobSearchProfile, skip []uint, rescoreBefore *time.Time) (scored, tried int, failed []uint, err error) { if strings.TrimSpace(profile.Profile) == "" { return 0, 0, nil, nil } - query := s.DB.Where("state = ? AND matched = ? AND score IS NULL AND score_attempts < ?", LeadNew, true, maxScoreAttempts) + query := s.DB.Where("state = ? AND matched = ? AND score_attempts < ?", LeadNew, true, maxScoreAttempts) + if rescoreBefore == nil { + query = query.Where("score IS NULL") + } else { + query = query.Where("(score IS NULL OR scored_at IS NULL OR scored_at < ?)", *rescoreBefore) + } if len(skip) > 0 { query = query.Where("id NOT IN ?", skip) } @@ -703,7 +760,7 @@ func (s *JobLeadService) scoreLeads(ctx context.Context, profile *models.JobSear case err == nil: reasons := strings.TrimSpace(result.Reasons) score := min(max(result.Score, 0), 100) - if dbErr := s.DB.Model(lead).Updates(map[string]any{"score": score, "score_reasons": reasons}).Error; dbErr != nil { + if dbErr := s.DB.Model(lead).Updates(map[string]any{"score": score, "score_reasons": reasons, "scored_at": time.Now()}).Error; dbErr != nil { return scored, tried, failed, fmt.Errorf("saving a score: %w", dbErr) } scored++ diff --git a/vue/README.md b/vue/README.md index 078aa87..b2d3259 100644 --- a/vue/README.md +++ b/vue/README.md @@ -239,8 +239,9 @@ until **Track** is pressed on a lead, which adds it to `/cv/jobs` as Saved. Same conventions as the tracker: the children emit `fail` / `ok` for the parent's banner, and a lead's `description` is fetched per row. Two things -differ. "Check now" (poll the sources, score up to forty) and "Score -unscored" (poll nothing, score the whole backlog) do not wait for the job — +differ. "Check now" (poll the sources, score up to forty), "Score unscored" +(poll nothing, score the whole backlog) and "Rescore all" (score every inbox +lead again) do not wait for the job — the mutation returns at once and the page polls `jobLeadSyncStatus` every three seconds, reloading the leads as it goes and the sources at the end. And the box styles the children share (`.jl-box`, `.jl-hint`, `.jl-warn`) are in an unscoped `