Skip to content

Learning Loop Internals

Claude edited this page Nov 12, 2026 · 5 revisions

Checked against v0.7.6 on November 13, 2026.

Learning loop internals

This page describes how Kestrel learns from the operator's own decisions: what gets recorded, how scoring weights are recalibrated, how few-shot examples reach the prompt, how the reranker is trained and promoted, how the Calibrate queue picks items, and how drift demotes a reranker. It also lists the code signals that show how far to trust a score. The code is in kestrel/learning/, with the Tier 1 fast path in kestrel/pipeline/reranker_gate.py.

Nothing here trains a language model. kestrel/learning/ledger.py states the boundary: Kestrel changes what the model is shown (few-shot examples), how dimension scores are combined (accepted calibration weights), and whether a learned reranker gates Tier 1. The loop also never acts outside the app. It does not apply, message or contact anyone on the operator's behalf (hard rule 1 in CLAUDE.md).

All thresholds below are defaults in Learning in kestrel/config.py and kestrel/resources/config/settings.yml, and the operator can override them.

Setting Default Used by
learning.min_labels_for_few_shot 15 Few-shot injection
learning.few_shot_k 3 Few-shot injection
learning.min_labels_for_calibration 30 Weight calibration
learning.min_labels_for_reranker 200 Reranker training
learning.reranker_max_mae 0.6 Promotion gate
learning.reranker_uncertain_band 0.4 Tier 1 fast path
learning.drift_threshold 0.8 Drift demotion
learning.use_examples true Switch: Tier 2 shows past ratings as examples
learning.tune_weights true Switch: calibration proposals
learning.build_model true Switch: reranker training and the Tier 1 fast path

The three switches are on Settings under Scoring and learning (kestrel/web/pages/settings_learn.py). A switch only lets the operator turn a stage off. Each stage still waits for its own label floor in the rows above. With use_examples off, _gather_few_shot() passes select_few_shot() a floor that is never reached, so Tier 2 runs zero-shot. With tune_weights off, propose_calibration() returns None. With build_model off, train_reranker() returns a not-trained result, request_training() queues nothing, and try_reranker_tier1() returns None so the LLM always decides Tier 1.

Capture

Three tables hold the operator's judgments, written from places where the operator is already acting.

  • verdict_override: written by Agree, Adjust and Override on an opportunity, through record_override() in kestrel/web/queries.py. Agree copies the system's verdict and score as the operator's. Adjust keeps the verdict and sets a score. Override sets both and requires a reason.
  • label: written by the Calibrate queue through record_label() in kestrel/learning/capture.py, via POST /api/learning/label.
  • selection_override: written when a document slot changes after model selection (record_selection_override()). The reranker and calibration do not read it.

A fourth store, requirement_correction, holds corrections to what Kestrel concluded about one requirement of a posting. It is not a label. See Operator corrections.

The UI speaks in fit words (strong fit, good fit, maybe, not a fit). verdict_for_fit() in kestrel/web/fit.py maps each word back to a stored verdict and a training score so the loop still receives a pair: strong fit is apply at 4.75, good fit apply at 4.0, maybe consider at 3.0, not a fit pass at 1.5. On the consulting track apply is stored as pursue.

labeled_examples() merges label rows and verdict_override rows that carry an operator score into one list per track. When one opportunity has several judgments, the most recent wins across both tables, so a later correction supersedes an earlier label. Each example carries the Tier 2 dimension scores the operator judged, taken from the override's evaluation, the label's stored dimensions, or the latest Tier 2 evaluation as a fallback. The list is oldest first so callers can take the most recent N.

Outcomes (record_outcome()) are another signal, used only for analytics and the score-discrimination check below, not for training.

Quick round answers

The quick round (kestrel/learning/quick.py) is a stream of yes or no cards that Today offers after a finished run. An answer is one label row with source set to quick: Top pick is 5, Yes is 4, Not for me is 2, and the verdict comes from the score the same way a Detailed rating derives it. Not sure writes nothing, so the role stays in the queue. Undo deletes the label through ledger.delete_label. A round is 10 roles (ROUND_SIZE), the strip does not show with fewer than 5 candidates, and the queue order is rank_uncertain() unchanged, served through uncertain_cache. The round never reads or shows Kestrel's own score, and no model is called.

The offer state is a few setting rows, never browser storage: the on/off switch, the cadence (every 3 runs by default, every run, or weekly) and, per track, the finished-run count at which the strip may show again. Not now snoozes for 3 runs (SNOOZE_RUNS); Stop asking sets the switch off. Quick answers count toward the 15, 30 and 200 steps like any other label. Bulk decisions on a selection in Pipeline do not: only decisions made one role at a time feed calibration, examples and the reranker. The routes are in kestrel/web/routes_quick.py.

Operator corrections

A correction (kestrel/learning/corrections.py) is the operator's answer to one requirement a posting asks for: overstated, not true of me, they mean something else, all of it, some of it (each of the last two can rest on a story), none of it, or a confirmed fair gap. save_correction, change_correction and remove_correction write the rows and return an Undo that puts back exactly what was there. A correction is never a label or verdict_override. It does not count toward the 15, 30 and 200 steps, does not appear in Calibrate history, and never changes a Tier 0 or Tier 1 keep or kill. The stored evaluation is never rewritten; apply_corrections lays the corrected states over the rows the role page builds, so the match wheel and counts use them.

Scope decides where a correction applies. A statement about the person (person scope) applies to every role on the track that asks the same thing, matched on requirement_hash, the normalized form of the requirement text. A "they mean something else" note is posting scope and stays on that role. A story-backed answer stops applying when its story is deleted.

Matching decides what scoring sees. for_scoring and for_role in the same module pick the corrections for a role: its own posting rows, and the person rows for requirements this posting asks for. A role with a stored read matches by hash against that read's requirements. A role's first score has no read yet, so a person correction is matched by whole words of its requirement text in the description, and a requirement under three normalized characters never matches by text. A person correction about something the posting does not ask for is never sent, because an unrelated "does not have X" line on every posting could lower verdicts. kestrel/learning/correction_lines.py turns the picked rows into the lines of the OPERATOR_CORRECTIONS block (Prompts and context budgets).

Corrections also decide when a score reads as older. kestrel/learning/score_age.py marks a score "Scored with older scoring instructions" only when the block its role would send has changed since: a correction added or changed after the score, or one the score was given (evaluation.correction_ids) removed, changed or without its story. With no corrections the new prompt version sends the same request as the old one, so no score is marked older.

When a role is scored on an online model, the confirmation covers the correction lines the dialog listed. lines_digest of the lines is stored with the confirmation, and a task whose current lines differ is deferred with the corrections hold reason until the operator confirms again (Task queue and concurrency).

Calibration

propose_calibration() in kestrel/learning/calibration.py fits new dimension weights that best predict the operator's own score from the sum of each dimension times its weight. It runs per track and needs min_labels_for_calibration examples that also have usable dimension scores. Below that it returns None.

The fit (fit_weights()) minimizes mean squared error plus a ridge penalty (_RIDGE_ALPHA = 0.02) with SciPy's SLSQP, under two constraints: every weight is between 0 and 1, and the weights sum to 1. The dimensions are fixed per track:

employment  role_fit, domain_match, company_context, comp_logistics, trajectory
consulting  engagement_fit, buyer_access, economics, delivery_feasibility, strategic_value

The proposal stores both weight sets and a cross-validated MAE for each. _cv_mae() uses five-fold CV (fewer folds when there are fewer than five samples), scoring the current weights as fixed and refitting the proposed weights inside each fold, on the same held-out folds. The result is a Calibration row with status proposed. Nothing is applied.

accept_calibration() writes the weights as setting rows named scoring.weights.<track>.<dimension>, which is the highest-precedence configuration layer, and marks the proposal accepted. reject_calibration() marks it rejected. Both are the operator's explicit action. kestrel calibrate only proposes.

Where proposals come from and where they are decided:

  • The Calibrate page shows a pending proposal as a tune-up card. tune_proposal() in kestrel/web/calibrate_view.py returns the pending one, or creates one only when none is pending and at least min_labels_for_calibration new ratings have arrived since the last decision, so viewing the page never piles up proposals.
  • The operator decides on that card (POST /calibrate/tune/{cal_id}/accept or /reject, kestrel/web/routes_learning.py), on the Settings page (POST /settings/calibration/{id}/{action}, kestrel/web/pages/settings.py), or through the /api/learning/calibration/... routes.
  • undo_calibration() takes back an accept or a reject (POST /calibrate/tune-undo/{cal_id}). The proposal waits again. For an accept, accept_calibration() first saved the weights it replaced in a setting row named undo.pursuit.calibration.<id>, and undo writes those back. It refuses, and changes nothing, if the live weights no longer equal the accepted ones or the saved row is gone.

Post-processing in kestrel/pipeline/scoring.py applies the weights. The verdict is derived from the score and the thresholds (4.0 for apply or pursue, 3.0 for consider), not taken from the model. Blockers and a reject legitimacy status force pass, and a suspect status caps the displayed score at 3.5.

Few-shot injection

Tier 2 can show the model a few of the operator's past judgments. _gather_few_shot() in kestrel/pipeline/tier2.py selects from label rows only, for the same track, excluding the opportunity being scored, and only those with an embedding from the current embedding model. Vectors from different models live in different spaces and are never compared.

select_few_shot() in kestrel/llm/fewshot.py then does three things:

  1. Returns nothing (zero-shot) if fewer than min_labels_for_few_shot candidates exist.
  2. Ranks candidates by cosine similarity to the current description.
  3. Buckets them by verdict and takes them round-robin, ordering buckets by their best similarity, so the few_shot_k examples spread across verdicts. The aim is to avoid showing three positives and teaching the model to inflate.

The chosen opportunity ids are saved on the evaluation as few_shot_ids. few_shot_block() in kestrel/pipeline/context.py renders them as a "prior evaluations" block. The summary and rationale are both built from label.rationale, so the Why: line is dropped when it repeats the summary. See Prompts and Context Budgets for the token cost.

Reranker

The reranker is a HistGradientBoostingRegressor (kestrel/learning/reranker.py). It replaces the Tier 1 model call for items it is confident about. The LLM path is never deleted, because it is the cold-start and fallback path.

Features

kestrel/learning/features.py builds one vector per opportunity: the description embedding reduced by PCA to at most 64 dimensions (fewer if the corpus is smaller), plus tabular columns. The tabular columns are seniority rank, comp minimum and maximum (in thousands), whether comp is known, the Tier 0 pre-score, description tokens, times seen, ghost score, days since posted, one-hot source kind, remote type, org size band and ownership, and a binary per soft signal read from Tier 0's stage_reason. Consulting rows add one-hot trigger event type and trigger confidence. Vocabularies are fixed, so an unseen category becomes all zeros instead of shifting columns.

Training

train_reranker() in kestrel/learning/reranker.py does the fit. It is reached three ways: kestrel train, POST /api/learning/train (both fit inline and return at once), and a durable task. kestrel/learning/training.py owns the task path:

  • A train_reranker task (TASK_TYPE) is inserted by request_training(). The Calibrate page's train button calls it (POST /calibrate/train), and the worker calls it automatically for each enabled track before it leases training work (run_cycle(), called from _worker_loop in kestrel/web/app.py while the worker is not paused).
  • request_training() queues nothing when build_model is off, when fewer than min_labels_for_reranker ratings exist, or when a task for that track is already pending or leased. A single INSERT ... SELECT ... WHERE NOT EXISTS makes concurrent clicks and the scheduler safe without a new table.
  • An automatic request has two more refusals. It does nothing while a promoted model is already active for the track. After a model exists or a task has run, it waits until there are RETRY_RATINGS (50) more ratings than the last attempt had.
  • run_cycle() leases the task on a 600 second lease with a 60 second heartbeat, fits locally (never a hosted model), stores the TrainResult in the task payload, and completes the lease. A crash after the result is saved but before completion does not refit. A failure releases the task for retry on the next cycle and ends the cycle, so one transient error cannot spend every attempt.
  • state() turns the latest task into the sentence the Calibrate page shows. The page also shows promotion progress (promotion_status()).

The fit itself:

  1. Fits the PCA on all embeddings of the current embedding model for the track.
  2. Builds rows for every opportunity that has an embedding and a target: the operator's score where they judged it, else the Tier 2 holistic score where they did not override it.
  3. Counts usable labels, meaning labeled rows that have an embedding. If that is below min_labels_for_reranker, it returns "insufficient usable labels" and saves nothing.
  4. Holds out 25 percent of the labeled rows (at least one, seeded), trains on the rest plus all unlabeled rows, and evaluates on the held-out set only.

Promotion criteria

The model is promoted only if all four criteria hold on the held-out set. A criterion that cannot be measured counts as failed, not as passed.

Criterion Rule
enough_labels Usable labels at or above min_labels_for_reranker
mae_ok At least 5 held-out rows and MAE below reranker_max_mae
beats_llm At least 5 held-out items with an LLM Tier 1 verdict, and reranker keep/kill agreement with the operator higher than the LLM's on those same items
recall_ok At least 5 held-out items the operator rated apply or pursue, and recall above 0.95 on them

"Keep" means a score at or above thresholds.consider (3.0). Recall is measured against the operator's own verdict, not a score proxy. Each refusal reason states its sample size, so "too few held-out items" reads differently from "does not beat the LLM". The constants are _MIN_APPLY_FOR_RECALL, _MIN_HELD_FOR_MAE, _MIN_LLM_FOR_COMPARISON and _RECALL_MIN_THRESHOLD, and promotion_status() reads the same ones to render the Calibrate progress panel, so the page cannot drift from the gate.

Storage and refusal

_save_model() writes two pickles to the ML folder from kestrel/paths.py, the model and the fitted features (PCA and column layout), and an MlModel row with the sklearn version, feature names and metrics, including the embedding model name. A promoted model deactivates the previous one for that track. A model that fails the gate is still saved, inactive.

load_active_reranker() returns None, so Tier 1 falls back to the LLM, when:

  • the row's embedding model differs from the current one (quiet, expected after switching embedding engines until the next retrain);
  • the sklearn version differs, because pickles are version-locked (a warning notification is raised);
  • an artifact file is missing or unreadable (also a notification);
  • a file's signature does not verify. Every saved model file and its fitted-features file is signed with HMAC-SHA256 under a per-install key (kestrel/learning/signing.py, stored in ml_model.artifact_signature and pca_artifact_signature) and the loader verifies the signature before it unpickles anything. The key lives under the data folder, is created on first use and is never part of a backup, so a restored or copied file does not verify. A model saved before signing, or one changed on disk, is refused with a notice and scoring uses the AI model step. A refused model queues one retrain on its own; if that attempt fails the checks, the next waits for 50 more ratings as usual.

Tier 1 fast path

try_reranker_tier1() runs before the LLM. It needs a current-model embedding of the right width. If the predicted score is within reranker_uncertain_band (0.4) of the keep cutoff (3.0), it returns None and the LLM decides. Outside the band it records a Tier 1 evaluation with forced_by="reranker", then either queues Tier 2 (keep) or sets stage t1_reject with the predicted score in the reason (kill).

Hard rule 4 still applies here: uncertainty escalates and never rejects. A reranker kill only happens at least 0.4 below the cutoff.

Active learning queue

rank_uncertain() in kestrel/learning/active.py ranks Tier 2-evaluated opportunities that have no label or override, for the Calibrate page. Four components combine, each in the range 0 to 1:

uncertainty = 0.40 * proximity + 0.25 * divergence + 0.20 * novelty + 0.15 * recency
  • proximity: how close the score is to the apply threshold (4.0), falling to zero at 1.5 points away.
  • divergence: the gap between the model's holistic score and the weighted score, over 1.5, capped at 1.
  • novelty: 1 minus the highest cosine similarity to any labeled example, or 0.5 when nothing can be compared.
  • recency: falls to zero over 90 days since first seen.

Only one role from each duplicate group is ranked: its canonical copy, or the lowest id when no copy is canonical. Ties in the uncertainty score sort by id.

The spec's fifth component, reranker prediction variance, is deliberately not implemented. The docstring notes that the gradient-boosted model exposes no per-tree variance. The page and GET /api/learning/queue return the top 10.

Drift

check_drift() looks at the labels recorded after the active reranker was trained, takes the last 50, scores each with the reranker and averages the absolute error. If the mean exceeds drift_threshold (0.8), it sets is_active to false, raises a reranker_drift notification and Tier 1 returns to the LLM.

Fewer than five usable post-training labels returns an "insufficient" result and never demotes. Labels the model trained on are excluded, otherwise right after promotion the window would be mostly rows the model fits by construction.

The worker calls it from _worker_loop in kestrel/web/app.py after any cycle that completed Tier 1 work, and otherwise at most once every 900 seconds (_DRIFT_INTERVAL_S).

When to trust a score

Use these signals the code produces, not a fixed accuracy claim.

  • A fit word of "your call" means needs_review is set: the holistic and weighted scores differ by more than scoring.divergence_flag (0.75). Read the dimensions before relying on either number.
  • "New" and "Scoring failed" are never a rejection. A quarantined item is parked, not scored down (fit_for() in kestrel/web/fit.py).
  • A suspect legitimacy status caps the displayed score at 3.5, and a blocker forces pass, so a low score can be a rule, not a fit judgment. forced_by on the evaluation says which.
  • With few labels the score reflects the shipped weights and prompt alone. Few-shot examples start at 15 labels, and a calibration proposal needs 30.
  • analyze_outcomes() in kestrel/learning/outcomes.py checks whether the score predicted anything real. It compares response rates across score bands (below 3.0, 3.0 to 4.0, 4.0 to 4.5, 4.5 and up), requires a score-to-response correlation of at least 0.15 and a spread of at least 5 points across bands, and says plainly that the score is not discriminating when it fails. With fewer than two bands holding five or more outcomes it reports insufficient data instead of a verdict.

Every rate in these reports is shown beside its sample size and labeled insufficient under five observations (hard rule 6). The same module suggests a ghosting threshold from the 90th percentile of time to first response, again only with five or more responses. See Analytics Internals for the shared rule.

Resetting

reset_learning() in kestrel/learning/ledger.py removes the three things the loop accumulates, each optional: all label and verdict_override rows, all ml_model rows plus the pickle files Kestrel wrote, and calibrations (marked rejected, with the scoring.weights.* rows deleted so shipped weights apply again). It does not touch opportunities, evaluations, pursuits, documents or outcomes.

Clone this wiki locally