-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathannual.py
More file actions
1252 lines (1162 loc) · 46.5 KB
/
Copy pathannual.py
File metadata and controls
1252 lines (1162 loc) · 46.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import json
import logging
import time
import traceback
from collections.abc import Callable, Mapping, Sequence
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, replace
from pathlib import Path
from typing import Any
import pandas as pd
import yaml
from csi500_alpha.config import AppConfig, ExperimentSettings
from csi500_alpha.data.storage import write_json_atomic, write_parquet_atomic
from csi500_alpha.errors import ConfigurationError
from csi500_alpha.research.universe import select_rebalance_dates
from csi500_alpha.study import (
GateRule,
StudyContext,
StudySpec,
StudyTrial,
select_study_candidates,
)
from csi500_alpha.utils import canonical_json, sha256_file, sha256_text, utc_now
_OPERATORS = {"==", "!=", ">", ">=", "<", "<="}
LOGGER = logging.getLogger(__name__)
@dataclass(frozen=True)
class HistoricalExperiment:
experiment_id: str
role: str
status: str
included_in_selection: bool
note: str
def to_dict(self) -> dict[str, Any]:
return {
"id": self.experiment_id,
"role": self.role,
"status": self.status,
"included_in_selection": self.included_in_selection,
"note": self.note,
}
@dataclass(frozen=True)
class AnnualStudySpec:
config_path: Path
annual_id: str
method_study_path: Path
method_study_reference: str
method_study: StudySpec
years: tuple[int, ...]
train_start: str
embargo_days: int
max_workers: int
publication_gates: tuple[GateRule, ...]
history: tuple[HistoricalExperiment, ...]
@classmethod
def from_yaml(cls, config_path: str | Path) -> AnnualStudySpec:
path = Path(config_path).resolve()
if not path.is_file():
raise ConfigurationError(
f"Annual study configuration does not exist: {path}"
)
raw = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
root = _mapping(raw, "annual study config")
_reject_unknown(
root,
{"annual_study", "publication_gates", "history"},
"annual study config",
)
annual = _mapping(
_required(root, "annual_study", "annual study config"),
"annual_study",
)
_reject_unknown(
annual,
{
"id",
"method_study",
"years",
"train_start",
"embargo_days",
"max_workers",
},
"annual_study",
)
annual_id = _simple_name(
_required(annual, "id", "annual_study"),
"annual_study.id",
)
method_reference = str(
_required(annual, "method_study", "annual_study")
)
method_path = (path.parent / method_reference).resolve()
method_study = StudySpec.from_yaml(method_path)
raw_years = _sequence(
_required(annual, "years", "annual_study"),
"annual_study.years",
)
years = tuple(int(value) for value in raw_years)
if not years or years != tuple(sorted(set(years))):
raise ConfigurationError(
"annual_study.years must be nonempty, sorted and unique"
)
if any(year < 1990 or year > 2100 for year in years):
raise ConfigurationError("annual_study.years contain an invalid year")
if any(
right != left + 1
for left, right in zip(years, years[1:], strict=False)
):
raise ConfigurationError("annual_study.years must be consecutive")
train_start = _date(
_required(annual, "train_start", "annual_study"),
"annual_study.train_start",
)
embargo_days = int(annual.get("embargo_days", 5))
if embargo_days < 0:
raise ConfigurationError("annual_study.embargo_days cannot be negative")
max_workers = int(annual.get("max_workers", 1))
if not 1 <= max_workers <= 8:
raise ConfigurationError("annual_study.max_workers must be between 1 and 8")
raw_gates = _sequence(root.get("publication_gates", ()), "publication_gates")
publication_gates = tuple(
_gate_rule(value, position)
for position, value in enumerate(raw_gates)
)
raw_history = _sequence(root.get("history", ()), "history")
history = tuple(
_historical_experiment(value, position)
for position, value in enumerate(raw_history)
)
history_ids = [item.experiment_id for item in history]
if len(history_ids) != len(set(history_ids)):
raise ConfigurationError("Historical experiment ids must be unique")
current_ids = {trial.trial_id for trial in method_study.trials}
collisions = sorted(current_ids.intersection(history_ids))
if collisions:
raise ConfigurationError(
"Historical experiment ids collide with current candidates: "
f"{collisions}"
)
if any(item.included_in_selection for item in history):
raise ConfigurationError(
"Historical experiments are disclosure records and cannot enter "
"the current candidate selection"
)
return cls(
config_path=path,
annual_id=annual_id,
method_study_path=method_path,
method_study_reference=method_reference,
method_study=method_study,
years=years,
train_start=train_start,
embargo_days=embargo_days,
max_workers=max_workers,
publication_gates=publication_gates,
history=history,
)
def to_dict(self) -> dict[str, Any]:
return {
"annual_study": {
"id": self.annual_id,
"method_study": self.method_study_reference,
"method_study_hash": self.method_study.spec_hash,
"years": list(self.years),
"train_start": self.train_start,
"embargo_days": self.embargo_days,
"max_workers": self.max_workers,
},
"publication_gates": [gate.to_dict() for gate in self.publication_gates],
"history": [item.to_dict() for item in self.history],
}
@property
def spec_hash(self) -> str:
return sha256_text(canonical_json(self.to_dict()))
def registry(self) -> dict[str, Any]:
candidates = [
{
"id": trial.trial_id,
"purpose": trial.purpose,
"role": "current_candidate",
"included_in_selection": True,
}
for trial in self.method_study.trials
]
history = [item.to_dict() for item in self.history]
return {
"current_candidates": candidates,
"historical_experiments": history,
"declared_current_candidate_count": len(candidates),
"declared_historical_experiment_count": len(history),
"declared_total_experiment_count": len(candidates) + len(history),
}
@dataclass(frozen=True)
class AnnualFold:
year: int
train_start: str
train_end: str
embargo_start: str
last_mature_label_date: str
evaluation_start: str
evaluation_end: str
first_decision_date: str
last_decision_date: str
open_session_count: int
decision_count: int
@property
def fold_id(self) -> str:
return str(self.year)
def to_dict(self) -> dict[str, Any]:
return {
"fold_id": self.fold_id,
"year": self.year,
"train_start": self.train_start,
"train_end": self.train_end,
"embargo_start": self.embargo_start,
"last_mature_label_date": self.last_mature_label_date,
"evaluation_start": self.evaluation_start,
"evaluation_end": self.evaluation_end,
"first_decision_date": self.first_decision_date,
"last_decision_date": self.last_decision_date,
"open_session_count": self.open_session_count,
"decision_count": self.decision_count,
}
@dataclass(frozen=True)
class AnnualFoldExecution:
run_id: str
config_hash: str
method_hash: str
cost_hash: str
summary: dict[str, Any]
artifact_fingerprints: Mapping[str, str]
@dataclass(frozen=True)
class AnnualTrialAggregate:
summary: dict[str, Any]
artifact_fingerprints: Mapping[str, str]
@dataclass(frozen=True)
class AnnualStudyResult:
annual_id: str
status: str
annual_root: Path
task_count: int
completed_task_count: int
failed_task_count: int
pending_task_count: int
completed_trial_count: int
skipped_task_count: int
selected_trial_id: str | None
def to_dict(self) -> dict[str, Any]:
return {
"annual_id": self.annual_id,
"status": self.status,
"annual_root": str(self.annual_root),
"task_count": self.task_count,
"completed_task_count": self.completed_task_count,
"failed_task_count": self.failed_task_count,
"pending_task_count": self.pending_task_count,
"completed_trial_count": self.completed_trial_count,
"skipped_task_count": self.skipped_task_count,
"selected_trial_id": self.selected_trial_id,
}
AnnualFoldExecutor = Callable[[StudyTrial, AnnualFold, Path], AnnualFoldExecution]
AnnualTrialAggregator = Callable[
[StudyTrial, Sequence[Mapping[str, Any]], Path],
AnnualTrialAggregate,
]
def build_annual_folds(
spec: AnnualStudySpec,
base_config: AppConfig,
open_dates: Sequence[str],
) -> tuple[AnnualFold, ...]:
dates = tuple(str(value) for value in open_dates)
if dates != tuple(sorted(set(dates))):
raise ConfigurationError("Annual fold open dates must be sorted and unique")
if spec.train_start not in dates:
raise ConfigurationError(
f"annual_study.train_start is not an open date: {spec.train_start}"
)
if spec.train_start < base_config.workflow.feature_start:
raise ConfigurationError(
"annual_study.train_start cannot predate workflow.feature_start"
)
if spec.embargo_days < base_config.features.label_horizon:
raise ConfigurationError(
"Annual embargo must be at least the forward-label horizon"
)
decision_dates = select_rebalance_dates(
list(dates),
start_date=base_config.workflow.feature_start,
end_date=base_config.dates.end,
every=base_config.research.rebalance_every,
)
folds: list[AnnualFold] = []
for year in spec.years:
prefix = str(year)
year_open = [date for date in dates if date.startswith(prefix)]
year_decisions = [date for date in decision_dates if date.startswith(prefix)]
if not year_open or not year_decisions:
raise ConfigurationError(f"Annual fold {year} has no open or decision dates")
evaluation_start = year_decisions[0]
evaluation_end = year_open[-1]
earlier_decisions = [date for date in decision_dates if date < evaluation_start]
if not earlier_decisions:
raise ConfigurationError(f"Annual fold {year} has no prior training decision")
train_end = earlier_decisions[-1]
start_position = dates.index(evaluation_start)
mature_position = start_position - spec.embargo_days - 1
embargo_position = start_position - spec.embargo_days
if mature_position < 0 or embargo_position < 0:
raise ConfigurationError(
f"Annual fold {year} lacks history for its embargo"
)
folds.append(
AnnualFold(
year=year,
train_start=spec.train_start,
train_end=train_end,
embargo_start=dates[embargo_position],
last_mature_label_date=dates[mature_position],
evaluation_start=evaluation_start,
evaluation_end=evaluation_end,
first_decision_date=year_decisions[0],
last_decision_date=year_decisions[-1],
open_session_count=len(year_open),
decision_count=len(year_decisions),
)
)
for previous, current in zip(folds, folds[1:], strict=False):
if previous.evaluation_end >= current.evaluation_start:
raise ConfigurationError("Annual fold evaluation windows overlap")
return tuple(folds)
def resolve_annual_fold_config(
method_config: AppConfig,
*,
annual_id: str,
trial_id: str,
fold: AnnualFold,
embargo_days: int,
) -> AppConfig:
protocol_id = _simple_name(
f"{method_config.experiment.protocol_id}-{annual_id}-{trial_id}-{fold.fold_id}",
"annual fold protocol_id",
)
experiment = ExperimentSettings(
stage="validation",
protocol_id=protocol_id,
train_start=fold.train_start,
train_end=fold.train_end,
validation_start=fold.evaluation_start,
validation_end=fold.evaluation_end,
test_start=f"{fold.year + 1}0101",
test_end=f"{fold.year + 1}0101",
embargo_days=embargo_days,
allow_frozen_test=False,
)
result = replace(method_config, experiment=experiment)
result.validate()
return result
def annual_feature_contract(config: AppConfig) -> dict[str, Any]:
"""Return inputs that must match before a prepared factor layer is shared."""
return {
"dataset": config.paths.dataset,
"dates": {
"raw_start": config.dates.raw_start,
"backtest_start": config.dates.backtest_start,
"end": config.dates.end,
},
"feature_start": config.workflow.feature_start,
"rebalance_every": config.research.rebalance_every,
"factor_names": list(config.workflow.factor_names),
"feature_provider": {
"name": config.workflow.feature_provider.name,
"params": config.workflow.feature_provider.params,
},
"feature_processing": {
"label_horizon": config.features.label_horizon,
"min_factor_coverage": config.features.min_factor_coverage,
"mad_clip": config.features.mad_clip,
"industry_coverage_threshold": (
config.features.industry_coverage_threshold
),
"industry_transition_date": config.features.industry_transition_date,
},
}
def annual_cost_contract(config: AppConfig) -> dict[str, Any]:
return {
"linear_cost_bps": config.research.linear_cost_bps,
"stamp_duty_change_date": config.research.stamp_duty_change_date,
"stamp_duty_before": config.research.stamp_duty_before,
"stamp_duty_after": config.research.stamp_duty_after,
"portfolio_aum_cny": config.optimizer.portfolio_aum_cny,
"liquidity_enabled": config.optimizer.liquidity_enabled,
"adv_lookback": config.optimizer.adv_lookback,
"min_adv_observations": config.optimizer.min_adv_observations,
"max_adv_participation": config.optimizer.max_adv_participation,
"impact_bps_at_max_participation": (
config.optimizer.impact_bps_at_max_participation
),
}
def annual_study_plan(
config_path: str | Path,
*,
open_dates: Sequence[str] | None = None,
) -> dict[str, Any]:
spec = AnnualStudySpec.from_yaml(config_path)
base = AppConfig.from_yaml(spec.method_study.base_config_path)
payload: dict[str, Any] = {
"annual_id": spec.annual_id,
"annual_spec_hash": spec.spec_hash,
"method_study_id": spec.method_study.study_id,
"method_study_hash": spec.method_study.spec_hash,
"base_config_path": str(spec.method_study.base_config_path),
"years": list(spec.years),
"trial_ids": [trial.trial_id for trial in spec.method_study.trials],
"task_count": len(spec.years) * len(spec.method_study.trials),
"max_workers": spec.max_workers,
"publication_gates": [gate.to_dict() for gate in spec.publication_gates],
"registry": spec.registry(),
}
if open_dates is not None:
folds = build_annual_folds(spec, base, open_dates)
payload["folds"] = [fold.to_dict() for fold in folds]
payload["fold_plan_hash"] = _fold_plan_hash(folds)
return payload
class AnnualStudyRunner:
"""Run and resume a deterministic candidate-by-year research matrix."""
def __init__(
self,
spec: AnnualStudySpec,
*,
folds: Sequence[AnnualFold],
annual_root: Path,
context: StudyContext,
executor: AnnualFoldExecutor,
aggregator: AnnualTrialAggregator,
max_workers: int | None = None,
selected_years: Sequence[int] | None = None,
selected_trials: Sequence[str] | None = None,
) -> None:
self.spec = spec
self.folds = tuple(folds)
self.annual_root = annual_root.resolve()
self.context = context
self.executor = executor
self.aggregator = aggregator
self.max_workers = spec.max_workers if max_workers is None else max_workers
if not 1 <= self.max_workers <= 8:
raise ConfigurationError("Annual runner max_workers must be between 1 and 8")
known_years = {fold.year for fold in self.folds}
known_trials = {trial.trial_id for trial in spec.method_study.trials}
self.selected_years = (
set(int(value) for value in selected_years)
if selected_years is not None
else known_years
)
self.selected_trials = (
set(str(value) for value in selected_trials)
if selected_trials is not None
else known_trials
)
unknown_years = sorted(self.selected_years.difference(known_years))
unknown_trials = sorted(self.selected_trials.difference(known_trials))
if unknown_years or unknown_trials:
raise ConfigurationError(
"Annual task filter contains unknown values: "
f"years={unknown_years}, trials={unknown_trials}"
)
def run(self) -> AnnualStudyResult:
parent = self._initialize_manifest()
runnable: list[tuple[StudyTrial, AnnualFold, int, Path]] = []
skipped = 0
for trial in self.spec.method_study.trials:
for fold in self.folds:
path = self._task_manifest_path(trial, fold)
existing = self._read_json(path)
task_hash = self._task_hash(trial, fold)
if existing:
self._assert_task_identity(existing, trial, fold, task_hash)
if existing.get("status") == "completed":
self._verify_completed_manifest_artifacts(existing)
skipped += int(
trial.trial_id in self.selected_trials
and fold.year in self.selected_years
)
continue
if (
trial.trial_id not in self.selected_trials
or fold.year not in self.selected_years
):
continue
attempts = int(existing.get("attempts", 0)) + 1 if existing else 1
attempt_root = path.parent / f"attempt-{attempts:03d}"
runnable.append((trial, fold, attempts, attempt_root))
LOGGER.info(
"annual=%s | runnable_tasks=%d | skipped_tasks=%d | workers=%d",
self.spec.annual_id,
len(runnable),
skipped,
self.max_workers,
)
if self.max_workers == 1:
for trial, fold, attempts, attempt_root in runnable:
self._execute_task(trial, fold, attempts, attempt_root)
else:
with ThreadPoolExecutor(max_workers=self.max_workers) as pool:
futures = {
pool.submit(
self._execute_task,
trial,
fold,
attempts,
attempt_root,
): (trial.trial_id, fold.year)
for trial, fold, attempts, attempt_root in runnable
}
for future in as_completed(futures):
future.result()
manifests = self._all_task_manifests()
self._assert_completed_contracts(manifests)
write_parquet_atomic(
self._task_table(manifests),
self.annual_root / "fold-tasks.parquet",
)
aggregate_manifests = self._aggregate_trials(manifests)
write_parquet_atomic(
self._aggregate_table(aggregate_manifests),
self.annual_root / "trial-aggregates.parquet",
)
gates = self._publication_gate_results(aggregate_manifests)
write_json_atomic(gates, self.annual_root / "publication-gates.json")
selection = select_study_candidates(
self.spec.method_study,
aggregate_manifests,
)
write_json_atomic(selection, self.annual_root / "selection.json")
selected_trial_id = selection["selected_trial_id"]
completed_tasks = sum(
manifest.get("status") == "completed" for manifest in manifests
)
failed_tasks = sum(
manifest.get("status") == "failed" for manifest in manifests
)
total_tasks = len(self.folds) * len(self.spec.method_study.trials)
pending_tasks = total_tasks - completed_tasks - failed_tasks
completed_trials = sum(
manifest.get("status") == "completed"
for manifest in aggregate_manifests
)
if completed_tasks == total_tasks and completed_trials == len(
self.spec.method_study.trials
):
if selected_trial_id is None:
status = "completed_without_selection"
elif selected_trial_id not in gates["passed"]:
status = "completed_without_publishable_candidate"
else:
status = "completed"
elif failed_tasks:
status = "incomplete_with_failures"
else:
status = "incomplete"
final = {
**parent,
"status": status,
"updated_at": utc_now(),
"task_count": total_tasks,
"completed_task_count": completed_tasks,
"failed_task_count": failed_tasks,
"pending_task_count": pending_tasks,
"completed_trial_count": completed_trials,
"selected_trial_id": selected_trial_id,
"artifacts": {
"fold_tasks": "fold-tasks.parquet",
"trial_aggregates": "trial-aggregates.parquet",
"publication_gates": "publication-gates.json",
"selection": "selection.json",
"fold_root": "folds",
"aggregate_root": "aggregates",
},
}
write_json_atomic(final, self.annual_root / "annual-study-manifest.json")
return AnnualStudyResult(
annual_id=self.spec.annual_id,
status=status,
annual_root=self.annual_root,
task_count=total_tasks,
completed_task_count=completed_tasks,
failed_task_count=failed_tasks,
pending_task_count=pending_tasks,
completed_trial_count=completed_trials,
skipped_task_count=skipped,
selected_trial_id=selected_trial_id,
)
def _execute_task(
self,
trial: StudyTrial,
fold: AnnualFold,
attempts: int,
attempt_root: Path,
) -> None:
started = time.perf_counter()
path = self._task_manifest_path(trial, fold)
running = {
"schema_version": 1,
"annual_id": self.spec.annual_id,
"method_study_id": self.spec.method_study.study_id,
"trial": trial.to_dict(),
"fold": fold.to_dict(),
"task_hash": self._task_hash(trial, fold),
**self.context.identity(),
"status": "running",
"attempts": attempts,
"started_at": utc_now(),
"completed_at": None,
"artifact_root": attempt_root.relative_to(self.annual_root).as_posix(),
"run_id": None,
"resolved_config_hash": None,
"method_hash": None,
"cost_hash": None,
"summary": None,
"artifact_fingerprints": None,
"error": None,
}
write_json_atomic(running, path)
LOGGER.info(
"annual=%s | trial=%s | year=%d | status=running | attempt=%d",
self.spec.annual_id,
trial.trial_id,
fold.year,
attempts,
)
try:
execution = self.executor(trial, fold, attempt_root)
self._verify_artifacts(attempt_root, execution.artifact_fingerprints)
except Exception as exc: # noqa: BLE001 - task failures are research data
LOGGER.exception(
"annual=%s | trial=%s | year=%d | status=failed | elapsed=%.1fs",
self.spec.annual_id,
trial.trial_id,
fold.year,
time.perf_counter() - started,
)
write_json_atomic(
{
**running,
"status": "failed",
"completed_at": utc_now(),
"error": {
"type": type(exc).__name__,
"message": str(exc),
"traceback": traceback.format_exc(),
},
},
path,
)
return
write_json_atomic(
{
**running,
"status": "completed",
"completed_at": utc_now(),
"run_id": execution.run_id,
"resolved_config_hash": execution.config_hash,
"method_hash": execution.method_hash,
"cost_hash": execution.cost_hash,
"summary": execution.summary,
"artifact_fingerprints": dict(
sorted(execution.artifact_fingerprints.items())
),
},
path,
)
LOGGER.info(
"annual=%s | trial=%s | year=%d | status=completed | elapsed=%.1fs",
self.spec.annual_id,
trial.trial_id,
fold.year,
time.perf_counter() - started,
)
def _aggregate_trials(
self,
manifests: Sequence[Mapping[str, Any]],
) -> list[dict[str, Any]]:
results: list[dict[str, Any]] = []
for trial in self.spec.method_study.trials:
selected = [
manifest
for manifest in manifests
if _trial_id(manifest) == trial.trial_id
]
path = self._aggregate_manifest_path(trial)
if len(selected) != len(self.folds) or any(
manifest.get("status") != "completed" for manifest in selected
):
pending = {
"schema_version": 1,
"annual_id": self.spec.annual_id,
"trial": trial.to_dict(),
"status": "pending",
"fold_count": len(selected),
"completed_fold_count": sum(
manifest.get("status") == "completed"
for manifest in selected
),
"task_set_hash": self._task_set_hash(selected),
"summary": None,
"artifact_fingerprints": None,
"error": None,
}
write_json_atomic(pending, path)
results.append(pending)
continue
selected = sorted(selected, key=_fold_year)
task_set_hash = self._task_set_hash(selected)
existing = self._read_json(path)
if (
existing.get("status") == "completed"
and existing.get("task_set_hash") == task_set_hash
):
fingerprints = existing.get("artifact_fingerprints")
if not isinstance(fingerprints, Mapping):
raise ConfigurationError(
f"Aggregate {trial.trial_id!r} lacks artifact fingerprints"
)
self._verify_artifacts(path.parent, fingerprints)
results.append(existing)
continue
aggregate_root = path.parent
running = {
"schema_version": 1,
"annual_id": self.spec.annual_id,
"trial": trial.to_dict(),
"status": "running",
"fold_count": len(selected),
"completed_fold_count": len(selected),
"task_set_hash": task_set_hash,
"started_at": utc_now(),
"completed_at": None,
"summary": None,
"artifact_fingerprints": None,
"error": None,
}
write_json_atomic(running, path)
try:
aggregate = self.aggregator(trial, selected, aggregate_root)
self._verify_artifacts(
aggregate_root,
aggregate.artifact_fingerprints,
)
except Exception as exc: # noqa: BLE001 - aggregate failures are auditable
failed = {
**running,
"status": "failed",
"completed_at": utc_now(),
"error": {
"type": type(exc).__name__,
"message": str(exc),
"traceback": traceback.format_exc(),
},
}
write_json_atomic(failed, path)
results.append(failed)
continue
completed = {
**running,
"status": "completed",
"completed_at": utc_now(),
"summary": aggregate.summary,
"artifact_fingerprints": dict(
sorted(aggregate.artifact_fingerprints.items())
),
}
write_json_atomic(completed, path)
results.append(completed)
return results
def _initialize_manifest(self) -> dict[str, Any]:
path = self.annual_root / "annual-study-manifest.json"
existing = self._read_json(path)
identity = {
"annual_spec_hash": self.spec.spec_hash,
"method_study_hash": self.spec.method_study.spec_hash,
"fold_plan_hash": _fold_plan_hash(self.folds),
**self.context.identity(),
}
if existing:
changed = sorted(
key for key, value in identity.items() if existing.get(key) != value
)
if changed:
raise ConfigurationError(
"Existing annual study identity differs; create a new annual id. "
f"Changed fields: {changed}"
)
return existing
manifest = {
"schema_version": 1,
"annual_id": self.spec.annual_id,
"annual_config_path": str(self.spec.config_path),
"method_study_id": self.spec.method_study.study_id,
"method_study_path": str(self.spec.method_study_path),
**identity,
"data_fingerprints": dict(sorted(self.context.data_fingerprints.items())),
"git": dict(self.context.git),
"folds": [fold.to_dict() for fold in self.folds],
"publication_gates": [
gate.to_dict() for gate in self.spec.publication_gates
],
"registry": self.spec.registry(),
"status": "running",
"created_at": utc_now(),
"updated_at": utc_now(),
}
write_json_atomic(manifest, path)
return manifest
def _all_task_manifests(self) -> list[dict[str, Any]]:
results: list[dict[str, Any]] = []
for trial in self.spec.method_study.trials:
for fold in self.folds:
manifest = self._read_json(self._task_manifest_path(trial, fold))
if manifest:
results.append(manifest)
return results
def _assert_completed_contracts(
self,
manifests: Sequence[Mapping[str, Any]],
) -> None:
completed = [item for item in manifests if item.get("status") == "completed"]
cost_hashes = {str(item.get("cost_hash", "")) for item in completed}
if "" in cost_hashes or len(cost_hashes) > 1:
raise ConfigurationError(
"Completed annual folds do not share one frozen cost contract"
)
for trial in self.spec.method_study.trials:
method_hashes = {
str(item.get("method_hash", ""))
for item in completed
if _trial_id(item) == trial.trial_id
}
if "" in method_hashes or len(method_hashes) > 1:
raise ConfigurationError(
f"Trial {trial.trial_id!r} changed method settings across folds"
)
def _task_table(
self,
manifests: Sequence[Mapping[str, Any]],
) -> pd.DataFrame:
indexed = {
(_trial_id(item), _fold_year(item)): item for item in manifests
}
rows: list[dict[str, Any]] = []
for trial in self.spec.method_study.trials:
for fold in self.folds:
item = indexed.get((trial.trial_id, fold.year), {})
error = item.get("error")
rows.append(
{
"annual_id": self.spec.annual_id,
"trial_id": trial.trial_id,
"fold_year": fold.year,
"status": item.get("status", "pending"),
"attempts": int(item.get("attempts", 0)),
"run_id": item.get("run_id"),
"task_hash": item.get("task_hash"),
"resolved_config_hash": item.get("resolved_config_hash"),
"method_hash": item.get("method_hash"),
"cost_hash": item.get("cost_hash"),
"data_snapshot_hash": item.get("data_snapshot_hash"),
"artifact_root": item.get("artifact_root"),
"train_end": fold.train_end,
"last_mature_label_date": fold.last_mature_label_date,
"embargo_start": fold.embargo_start,
"evaluation_start": fold.evaluation_start,
"evaluation_end": fold.evaluation_end,
"summary_json": (
canonical_json(item.get("summary"))
if item.get("summary") is not None
else None
),
"error_type": (
error.get("type") if isinstance(error, Mapping) else None
),
"error_message": (
error.get("message")
if isinstance(error, Mapping)
else None
),
}
)
return pd.DataFrame(rows)
def _aggregate_table(
self,
manifests: Sequence[Mapping[str, Any]],
) -> pd.DataFrame:
rows: list[dict[str, Any]] = []
for item in manifests:
trial = _mapping(item.get("trial", {}), "aggregate trial")
error = item.get("error")
rows.append(
{
"annual_id": self.spec.annual_id,
"trial_id": str(trial.get("id", "")),
"status": item.get("status"),
"fold_count": int(item.get("fold_count", 0)),
"completed_fold_count": int(
item.get("completed_fold_count", 0)
),
"task_set_hash": item.get("task_set_hash"),
"summary_json": (
canonical_json(item.get("summary"))
if item.get("summary") is not None
else None
),
"error_type": (
error.get("type") if isinstance(error, Mapping) else None
),
"error_message": (
error.get("message") if isinstance(error, Mapping) else None
),
}
)
return pd.DataFrame(rows)
def _publication_gate_results(
self,
manifests: Sequence[Mapping[str, Any]],
) -> dict[str, Any]:
rows: list[dict[str, Any]] = []
for item in manifests:
trial = _mapping(item.get("trial", {}), "aggregate trial")
trial_id = str(trial.get("id", ""))
failures = (
_gate_failures(item.get("summary"), self.spec.publication_gates)
if item.get("status") == "completed"
else [f"aggregate_status={item.get('status')}" ]
)
rows.append(
{
"trial_id": trial_id,
"passed": not failures,
"failures": failures,
}
)
return {
"schema_version": 1,
"annual_id": self.spec.annual_id,
"created_at": utc_now(),
"rules": [gate.to_dict() for gate in self.spec.publication_gates],
"trials": rows,