How-To Guides

Purpose

Provide task-oriented recipes for common DSAMbayes operational workflows. Each guide starts from a user objective, gives minimal reproducible steps, and includes expected output artefacts and quick verification checks.

Audience

  • Users who know the concepts but need execution steps.
  • Engineers debugging run and artefact issues.

Pages

Guide Objective
Run from YAML Execute a complete runner workflow and verify staged outputs
Interpret Diagnostics Read and act on diagnostics gate results
Compare Runs Compare multiple runs and select a candidate model
Debug Run Failures Diagnose and resolve common runner failure modes

Subsections of How-To Guides

Run from YAML

Objective

Execute a complete DSAMbayes model run from a YAML configuration file and verify the staged output artefacts.

Prerequisites

  • DSAMbayes installed locally (see Install and Setup).
  • A YAML config file (see Config Schema for structure).
  • Data file(s) referenced by the config are accessible.

Steps

1. Set up the environment

Complete the environment setup in Install and Setup (selecting the host library, creating the cache directory, and exporting XDG_CACHE_HOME) before continuing.

2. Validate the configuration (dry run)

Rscript scripts/dsambayes.R validate --config config/blm_timeseries.yaml

Expected outcome:

  • Exit code 0.
  • No Stan compilation or sampling occurs.
  • Metadata artefacts are written only if you supply --run-dir or set outputs.run_dir.

If validation fails:

  • Check the error message for missing data paths, invalid YAML keys, or formula errors.
  • Remember that the authored v2 schema does not expose model.formula; the runner compiles it from target, media, controls, and optional hierarchy / effects.
  • Fix the config and re-run validate before proceeding.

3. Run the model

Rscript scripts/dsambayes.R run --config config/cre_geo_panel.yaml

Expected outcome:

  • Exit code 0.
  • Full staged artefact tree under the run directory.

For the bounded fixed-effects runner path:

Rscript scripts/dsambayes.R run --config config/fe_panel.yaml

This runs the coefficient-only FE MCMC estimator and writes only the dedicated FE files documented under Output Artefacts. It does not run generic level-scale diagnostics, model selection, scenario analysis, optimisation, forecasting, or deployment. A completed FE run is not a production qualification; its diagnostics summary records qualification_status: not_assessed.

4. Locate the run directory

The runner prints the run directory path during execution. It follows the pattern:

results/YYYYMMDD_HHMMSS_<run_label>/

5. Verify artefacts

Check that the following stage folders are populated:

Stage Folder Key files
Metadata 00_run_metadata/ config.original.yaml, config.resolved.yaml, config.compiled.yaml, artifact_schema.yaml, session_info.txt
Pre-run 10_pre_run/ Media spend plots, VIF bar chart
Model fit 20_model_fit/ model.rds, optional deployment_model.rds, fit plots
Post-run 30_post_run/ posterior_summary.csv, observed.csv, fitted.csv, plus runner linear term-contribution tables/plots when enabled and supported

The runner files retain legacy decomp_* names, but they are not the mapping/reference-point result returned by interactive decomp(). They fail closed for hierarchical, offset-bearing, and probabilistic-media-transform models, with the reason recorded in artifact_status.csv. | Diagnostics | 40_diagnostics/ | diagnostics_report.csv, diagnostic plots | | Model selection | 50_model_selection/ | LOO summary, Pareto-k plot (if MCMC) | | Scenario analysis | 60_scenario_analysis/ | Scenario/reference response summaries (if enabled) | | Forecast | 70_forecast/ | Reserved directory only (if enabled) | | Optimisation | 80_optimisation/ | Allocation summary, response curves (if enabled) |

Optional deployment artifact:

  • Set outputs.save_deployment_model_rds: true to write 20_model_fit/deployment_model.rds.
  • This artifact is a compact deployment package for explicit predict(newdata = ...) and explicit-data decomposition; it does not replace model.rds.
  • Supported for model.type: blm, model.type: pooled with fit.method: mcmc, or hierarchical model.type: re / cre with fit.method: mcmc.
  • Pooled deployment artifacts score on authored terms and do not require pooling columns in deployment-time newdata / data = ... unless those columns are also ordinary formula terms.
  • Hierarchical deployment artifacts are seen-groups-only. Explicit newdata / data = ... must include the raw grouping columns, and decomposition also requires the response source column(s).
  • FE does not support deployment_model.rds. Its optional posterior.rds is a compact extracted posterior table, while model.rds is the fitted same-environment analysis object.

6. Quick verification commands

# Check diagnostics overall status
head -1 results/<run_dir>/40_diagnostics/diagnostics_report.csv

# View posterior summary
head results/<run_dir>/30_post_run/posterior_summary.csv

# Count artefact files
find results/<run_dir> -type f | wc -l

Failure handling

Symptom Likely cause Action
Exit code 2 during validate Config, data, or environment error Read error message; fix config or local setup
Exit code 1 during run Diagnostics overall status is fail, requested scenario analysis failed, diagnostics publish-gate enforcement failed, or a post-fit artefact write failed Review diagnostics and 00_run_metadata/run_status.yaml if present; the fit completed but the outcome is not publishable
Exit code 2 during run Stan compilation, sampling, config, or environment failure before a completed run result was returned Check the CLI error message, Stan cache, and local setup
Missing 20_model_fit/model.rds Fit did not complete Review runner log for Stan errors
Missing 20_model_fit/deployment_model.rds outputs.save_deployment_model_rds is false, model type / fit method is unsupported, or fit did not complete Check resolved config and confirm either model.type: blm, model.type: pooled with fit.method: mcmc, or hierarchical model.type: re/cre with fit.method: mcmc
Missing 40_diagnostics/ Diagnostics writer failed Check for upstream fit failures; review tryCatch messages
Missing 60_scenario_analysis/ Scenario analysis is disabled or failed Check scenario_analysis.enabled, input paths, and 00_run_metadata/run_status.yaml

For FE runs, missing generic observed.csv, fitted.csv, diagnostics_report.csv, model-selection, scenario, optimisation, forecast, or deployment files is expected. Use within_design.csv, contrast_residuals.csv, contrast_ppc.csv, and diagnostics_summary.txt for the bounded FE reporting contract.

Programmatic API note:

  • DSAMbayes::run_from_yaml() can return outcome: completed_with_scenario_analysis_fail when the fit succeeded but the requested scenario analysis failed, or completed_with_artifact_write_fail when a later artefact-writing step failed, including TSCV artefact writes.
  • For automation, inspect outcome, postfit_issue, and postfit_message instead of assuming every non-error return is fully successful.
  • Diagnostics publish-gate failures still raise dsambayes_runtime_error, with the same runner_result attached as condition$result.

Interpret Diagnostics

Objective

Read and act on the diagnostics report produced by a DSAMbayes runner execution, understanding which checks matter most and what remediation steps to take.

This is the operational triage guide. For the methodological meaning of the gates themselves, see Stage 4: Computation and Sampler and Stage 5: Model Adequacy.

Prerequisites

  • A completed runner run execution with artefacts under 40_diagnostics/.
  • Familiarity with Diagnostics Gates definitions.

Steps

1. Open the diagnostics report

cat results/<run_dir>/40_diagnostics/diagnostics_report.csv

Each row is one diagnostic check. The key columns are:

Column What to look at
check_id Identifies the specific diagnostic
status pass, warn, fail, or skipped
value The observed metric value
threshold The threshold that was applied
message Human-readable explanation

2. Check the overall status

The overall status follows a simple rule:

  • Any fail → overall fail.
  • Any warn (no fails) → overall warn.
  • All pass → overall pass.

If the overall status is pass, no enabled check breached its configured threshold. Continue with substantive fit, predictive, sensitivity, identifiability and intended-use review. A pass is not model approval.

3. Triage failing checks

Focus on fail rows first, then warn rows. Use the check phase to prioritise:

Phase Priority Meaning
P0 Highest Data integrity or critical MCMC reliability, fix before interpretation
P1 High Conditioning, residual or identifiability concerns, review before use
P2 Supplementary Predictive scoring and influence evidence, never causal validation

4. Common diagnostics and actions

The phase assignments below match the emitted phase field:

Check ID Phase
pre_response_finite P0
pre_design_constants_duplicates P0
pre_design_rank_deficit P0
post_rhat_max P0
post_ess_bulk_min P0
post_ess_tail_min P0
post_divergences P0
post_treedepth_saturation P0
post_ebfmi P0
pre_design_condition_number P1
post_residual_ljung_box_p_min P1
post_residual_max_abs_acf P1
post_boundary_hit_rate_max P1
pre_within_variation_ratio_min P1
pre_identifiability_baseline_media_corr P1

Design integrity (P0)

Check Symptom Action
pre_response_finite fails Non-finite values in response Clean data; remove or impute NA/Inf rows
pre_design_constants_duplicates fails Constant or duplicate columns Remove redundant terms from formula
pre_design_rank_deficit warns/fails Rank-deficient design Remove redundant terms; review whether the specification can identify separate effects

Design conditioning (P1)

Check Symptom Action
pre_design_condition_number warns/fails High collinearity Reduce correlated predictors; simplify formula

Sampler quality (P0, MCMC only)

Check Symptom Action
post_rhat_max warns/fails Poor convergence Increase fit.mcmc.iter and fit.mcmc.warmup; simplify model
post_ess_bulk_min or post_ess_tail_min warns/fails Insufficient effective samples Increase iterations; check for multimodality
post_divergences fails Divergent transitions Increase fit.mcmc.adapt_delta (e.g. 0.95 → 0.99); consider reparameterisation
post_treedepth_saturation warns/fails Max treedepth saturation Increase fit.mcmc.max_treedepth
post_ebfmi warns/fails Low energy diagnostic Indicates difficult posterior geometry; simplify model or increase warmup

Residual behaviour (P1)

Check Symptom Action
post_residual_ljung_box_p_min warns/fails Significant residual autocorrelation Add time controls (trend, seasonality, holidays)
post_residual_max_abs_acf warns/fails High residual ACF at early lags Same as above; check for missing structural components

Boundary and variation checks (P1)

Check Symptom Action
post_boundary_hit_rate_max warns/fails Posterior draws hitting parameter bounds Review boundary specification; widen constraints or remove unnecessary bounds
pre_within_variation_ratio_min warns/fails Low within-group variation (hierarchical) Check group structure; some groups may have insufficient temporal variation

Identifiability gate (P1)

Check Symptom Action
pre_identifiability_baseline_media_corr warns/fails High baseline-media correlation Add controls to separate baseline from media effects; review formula specification

5. Review diagnostic plots

Cross-reference the numeric report with visual diagnostics in 40_diagnostics/:

  • Residual diagnostics plot: check for patterns in residuals over time.
  • Boundary hits plot: identify which parameters are constrained.
  • Latent residual ACF plot: confirm autocorrelation structure.

See Diagnostics Plots for interpretation guidance.

6. Decide on next steps

Overall status Action
pass Continue the remaining adequacy and intended-use review; do not treat the pass as approval
warn Review warnings; proceed if acceptable for the use case
fail Remediate failing checks before using model results for decisions

7. Change policy mode if appropriate

If you are in early model development, consider switching to explore mode to relax thresholds:

diagnostics:
  policy_mode: explore

For production or audit runs, use publish (default) or strict.

Compare Runs

Objective

Compare multiple DSAMbayes runner executions and select a candidate model for reporting or decision-making, using predictive scoring and diagnostic summaries.

This page is a late-stage selection aid, not a full workflow. Use it only after the candidate runs are computationally trustworthy enough to compare. In the principled workflow, that means Stage 4 and Stage 5 work has already been done: the sampler is behaving acceptably, and the model is at least adequate enough to remain a candidate. For the surrounding methodology, see Stage 4: Computation and Sampler and Stage 5: Model Adequacy.

Prerequisites

  • Two or more completed runner run executions (MCMC fit method).
  • Artefacts under 50_model_selection/ for each run (LOO summary, ELPD outputs).
  • Familiarity with Diagnostics Gates and Model Selection Plots.
  • Candidate runs that are still eligible after basic diagnostic review. Do not compare obviously broken runs just because they produced LOO outputs.

Steps

1. Collect run directories

Identify the run directories to compare:

results/20260228_083808_blm_synth_kpi_os_hfb01/
results/20260228_084410_blm_synth_kpi_os_hfb01/
results/20260228_084602_blm_synth_kpi_os_hfb01/

2. Compare ELPD scores

The compare_runs() helper ranks runs by expected log predictive density (ELPD):

library(DSAMbayes)
comparison <- compare_runs(
  run_dirs = c(
    "results/20260228_083808_blm_synth_kpi_os_hfb01",
    "results/20260228_084410_blm_synth_kpi_os_hfb01"
  )
)
print(comparison)

The output ranks runs by ELPD (higher is better) and reports Pareto-k diagnostics. When TSCV summaries are present, the table also carries tscv_method, tscv_horizon_weeks, tscv_stride_weeks, tscv_min_train_weeks, and tscv_gap_weeks so you can see whether holdout policies actually match. When 00_run_metadata/artifact_schema.yaml is present, the table also carries artifact_schema_version. Treat this as ranking among plausible candidates, not as an automatic winner-selection rule.

3. Check Pareto-k reliability

Examine the loo_summary.csv in each run’s 50_model_selection/ folder:

cat results/<run_dir>/50_model_selection/loo_summary.csv

Key metrics:

Metric Interpretation
elpd_loo Expected log predictive density; higher is better
p_loo Effective number of parameters
looic LOO information criterion; lower is better
Pareto-k counts Observations with k > 0.7 indicate unreliable LOO estimates

If many observations have high Pareto-k values, the LOO approximation is unreliable for that run. Consider time-series cross-validation as an alternative.

4. Review time-series CV (if available)

If diagnostics.time_series_selection.enabled: true was configured, check:

cat results/<run_dir>/50_model_selection/tscv_summary.csv

This provides blocked-CV or leave-future-out scores (holdout ELPD, RMSE, SMAPE), optionally with an embargo gap when gap_weeks is configured, and is usually more appropriate for time-series data than standard LOO.

compare_runs() ranks a TSCV result only when every scheduled fold succeeded. It also requires candidate runs to use the same method, horizon_weeks, stride_weeks, min_train_weeks, gap_weeks, number of folds, and realised holdout start and end dates. If these conditions do not hold, rank_tscv and delta_tscv_elpd remain NA; the helper warns when otherwise eligible runs are not comparable.

compare_runs() also warns when explicit artifact_schema_version values differ across runs. That warning does not block ranking, but it means the helper is reading known artifacts on a best-effort basis across evolving run contracts.

Time-series selection is advisory in the current runner contract. It is useful for model comparison, but it does not change publish-gate status.

5. Cross-reference diagnostics

For each candidate run, check the diagnostics overall status:

head -1 results/<run_dir>/40_diagnostics/diagnostics_report.csv

A model with better ELPD but failing diagnostics should not be preferred over a model with slightly lower ELPD and passing diagnostics.

If a run is computationally untrustworthy, remove it from contention before you start arguing about small predictive-score differences.

6. Compare fit quality visually

Review the fit time series and scatter plots in 20_model_fit/ for each run:

  • Fit time series: does the model track the observed KPI?
  • Fit scatter: is the predicted-vs-observed relationship close to the diagonal?
  • Posterior forest: are coefficient estimates reasonable and well-identified?

7. Selection decision matrix

Criterion Weight Run A Run B
Eligible after diagnostics review? Gate yes/no yes/no
ELPD (higher is better) High value value
Pareto-k reliability (fewer high-k) High value value
Diagnostics overall status High pass/warn/fail pass/warn/fail
TSCV holdout RMSE (if available) Medium value value
Coefficient plausibility Medium judgement judgement
Fit visual quality Low judgement judgement

Use the matrix in order:

  1. Remove runs that are not computationally trustworthy enough to compare.
  2. Rank the remaining candidates by predictive evidence.
  3. Prefer the run whose coefficients, decomposition, and fit behaviour remain most defensible for the business question.

8. Record the selection

Document the selected run directory and rationale. If using the runner for release evidence, the selected run’s artefacts form part of the evidence pack.

Caveats

  • ELPD is not causal validation. Predictive scoring measures in-sample predictive quality, not whether the model identifies causal media effects correctly.
  • ELPD is not a substitute for adequacy. Stronger predictive ranking does not rescue a run that is diagnostically broken or substantively implausible.
  • Pooled models do not support time-series CV (rejected by config validation).
  • Adstock/Hill media transforms are not supported by time-series CV; lower-level scoring aborts if transformed-media paths are used.
  • MAP-fitted models do not produce LOO diagnostics. Use MCMC for model comparison.

Debug Run Failures

Objective

Diagnose and resolve the most common failure modes encountered when running DSAMbayes via the YAML/CLI runner.

Prerequisites

  • A failed runner execution (non-zero exit code or missing artefacts).
  • Access to the terminal output or log from the failed run.
  • Familiarity with CLI Usage and Config Schema.

Triage by failure stage

Stage 0: Config resolution failures

Symptoms: runner exits immediately after validate or at the start of run; no run directory created or only 00_run_metadata/ is present.

Error pattern Cause Fix
data_path not found Data file path is wrong or missing Check data.path in YAML; use absolute path or path relative to config file
Unknown YAML key Typo or unsupported config key Compare against Config Schema; fix spelling
Compiled formula error Invalid generated model formula Check target, media, controls, and hierarchy for unsupported or missing terms
effects.holidays.path not found Holiday calendar file missing Check effects.holidays.path; ensure file exists

Quick check:

Rscript scripts/dsambayes.R validate --config config/blm_timeseries.yaml

If validate passes, the config is structurally valid.

Stage 1: Stan compilation failures

Symptoms: runner reports compilation errors after “Compiling model”; may reference C++ or Stan syntax errors.

Error pattern Cause Fix
Stan syntax error in generated template Template rendering issue Clear the Stan cache (rm -rf .cache/dsambayes/) and retry
C++ compiler not found Toolchain not installed Install a C++ toolchain (see Install and Setup)
Permission denied on cache directory Cache path not writable Set XDG_CACHE_HOME to a writable directory

Quick check:

mkdir -p .cache
export XDG_CACHE_HOME="$PWD/.cache"

Stage 2: Data preparation failures

Symptoms: runner fails after compilation but before sampling; error messages reference prep_data_for_fit, model.frame, or scaling.

Error pattern Cause Fix
“Cannot scale model data with zero variance” A column in the model frame is constant Remove constant terms from formula, or set model.scale: false
“Constant CRE mean terms” CRE variable has identical group means Use model.type: re (without CRE) or add variation
“non-finite values” in model frame NA or Inf values in data Clean data before running; remove rows with missing values
“Offset vector length does not match” NA handling created length mismatch Ensure offset column has no NA values, or report as a bug

Stage 3: Sampling failures

Symptoms: runner fails during rstan::sampling() or rstan::optimizing(); may report Stan runtime errors.

Error pattern Cause Fix
“Exception: validate transformed params” Parameter hits boundary during sampling Widen boundaries; check for overly tight constraints
“Initialization failed” Poor initial values Increase fit.mcmc.init range or simplify model
Timeout or very slow sampling Model too complex for data size Reduce iterations for initial testing; simplify formula
All chains fail Severe model misspecification Review formula, priors, and data for fundamental issues

Stage 4: Post-fit artefact failures

Symptoms: runner completes sampling but some artefact folders are empty or missing files.

Error pattern Cause Fix
00_run_metadata/run_status.yaml shows completed_with_artifact_write_fail Fit completed but a later artifact write failed Inspect run_status.yaml if present for the message, keep the fitted run directory, then fix the file-system or payload issue and rerun artifact generation
00_run_metadata/run_status.yaml shows completed_with_scenario_analysis_fail Fit completed but the requested scenario analysis failed Inspect the saved message, scenario/reference paths and fitted-model input contract; the fitted model remains available
00_run_metadata/run_status.yaml shows completed_with_publish_gate_fail Fit completed but diagnostics publish-gate enforcement rejected the run Review diagnostics outputs before treating the run as publishable
Missing decomposition files under 30_post_run/ Decomposition failed or was skipped Check formula compatibility with model.matrix(), confirm the fitted model retained original data, and inspect 40_diagnostics/artifact_status.csv for response_decomposition skip details
Missing 40_diagnostics/ files Diagnostics writer error Check for upstream issues in model object; review tryCatch messages in log
Missing 50_model_selection/ files LOO computation failed Ensure MCMC fit (not MAP); check for valid posterior
Missing 80_optimisation/ files Allocation not enabled or failed Check allocation.enabled: true in config; review scenario specification

Quick check:

find results/<run_dir> -type f | sort

Compare against the expected artefact list in Output Artefacts.

Stage 5: Plot generation failures

Symptoms: CSV artefacts are present but PNG plot files are missing.

Error pattern Cause Fix
“cannot open connection” for PNG Graphics device issue Check that grDevices is available; ensure sufficient disk space
Plot function error for hierarchical model Group-level coefficient draws are vectors, not scalars This has been fixed in recent releases; ensure you are running the latest version

General debugging steps

  1. Read the full error message. DSAMbayes uses cli::cli_abort() with descriptive messages that identify the failing function and parameter.

  2. Check the terminal run status first. If a run directory was created, inspect 00_run_metadata/run_status.yaml if present to see whether the run ended as fit_failed, completed, completed_with_scenario_analysis_fail, completed_with_publish_gate_fail, or completed_with_artifact_write_fail.

  3. Check the resolved and compiled configs. Inspect 00_run_metadata/config.resolved.yaml to see what defaults were applied and 00_run_metadata/config.compiled.yaml to see the internal runner config that was actually passed downstream.

  4. Check session info. Inspect 00_run_metadata/session_info.txt for package version mismatches.

  5. Clear the Stan cache. Stale compiled models can cause unexpected failures:

    rm -rf .cache/dsambayes/
  6. Run validate before run. Always validate first to catch config errors before committing to a full MCMC run.

  7. Reduce iterations for debugging. Use a small fit.mcmc block or switch temporarily to fit.method: optimise to iterate quickly on schema and data issues.