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 <[email protected]>
This commit is contained in:
+8
-1
@@ -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
|
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,
|
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.
|
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
|
- **When it runs.** `JOB_LEADS_ENABLED=true` starts a timer
|
||||||
(`JOB_LEADS_INTERVAL`, default `6h`); it does not run at start-up, so a
|
(`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
|
deploy spends nothing. The `runJobLeadSync` mutation starts a run in a
|
||||||
goroutine and returns at once, whether or not the timer is on, and
|
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
|
`POST /email/sync` it does not hold the request open. The status is in
|
||||||
memory and resets on restart.
|
memory and resets on restart.
|
||||||
- **Promotion** (`promoteJobLead`) is the only way a lead reaches the tracker.
|
- **Promotion** (`promoteJobLead`) is the only way a lead reaches the tracker.
|
||||||
|
|||||||
@@ -189,6 +189,7 @@ type ComplexityRoot struct {
|
|||||||
RefreshToken func(childComplexity int) int
|
RefreshToken func(childComplexity int) int
|
||||||
RestoreJobLead func(childComplexity int, id int) int
|
RestoreJobLead func(childComplexity int, id int) int
|
||||||
RunJobLeadSync func(childComplexity int) int
|
RunJobLeadSync func(childComplexity int) int
|
||||||
|
ScoreJobLeads func(childComplexity int) int
|
||||||
SetUserAdmin func(childComplexity int, id int, admin bool) int
|
SetUserAdmin func(childComplexity int, id int, admin bool) int
|
||||||
UpdateJobAppReference func(childComplexity int, id int, input model.UpdateJobAppReferenceInput) int
|
UpdateJobAppReference func(childComplexity int, id int, input model.UpdateJobAppReferenceInput) int
|
||||||
UpdateJobApplication func(childComplexity int, id int, input model.UpdateJobApplicationInput) 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)
|
PromoteJobLead(ctx context.Context, id int) (*models.JobLead, error)
|
||||||
UpdateJobSearchProfile(ctx context.Context, input model.UpdateJobSearchProfileInput) (*models.JobSearchProfile, error)
|
UpdateJobSearchProfile(ctx context.Context, input model.UpdateJobSearchProfileInput) (*models.JobSearchProfile, error)
|
||||||
RunJobLeadSync(ctx context.Context) (bool, error)
|
RunJobLeadSync(ctx context.Context) (bool, error)
|
||||||
|
ScoreJobLeads(ctx context.Context) (bool, error)
|
||||||
CreatePlace(ctx context.Context, input model.CreatePlaceInput) (*models.Place, error)
|
CreatePlace(ctx context.Context, input model.CreatePlaceInput) (*models.Place, error)
|
||||||
UpdatePlace(ctx context.Context, id int, input model.UpdatePlaceInput) (*models.Place, error)
|
UpdatePlace(ctx context.Context, id int, input model.UpdatePlaceInput) (*models.Place, error)
|
||||||
DeletePlace(ctx context.Context, id int) (*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
|
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":
|
case "Mutation.setUserAdmin":
|
||||||
if e.ComplexityRoot.Mutation.SetUserAdmin == nil {
|
if e.ComplexityRoot.Mutation.SetUserAdmin == nil {
|
||||||
break
|
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"))
|
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) {
|
func (ec *executionContext) _Mutation_createPlace(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {
|
||||||
return graphql.ResolveField(
|
return graphql.ResolveField(
|
||||||
ctx,
|
ctx,
|
||||||
@@ -11672,6 +11716,13 @@ func (ec *executionContext) _Mutation(ctx context.Context, sel ast.SelectionSet)
|
|||||||
if out.Values[i] == graphql.Null {
|
if out.Values[i] == graphql.Null {
|
||||||
out.Invalids++
|
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":
|
case "createPlace":
|
||||||
out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) {
|
out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) {
|
||||||
return ec._Mutation_createPlace(ctx, field)
|
return ec._Mutation_createPlace(ctx, field)
|
||||||
|
|||||||
@@ -144,7 +144,15 @@ func (r *mutationResolver) RunJobLeadSync(ctx context.Context) (bool, error) {
|
|||||||
if r.Store.JobLeads == nil {
|
if r.Store.JobLeads == nil {
|
||||||
return false, fmt.Errorf("job leads are not configured")
|
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.
|
// JobSources is the resolver for the jobSources field.
|
||||||
|
|||||||
@@ -130,4 +130,9 @@ extend type Mutation {
|
|||||||
# if it started, false if one was already running. Poll jobLeadSyncStatus
|
# if it started, false if one was already running. Poll jobLeadSyncStatus
|
||||||
# to see it finish.
|
# to see it finish.
|
||||||
runJobLeadSync: Boolean! @admin
|
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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,9 +41,10 @@ const (
|
|||||||
// nginx forwarded.
|
// nginx forwarded.
|
||||||
jobScorePath = "/internal/jobs/score"
|
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
|
// 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
|
maxScoresPerRun = 40
|
||||||
|
|
||||||
// maxScoreAttempts caps how many times a lead Claude failed to score is
|
// maxScoreAttempts caps how many times a lead Claude failed to score is
|
||||||
@@ -56,6 +57,11 @@ const (
|
|||||||
// simply still unscored next time.
|
// simply still unscored next time.
|
||||||
maxRunDuration = 20 * time.Minute
|
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
|
// leadBatch sizes the IN lists and inserts, well inside Postgres's limit
|
||||||
// of 65535 bound parameters per statement.
|
// of 65535 bound parameters per statement.
|
||||||
leadBatch = 500
|
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
|
// 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
|
// far longer than a request should be held open, so the page polls Status
|
||||||
// instead of waiting.
|
// instead of waiting.
|
||||||
func (s *JobLeadService) RunInBackground() bool {
|
func (s *JobLeadService) RunInBackground(scoreOnly bool) bool {
|
||||||
if s.Status().Running {
|
if s.Status().Running {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
run := s.Run
|
||||||
|
if scoreOnly {
|
||||||
|
run = s.ScoreAll
|
||||||
|
}
|
||||||
go func() {
|
go func() {
|
||||||
// Not the request's context: the request is over long before this is.
|
// 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)
|
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.
|
// 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() {
|
if !s.mu.TryLock() {
|
||||||
return ErrLeadSyncRunning
|
return ErrLeadSyncRunning
|
||||||
}
|
}
|
||||||
@@ -185,7 +244,7 @@ func (s *JobLeadService) Run(ctx context.Context) (err error) {
|
|||||||
s.statusMu.Unlock()
|
s.statusMu.Unlock()
|
||||||
|
|
||||||
// Runs before the unlock above. It also absorbs a panic, turning it into
|
// 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.
|
// or leave `running` stuck true.
|
||||||
defer func() {
|
defer func() {
|
||||||
if r := recover(); r != nil {
|
if r := recover(); r != nil {
|
||||||
@@ -203,9 +262,13 @@ func (s *JobLeadService) Run(ctx context.Context) (err error) {
|
|||||||
s.statusMu.Unlock()
|
s.statusMu.Unlock()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(ctx, maxRunDuration)
|
ctx, cancel := context.WithTimeout(ctx, limit)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
return work(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetchAndScore is the body of Run.
|
||||||
|
func (s *JobLeadService) fetchAndScore(ctx context.Context) error {
|
||||||
profile, err := LoadJobSearchProfile(s.DB)
|
profile, err := LoadJobSearchProfile(s.DB)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("loading the search profile: %w", err)
|
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 {
|
if err := s.refilter(filter); err != nil {
|
||||||
return fmt.Errorf("re-applying the filter: %w", err)
|
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)
|
log.Printf("[JobLeads] Run finished: %d new leads, %d scored", added, scored)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -610,26 +673,30 @@ type scoreRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// scoreLeads asks Claude to score the matched leads that have no score yet,
|
// 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
|
// 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.
|
// — 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) == "" {
|
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
|
var leads []models.JobLead
|
||||||
if err := s.DB.
|
if err := query.Order("created_at DESC, id DESC").Limit(maxScoresPerRun).Find(&leads).Error; err != nil {
|
||||||
Where("state = ? AND matched = ? AND score IS NULL AND score_attempts < ?", LeadNew, true, maxScoreAttempts).
|
return 0, 0, nil, fmt.Errorf("loading leads to score: %w", err)
|
||||||
Order("created_at DESC, id DESC").Limit(maxScoresPerRun).
|
|
||||||
Find(&leads).Error; err != nil {
|
|
||||||
return 0, fmt.Errorf("loading leads to score: %w", err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
scored := 0
|
|
||||||
for i := range leads {
|
for i := range leads {
|
||||||
lead := &leads[i]
|
lead := &leads[i]
|
||||||
result, err := s.scoreLead(ctx, profile.Profile, lead)
|
result, err := s.scoreLead(ctx, profile.Profile, lead)
|
||||||
|
tried++
|
||||||
|
|
||||||
var readErr *PythonError
|
var readErr *PythonError
|
||||||
switch {
|
switch {
|
||||||
@@ -637,7 +704,7 @@ func (s *JobLeadService) scoreLeads(ctx context.Context, profile *models.JobSear
|
|||||||
reasons := strings.TrimSpace(result.Reasons)
|
reasons := strings.TrimSpace(result.Reasons)
|
||||||
score := min(max(result.Score, 0), 100)
|
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}).Error; dbErr != nil {
|
||||||
return scored, fmt.Errorf("saving a score: %w", dbErr)
|
return scored, tried, failed, fmt.Errorf("saving a score: %w", dbErr)
|
||||||
}
|
}
|
||||||
scored++
|
scored++
|
||||||
case errors.As(err, &readErr):
|
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.
|
// move on; maxScoreAttempts stops it being retried forever.
|
||||||
log.Printf("[JobLeads] Scoring lead %d failed: %v", lead.ID, err)
|
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 {
|
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:
|
default:
|
||||||
// Anything else is not about this lead: no API key, the Python
|
// Anything else is not about this lead: no API key, or the Python
|
||||||
// service down, the run cancelled. The next lead would fail the
|
// service down. The next lead would fail the same way, so stop,
|
||||||
// same way, so stop, and spend no attempt on it.
|
// and spend no attempt on it.
|
||||||
// The detail names internal addresses and goes to the log; the
|
// The detail names internal addresses and goes to the log; the
|
||||||
// returned error is shown on the leads page.
|
// returned error is shown on the leads page.
|
||||||
log.Printf("[JobLeads] Scoring stopped at lead %d: %v", lead.ID, err)
|
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) {
|
func (s *JobLeadService) scoreLead(ctx context.Context, profile string, lead *models.JobLead) (LeadScore, error) {
|
||||||
|
|||||||
+4
-3
@@ -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
|
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
|
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
|
differ. "Check now" (poll the sources, score up to forty) and "Score
|
||||||
and the page polls `jobLeadSyncStatus` every three seconds, then reloads the
|
unscored" (poll nothing, score the whole backlog) do not wait for the job —
|
||||||
leads and sources. And the box styles the children share (`.jl-box`,
|
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 `<style>` block in `JobLeads.vue`,
|
`.jl-hint`, `.jl-warn`) are in an unscoped `<style>` block in `JobLeads.vue`,
|
||||||
under `.jl-root`, for the reason `jobs-shared.css` exists.
|
under `.jl-root`, for the reason `jobs-shared.css` exists.
|
||||||
|
|
||||||
|
|||||||
@@ -98,5 +98,14 @@ export const useJobLeadsStore = defineStore("jobLeads", () => {
|
|||||||
return data.runJobLeadSync;
|
return data.runJobLeadSync;
|
||||||
}
|
}
|
||||||
|
|
||||||
return { leads, loading, error, status, fetch, dismiss, restore, promote, fetchDescription, fetchStatus, runSync };
|
/**
|
||||||
|
* Score every unscored lead in the inbox without polling any source. Same
|
||||||
|
* contract as runSync(): resolves at once, and fetchStatus() shows it finish.
|
||||||
|
*/
|
||||||
|
async function scoreAll() {
|
||||||
|
const data = await gql(`mutation ScoreJobLeads { scoreJobLeads }`);
|
||||||
|
return data.scoreJobLeads;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { leads, loading, error, status, fetch, dismiss, restore, promote, fetchDescription, fetchStatus, runSync, scoreAll };
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -12,9 +12,11 @@
|
|||||||
* This view owns the page frame, the single error banner, the run button and
|
* This view owns the page frame, the single error banner, the run button and
|
||||||
* the list. Data access is in stores/jobLeads.js; nothing here calls gql().
|
* the list. Data access is in stores/jobLeads.js; nothing here calls gql().
|
||||||
*
|
*
|
||||||
* A run takes from seconds to a few minutes, so "Check now" does not wait for
|
* There are two server jobs. "Check now" polls the sources and scores up to
|
||||||
* it: the server starts the run and this page polls its status, then reloads
|
* forty new leads; "Score unscored" polls nothing and scores the whole
|
||||||
* the list when it finishes.
|
* backlog. Either takes from seconds to many minutes, so the button does not
|
||||||
|
* wait: the server starts the job and this page polls its status, then
|
||||||
|
* reloads the list when it finishes.
|
||||||
*/
|
*/
|
||||||
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
|
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
|
||||||
import { RouterLink } from "vue-router";
|
import { RouterLink } from "vue-router";
|
||||||
@@ -159,6 +161,9 @@ function stopPolling() {
|
|||||||
async function pollStatus() {
|
async function pollStatus() {
|
||||||
const current = await store.fetchStatus();
|
const current = await store.fetchStatus();
|
||||||
if (current?.running) {
|
if (current?.running) {
|
||||||
|
// Scores are saved one at a time, so reloading as it goes lets a long
|
||||||
|
// "Score unscored" fill the list in rather than sit still for minutes.
|
||||||
|
await fetchLeads();
|
||||||
pollTimer = setTimeout(pollStatus, POLL_MS);
|
pollTimer = setTimeout(pollStatus, POLL_MS);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -167,11 +172,12 @@ async function pollStatus() {
|
|||||||
await Promise.all([fetchLeads(), sourcesBox.value?.refresh()]);
|
await Promise.all([fetchLeads(), sourcesBox.value?.refresh()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function checkNow() {
|
/** Start one of the two server jobs ("runSync" or "scoreAll") and wait on it. */
|
||||||
|
async function start(job) {
|
||||||
try {
|
try {
|
||||||
// false means a run was already going (the scheduler's, say); either way
|
// false means a job was already going (the scheduler's, say); either way
|
||||||
// there is now one to wait for.
|
// there is now one to wait for.
|
||||||
await store.runSync();
|
await store[job]();
|
||||||
error.value = "";
|
error.value = "";
|
||||||
status.value = { ...(status.value ?? {}), running: true };
|
status.value = { ...(status.value ?? {}), running: true };
|
||||||
stopPolling();
|
stopPolling();
|
||||||
@@ -181,10 +187,17 @@ async function checkNow() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Matched inbox leads with no score: what "Score unscored" would work
|
||||||
|
// through. A lead Claude failed on three times stays in this count, though
|
||||||
|
// the server will not try it again.
|
||||||
|
const unscoredCount = computed(
|
||||||
|
() => leads.value.filter((lead) => lead.state === "new" && lead.matched && lead.score == null).length,
|
||||||
|
);
|
||||||
|
|
||||||
const running = computed(() => !!status.value?.running);
|
const running = computed(() => !!status.value?.running);
|
||||||
|
|
||||||
const lastRun = computed(() => {
|
const lastRun = computed(() => {
|
||||||
if (running.value) return "Checking sources and scoring…";
|
if (running.value) return "Working…";
|
||||||
if (!status.value?.lastRunAt) return "";
|
if (!status.value?.lastRunAt) return "";
|
||||||
const when = new Date(status.value.lastRunAt).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" });
|
const when = new Date(status.value.lastRunAt).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" });
|
||||||
return `Last checked ${when}`;
|
return `Last checked ${when}`;
|
||||||
@@ -210,13 +223,22 @@ onBeforeUnmount(stopPolling);
|
|||||||
</div>
|
</div>
|
||||||
<div class="jl-header-right">
|
<div class="jl-header-right">
|
||||||
<span class="jl-hint">{{ lastRun }}</span>
|
<span class="jl-hint">{{ lastRun }}</span>
|
||||||
|
<button
|
||||||
|
v-if="unscoredCount"
|
||||||
|
class="cv-btn"
|
||||||
|
:disabled="running"
|
||||||
|
title="Score every unscored lead in the inbox against the profile, without polling the sources. One Claude call per lead."
|
||||||
|
@click="start('scoreAll')"
|
||||||
|
>
|
||||||
|
Score unscored ({{ unscoredCount }})
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
class="cv-btn cv-btn-primary"
|
class="cv-btn cv-btn-primary"
|
||||||
:disabled="running"
|
:disabled="running"
|
||||||
title="Poll every source now, then score new leads. Profile and keyword changes take effect on a run."
|
title="Poll every source now, then score up to 40 new leads. Profile and keyword changes take effect on a run."
|
||||||
@click="checkNow"
|
@click="start('runSync')"
|
||||||
>
|
>
|
||||||
{{ running ? "Checking…" : "Check now" }}
|
{{ running ? "Working…" : "Check now" }}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Reference in New Issue
Block a user