From 299b5f52240c81bb0b01f27f2f8d83696a62296c Mon Sep 17 00:00:00 2001 From: Adam French Date: Mon, 12 Oct 2026 15:36:32 +0100 Subject: [PATCH] Add a way to score every unscored lead without polling A run caps its scoring at forty leads, so a first poll of several boards left a backlog that could only be cleared by pressing "Check now" repeatedly, re-fetching every source each time. scoreJobLeads (JobLeadService.ScoreAll, "Score unscored" on /cv/leads) re-applies the keyword filter and then scores every matched, unscored lead, with no cap on the count and a one-hour limit on the time. A lead Claude fails on is tried once per press rather than three times, so a passing failure does not write it off. It shares the run lock and the polled status with runJobLeadSync, and the page now reloads the leads while either job is in flight. Co-Authored-By: Claude Opus 5.5 --- backend/README.md | 9 +- backend/graph/generated.go | 51 +++++++++++ backend/graph/job_lead.resolvers.go | 10 ++- backend/graph/schema/job_lead.graphql | 5 ++ backend/services/job_leads.go | 122 ++++++++++++++++++++------ vue/README.md | 7 +- vue/src/stores/jobLeads.js | 11 ++- vue/src/views/CV/JobLeads.vue | 42 ++++++--- 8 files changed, 216 insertions(+), 41 deletions(-) diff --git a/backend/README.md b/backend/README.md index 0c862c1..4c886a8 100644 --- a/backend/README.md +++ b/backend/README.md @@ -284,11 +284,18 @@ throughout (`graph/schema/job_lead.graphql`, all `@admin`) with the work in lead Claude cannot score is retried on three runs and then left. With an empty profile nothing is scored. If scoring is unavailable (no API key, Python down) the run stops scoring without spending an attempt on any lead. +- **Scoring the backlog.** The `scoreJobLeads` mutation + (`JobLeadService.ScoreAll`, "Score unscored" on the page) scores every + matched, unscored lead with no cap and without polling any source. It is + 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. - **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 — a run can take minutes, so unlike + `jobLeadSyncStatus` reports on it (and on `scoreJobLeads`; only one of + the two 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 466a9e4..ba31697 100644 --- a/backend/graph/generated.go +++ b/backend/graph/generated.go @@ -189,6 +189,7 @@ type ComplexityRoot struct { RefreshToken func(childComplexity int) int RestoreJobLead func(childComplexity int, id int) int RunJobLeadSync func(childComplexity int) int + ScoreJobLeads func(childComplexity int) int SetUserAdmin func(childComplexity int, id int, admin bool) int UpdateJobAppReference func(childComplexity int, id int, input model.UpdateJobAppReferenceInput) int UpdateJobApplication func(childComplexity int, id int, input model.UpdateJobApplicationInput) int @@ -338,6 +339,7 @@ type MutationResolver interface { PromoteJobLead(ctx context.Context, id int) (*models.JobLead, error) UpdateJobSearchProfile(ctx context.Context, input model.UpdateJobSearchProfileInput) (*models.JobSearchProfile, error) RunJobLeadSync(ctx context.Context) (bool, error) + ScoreJobLeads(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) @@ -1157,6 +1159,12 @@ func (e *executableSchema) Complexity(ctx context.Context, typeName, field strin } return e.ComplexityRoot.Mutation.RunJobLeadSync(childComplexity), true + case "Mutation.scoreJobLeads": + if e.ComplexityRoot.Mutation.ScoreJobLeads == nil { + break + } + + return e.ComplexityRoot.Mutation.ScoreJobLeads(childComplexity), true case "Mutation.setUserAdmin": if e.ComplexityRoot.Mutation.SetUserAdmin == nil { break @@ -6003,6 +6011,42 @@ func (ec *executionContext) fieldContext_Mutation_runJobLeadSync(_ context.Conte return graphql.NewScalarFieldContext("Mutation", field, true, true, errors.New("field of type Boolean does not have child fields")) } +func (ec *executionContext) _Mutation_scoreJobLeads(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_scoreJobLeads(ctx, field) + }, + func(ctx context.Context) (any, error) { + return ec.Resolvers.Mutation().ScoreJobLeads(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_scoreJobLeads(_ 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, @@ -11672,6 +11716,13 @@ func (ec *executionContext) _Mutation(ctx context.Context, sel ast.SelectionSet) if out.Values[i] == graphql.Null { out.Invalids++ } + case "scoreJobLeads": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_scoreJobLeads(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 c8fe1b2..b9866b0 100644 --- a/backend/graph/job_lead.resolvers.go +++ b/backend/graph/job_lead.resolvers.go @@ -144,7 +144,15 @@ 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(), nil + return r.Store.JobLeads.RunInBackground(false), nil +} + +// ScoreJobLeads is the resolver for the scoreJobLeads field. +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 } // JobSources is the resolver for the jobSources field. diff --git a/backend/graph/schema/job_lead.graphql b/backend/graph/schema/job_lead.graphql index f823839..76ddff7 100644 --- a/backend/graph/schema/job_lead.graphql +++ b/backend/graph/schema/job_lead.graphql @@ -130,4 +130,9 @@ extend type Mutation { # if it started, false if one was already running. Poll jobLeadSyncStatus # to see it finish. runJobLeadSync: Boolean! @admin + + # Scores every matched lead that has no score yet, without polling any + # source. Background and polled like runJobLeadSync, and refused (false) + # while either is running. + scoreJobLeads: Boolean! @admin } diff --git a/backend/services/job_leads.go b/backend/services/job_leads.go index 78e489b..b818933 100644 --- a/backend/services/job_leads.go +++ b/backend/services/job_leads.go @@ -41,9 +41,10 @@ const ( // nginx forwarded. jobScorePath = "/internal/jobs/score" - // maxScoresPerRun bounds the Claude calls one run can make, and so both + // maxScoresPerRun bounds the Claude calls one Run can make, and so both // its cost and its length. A first poll of a few boards can match - // hundreds of leads; the rest are picked up by later runs, newest first. + // hundreds of leads; the rest are picked up by later runs, newest first, + // or all at once by ScoreAll. It is also ScoreAll's batch size. maxScoresPerRun = 40 // maxScoreAttempts caps how many times a lead Claude failed to score is @@ -56,6 +57,11 @@ const ( // simply still unscored next time. maxRunDuration = 20 * time.Minute + // maxScoreAllDuration bounds ScoreAll, which has no cap on the count. An + // hour is several hundred leads at a few seconds each; whatever is left + // when it runs out is picked up by pressing the button again. + maxScoreAllDuration = time.Hour + // leadBatch sizes the IN lists and inserts, well inside Postgres's limit // of 65535 bound parameters per statement. leadBatch = 500 @@ -157,16 +163,21 @@ 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 "Check now": a run can take minutes, +// 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() bool { +func (s *JobLeadService) RunInBackground(scoreOnly bool) bool { if s.Status().Running { return false } + run := s.Run + if scoreOnly { + run = s.ScoreAll + } go func() { // Not the request's context: the request is over long before this is. - if err := s.Run(context.Background()); err != nil && !errors.Is(err, ErrLeadSyncRunning) { + if err := run(context.Background()); err != nil && !errors.Is(err, ErrLeadSyncRunning) { log.Printf("[JobLeads] Manual run error: %v", err) } }() @@ -174,7 +185,55 @@ func (s *JobLeadService) RunInBackground() bool { } // Run is one pass of the pipeline: fetch, store, pre-filter, score. -func (s *JobLeadService) Run(ctx context.Context) (err error) { +func (s *JobLeadService) Run(ctx context.Context) error { + return s.exclusive(ctx, maxRunDuration, s.fetchAndScore) +} + +// ScoreAll scores every matched lead that has no score yet, without polling +// any source. It exists because Run caps its scoring at maxScoresPerRun: after +// a first poll of several boards, or after the profile was filled in late, +// there is a backlog, and clearing it should not mean re-fetching every board +// (and spending search-API quota) forty leads at a time. +// +// The pre-filter is re-applied first, so keywords edited since the last run +// 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.exclusive(ctx, maxScoreAllDuration, func(ctx context.Context) error { + profile, err := LoadJobSearchProfile(s.DB) + if err != nil { + return fmt.Errorf("loading the search profile: %w", err) + } + if strings.TrimSpace(profile.Profile) == "" { + return errors.New("the search profile is empty, so there is nothing to score against") + } + if err := s.refilter(newLeadFilter(profile)); err != nil { + return fmt.Errorf("re-applying the filter: %w", err) + } + + log.Println("[JobLeads] Scoring all unscored leads") + total := 0 + var failed []uint + for { + // Each pass takes the next batch. A lead that fails is skipped + // for the rest of this job, so one press spends one attempt on + // 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) + total += scored + failed = append(failed, nowFailed...) + if err != nil || tried == 0 { + log.Printf("[JobLeads] Scoring finished: %d scored", total) + return err + } + } + }) +} + +// exclusive runs work as the one pipeline job in flight, maintaining the +// status the page polls. A second job requested meanwhile is refused. +func (s *JobLeadService) exclusive(ctx context.Context, limit time.Duration, work func(context.Context) error) (err error) { if !s.mu.TryLock() { return ErrLeadSyncRunning } @@ -185,7 +244,7 @@ func (s *JobLeadService) Run(ctx context.Context) (err error) { s.statusMu.Unlock() // Runs before the unlock above. It also absorbs a panic, turning it into - // this run's error, so one malformed posting cannot take the backend down + // this job's error, so one malformed posting cannot take the backend down // or leave `running` stuck true. defer func() { if r := recover(); r != nil { @@ -203,9 +262,13 @@ func (s *JobLeadService) Run(ctx context.Context) (err error) { s.statusMu.Unlock() }() - ctx, cancel := context.WithTimeout(ctx, maxRunDuration) + ctx, cancel := context.WithTimeout(ctx, limit) defer cancel() + return work(ctx) +} +// fetchAndScore is the body of Run. +func (s *JobLeadService) fetchAndScore(ctx context.Context) error { profile, err := LoadJobSearchProfile(s.DB) if err != nil { return fmt.Errorf("loading the search profile: %w", err) @@ -239,7 +302,7 @@ func (s *JobLeadService) Run(ctx context.Context) (err error) { if err := s.refilter(filter); err != nil { return fmt.Errorf("re-applying the filter: %w", err) } - scored, err := s.scoreLeads(ctx, profile) + scored, _, _, err := s.scoreLeads(ctx, profile, nil) log.Printf("[JobLeads] Run finished: %d new leads, %d scored", added, scored) return err } @@ -610,26 +673,30 @@ type scoreRequest struct { } // scoreLeads asks Claude to score the matched leads that have no score yet, -// newest first, up to maxScoresPerRun, and reports how many it scored. +// newest first, up to maxScoresPerRun, leaving out the ids in skip. It reports +// how many it scored, how many it tried, and which ones Claude failed on; +// tried is zero once nothing is left to score, which is what ScoreAll loops +// on. // // 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) (int, error) { +func (s *JobLeadService) scoreLeads(ctx context.Context, profile *models.JobSearchProfile, skip []uint) (scored, tried int, failed []uint, err error) { if strings.TrimSpace(profile.Profile) == "" { - return 0, nil + return 0, 0, nil, nil + } + query := s.DB.Where("state = ? AND matched = ? AND score IS NULL AND score_attempts < ?", LeadNew, true, maxScoreAttempts) + if len(skip) > 0 { + query = query.Where("id NOT IN ?", skip) } var leads []models.JobLead - if err := s.DB. - Where("state = ? AND matched = ? AND score IS NULL AND score_attempts < ?", LeadNew, true, maxScoreAttempts). - Order("created_at DESC, id DESC").Limit(maxScoresPerRun). - Find(&leads).Error; err != nil { - return 0, fmt.Errorf("loading leads to score: %w", err) + if err := query.Order("created_at DESC, id DESC").Limit(maxScoresPerRun).Find(&leads).Error; err != nil { + return 0, 0, nil, fmt.Errorf("loading leads to score: %w", err) } - scored := 0 for i := range leads { lead := &leads[i] result, err := s.scoreLead(ctx, profile.Profile, lead) + tried++ var readErr *PythonError switch { @@ -637,7 +704,7 @@ func (s *JobLeadService) scoreLeads(ctx context.Context, profile *models.JobSear 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 { - return scored, fmt.Errorf("saving a score: %w", dbErr) + return scored, tried, failed, fmt.Errorf("saving a score: %w", dbErr) } scored++ case errors.As(err, &readErr): @@ -645,19 +712,24 @@ func (s *JobLeadService) scoreLeads(ctx context.Context, profile *models.JobSear // move on; maxScoreAttempts stops it being retried forever. log.Printf("[JobLeads] Scoring lead %d failed: %v", lead.ID, err) if dbErr := s.DB.Model(lead).UpdateColumn("score_attempts", gorm.Expr("score_attempts + 1")).Error; dbErr != nil { - return scored, fmt.Errorf("recording a failed score: %w", dbErr) + return scored, tried, failed, fmt.Errorf("recording a failed score: %w", dbErr) } + failed = append(failed, lead.ID) + case ctx.Err() != nil: + // Out of time (or shut down) mid-call. Nothing is wrong with + // scoring, so say what happened rather than "unavailable". + return scored, tried, failed, errors.New("ran out of time before every lead was scored; run it again to continue") default: - // Anything else is not about this lead: no API key, the Python - // service down, the run cancelled. The next lead would fail the - // same way, so stop, and spend no attempt on it. + // Anything else is not about this lead: no API key, or the Python + // service down. The next lead would fail the same way, so stop, + // and spend no attempt on it. // The detail names internal addresses and goes to the log; the // returned error is shown on the leads page. log.Printf("[JobLeads] Scoring stopped at lead %d: %v", lead.ID, err) - return scored, errors.New("scoring is unavailable: the Python service did not answer, or has no Claude key (see the backend log)") + return scored, tried, failed, errors.New("scoring is unavailable: the Python service did not answer, or has no Claude key (see the backend log)") } } - return scored, nil + return scored, tried, failed, nil } func (s *JobLeadService) scoreLead(ctx context.Context, profile string, lead *models.JobLead) (LeadScore, error) { diff --git a/vue/README.md b/vue/README.md index abcc143..078aa87 100644 --- a/vue/README.md +++ b/vue/README.md @@ -239,9 +239,10 @@ 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" does not wait for the run — the mutation returns at once -and the page polls `jobLeadSyncStatus` every three seconds, then reloads the -leads and sources. And the box styles the children share (`.jl-box`, +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 — +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 `