File size: 23,074 Bytes
ff4becd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Canonical-indices generator.

Reads the immutable benchmark artifacts and produces deterministic,
stratified train/eval index lists per task. Every family runner reads
from here so cross-method comparison is fair: same N, same instances,
same indices.

The cache lives under `experiments/cache/canonical_indices/<key>/`
where `<key>` encodes (n_eval, n_train, seed, stratifier_version) -- so
changing any sample-budget parameter produces a new cache directory.
The cache is an experiment-side speed optimisation; the canonical
dataset tree under `data_small_caps/` contains only raw and derived
benchmark artifacts (which are immutable).

Per-task stratification:
  T1 (TSF):       sector x market_cap_quartile        -> (ticker, anchor_date)
  T2 (Val-PT):    full 30% ticker holdout              -> (ticker, date)
  T3 (Stmt-Gen):  per-(ticker, fiscal_year) holdout    -> (ticker, fiscal_year)
  T4 (Scen-Ret):  sector x mcap_q x event_type        -> (scenario_id, ticker)
  T5 (Val-Priv):  full 30% ticker holdout              -> (ticker, date)
  T6 (Gen-Eval):  per-(ticker, fiscal_year) holdout    -> (ticker, fiscal_year)
  T7 (RE-Val):    property_type x state                -> address
"""

from __future__ import annotations

import logging
from pathlib import Path
from typing import Literal

import numpy as np
import pandas as pd

from .. import config
from . import budgets
from .budgets import EVAL_N_PER_TASK, TRAIN_N_PER_TASK, SEED, Task

logger = logging.getLogger(__name__)


Split = Literal["train", "eval"]


def _cfg_get_lookback(granularity: str) -> int:
    """Return the canonical (shortest) lookback for ``granularity``."""
    return config.get_lookback_windows(granularity)[0] if hasattr(config, "get_lookback_windows") else 63


def _provenance_suffix(granularity: str) -> str:
    """16-char SHA-256-derived suffix encoding the relevant benchmark
    parquets for ``granularity``. Mutating any of those parquets changes
    the cache key, forcing canonical-indices regeneration.
    """
    from ._provenance import sha256_combined

    bench_dir = config.get_benchmark_dir(granularity)
    candidates = [
        bench_dir / "panel_train.parquet",
        bench_dir / "panel_test.parquet",
        bench_dir / "valuation_inputs.parquet",
        bench_dir / "valuation_ground_truth.parquet",
        bench_dir / "private_valuation_inputs.parquet",
        bench_dir / "private_valuation_ground_truth.parquet",
        bench_dir / "generation_inputs.parquet",
        bench_dir / "generation_ground_truth.parquet",
        bench_dir / "generator_eval_inputs.parquet",
        bench_dir / "generator_eval_ground_truth.parquet",
        bench_dir / "scenario_forecast_ground_truth.parquet",
        bench_dir / "scenarios.parquet",
        bench_dir / "re_train_properties.parquet",
        bench_dir / "re_eval_inputs.parquet",
        bench_dir / "re_eval_ground_truth.parquet",
    ]
    existing = [p for p in candidates if p.exists()]
    if not existing:
        return "noprov"
    return sha256_combined(existing)


def _cache_dir(granularity: str, key: str | None = None) -> Path:
    """Return the cache directory for a given budget key.

    Lives under ``experiments/cache/canonical_indices/`` (experiment-side
    speed optimisation, regenerable on miss). The canonical dataset tree
    under ``data_small_caps/`` contains only raw and derived benchmark
    artifacts; experiment-side caches NEVER live there.

    The cache key suffix encodes (i) a SHA-256 over the benchmark
    parquets and (ii) the current ``max(lookback)`` and ``max(horizon)``
    for ``granularity``. Either upstream-data drift or a horizon/lookback
    config change atomically invalidates the cache.
    """
    k = key or budgets.cache_key()
    suffix = _provenance_suffix(granularity)
    max_lb = max(config.get_lookback_windows(granularity))
    max_h = max(config.get_horizons(granularity))
    # Resolve experiments/ as a sibling of dataloader/ (this file lives
    # at projects/.../whatif_bench/dataloader/canonical_indices.py).
    experiments_dir = Path(__file__).resolve().parents[1] / "experiments"
    return (
        experiments_dir
        / "cache"
        / "canonical_indices"
        / granularity
        / f"{k}_prov={suffix}_lb={max_lb}_h={max_h}"
    )


def _stratified_sample(
    df: pd.DataFrame,
    n: int,
    strata_cols: list[str],
    seed: int,
) -> pd.DataFrame:
    """Stratified subsample of `df` to size `n`, preserving the joint
    distribution of `strata_cols` (Cartesian-product strata, with
    proportional allocation and remainder spread by row order).

    Deterministic at fixed `seed`. If `n >= len(df)`, returns df shuffled.
    """
    if n >= len(df):
        return df.sample(frac=1.0, random_state=seed).reset_index(drop=True)

    # Drop rows with NaN in any stratifier column -- they would form a
    # spurious "missing" stratum.
    valid_mask = df[strata_cols].notna().all(axis=1)
    df_valid = df[valid_mask].copy()
    if df_valid.empty:
        # Fall back to uniform random
        return df.sample(n=n, random_state=seed).reset_index(drop=True)

    df_valid["_stratum"] = df_valid[strata_cols].astype(str).agg("|".join, axis=1)

    rng = np.random.RandomState(seed)
    out_rows: list[pd.DataFrame] = []
    total = len(df_valid)

    for stratum, grp in df_valid.groupby("_stratum"):
        # Proportional allocation; at least 1 if stratum has rows.
        q = max(1, round(len(grp) * n / total))
        q = min(q, len(grp))
        out_rows.append(grp.sample(n=q, random_state=rng.randint(0, 2**31 - 1)))

    out = pd.concat(out_rows, ignore_index=True)
    # Trim or top-up to exactly n
    if len(out) > n:
        out = out.sample(n=n, random_state=seed).reset_index(drop=True)
    elif len(out) < n:
        # Top up with non-selected rows (still stratified by selection above)
        remaining = df_valid.loc[~df_valid.index.isin(out.index)]
        extra = remaining.sample(n=min(n - len(out), len(remaining)), random_state=seed)
        out = pd.concat([out, extra], ignore_index=True)

    return out.drop(columns=["_stratum"]).reset_index(drop=True)


# ── Per-task generators ───────────────────────────────────────────────────


def _gen_t1(
    granularity: str,
    n_eval: int,
    n_train: int,
    seed: int,
) -> dict[Split, pd.DataFrame]:
    """T1 TSF: stratified by sector x market_cap_quartile.

    Each (ticker, anchor_date) pair must admit a complete
    ``(lookback, max_horizon)`` window inside the corresponding split's panel,
    so every horizon evaluated by every T1 runner reuses the same anchor set.
    Concretely, for a ticker with ``T`` panel rows we keep only anchor dates
    at per-ticker positions ``[lookback, T - max_horizon - 1]``.

    Returns DataFrames with columns (ticker, anchor_date, sector, mcap_q).
    """
    from .. import config as _cfg

    # Build the canonical anchor pool against the SHORTEST lookback and
    # the LONGEST horizon. The test panel (post-2024-09-03) is ~378
    # trading days; pairing max_lookback (252) with max_horizon (252)
    # exhausts it. Methods that want a longer lookback can request it
    # at load time (load(..., lookback=252)); anchors with insufficient
    # history will be dropped by _build_t1_x_y and counted in
    # ``meta.attrs["n_canonical_dropped"]``.
    lookback = _cfg.get_lookback_windows(granularity)[0]
    max_horizon = max(_cfg.get_horizons(granularity))

    bench_dir = config.get_benchmark_dir(granularity)
    train = pd.read_parquet(
        bench_dir / "panel_train.parquet",
        columns=["ticker", "date", "sector", "derived_market_cap"],
    )
    test = pd.read_parquet(
        bench_dir / "panel_test.parquet",
        columns=["ticker", "date", "sector", "derived_market_cap"],
    )

    # Latest market_cap per ticker for the quartile assignment (across the
    # full panel, so train and eval split on the same definition).
    latest = (
        pd.concat([train, test], ignore_index=True)
        .sort_values("date")
        .groupby("ticker")
        .tail(1)[["ticker", "derived_market_cap"]]
    )
    latest["mcap_q"] = pd.qcut(
        latest["derived_market_cap"].clip(lower=1),
        4, labels=["Q1", "Q2", "Q3", "Q4"], duplicates="drop",
    )
    mcap_q = dict(zip(latest["ticker"], latest["mcap_q"]))

    def _restrict_to_valid_anchors(df: pd.DataFrame) -> pd.DataFrame:
        """Keep only rows at per-ticker positions [lookback, T-max_horizon-1]
        so a complete (lookback + max_horizon) window fits."""
        df = df.sort_values(["ticker", "date"]).reset_index(drop=True)
        df["_row_in_ticker"] = df.groupby("ticker", sort=False).cumcount()
        df["_ticker_len"] = df.groupby("ticker", sort=False)["date"].transform("size")
        valid = (df["_row_in_ticker"] >= lookback) & (
            df["_row_in_ticker"] < df["_ticker_len"] - max_horizon
        )
        return df.loc[valid].drop(columns=["_row_in_ticker", "_ticker_len"])

    out: dict[Split, pd.DataFrame] = {}
    for split, df in (("train", train), ("eval", test)):
        df = _restrict_to_valid_anchors(df)
        df = df.rename(columns={"date": "anchor_date"}).copy()
        df["mcap_q"] = df["ticker"].map(mcap_q)
        n = n_train if split == "train" else n_eval
        sampled = _stratified_sample(df, n, ["sector", "mcap_q"], seed)
        out[split] = sampled[["ticker", "anchor_date", "sector", "mcap_q"]]
    return out


def _gen_t2_t5(
    granularity: str,
    task: str,
    n_eval: int,
    n_train: int,
    seed: int,
) -> dict[Split, pd.DataFrame]:
    """T2 (Val-PT) and T5 (Val-Priv): full 30% ticker holdout for eval;
    latest snapshot per non-holdout ticker for train.

    Returns DataFrames with columns (ticker, date).
    """
    bench_dir = config.get_benchmark_dir(granularity)
    if task == "T2":
        inputs_path = bench_dir / "valuation_inputs.parquet"
        gt_path = bench_dir / "valuation_ground_truth.parquet"
    else:
        inputs_path = bench_dir / "private_valuation_inputs.parquet"
        gt_path = bench_dir / "private_valuation_ground_truth.parquet"
    inputs = pd.read_parquet(inputs_path, columns=["ticker", "date", "sector"])
    gt = pd.read_parquet(gt_path, columns=["ticker", "date"])

    # Restrict the eval pool to (ticker, date) pairs that are present in
    # BOTH inputs and gt. Without this, ~21 quarter-end snapshots per
    # task have inputs but no gt (close or shares_outstanding missing
    # on that date), and the loader silently dropped them at merge
    # time so canonical-eval N came up short of the budget.
    inputs["date"] = pd.to_datetime(inputs["date"])
    gt["date"] = pd.to_datetime(gt["date"])
    eval_pool = inputs.merge(gt, on=["ticker", "date"], how="inner")

    train_panel = pd.read_parquet(
        bench_dir / "panel_train.parquet",
        columns=["ticker", "date", "sector"],
    )

    holdout_tickers = set(inputs["ticker"].unique())
    non_holdout = train_panel[~train_panel["ticker"].isin(holdout_tickers)]
    # Latest snapshot per non-holdout ticker as the train set.
    train_latest = (
        non_holdout.sort_values("date").groupby("ticker").tail(1)
        .reset_index(drop=True)
    )

    rng = np.random.RandomState(seed)
    train_idx = train_latest.sample(
        n=min(n_train, len(train_latest)), random_state=rng.randint(0, 2**31 - 1),
    ).reset_index(drop=True)

    eval_idx = eval_pool.sample(
        n=min(n_eval, len(eval_pool)), random_state=rng.randint(0, 2**31 - 1),
    ).reset_index(drop=True)

    return {"train": train_idx, "eval": eval_idx}


def _gen_t3_t6(
    granularity: str,
    task: str,
    n_eval: int,
    n_train: int,
    seed: int,
) -> dict[Split, pd.DataFrame]:
    """T3 (Stmt-Gen) and T6 (Gen-Eval): per-(ticker, fiscal_year) split.

    Every ticker in the per-task ground-truth file is also in the
    holdout (`*_inputs.parquet` lists holdout tickers only), so a
    plain ``~ticker.isin(holdout)`` train pool would always be empty.
    Instead: per ticker, the **latest** fiscal year is the eval anchor
    and **earlier** fiscal years are train anchors. Train-eval are
    cleanly separated by fiscal year within ticker; both pools are
    non-empty as long as a ticker has >=2 reported fiscal years.

    Eval = unique (ticker, latest_fiscal_year) pairs across all tickers.
    Train = unique (ticker, prior_fiscal_year) pairs across all tickers.
    """
    bench_dir = config.get_benchmark_dir(granularity)
    if task == "T3":
        gt_path = bench_dir / "generation_ground_truth.parquet"
    else:
        gt_path = bench_dir / "generator_eval_ground_truth.parquet"

    gt = pd.read_parquet(gt_path)
    if "fiscal_year" not in gt.columns:
        if "filing_date" in gt.columns:
            gt["fiscal_year"] = pd.to_datetime(gt["filing_date"]).dt.year
        else:
            gt["fiscal_year"] = 0

    pairs = gt[["ticker", "fiscal_year"]].drop_duplicates().reset_index(drop=True)
    pairs["fiscal_year"] = pd.to_numeric(pairs["fiscal_year"], errors="coerce")
    pairs = pairs.dropna(subset=["fiscal_year"]).copy()
    pairs["fiscal_year"] = pairs["fiscal_year"].astype(int)

    # Per-ticker: latest FY -> eval, earlier FYs -> train
    pairs = pairs.sort_values(["ticker", "fiscal_year"]).reset_index(drop=True)
    pairs["_rank_desc"] = pairs.groupby("ticker")["fiscal_year"].rank(
        method="first", ascending=False,
    )
    eval_pairs = pairs[pairs["_rank_desc"] == 1][["ticker", "fiscal_year"]]
    train_pairs = pairs[pairs["_rank_desc"] > 1][["ticker", "fiscal_year"]]

    rng = np.random.RandomState(seed)
    eval_idx = eval_pairs.sample(
        n=min(n_eval, len(eval_pairs)), random_state=rng.randint(0, 2**31 - 1),
    ).reset_index(drop=True)
    train_idx = train_pairs.sample(
        n=min(n_train, len(train_pairs)), random_state=rng.randint(0, 2**31 - 1),
    ).reset_index(drop=True)

    return {"train": train_idx, "eval": eval_idx}


def _gen_t4(
    granularity: str,
    n_eval: int,
    n_train: int,
    seed: int,
) -> dict[Split, pd.DataFrame]:
    """T4 Scen-Ret: stratified by sector x mcap_q x event_type.

    Returns DataFrames with columns (scenario_id, ticker, event_type).
    """
    bench_dir = config.get_benchmark_dir(granularity)
    gt = pd.read_parquet(
        bench_dir / "scenario_forecast_ground_truth.parquet",
        columns=["scenario_id", "ticker", "event_type", "event_date",
                 "actual_return_pct"],
    )
    gt = gt.dropna(subset=["actual_return_pct"])

    # Use the panel-train cutoff as the train/eval split anchor (matches
    # the canonical T1 split semantics).
    panel_train_df = pd.read_parquet(
        bench_dir / "panel_train.parquet", columns=["ticker", "date"],
    )
    panel_test_df = pd.read_parquet(
        bench_dir / "panel_test.parquet", columns=["ticker", "date"],
    )
    panel_train_df["date"] = pd.to_datetime(panel_train_df["date"])
    panel_test_df["date"] = pd.to_datetime(panel_test_df["date"])
    split_date = panel_train_df["date"].max()
    gt["event_date"] = pd.to_datetime(gt["event_date"])

    # Restrict the eval/train pools to events whose ticker has at least
    # ``min_history`` panel days BEFORE the event date in the combined
    # panel. Without this filter, ~6.5% of train events sampled at the
    # canonical step cannot produce a valid 63-day lookback at load
    # time and were silently zero-padded then dropped.
    min_history = max(_cfg_get_lookback(granularity), 63)
    panel_full = pd.concat([panel_train_df, panel_test_df], ignore_index=True)
    panel_full = panel_full.drop_duplicates(subset=["ticker", "date"])
    panel_dates_per_ticker = (
        panel_full.sort_values(["ticker", "date"]).groupby("ticker")["date"]
    )
    first_panel_date = panel_dates_per_ticker.first().to_dict()

    def _has_lookback_history(row) -> bool:
        first = first_panel_date.get(row["ticker"])
        if first is None:
            return False
        # need at least min_history trading-day rows prior (use calendar
        # days as a fast upper bound: 252 trading days ~ 365 calendar days).
        return (row["event_date"] - first).days >= int(min_history * 1.45)

    gt = gt[gt.apply(_has_lookback_history, axis=1)].copy()

    train_pool = gt[gt["event_date"] <= split_date].copy()
    eval_pool = gt[gt["event_date"] > split_date].copy()

    # Sector and mcap_q come from the panel (across full date range).
    full_panel = pd.read_parquet(
        bench_dir / "panel_train.parquet",
        columns=["ticker", "sector", "derived_market_cap"],
    )
    latest = full_panel.groupby("ticker").tail(1)[["ticker", "sector", "derived_market_cap"]]
    latest["mcap_q"] = pd.qcut(
        latest["derived_market_cap"].clip(lower=1),
        4, labels=["Q1", "Q2", "Q3", "Q4"], duplicates="drop",
    )
    sector_map = dict(zip(latest["ticker"], latest["sector"]))
    mcap_map = dict(zip(latest["ticker"], latest["mcap_q"]))

    out: dict[Split, pd.DataFrame] = {}
    for split, pool in (("train", train_pool), ("eval", eval_pool)):
        pool = pool.copy()
        pool["sector"] = pool["ticker"].map(sector_map)
        pool["mcap_q"] = pool["ticker"].map(mcap_map)
        n = n_train if split == "train" else n_eval
        sampled = _stratified_sample(
            pool, n, ["sector", "mcap_q", "event_type"], seed,
        )
        out[split] = sampled[["scenario_id", "ticker", "event_type"]]
    return out


def _gen_t7(
    granularity: str,
    n_eval: int,
    n_train: int,
    seed: int,
) -> dict[Split, pd.DataFrame]:
    """T7 RE-Val: stratified by property_type x state."""
    bench_dir = config.get_benchmark_dir(granularity)
    train = pd.read_parquet(bench_dir / "re_train_properties.parquet")
    eval_in = pd.read_parquet(bench_dir / "re_eval_inputs.parquet")
    # ``re_train_properties`` carries 854 duplicate-address rows from
    # multiple RentCast variants of the same listing. Dedup BEFORE
    # sampling so the canonical eval set has unique addresses (the
    # loader otherwise dedups, leaving the canon n short of budget).
    if "address" in train.columns:
        train = train.drop_duplicates(subset="address", keep="first").reset_index(drop=True)
    if "address" in eval_in.columns:
        eval_in = eval_in.drop_duplicates(subset="address", keep="first").reset_index(drop=True)

    def _sample(df: pd.DataFrame, n: int) -> pd.DataFrame:
        ptype_col = next(
            (c for c in ("property_type", "propertyType", "type") if c in df.columns),
            None,
        )
        state_col = next(
            (c for c in ("state", "State") if c in df.columns), None,
        )
        addr_col = next(
            (c for c in ("address", "addressLine1", "Address") if c in df.columns),
            None,
        )
        strata = [c for c in (ptype_col, state_col) if c is not None]
        if not strata or addr_col is None:
            return df.sample(n=min(n, len(df)), random_state=seed).reset_index(drop=True)
        sampled = _stratified_sample(df, n, strata, seed)
        cols_to_keep = [addr_col] + strata
        return sampled[cols_to_keep].rename(columns={addr_col: "address"})

    return {"train": _sample(train, n_train), "eval": _sample(eval_in, n_eval)}


_GENERATORS = {
    "T1": _gen_t1,
    "T2": lambda g, ne, nt, s: _gen_t2_t5(g, "T2", ne, nt, s),
    "T3": lambda g, ne, nt, s: _gen_t3_t6(g, "T3", ne, nt, s),
    "T4": _gen_t4,
    "T5": lambda g, ne, nt, s: _gen_t2_t5(g, "T5", ne, nt, s),
    "T6": lambda g, ne, nt, s: _gen_t3_t6(g, "T6", ne, nt, s),
    "T7": _gen_t7,
}


# ── Public API ────────────────────────────────────────────────────────────


def get_canonical_indices(
    task: Task,
    split: Split = "eval",
    *,
    granularity: str = "daily",
    n_eval: dict[Task, int] | None = None,
    n_train: dict[Task, int] | None = None,
    seed: int | None = None,
) -> pd.DataFrame:
    """Return the canonical index list for `(task, split)`.

    Reads from cache if available; otherwise generates, persists to cache,
    and returns. The cache key encodes (n_eval, n_train, seed,
    stratifier_version) so non-canonical re-tunes get their own cache dir.

    Smoke-mode override: when ``MACROLENS_N_TRAIN`` and / or
    ``MACROLENS_N_EVAL`` env vars are set (positive int), they replace the
    default budget for every task in this call. This lets the runner do an
    end-to-end smoke (e.g. n_train=2, n_eval=1 across all 22 methods × 7
    tasks) without touching the canonical cache or the CLI signature.
    Explicit ``n_eval`` / ``n_train`` kwargs still take precedence.
    """
    import os as _os
    env_n_eval = _os.environ.get("MACROLENS_N_EVAL")
    env_n_train = _os.environ.get("MACROLENS_N_TRAIN")
    if n_eval is None and env_n_eval is not None:
        try:
            v = int(env_n_eval)
            if v > 0:
                n_eval = {t: v for t in EVAL_N_PER_TASK}
        except ValueError:
            pass
    if n_train is None and env_n_train is not None:
        try:
            v = int(env_n_train)
            if v > 0:
                n_train = {t: v for t in TRAIN_N_PER_TASK}
        except ValueError:
            pass
    n_eval_map = n_eval or EVAL_N_PER_TASK
    n_train_map = n_train or TRAIN_N_PER_TASK
    s = SEED if seed is None else seed

    key = budgets.cache_key(n_eval=n_eval_map, n_train=n_train_map, seed=s)
    cache_dir = _cache_dir(granularity, key)
    cache_path = cache_dir / f"{split}_{task}.parquet"

    if cache_path.exists():
        return pd.read_parquet(cache_path)

    # Cache miss: generate both splits for this task and persist.
    gen = _GENERATORS[task]
    pair = gen(granularity, n_eval_map[task], n_train_map[task], s)
    cache_dir.mkdir(parents=True, exist_ok=True)
    for sp, df in pair.items():
        df.to_parquet(cache_dir / f"{sp}_{task}.parquet", index=False)
        logger.info(
            "Canonical-indices cache write: %s (%d rows)",
            cache_dir / f"{sp}_{task}.parquet", len(df),
        )

    return pair[split]


def build_all(
    granularity: str = "daily",
    *,
    n_eval: dict[Task, int] | None = None,
    n_train: dict[Task, int] | None = None,
    seed: int | None = None,
) -> dict[str, int]:
    """Build canonical indices for every (task, split) pair.

    Returns a summary dict mapping `<task>_<split>` -> n_rows. Idempotent:
    re-running with the same budgets is a no-op (cache hits).
    """
    summary: dict[str, int] = {}
    for task in ("T1", "T2", "T3", "T4", "T5", "T6", "T7"):
        for split in ("train", "eval"):
            df = get_canonical_indices(
                task, split, granularity=granularity,
                n_eval=n_eval, n_train=n_train, seed=seed,
            )
            summary[f"{task}_{split}"] = len(df)
    return summary