# CAL-QC v1 — Historical calibration and verified-error learning **Artifact:** `artifacts/goal/batches/protocol-sections/items/calibration-qc/result.md`. For later integration. **All policies/thresholds are proposed, not measured.** Sources checked **2026-11-29**; synthetic fixtures are not real forecasts/quotes. **Measured performance: null; no IMD ledger/settlements supplied.** Existing allowance/price amounts are unknown. Use existing Swarm budgets and the current customer price. **IMD Swarm remains the sole research and prediction engine**; evaluation/calibration stays within its workflow. No independent AI, paid API or additional customer fee. ## 1. Freeze candidates and evidence Unit: **event × exact market × forecast horizon × issued version**, including the full outcome vector. Quotes, repeated customer requests and translations are not independent predictions. Before outcomes, register the 1–14 events, markets, fixture snapshot, eligibility/selection rules, discovery cutoff and deduplication keys. Freeze all candidates/forecasts/alternatives/abstentions and exclusions/discovery failures. Never rebuild the universe from winners; claims apply only to this selected universe. Required append-only ledger bundles: | Bundle | Required fields | |---|---| | Target | Candidate/request/event/dependency IDs; sport, competition, participants; scheduled/actual start; exact market, line, period, ordered classes and settlement-rule version, including overtime/retirement/dead-heat treatment. | | Freeze | UTC cutoff, issue/freeze times, horizon, append sequence; Swarm/model/prompt, feature/parser, calibrator, decision and evaluation versions; parameters, software versions, seeds and content hashes. | | Evidence | As-of feature values/units/transforms and missingness reasons; primary/contradictory evidence, confirmed/projected status, URLs and retained permitted snapshots; publication, first-observation, capture and revision-availability times. | | Decision | Raw/calibrated vectors; most probable outcome, uncertainty method/range or null/reason, evidence-confidence/rule version; estimated value and recommend/no-bet verdict/reason. No-value abstentions retain p; insufficient evidence may require p=null. | | Quotes/audit | Each accessible book's complete matching market/prices, quote/observation times, URL/snapshot, access/jurisdiction/status/rules; attempted Stake/BET99/bet365 entries null/reason if unavailable. Include budget use, exclusions and supersession links. | Require `cutoff <= issued_at <= frozen_at < start`; recheck actual start. Fact availability is the maximum known publication, first-observation, capture and revision-availability time, and must be <= cutoff. First-observation/capture are mandatory; unknown publication needs a reason and contemporaneous proof. Old effective dates do not prove availability. Reject conflicting clocks; numerical training-fitted imputation cannot invent injuries/lineups. Retain canonical UTF-8 JSON bytes; SHA-256 excludes its own digest. Chain prior digests and trusted append receipts: hashes alone do not prove time. Append updates and pre-register which horizon/version is scored; never select after outcomes. Revised statistics get new observation times/hashes. Replay uses original vintages; corrections affect future forecasts after observation. Later closing odds stay outside earlier feature/calibrator joins. ## 2. Append verified settlement Append forecast/settlement IDs, authoritative organizer/competition result and evidence, publication/observation/verification times, verifier/parser version, actual start/end, outcome/finality, book rules/payout and correction links. Distinguish sporting targets from contractual payouts. Conflicting or inadequate evidence remains unresolved with reasons/sources. Statuses: pending, unresolved, resolved, void, push. Score only verified labels matching the frozen target. Draws can be classes; pushes are not y=0.5. Predeclare win/push/loss probabilities or explicitly condition on non-push and disclose exclusions. Quarter-lines need predeclared component targets or settlement categories; fractional payouts are not fractional binary labels. Keep voids/unresolved events in coverage/status counts and pending-age reports, outside applicable losses. A book void does not erase a valid sporting-target score. Never assume refunds, labels or delete unresolved events. Corrections/late settlements append versions; every evaluation pins versions/as-of time and preserves initial results beside restatements. Historical fitting uses labels then verified, never later corrections. Hypothetical returns use frozen one-unit stakes/quotes/rules; report net return, turnover/refunds and void rates. Missing inputs mean null/reason. Profit/closing diagnostics do not replace probability scores. ## 3. Reproducible chronological recipe Time ordering avoids future-to-past training. The standard splitter assumes equally spaced samples and expresses gaps in rows; irregular sports require this timestamp/group recipe. [TimeSeriesSplit](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.TimeSeriesSplit.html) 1. **Pre-register:** universe/targets, hashes/vintages/versions, exclusions, class order, groups/weights/windows, seeds/optimizer, metrics/baselines and review/release gates. Keep per-row assignments/losses; separate prospective and reconstructed evidence. 2. **Group/purge:** keep all markets/snapshots/horizons of an event together. Group shared labels: series, racing weekends, tournament outrights/constituents and accumulators sharing legs. Label intervals extend from earliest cutoff to latest required verification. Purge fitting intervals crossing the next stage's admission boundary and entire groups spanning stages. Causal reuse of already-public history is allowed; centered windows/shared future labels are not. 3. **UTC half-open windows:** for test origin `t`, embargo `E=max(48 hours,H+L)`, with registered maximum forecast-to-resolution horizon H and delay bound L estimated only from earlier training. Unknown bounds disable that family's fit; unfinished events remain excluded. Set `C_end=t-E`, `C_start=C_end-90d`, `T_end=C_start-E`, `T_start=T_end-365d`. Train `[T_start,T_end)`, calibrate `[C_start,C_end)`, test `[t,t+30d)`. Labels must be verified by their fitting stage's end. Exact interval purging still applies. 4. **Train-only choices:** fit imputation/scaling, encodings, feature selection, rating parameters, hyperparameters and prompt/decision rules on train, using inner chronological grouped splits. Apply transforms unchanged to calibration/test. Causal state features may update from observed past results under frozen rules; fitted parameters remain fixed. [Leakage/preprocessing guidance](https://scikit-learn.org/stable/common_pitfalls.html) 5. **Calibrate/freeze:** produce calibration probabilities with the frozen base and as-of inputs; fit calibrator parameters only on calibration labels. Do not refit the base on calibration. Choose calibrator family/pooling/decision thresholds in earlier nested development, never current test. Freeze compatible base/calibrator artifacts before t. 6. **Rolling origins:** advance 30 days; use at least three development origins when supported. Test blocks do not overlap; each row counts once per horizon/experiment. Later origins may use earlier test labels only after verification/embargo. Retain failed folds. Reserve untouched prospective blocks after candidate selection; insufficient history is reported, not remedied by outcome-driven window changes. 7. **Replay:** score original vectors with pinned features/settlements, artifacts, seeds and numeric tolerance. Refitting needs original Swarm artifacts/training inputs; missing versions/snapshots mean not_replayable. Today's Swarm may know past outcomes; instructions to ignore them cannot prove clean backtesting. Reconstructed forecasts cannot support prospective claims/promotion. Pin evaluation_as_of and publish corrected-label restatements separately. **Matched baselines:** uniform 1/K; training-frequency `(n_k+1)/(n+K)` within scope; raw Swarm; incumbent; contemporaneous bookmaker probabilities. Added-one smoothing is proposed. For each complete book market use declared margin-removal approximation `q_k=(1/odds_k)/sum_j(1/odds_j)`, retaining overround. Require identical classes/line/period/rules, pre-cutoff observation and proposed maximum quote age five minutes (or stricter registered rule). Do not combine best prices from different books/times. Optional consensus normalizes componentwise medians of complete vectors. Report paired-intersection losses and missing-book/full Swarm coverage. Closing odds are later-information diagnostics with timestamps/completeness, never replacement inputs or equal-information baselines. ## 4. Scores, reliability and coverage Binary `p_i=P(y_i=1)`; multiclass vectors use ordered classes/one-hot y. Reject nonfinite/out-of-range values or sum error >1e-8; never silently repair forecasts. Each event's m pre-registered markets within a reported family get weights `w_i=1/m`, fixed before outcomes; `W=sum w_i` over scored rows. Report W, rows and groups; no stake/outcome weighting. | Loss; lower is better | Formula | |---|---| | Binary Brier, 0–1 | `sum_i w_i*(p_i-y_i)^2 / W` | | Multiclass Brier, 0–2 | `sum_i w_i*sum_k(p_ik-y_ik)^2 / W` | | Binary log loss | `-sum_i w_i*[y_i*ln(p_i)+(1-y_i)*ln(1-p_i)] / W` | | Multiclass log loss | `-sum_i w_i*ln(p_i,true_class) / W` | Name the Brier scale explicitly. [Brier definitions](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.brier_score_loss.html) Logs are natural. [Log-loss definition](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.log_loss.html) Realized zero-probability classes give infinite exact log loss; unobserved 0*ln(0) contributes zero. JSON uses null/reason plus infinity flag. Secondary `clipped_log_loss` may floor components at epsilon=1e-9, renormalize and count altered rows, equally for all baselines; it cannot hide infinities/pass promotion. Empty denominators return null/reason. Do not mix binary/unscaled multiclass Brier without a declared common scale. **Reliability:** fixed bins `[0,.1),...,[.9,1]`, including empty bins. Show rows, unique groups, weight, mean p, observed frequency and gap. Multiclass needs each class-versus-rest and separate top-label correctness diagrams. `ECE=sum_b(W_b/W)*abs(mean_p_b-frequency_b)` is bin-dependent, not a sole gate. Losses mix calibration/discrimination. [Calibration documentation](https://scikit-learn.org/stable/modules/calibration.html) For independent unweighted counts, 95% Wilson frequency intervals use z=1.96, center `(f+z²/(2n))/(1+z²/n)`, half-width `z*sqrt(f*(1-f)/n+z²/(4n²))/(1+z²/n)`. This uses no continuity correction. [SciPy proportion intervals](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats._result_classes.BinomTestResult.proportion_ci.html) State binomial assumptions; this is not an interval for one event's true probability. Dependent/weighted scores and paired differences use proposed whole-cluster bootstrap: group shared events/series/legs plus competition-calendar-week blocks, merge intersecting groups, resample groups with replacement preserving pairs and recompute weighted metrics. Pin grouping, PRNG/seed 17, 1,000 replicates and percentile bounds 2.5/97.5. Below 20 groups, degenerate replicates or known unmodeled dependence: uncertainty=null/reason. Bins below 30 groups remain visible as sparse. Freeze bins/clusters before outcomes; residual dependence can invalidate coverage. **Denominators:** eligible N; probability coverage N_with_p/N; recommendation coverage N_recommend/N; valid-label coverage N_valid_labels/N; scoreability N_scored/N_with_p; matched-book coverage. Include invalid, excluded, missing, budget-deferred, pending, unresolved, void/push counts/reasons/ages. Score all probability-bearing abstentions and report recommended-only scores separately. Never invent p for missing-evidence abstentions. Compare natural and predeclared matched coverage; disclose selection/resolved-only bias. Unknown inclusion probabilities prevent population reweighting claims. Across all 20 supported sports, diagnose sport × market/settlement × horizon, confidence/probability bin, competition, version, favorite/underdog, lineup/source completeness, season and verdict. Include prevalence/sharpness, paired baseline losses, coverage/uncertainty and contradictory-evidence counts. Empty slices show null/reason/counts; exploratory slices generate hypotheses, not repeated significance claims. ## 5. Sparse calibration and combinations Proposed local minimum: 500 calibration event groups, 50 distinct groups/class. Binary: `sigmoid(a*logit(p_raw)+b)`, minimizing weighted mean log loss + `0.01*((a-1)^2+b^2)`, with a in [0,5], b in [-5,5]. Multiclass: `p'_k=p_k^(1/T)/sum_j p_j^(1/T)`, T in [.5,5], minimizing weighted mean log loss + `0.01*(ln T)^2`. Use the epsilon transform for fitting endpoints. Pin optimizer/version, initial (a,b)=(1,0) or T=1, tolerance 1e-8, 500-iteration cap; failure retains incumbent. Temperature scaling's image/document evidence is not sports validation. [Guo et al., 2017](https://proceedings.mlr.press/v70/guo17a.html) Choose family in earlier development; no isotonic search in this initial budget. Base/calibrator fitting data must be disjoint. [Calibration requirement](https://scikit-learn.org/stable/modules/calibration.html) Sparse fallback: validated parent within the same sport, target schema, horizon and compatible base family; store local/parent counts. Binary shape alone cannot justify pooling. Cross-sport pooling defaults off; require predeclared equivalence and untouched destination-sport validation. Without valid parent, evidence-supported raw p is labeled uncalibrated/low-confidence/no value recommendation. Without primary evidence: p=null/no-bet/reason. Freeze evidence-confidence: low for unvalidated fallback/gaps; medium for validated parent and adequate evidence; high for local validation/fresh evidence/no material contradiction. Keep it distinct from probability. For 1–14 events retain legs/dependency links and Swarm joint probability/method or null/reason. Multiplication needs defensible registered independence. Score joint all-win targets separately, grouping shared legs and slicing leg count/dependence. Sparse joints cannot inherit leg calibration. A void leg does not retrospectively redefine the forecast; handle original target and contractual payout separately. ## 6. Verified-error learning and prospective release Append reviews linked to forecast/settlement. Inspect as-of compliance before revealing outcome where feasible; then record scenarios, realized-outcome probability, contradictions, root-cause confidence and repair hypothesis. Review wins too. | Classification | Evidence/action | |---|---| | Surprise | Valid process, lower-probability outcome. Retain loss; one upset does not prove miscalibration. | | Process/data error | Proven mishandled pre-cutoff evidence, stale/duplicate/wrong-target inputs, leakage, probability arithmetic or market/rule/publication failure. Link artifacts, fix process, add regression fixture. | | Later information | First available after cutoff; cannot enter old forecast/replay. Omitted pre-cutoff facts need timestamped proof. | | Model weakness | Repeated supported residual pattern across groups/time; develop changes on earlier windows, test prospectively. | | Unknown | Root cause null/reason; retain conflicting explanations and queue verification. | Counterfactuals use original-cutoff-available evidence, remain diagnostic and cannot replace issued results. Newly discovered old evidence can prove collection failure, not original consumption. Fixes receive new versions/effective dates. Keep scoreable invalid issued forecasts in operational audit/losses; leakage-contaminated rows are excluded from clean validation with counts, never silently deleted. **Proposed promotion:** one precommitted challenger/scope/cycle; two untouched consecutive 30-day blocks, >=500 resolved groups and >=50 groups/class. Matched-row log-loss improvement >=0.01 nats versus incumbent; upper 95% paired bootstrap bound on challenger-minus-incumbent <0; Brier degradation <=0.005 on named scale. Require no infinite exact loss/integrity violations, probability-coverage decline <=5 percentage points, no supported predeclared sport/market slice log-loss deterioration >0.05, and beat training-frequency baseline on both losses. Define supported slices as >=200 groups and >=50 groups/class. Show bookmaker comparisons separately. Insufficient/conflicting evidence retains incumbent; failure requires a new future cohort, not test reuse. Passing does not certify profit. **Drift/rollback proposal:** weekly compare recent 30 days with preceding 90. Review feature-missingness/prevalence shifts >=10 percentage points, or reliability gap >0.10 in a bin with >=100 groups whose interval excludes mean p. Triggers prompt investigation, not automatic model changes. Confirm on scheduled non-overlapping blocks; no promotion from repeated peeking. Proven leakage/provenance/market-mapping failures immediately suspend affected value recommendations; use compatible validated version or no-bet. Performance rollback: two predeclared non-overlapping 30-day blocks, >=200 groups each, current-minus-reference log loss >0.02 in both and pooled paired 95% interval entirely >0. Reference forecasts must be contemporaneously stored. Missing compatible reference means rollback_target=null/reason and no-bet pending review. Retain incident/effective times and restatements. **Within existing allowances:** reuse canonical Swarm evidence across users/languages; deterministic scoring needs no research calls. Batch unique-result verification/cache corrections. Weekly review up to five largest-loss groups plus five seeded sampled groups including wins, queue remainder. Defer experiments/shadows or abstain when budget cannot support them; never lower evidence gates or infer additional allowances. QC output: manifest/dataset hashes, as-of date, fold losses/exclusions, baseline intersections, reliability/coverage/uncertainty, review/drift links and gate decisions. Separate proposed_policy, synthetic_test_results, measured_performance. Show primary probability/confidence/explanation and material limitations; collapse detail. Swarm translations, including Hindi, preserve one numeric object and verdicts. ## 7. Minimal row and worked acceptance case **Synthetic only, not publishable.** Fixture IDs/values below are not real evidence. Null source/hash fields fail production provenance gates; omitted contract fields belong in referenced bundles. ```json { "type":"forecast", "synthetic":true, "publishable":false, "candidate_id":"SYN-A", "request_id":"SYN-request", "event_id":"SYN-E1", "group_id":"SYN-E1", "sport":"tennis", "eligible":true, "market":{"type":"match_winner","period":"match","line":null, "outcomes":["A","B"],"rules":"SYN: completed match; retirement void"}, "cutoff":"2026-01-10T10:00:00Z", "issued_at":"2026-01-10T10:00:01Z", "frozen_at":"2026-01-10T10:00:02Z", "start":"2026-01-10T11:00:00Z", "versions":{"swarm":"SYN-v1","prompt":"SYN-p1","features":"SYN-f1", "parser":"SYN-s1","calibrator":"SYN-c1","policy":"SYN-d1","evaluation":"SYN-e1"}, "features":{"strength_difference":0.4}, "evidence":[{"url":null,"published_at":"2026-01-10T09:40:00Z", "first_seen_at":"2026-01-10T09:41:00Z","snapshot_at":"2026-01-10T09:41:00Z"}], "p_raw":[0.72,0.28], "p":[0.70,0.30], "primary":"A", "confidence":"medium", "verdict":"recommend", "verdict_reason":"synthetic_value_test", "estimated_value":0.12, "quotes":[{"book":"synthetic","odds":[1.60,2.40],"url":null, "quoted_at":"2026-01-10T09:59:00Z","observed_at":"2026-01-10T09:59:00Z"}], "digest":null, "settlement":null, "null_reasons":{"line":"not_applicable","source_urls":"synthetic_fixture", "digest":"not_archived_fixture","settlement":"pending_at_freeze"} } ``` No named book was queried for this fixture; real rows must record missing-book attempts/reasons. Append synthetic settlement `forecast=SYN-A, status=resolved, outcome=B, verified_at=2026-01-10T13:00:00Z, source_url=null, reason=synthetic_fixture`, without changing the forecast. Expected A losses: Brier .49, log loss 1.2039728043. **Synthetic scoring fixture:** six eligible binary candidates; one independent event/group each, equal weights; label 1 means outcome A. Recommendation evidence/prices are fictional. | ID | p | Verdict | Verified target | |---|---:|---|---| | A | .70 | recommend | 0 | | B | .20 | no-bet: no value | 0 | | C | .60 | recommend | 1 | | D | null | no-bet: insufficient evidence | 1 | | E | .80 | recommend | pending; null | | F | .65 | recommend | void under target rules; null | Expected probability coverage 5/6, recommendation coverage 4/6, valid-label coverage 4/6, scoreability 3/5. A/B/C: Brier **.23**, log loss **.6459806598**. Recommended scored A/C: .325 and .8573992140 (n=2). Uniform baseline on A/B/C: .25 and .6931471806. D has no invented score; E/F are excluded from losses. These are arithmetic fixtures, **not measured IMD skill**. Bins `[.2,.3)`, `[.6,.7)`, `[.7,.8)` each have one row/group; mean p=.2,.6,.7; frequency=0,1,0. Wilson intervals approximately [0,.79346], [.20654,1], [0,.79346]; sparse flags required. Bootstrap uncertainty=null (<20 groups). ECE=.4333333333. Multiclass `[.5,.3,.2]`, true zero-based index 1: Brier .78, log loss 1.2039728043. Fictional odds [1.60,2.40] normalize to [.60,.40]; p=.70 gives expected net `.70*1.60-1=.12` per unit before costs. These are not named-book prices. **Late-fact acceptance test (Python standard library, synthetic):** ```python from datetime import datetime def dt(s): return datetime.fromisoformat(s.replace("Z", "+00:00")) def gate(f, cutoff): if any(f.get(k) is None for k in ("first_seen_at", "snapshot_at")): return "UNKNOWN_AVAILABILITY" keys = ("published_at", "first_seen_at", "snapshot_at", "revision_at") return "ACCEPT" if max(dt(f[k]) for k in keys if f.get(k)) <= dt(cutoff) else "LATE_FACT" def ts(hm): return "2026-01-10T" + hm + ":00Z" old = dict(effective_at=ts("09:00"), published_at=ts("09:40"), first_seen_at=ts("09:41"), snapshot_at=ts("09:41"), revision_at=None) late = dict(old, snapshot_at=ts("10:01"), revision_at=ts("10:01")) assert gate(old, ts("10:00")) == "ACCEPT" assert gate(late, ts("10:00")) == "LATE_FACT" assert gate(dict(old, first_seen_at=None), ts("10:00")) == "UNKNOWN_AVAILABILITY" assert old["revision_at"] is None ``` Expected: old effective/publication dates cannot admit the late correction or change original scores. Integration also must reject cross-split event groups, late fitting labels, mismatched lines/overtime and closing-price leakage; deduplicate customer/language copies; flag realized zero-probability outcomes as infinite exact loss; append resolutions only into new evaluation versions. English/Hindi renderings must preserve vectors, values and verdicts. ## 8. Limitations Archives/retention rights, book access/rules, delay bounds, Swarm artifacts and numeric budgets remain null/unknown until integration verifies them. Free method documentation does not establish free sports/odds archives; missing history requires prospective collection. Selection/unresolved bias, timestamp errors, approximate margin removal and residual dependence remain possible. Gates/intervals guarantee neither calibration nor profit. Temperature scaling cannot fix all class-specific bias; repair hypotheses need future validation.