Skip to content

Chapter 4 — Pipeline orchestration and scoped rebuilds

Part II of the assayinganomalies tutorial. Prerequisite chapters: 1, 2, 3. Python modules covered: pipeline.py, stage_registry.py.

What this chapter answers

  • How the database build is organized: a 24-stage STAGES list run by setup_database / rebuild.
  • What PipelineContext and PipelineStage own (history, WRDS client, logging, timing), and how stage history makes scoped rebuilds possible.
  • What each of the 24 stages reads and writes (detail of the ingest/transform bodies is deferred to Ch 5–11).
  • How stage_registry.py encodes the dependency graph that _expand_plan walks, including the ccm_panel multi-writer cascade rule.
  • How the entire rebuild subsystem works: plan expansion, five Rebuild*Error types, the rebuild_state journal, and the JSON audit log.
  • Where file-based inputs (crspgibbs.csv, hf_monthly.csv, COMPUSTAT variable names) enter the pipeline, and what validate-bm-hml checks.

Where this sits in the pipeline

Chapter 2 showed the three entry scripts. Chapter 3 covered the DuckDB write/read API. This chapter is the orchestrator that calls those writers in order: every WRDS fetch, every panel enrichment, every trading-cost and beta merge runs as a named stage under setup_database or a subset under rebuild.

flowchart TB
  CFG["AssayConfig<br/>Ch 1"]
  SETUP["setup_database<br/>or rebuild"]
  CTX["PipelineContext"]
  ST["STAGES / plan"]
  REG["stage_registry<br/>cascade + reads"]
  ING["ingest/*<br/>Ch 5"]
  TR["transforms/*<br/>Ch 6–11"]
  DB[("Data/aa.duckdb<br/>Ch 3")]
  META["metadata.stage_history<br/>rebuild_state"]

  CFG --> SETUP
  SETUP --> CTX
  SETUP --> ST
  REG --> SETUP
  ST --> CTX
  CTX --> ING
  CTX --> TR
  ING --> DB
  TR --> DB
  CTX --> META
  META --> DB

Because the build is a list of named stages rather than one script, it is restartable (--start-from), can preview a plan without running it (dry run), and supports cascade-aware partial rebuilds.


Observability helpers

A full build takes about five hours. These three helpers keep console and file logs usable without changing numeric results.

_fmt_bytes(n)

Signature

  • n: int | float | None — byte count; None / NaN → "n/a".

Returns — human string ("16 B", "2.35 MB", …).

What it does — scales by 1024 with unit labels. Used when logging staging parquet sizes after fetches.

_df_brief(df, *, name)

Signature

  • df: pd.DataFrame
  • name: str — label in the log line

Returns — one-line summary: shape plus first eight column names.

What it does — keeps INFO logs short when a stage loads a wide panel.

_configure_setup_logging(*, db_path, verbose=False)

Signature

  • db_path: Path — database path; log file is db_path.parent / "logs" / "setup_database.log"
  • verbose: bool — DEBUG vs INFO on the assayinganomalies logger family

Returns — None. Idempotent: returns immediately if the root logger already has handlers.

What it does — configures only logging.getLogger("assayinganomalies") (not the process root), so importing the library does not reconfigure the caller's root logger. Console format is %H:%M:%S + message; a rotating file handler (5 MB × 3) keeps the detailed format. Console filter drops messages that start with [ so the explicit [i/24] Running … progress prints are not duplicated on stdout (they still land in the file log).

def _configure_setup_logging(*, db_path: Path, verbose: bool = False) -> None:
    # ...
    root = logging.getLogger("assayinganomalies")
    if root.handlers:
        return
    # ...
    sh.addFilter(lambda record: not str(record.getMessage()).startswith("["))

PipelineContext

PipelineContext

Signature (dataclass fields)

  • config: AssayConfig — sample window, dom_com_eq, tcosts_type, paths, …
  • db_path: Path — DuckDB file (expanded in __post_init__)
  • staging_dir: Path — usually db_path.parent / "staging"; parquet extracts
  • full_refresh: bool — if true, initialize-database drops metadata
  • logger — defaults to assayinganomalies.pipeline
  • stage_history: list[dict] — append-only run log
  • _wrds_client: WRDSClient | None — lazy singleton for the run

Returns — N/A (context object).

What it does

__post_init__ expands db_path and creates parent / staging directories.

record_stage(name, status, message="", hint="") appends a UTC ISO timestamp entry (with a hint key only when one is given). PipelineStage.run records "succeeded", "failed" or "failed-nonfatal" (below).

persist_metadata() writes a metadata key/value table:

key value
refresh_completed_at UTC ISO timestamp
sample_start / sample_end / dom_com_eq from config; sample_end is the resolved year, never "latest"
crsp_format the tape the build read
sample_end_requested latest or the configured year
sample_end_resolved the year the build ran through; what --start-from runs and AssayConfig.resolved_sample_end() reuse
sample_end_source wrds (looked up), metadata (reused), demo, explicit or clamped-siz
crsp_tape_max_date / crsp_tape_last_december last month and last December on the CRSP monthly file, when WRDS was asked (else carried over or null)
compustat_max_datadate / compustat_last_december the same for Compustat funda
stage_history JSON list of record_stage entries

Two stages write a key of their own to the same table, as a record of how their output was computed: transform-compustat writes annual_layout ("june": annual Compustat columns are stored on the June row only, Ch 7) and compute-ff-tcosts writes ff_tcosts (the factor costs are held-leg costs, Ch 9b). aa.load and the protocol check these records and refuse a database that lacks them.

The persisted stage_history is what rebuild checks to decide whether a stage's upstream inputs have ever been built successfully.

def persist_metadata(self) -> None:
    payload = {
        "refresh_completed_at": datetime.now(timezone.utc).isoformat(),
        "sample_start": self.config.sample_start,
        "sample_end": self.config.sample_end,  # the resolved int
        "dom_com_eq": int(self.config.dom_com_eq),
        "crsp_format": self.source.name,
        "stage_history": self.stage_history,
    }
    resolution = self.resolved_sample_end_record()
    if resolution is not None:
        payload.update(resolution.as_metadata())  # the sample_end_* and tape-date keys
    with DuckDBManager(self.db_path) as manager:
        # CREATE TABLE IF NOT EXISTS metadata ...
        # INSERT OR REPLACE ...

get_wrds_client(*, prompt=True) constructs WRDSClient once, calls ensure_credentials, copies any interactively entered username onto config.wrds_username for this process only (does not auto-persist), and returns None when credentials cannot be resolved. Every fetch-* stage goes through require_wrds_client, which turns that None into an error naming the stage — unless the run is a demo build (--demo), where it logs a warning and the stage writes deterministic placeholder data instead (Ch 5).


PipelineStage

PipelineStage

Signature

  • name: str — kebab-case id used by CLI --start-from, rebuild(stages=...), and the registry
  • func: Callable[[PipelineContext], None] — stage body

Returns — run(ctx) returns None; raises on failure after recording, except for a NonFatalStageError.

What it does — times the call, logs start/complete, records success or failure on the context, re-raises exceptions. A failed stage leaves a "failed" history entry before the exception propagates.

A stage whose output the rest of the database can do without raises NonFatalStageError(message, hint=...) instead. run records it as "failed-nonfatal" (with the message and the hint), logs a WARNING (the traceback only at DEBUG) and returns normally, so the build goes on. Only fetch-cz-anomalies does this today: a Chen–Zimmerman download that fails (say, a firewall blocks Hugging Face), or a local C-Z file that cannot be read, leaves the database without cz_anomalies but with everything else.

@dataclass
class PipelineStage:
    name: str
    func: Callable[[PipelineContext], None]

    def run(self, ctx: PipelineContext) -> None:
        t0 = time.perf_counter()
        ctx.logger.info("Starting stage %s", self.name)
        try:
            self.func(ctx)
        except NonFatalStageError as exc:
            ctx.record_stage(self.name, "failed-nonfatal", str(exc), exc.hint)
            # WARNING with the message and hint; traceback at DEBUG; no raise
        except Exception as exc:  # pragma: no cover - defensive logging
            ctx.record_stage(self.name, "failed", str(exc))
            # ...
            raise
        else:
            ctx.record_stage(self.name, "succeeded")
            # ...

Staging constants

Top-level staging filenames (under Data/staging/ by default):

Constant File Used by
CRSP_RAW_FILE crsp_monthly_raw.parquet monthly fetch/load/transform
CRSP_DAILY_RAW_FILE crsp_daily_raw.parquet daily + tcosts + betas
CRSP_DAILY_FACTORS_FILE ff_daily_factors.parquet daily FF factors
CRSP_DAILY_MONTHLY_AGG_FILE crsp_daily_monthly_agg.parquet full-universe monthly aggs for tcosts NN-fill
COMPUSTAT_ANNUAL_FILE compustat_funda_raw.parquet COMPUSTAT annual
COMPUSTAT_QUARTERLY_FILE compustat_fundq_raw.parquet COMPUSTAT quarterly
CRSP_AUX_RAW six crsp_*_raw.parquet files aux fetch/load; keys are DuckDB table names
CRSP_AUX_RAW = {
    "msfhdr": "crsp_msfhdr_raw.parquet",
    "msedelist": "crsp_msedelist_raw.parquet",
    "dsedelist": "crsp_dsedelist_raw.parquet",
    "mseexchdates": "crsp_mseexchdates_raw.parquet",
    "stocknames": "crsp_stocknames_raw.parquet",
    "ccmxpf_lnkhist": "crsp_ccmxpf_lnkhist_raw.parquet",
}

load-crsp-aux writes DuckDB tables under these short names (msfhdr, …), and stage_registry.TABLE_WRITER_CHAIN keys them the same way, so a table-targeted rebuild such as tables=["ccmxpf_lnkhist"] resolves. Only the staging parquets carry the crsp_ prefix.


The 24-stage STAGES list

STAGES: List[PipelineStage] = [
    PipelineStage("initialize-database", _stage_initialize_database),
    PipelineStage("generate-field-catalog", _stage_generate_field_catalog),
    PipelineStage("fetch-crsp-monthly", _stage_fetch_crsp_monthly),
    PipelineStage("fetch-crsp-aux", _stage_fetch_crsp_aux),
    PipelineStage("fetch-ff-daily", _stage_fetch_ff_daily),
    PipelineStage("fetch-ff-factors", _stage_fetch_ff_factors),
    PipelineStage("fetch-compustat-annual", _stage_fetch_compustat_annual),
    PipelineStage("fetch-compustat-quarterly", _stage_fetch_compustat_quarterly),
    PipelineStage("fetch-crsp-daily", _stage_fetch_crsp_daily),
    PipelineStage("load-crsp-msf", _stage_load_crsp_msf),
    PipelineStage("transform-crsp-monthly", _stage_transform_crsp_monthly),
    PipelineStage("load-crsp-aux", _stage_load_crsp_aux),
    PipelineStage("load-crsp-dsf", _stage_load_crsp_dsf),
    PipelineStage("transform-crsp-daily", _stage_transform_crsp_daily),
    PipelineStage("load-compustat", _stage_load_compustat),
    PipelineStage("transform-compustat", _stage_transform_compustat),
    PipelineStage("validate-bm-hml", _stage_validate_bm_hml),
    PipelineStage("compute-tcosts", _stage_compute_tcosts),
    PipelineStage("compute-ff-tcosts", _stage_compute_ff_tcosts),
    PipelineStage("compute-betas", _stage_compute_betas),
    PipelineStage("compute-car3", _stage_compute_car3),
    PipelineStage("compute-nmv-anomalies", _stage_compute_nmv_anomalies),
    PipelineStage("fetch-cz-anomalies", _stage_fetch_cz_anomalies),
    PipelineStage("finalize", _stage_finalize),
]

Why this order. Every WRDS download runs first (stages 3–9), so the one WRDS login and its Duo approval happen at the start, and the hours of local work after them need no network. No download reads anything a load or transform stage writes, so this costs nothing; the daily extract, by far the longest, goes last among them. After that, the monthly CRSP panel is built, then daily CRSP (so daily aggregates can merge into ccm_panel), then COMPUSTAT enrichment, then validation, then trading costs → betas → CAR3 → NMV, and Chen–Zimmerman last before finalize: its Hugging Face download is the least reliable step, so it runs once everything else has finished. A --start-from at any load, transform or compute stage therefore skips every WRDS stage and needs no credentials. Daily-derived columns and COMPUSTAT columns both DROP+CREATE ccm_panel, and the rebuild cascade assumes exactly this order (see TABLE_WRITER_CHAIN).

Approximate wall times below are from one full build. Stage bodies are thin glue; numeric logic lives in Ch 5–11.

# Stage Reads Writes Detail ~Time
1 initialize-database config, existing DB metadata (create; drop if full_refresh); runs date migration — <1 s
2 generate-field-catalog — Data/aa.catalog.json via save_field_catalog Ch 3 <1 s
3 fetch-crsp-monthly WRDS staging crsp_monthly_raw.parquet Ch 5 ~3 min
4 fetch-crsp-aux WRDS six aux staging parquets Ch 5 ~17 s
5 fetch-ff-daily WRDS ff_daily_factors.parquet Ch 5 ~2 s
6 fetch-ff-factors WRDS DuckDB ts_data Ch 5 ~5 s
7 fetch-compustat-annual WRDS compustat_funda_raw.parquet Ch 5 ~1 min
8 fetch-compustat-quarterly WRDS compustat_fundq_raw.parquet Ch 5 ~2 min
9 fetch-crsp-daily WRDS crsp_daily_raw.parquet Ch 5 ~56 min
10 load-crsp-msf staging parquet DuckDB crsp_msf — ~16 s
11 transform-crsp-monthly staging MSF + aux DuckDB ccm_panel (create) Ch 6 ~5 min
12 load-crsp-aux aux staging DuckDB msfhdr, msedelist, … — ~5 s
13 load-crsp-dsf daily staging DuckDB crsp_dsf — ~2 min
14 transform-crsp-daily daily raw, delist, FF daily, ccm_panel crsp_daily_panel, monthly agg parquet, merges into ccm_panel, ts_data_daily Ch 8 ~2 h
15 load-compustat staging funda/fundq DuckDB compustat_funda, compustat_fundq — ~25 s
16 transform-compustat funda, fundq, link, ccm_panel ccm_link (cleaned link); ccm_panel (merge) Ch 7 ~2 min
17 validate-bm-hml ccm_panel, ts_data.hml validation_bm_hml (check only) below ~20 s
18 compute-tcosts daily raw, Gibbs/HF CSVs, ccm_panel, monthly agg tcosts; merges tcost into ccm_panel Ch 9 ~11 min
19 compute-ff-tcosts tcosts, ccm_panel, ts_data, funda + ccm_link ts_data (mkt_tc, smb_tc … umd_tc, smb_tc_capital … umd_tc_capital, smb_tc_capital_short … umd_tc_capital_short); metadata.ff_tcosts Ch 9b ~10 s (a build of November 2026 on a faster machine than the other rows; the stage took the same time before the held-leg calculation there)
20 compute-betas daily raw, FF daily, delist, ccm_panel betas; merges beta cols into ccm_panel Ch 10 ~65 min
21 compute-car3 crsp_daily_panel, fundq, ccm_link, factors merges car3 into ccm_panel Ch 8 ~5 min
22 compute-nmv-anomalies ccm_panel, optional ts_data nmv_anomalies Ch 11 ~2 min
23 fetch-cz-anomalies config paths, ccm_panel (prc, ret, me) cz_anomalies, cz_signal_info Ch 5 ~13 min
24 finalize — log line only — <1 s

Short stage notes

initialize-database — ensures metadata exists; on full_refresh=True drops it first. Always runs migrate_ts_data_monthly_dates_to_month_end (Ch 3) so older DBs get month-end ts_data.date values.

generate-field-catalog — writes a small alias map (ret→ret, NYSE→nyse_flag, …). Not a DuckDB table, despite the registry listing field_catalog as one.

Fetch stages (monthly, aux, daily, FF daily, COMPUSTAT ×2, FF monthly, CZ) — all in FETCH_STAGES. Pattern: require_wrds_client → real extract → parquet (or DuckDB for CZ / FF monthly); only a demo build substitutes a deterministic placeholder. Fetch stages always re-query WRDS when credentials resolve; they do not skip because a staging file already exists. Clearing staging before a from-scratch rebuild is still advisable so a failed fetch cannot leave a stale parquet for the following load-* stage.

fetch-cz-anomalies (stage 23) — reads a local C-Z panel or downloads it from Hugging Face (Ch 5), then writes cz_anomalies and cz_signal_info. It runs last before finalize and is the one stage whose failure does not stop the build: outside demo mode it raises NonFatalStageError, drops any half-written cz_anomalies, and skips the SignalDoc when the panel failed. A download failure keeps the manual-download hint; any other error is worded as a failure to read the local file, so the hint does not send you off to download it again.

Load stages — pd.read_parquet → write_table(..., mode="replace"). load-crsp-dsf / load-compustat warn and skip if the staging file is missing rather than hard-failing.

transform-crsp-monthly — builds the initial ccm_panel from staging MSF + aux via crsp_monthly.transform_monthly (Ch 6).

transform-crsp-daily — writes crsp_daily_panel, builds full-universe monthly aggregates (with delisting-return rows placed via _load_daily_delist), left-merges daily-derived columns into ccm_panel, writes ts_data_daily. Longest stage (~2 h).

transform-compustat — cleans the staged CCM link (compustat.clean_ccm_link) and writes it as ccm_link first, even when the Compustat extract or ccm_panel is missing; then compustat.merge_compustat_crsp and REPLACE ccm_panel (Ch 7). compute-ff-tcosts and compute-car3 read ccm_link (through _read_ccm_link, which falls back to cleaning the raw ccmxpf_lnkhist table, then the staged extract, with a warning, on a database built before ccm_link existed).

compute-ff-tcosts — prices SMB, HML, RMW, CMA and UMD on held legs (Ch 9b) and replaces the factor-cost columns of ts_data: mkt_tc (zero), smb_tc … umd_tc for convention="dollar", smb_tc_capital … umd_tc_capital for "capital", and smb_tc_capital_short … umd_tc_capital_short for the factors held short under "capital". After the columns it writes the metadata key ff_tcosts ({"calculation": "held", "version": 2, "capital_restarts": {…}, "entry_cost": {…}}) and logs, per factor, the held sides' return beside the published factor and the part of the cost that comes from the monthly re-splits, and each factor's entry cost (the first purchase, which is not in the cost series); a factor whose capital was zero or negative at a trade gets a warning. A protocol run that reads factor costs from a database without this record, or with a record that has no "version": 2, raises FactorCostsError (Ch 16); the fix is aa setup-database --start-from compute-ff-tcosts, or --start-from transform-compustat on a database that also predates June-only annual columns (Ch 7), because the stages after compute-ff-tcosts refuse such a panel.

compute-tcosts / compute-ff-tcosts / compute-betas / compute-car3 / compute-nmv-anomalies — orchestrate transform modules; several re-write ccm_panel after dropping stale columns so rebuilds replace rather than duplicate. Order within ccm_panel's writer chain is fixed by TABLE_WRITER_CHAIN.

finalize — logs "Pipeline finished." so the file log has an unambiguous end marker.


File-based inputs

Two kinds of file input enter the build besides WRDS: the trading-cost CSVs (Gibbs estimates and, for tcosts_type="full", high-frequency spreads) and the Compustat variable list, which ships inside the package (ingest/data/compustat_variables.csv).

_find_input_file(ctx, pattern, label)

Signature

  • ctx: PipelineContext
  • pattern: str — glob fragment, e.g. "crspgibbs*.csv", "hf_monthly.csv"
  • label: str — for the log line

Returns — the matching Path, or None.

What it does — searches ctx.staging_dir and ctx.db_path.parent with **/pattern (first hit in sorted order wins), then the rest of the project folder (the parent of Data/), then the current working directory. The last two do not enter Scratch/ or folders whose name starts with a dot, and raise AmbiguousInputError (a MissingInputError) when more than one file matches. A file anywhere in the project folder is therefore found wherever the build is launched from; the working directory matters only when the project has none.

def _find_input_file(ctx: PipelineContext, pattern: str, label: str) -> Path | None:
    # ...
    search_dirs = [
        ctx.staging_dir,
        ctx.db_path.parent,
        Path("."),
    ]
    for d in search_dirs:
        matches = glob.glob(str(d / "**" / pattern), recursive=True)
        if matches:
            # ...
            return Path(matches[0])

Call sites: the HF spreads file when tcosts_type == "full" (a missing file stops the build with MissingInputError before stage 1), and bare Compustat variable-list names (below). The Gibbs file is resolved separately by ingest/gibbs.py resolve_gibbs_file, which looks for a local copy and otherwise downloads it into staging; if neither works, a production build stops with MissingInputError (Ch 9).

Compustat variable list — AssayConfig.compustat_variables (default "compustat_variables.csv"). The two fetch stages resolve it with ingest/compustat.py resolve_variables_file (Ch 5) and pass the names as variables=. A bare file name goes through _find_input_file (the label in the log line is Compustat variable list), except compustat_variables.csv and the legacy name COMPUSTAT Variable Names.csv: both always mean the packaged copy, so a source checkout never picks up the original MATLAB toolkit's CSV, which lists different variables. A path is used as given, and 'All' means every column. setup-database and rebuild read the file before the first stage runs, so a bad path or a CSV without Annual,Quarterly columns fails at once.

_load_daily_delist(ctx)

Signature — ctx: PipelineContext.

Returns — non-empty delist DataFrame, or None.

What it does — prefers staging crsp_dsedelist_raw.parquet, else falls back to monthly msedelist with a warning. Used by transform-crsp-daily, compute-tcosts, compute-betas, and compute-car3 before betas_mod._insert_matlab_dlret_rows. The monthly file is the wrong grain for daily work, so the fallback is a degraded path whose results can differ near delistings.

def _load_daily_delist(ctx: PipelineContext) -> pd.DataFrame | None:
    for key in ("dsedelist", "msedelist"):
        path = ctx.staging_dir / CRSP_AUX_RAW[key]
        if path.exists():
            df = pd.read_parquet(path)
            if not df.empty:
                if key == "msedelist":
                    ctx.logger.warning(
                        "Daily delist file missing; falling back to monthly "
                        "msedelist for dlret placement"
                    )
                return df
    return None

Check-only stage: validate-bm-hml

_stage_validate_bm_hml(ctx)

Signature — ctx: PipelineContext.

Returns — None. Soft-skips if tables/columns/overlap are insufficient, so a demo build still finishes.

What it does

  1. Requires ccm_panel with bm and ts_data with hml.
  2. Selects stock-months with positive BM, finite ME and ret (financials not excluded — matches FF 1993 factor construction, not FF 1992 sample filters).
  3. Runs run_bivariate_sort 2×3 on ME × BM with NYSE breakpoints, sort_type="unconditional", value weights.
  4. Forms HML as (SmallHigh + BigHigh)/2 − (SmallLow + BigLow)/2.
  5. Logs correlation, beta, means vs published HML; writes aligned series to DuckDB validation_bm_hml.

A correlation ~0.95+ is the operational green light that the COMPUSTAT merge and BM column are sane after a long build. It does not gate later stages — failure to sort only logs and returns.


Mermaid: stage dependency graph

Edges below follow STAGE_READS in stage_registry.py (what a stage consumes). The ccm_panel writer cascade is a separate rule used by _expand_plan (shown as a subgraph).

flowchart TB
  init[initialize-database]
  cat[generate-field-catalog]
  fcm[fetch-crsp-monthly]
  lmsf[load-crsp-msf]
  faux[fetch-crsp-aux]
  tcm[transform-crsp-monthly]
  laux[load-crsp-aux]
  fcd[fetch-crsp-daily]
  ldsf[load-crsp-dsf]
  ffd[fetch-ff-daily]
  tcd[transform-crsp-daily]
  fca[fetch-compustat-annual]
  fcq[fetch-compustat-quarterly]
  lc[load-compustat]
  tc[transform-compustat]
  fff[fetch-ff-factors]
  vbm[validate-bm-hml]
  fcz[fetch-cz-anomalies]
  ctc[compute-tcosts]
  cftc[compute-ff-tcosts]
  cb[compute-betas]
  ccar[compute-car3]
  cnmv[compute-nmv-anomalies]
  fin[finalize]

  init --> cat
  init --> fcm
  init --> faux
  init --> ffd
  init --> fca
  init --> fcq
  init --> fff
  fcm --> lmsf
  faux --> tcm
  lmsf --> tcm
  faux --> laux
  init --> fcd
  fcd --> ldsf
  ldsf --> tcd
  laux --> tcd
  ffd --> tcd
  tcm --> tcd
  fca --> lc
  fcq --> lc
  lc --> tc
  tcm --> tc
  tc --> vbm
  fff --> vbm
  tc --> ctc
  tcd --> ctc
  ctc --> cftc
  fff --> cftc
  tc --> cftc
  tcd --> cb
  ctc --> cb
  tcd --> ccar
  tc --> ccar
  cb --> ccar
  ccar --> cnmv
  tcm --> fcz
  fcz --> fin

  subgraph ccm_cascade ["ccm_panel writer cascade"]
    tcm2[transform-crsp-monthly]
    tcd2[transform-crsp-daily]
    tc2[transform-compustat]
    ctc2[compute-tcosts]
    cb2[compute-betas]
    ccar2[compute-car3]
    tcm2 --> tcd2 --> tc2 --> ctc2 --> cb2 --> ccar2
  end

setup_database

setup_database(config=None, *, full_refresh=False, verbose=False, start_from=None)

Signature

  • config: AssayConfig | None — defaults to load_config()
  • full_refresh: bool — passed into context; only initialize-database treats it specially today (drops metadata)
  • verbose: bool — DEBUG logging
  • start_from: str | None — kebab-case stage name; stages before it are skipped (printed as [i/24] Skipping …) but not re-validated
  • demo: bool — build from deterministic placeholders wherever a real input is unavailable, and stamp the database as synthetic (Ch 5)
  • skip_memory_check: bool — start even when the RAM check fails (--skip-memory-check); the shortfall is logged as a warning

Returns — Path to the DuckDB file.

What it does

  1. Resolve db_path and staging_dir = db_path.parent / "staging".
  2. Configure logging; build PipelineContext.
  3. If start_from is set, validate against STAGES names and set skip_to.
  4. Run the preflights for the planned stages: the SIZ clamp (an explicit sample_end past 2024 on SIZ is lowered to 2024 with a warning), memory (when a stage that holds the CRSP daily panel is planned, stop if the machine has less RAM than config.required_setup_ram_gb gives for the sample, unless skip_memory_check=True; for sample_end = "latest" this runs after the sample end is resolved), WRDS credentials (which logs in, so the one Duo push comes now, and offers to save a typed password to ~/.pgpass), the sample end (_preflight_sample_end: "latest" is looked up on the open session, reused from metadata.sample_end_resolved when the run fetches nothing, or DEMO_SAMPLE_END in a demo build; ctx.config becomes a copy holding the year, and the year is printed), the Chen–Zimmerman release label (offline: nothing is downloaded before stage 23, Ch 5), the trading-cost inputs, the COMPUSTAT variables.
  5. Run each remaining stage via PipelineStage.run, printing [i/24] Running|Done … to stdout (and the file log), or [i/24] Did not complete … ; continuing after a failed-nonfatal stage.
  6. persist_metadata() once at the end (not after each stage), then the demo stamp and the run manifest.
  7. If any stage ended failed-nonfatal, log and print a summary — Build finished; N stage(s) did not complete: … with each stage's message and hint — and still return the database path (exit code 0). For the C-Z stage the hint is the way to fetch it later: aa setup-database --start-from fetch-cz-anomalies, which runs only fetch-cz-anomalies and finalize.
def setup_database(
    config: AssayConfig | None = None,
    *,
    full_refresh: bool = False,
    verbose: bool = False,
    start_from: str | None = None,
) -> Path:
    cfg = config or load_config()
    db_path = Path(cfg.database_path)
    staging_dir = db_path.parent / "staging"
    # ...
    for idx, stage in enumerate(STAGES, start=1):
        if idx - 1 < skip_to:
            # Skipping ...
            continue
        # Running ... / stage.run(ctx) / Done ... (or Did not complete ...)
    ctx.persist_metadata()
    # ... demo stamp, run manifest ...
    _report_nonfatal_stages(ctx)  # "Build finished; N stage(s) did not complete"
    return ctx.db_path

CLI: aa setup-database [--full-refresh] [--verbose] [--start-from STAGE] (Ch 1). Resume guidance: only use --start-from when every earlier stage's staging files and tables are already good.


stage_registry.py — the dependency graph

Hand-maintained maps, kept in step with the write_table calls in the stage bodies. Docstring states the rule: only ccm_panel is a genuine multi-writer chain; every other table has one writer.

Module tables

Name Role
TABLE_WRITER_CHAIN table → ordered writer stages; cascade walks later writers
COLUMN_TO_STAGE column → (table, last_writer_stage)
STAGE_READS stage → upstream stages it consumes
FETCH_STAGES frozenset of network stages blocked unless allow_refetch

stage_writes(stage)

Signature — stage: str.

Returns — list of table names whose chain contains stage.

stages_in_order()

Returns — [s.name for s in pipeline.STAGES] via lazy import (breaks the circular import with pipeline).

downstream_of(stage)

What it does — for each table stage writes, include that stage and every later writer in the chain; return unique names in pipeline order. This is the cascade rule: rebuilding transform-crsp-monthly pulls transform-crsp-daily → transform-compustat → compute-tcosts → compute-betas → compute-car3 so DROP+CREATE writers do not silently drop columns.

def downstream_of(stage: str) -> List[str]:
    needed: Set[str] = {stage}
    for table in stage_writes(stage):
        chain = TABLE_WRITER_CHAIN[table]
        # ...
        for downstream in chain[i:]:
            needed.add(downstream)
    order = stages_in_order()
    return [s for s in order if s in needed]

stages_for_columns(columns) / stages_for_tables(tables)

What they do — map request selectors to root stages only; cascade is applied later by _expand_plan. Unknown names raise KeyError. stages_for_tables takes the first writer in the chain (rebuild from the start of that table's life).

Known drift (do not trust blindly): field_catalog is a JSON sidecar, not a DuckDB table (see Ch 2). The aux keys now match the live table names (msfhdr, ccmxpf_lnkhist, …; a test checks it).


Scoped rebuild subsystem

Designed for targeted repairs: preview a plan with dry_run=True, refuse network fetches by default, refuse huge cascades without confirm_large, refuse rebuilding when upstream stages never succeeded.

Error types

Class Trigger
RebuildError base class
RebuildRefetchBlockedError resolved plan intersects FETCH_STAGES and allow_refetch=False
RebuildAbortedError len(plan) > REBUILD_PLAN_SOFT_LIMIT (8) and confirm_large=False
RebuildUpstreamMissingError a plan stage reads an upstream that is neither in the plan nor marked succeeded in metadata.stage_history
RebuildInterruptedError rebuild_state has non-terminal (pending/running) rows whose plan_json does not match the new plan

ValueError (not a RebuildError) is raised when zero or more than one of stages|columns|tables is provided, or when a requested stage name is unknown.

StageResult / RebuildReport / REBUILD_PLAN_SOFT_LIMIT

StageResult — per-stage status (done|failed|skipped|pending|running), timestamps, message.

RebuildReport — request echoes, resolved_plan, executed, dry_run, timestamps, db_path, optional rebuild_id / log_path.

REBUILD_PLAN_SOFT_LIMIT = 8 — soft cap before confirm_large is required.

_expand_plan(*, stages, columns, tables)

Signature — exactly one of the three selectors must be non-None.

Returns — ordered unique stage name list.

What it does

  1. Resolve roots (stages as-is after dedupe; or stages_for_columns / stages_for_tables).
  2. Union downstream_of for each root.
  3. Filter STAGES order.
def _expand_plan(
    *,
    stages: list[str] | None,
    columns: list[str] | None,
    tables: list[str] | None,
) -> list[str]:
    # exactly one selector ...
    # roots → downstream_of → STAGES order

Example: stages=["transform-crsp-monthly"] expands to the six-stage ccm_panel cascade. columns=["bm"] roots at transform-compustat and cascades through tcosts → betas → car3.

Guard helpers

_check_refetch_policy(plan, allow_refetch) — raises RebuildRefetchBlockedError if any plan member is in FETCH_STAGES without permission.

_check_plan_size(plan, confirm_large) — raises RebuildAbortedError when over the soft limit.

_check_upstream_satisfied(plan, stage_history) — for each plan stage, every member of STAGE_READS[stage] must be in the plan or have a prior status == "succeeded" history entry.

_load_stage_history(db_path) — reads JSON from metadata where key='stage_history'; returns [] if the DB/table/key is missing or corrupt.

rebuild(...)

Signature

  • Exactly one of stages, columns, tables
  • dry_run: bool = False — return report without touching the DB
  • allow_refetch: bool = False
  • confirm_large: bool = False
  • config, verbose — same roles as setup_database

Returns — RebuildReport.

What it does

  1. _expand_plan → refetch policy → plan size.
  2. If db_path.exists(), load history and _check_upstream_satisfied (skipped when the file is absent so dry-run previews stay cheap).
  3. Build a pending RebuildReport.
  4. On dry_run, stamp finished_at and return.
  5. Else _execute_rebuild.
def rebuild(
    *,
    stages: list[str] | None = None,
    columns: list[str] | None = None,
    tables: list[str] | None = None,
    dry_run: bool = False,
    allow_refetch: bool = False,
    confirm_large: bool = False,
    config: AssayConfig | None = None,
    verbose: bool = False,
) -> RebuildReport:
    # expand → guardrails → dry_run or _execute_rebuild

Not re-exported from assayinganomalies.__init__ today — import from assayinganomalies.pipeline.

Rebuild-state journal and execution

_rebuild_log_dir(db_path) — db_path.parent / "logs" / "rebuilds".

_init_rebuild_state(db_path) — CREATE TABLE IF NOT EXISTS rebuild_state (rebuild_id, stage, status, plan_json, ts).

_write_rebuild_state(...) — appends one journal row per status transition.

_check_rebuild_state_clean(db_path, plan) — scans latest status per (rebuild_id, stage). Non-terminal statuses are allowed only when plan_json matches the new plan (resume same plan); otherwise RebuildInterruptedError. Clear with DELETE FROM rebuild_state if abandoning an interrupted run.

_persist_rebuild_log(report) — writes logs/rebuilds/{rebuild_id}.json with the full report payload; sets report.log_path.

_execute_rebuild(report, cfg, *, verbose) — creates a fresh PipelineContext(full_refresh=False), initializes journal, checks cleanliness, assigns rebuild_id = rebuild_YYYYMMDDTHHMMSSZ, then for each planned stage:

  1. mark running in report + journal;
  2. stages_by_name[name].run(ctx);
  3. on failure: mark failed, persist log, re-raise;
  4. on success: mark done.

After all stages succeed, ctx.persist_metadata() merges the new successes into stage_history so the next upstream check sees them, then persists the JSON log.

def _execute_rebuild(
    report: "RebuildReport",
    cfg: AssayConfig,
    *,
    verbose: bool,
) -> "RebuildReport":
    # PipelineContext → journal → per-stage run → persist_metadata + log