Skip to main content

Chapter 13. Causal and Counterfactual Evaluation from Logged Data

Imagine that Juniper passes an offline return-handling suite, but its team still faces a deployment decision: will the new agent improve customer outcomes compared with the current workflow? The test cases may not resemble live traffic, and customers who receive agent assistance may differ from those who do not. For both reasons, a higher score on the suite does not answer the deployment question by itself.

This chapter follows that question from potential outcomes to off-policy estimation and causal attribution. Each method asks for different evidence and rests on assumptions that logs alone may not verify. A randomized experiment, when safe and feasible, can answer some questions more directly; otherwise, the team must be explicit about what the available data can support.

13.1 The Fundamental Problem of Causal Evaluation

Imagine comparing the same return request under the new agent and under the existing workflow. We can describe what each outcome would mean, but in ordinary production the customer experiences only one of them.

Definition 21.1 (Potential outcomes). For each task instance \(i\), let \(Y_i(1)\) be the outcome if the agent is deployed and \(Y_i(0)\) be the outcome under the specified comparison workflow. The individual causal effect is \(\tau_i = Y_i(1) - Y_i(0)\).

The fundamental problem: For one task instance, we observe either the outcome with deployment or the outcome without it. We never observe both \(Y_i(1)\) and \(Y_i(0)\) for that same instance.

Definition 21.2 (Average treatment effect). \(\tau = \mathbb{E}[Y(1) - Y(0)]\) is the average effect over a specified population of task instances. The population, comparison workflow, outcome, and observation window must be defined before interpreting the estimate.

Random assignment can support an estimate of this average without observing both potential outcomes for each instance, provided the experimental design and its assumptions hold. Logged data may also support an estimate, but only under additional identification and coverage assumptions. The off-policy methods below estimate a target policy’s value; to estimate an effect, the team also needs a comparable estimate for the alternative policy.

Why offline evaluation is confounded

Suppose Juniper has logs from its current workflow, the behavior policy \(\pi_b\), and wants to evaluate a different target policy \(\pi_e\). The distributions over trajectories \(\xi\) can differ:

\[P_{\pi_b}(\xi) \neq P_{\pi_e}(\xi).\]

The average success in those logs describes \(\mathbb{E}_{\pi_b}[Y]\) for the logged population; it is not automatically \(\mathbb{E}_{\pi_e}[Y]\). Different actions can lead to different subsequent states, and logged users or tasks may not represent the intended deployment population. Addressing the first difference calls for policy adjustment, while the second also requires population coverage or justified transport assumptions. Inspect both before applying an offline estimator.

13.2 Importance Sampling (Offline Evaluation)

Importance sampling reweights logged trajectories according to how likely the target policy was to take their actions. This can reuse data from the old workflow, but only where that workflow gives the target’s actions support.

Definition 21.3 (Importance sampling estimator). Given logged trajectories \(\xi_i \sim P_{\pi_b}\) with returns \(r_i = r(\xi_i)\), the IS estimator for target policy \(\pi_e\) is:

\[\hat{V}_{\text{IS}}(\pi_e) = \frac{1}{N}\sum_{i=1}^{N} \frac{P_{\pi_e}(\xi_i)}{P_{\pi_b}(\xi_i)} r_i.\]

If the initial population and environment dynamics are the same under both policies, the non-policy factors cancel. The weight is then \(w(\xi_i) = \prod_{t=0}^{T} \frac{\pi_e(a_t^{(i)} \mid h_t^{(i)})}{\pi_b(a_t^{(i)} \mid h_t^{(i)})}\), where \(h_t\) is the observed history before action \(a_t\). These probabilities must describe the actual behavior and target policies; action likelihoods alone do not correct a change in the initial population, environment, or unobserved action-selection factors.

Theorem 21.1 (Unbiasedness). With the correct trajectory density ratio, target trajectories supported by the behavior distribution, and a finite expected return, \(\mathbb{E}[\hat{V}_{\text{IS}}] = V(\pi_e) = \mathbb{E}_{\pi_e}[r(\xi)]\). The action-ratio form additionally relies on the shared-population and environment assumptions above and on valid conditional propensities. Estimated or misspecified propensities do not generally retain this finite-sample guarantee.

Practical limit: Importance sampling can have high variance. When \(\pi_e\) and \(\pi_b\) assign very different probabilities to actions, a few large weights can dominate the estimate.

Self-normalized IS

\[\hat{V}_{\text{SNIS}}(\pi_e) = \frac{\sum_{i=1}^{N} w_i r_i}{\sum_{i=1}^{N} w_i}.\]

SNIS divides by the observed sum of weights rather than by the number of trajectories. In many settings, it trades some bias for lower variance, although it is undefined if all weights are zero. Report which estimator you use and inspect the weight distribution.

Per-decision importance sampling

For long horizons, full-trajectory products can compound variance. When return is a sum of discounted step rewards, per-decision IS (PDIS) weights each reward only by the action ratios up to that step:

\[\hat{V}_{\text{PDIS}}(\pi_e) = \frac{1}{N}\sum_{i=1}^{N} \sum_{t=0}^{T} \gamma^t \left(\prod_{k=0}^{t} \frac{\pi_e(a_k^{(i)} \mid h_k^{(i)})}{\pi_b(a_k^{(i)} \mid h_k^{(i)})}\right) r_t^{(i)}.\]

Here \(\gamma\) is the discount factor, and \(r_t^{(i)}\) is the reward at step \(t\) in trajectory \(i\). Although this avoids multiplying early rewards by later action ratios, it does not eliminate variance or the need for overlap. A baseline can be used as a control variate only with an appropriate correction; subtracting one without that correction can bias the estimate.

13.3 Doubly Robust Estimation

When weights are unstable, a model of expected outcomes offers another way to use the logs. The direct method predicts the outcome for the target action, while doubly robust (DR) estimation adds an importance-weighted correction for observed prediction errors. DR can tolerate one of its two nuisance models being wrong under the conditions below, but it does not make missing confounders or absent support disappear.

Definition 21.4 (Direct method estimator). For a one-step contextual bandit with deterministic target action \(\pi_e(s)\), learn \(\hat{Q}(s, a) \approx \mathbb{E}[r \mid s, a]\) from logged data:

\[\hat{V}_{\text{DM}}(\pi_e) = \frac{1}{N}\sum_{i=1}^{N} \hat{Q}(s_i, \pi_e(s_i)).\]

Definition 21.5 (Doubly robust estimator). For the same one-step setting, using known behavior probabilities or estimates \(\hat\pi_b\):

\[\hat{V}_{\text{DR}}(\pi_e) = \frac{1}{N}\sum_{i=1}^{N} \left[ \hat{Q}(s_i, \pi_e(s_i)) + \frac{\mathbb{I}\{a_i = \pi_e(s_i)\}}{\hat\pi_b(a_i \mid s_i)} (r_i - \hat{Q}(s_i, a_i)) \right].\]

Theorem 21.2 (Double robustness). In this one-step setting, under consistency, conditional exchangeability, positivity, appropriate nuisance estimation and regularity conditions, DR is consistent if either the propensity estimate converges to the correct behavior policy or the outcome model converges to the correct conditional mean. Estimating both correctly does not by itself guarantee efficiency: the efficiency bound additionally requires appropriate convergence rates and inference conditions. Sample splitting or cross-fitting can help separate nuisance-model fitting from evaluation. These guarantees do not cover unmeasured confounding or unsupported deployment populations.

Worked example: logged bandit actions

Consider four independent fictional requests. The target policy always chooses action \(A\); the logging policy chose \(A\) or \(B\) with probability 0.5 each. The observed rewards and outcome-model predictions are:

Request Logged action Reward \(r_i\) \(\pi_b(A\mid x_i)\) \(\hat Q(x_i,A)\)
1 A 1 0.5 0.6
2 A 1 0.5 0.6
3 A 0 0.5 0.4
4 B 1 0.5 0.4

The unit is one request, and each estimator averages over \(N=4\) logged requests. For deterministic target action \(A\), the importance weight is \(w_i=\mathbb{I}\{a_i=A\}/0.5\), giving \((2,2,2,0)\).

\[ \hat V_{\mathrm{IS}}=(2\cdot1+2\cdot1+2\cdot0+0\cdot1)/4=1.00,\qquad \hat V_{\mathrm{SNIS}}=4/6=0.667. \]

The effective sample size is \(\mathrm{ESS}=(2+2+2+0)^2/(2^2+2^2+2^2+0^2)=3\), despite four logged requests. For DR, the four per-request terms are \(0.6+2(1-0.6)=1.4\), \(1.4\), \(0.4+2(0-0.4)=-0.4\), and \(0.4\). Their mean is \(0.70\).

actions = ["A", "A", "A", "B"]
rewards = [1.0, 1.0, 0.0, 1.0]
behavior_p_a = [0.5, 0.5, 0.5, 0.5]
q_target = [0.6, 0.6, 0.4, 0.4]

weights = [
    1.0 / p if action == "A" else 0.0
    for action, p in zip(actions, behavior_p_a)
]
is_value = sum(w * r for w, r in zip(weights, rewards)) / len(rewards)
snis_value = (
    sum(w * r for w, r in zip(weights, rewards)) / sum(weights)
)
ess = sum(weights) ** 2 / sum(w * w for w in weights)
dr_terms = [
    q + (w * (r - q) if action == "A" else 0.0)
    for action, r, q, w in zip(actions, rewards, q_target, weights)
]
dr_value = sum(dr_terms) / len(dr_terms)
print(f"IS: {is_value:.3f}; SNIS: {snis_value:.3f}")
print(f"ESS: {ess:.1f} of {len(rewards)}; DR: {dr_value:.3f}")
IS: 1.000; SNIS: 0.667
ESS: 3.0 of 4; DR: 0.700

Four requests are far too few to support a deployment decision. The IS estimate reaches the reward maximum because the logged outcomes for action \(A\) happen to include two successes and one failure; request 4 provides no observed outcome for the target action. DR uses both the outcome prediction and the propensity: misspecification of both can bias it, and finite-sample estimates remain uncertain even when a model is correct. Therefore, report overlap, weight distributions, and effective sample size, and quantify uncertainty with a method suited to the estimator and design. Resampling independent requests or user-level clusters may be appropriate when requests share users. Use the example to check the arithmetic, not to justify deployment.

Worked example: extreme weights and clipping sensitivity

Suppose four logged requests have rewards \([0,0,0,1]\) and importance weights \([1,1,1,20]\). The ordinary IS estimate is \((20\cdot1)/4=5.00\), above the reward range \([0,1]\); this is possible for finite-sample IS and is a warning, not a valid probability. SNIS is \(20/23\approx0.870\), while \(\mathrm{ESS}=23^2/(1^2+1^2+1^2+20^2)\approx1.31\), so the nominal four requests carry little effective information.

If weights are clipped at a prespecified cap of 5, the clipped weights become \([1,1,1,5]\). Clipped IS is \(5/4=1.25\), clipped SNIS is \(5/8=0.625\), and ESS rises to \(8^2/(1+1+1+25)\approx2.29\). Although clipping reduces the influence of the extreme observation, it introduces bias; it does not create overlap or new evidence.

rewards = [0.0, 0.0, 0.0, 1.0]
weights = [1.0, 1.0, 1.0, 20.0]
cap = 5.0
clipped = [min(weight, cap) for weight in weights]

def summarize(weights, rewards):
    is_estimate = sum(w * r for w, r in zip(weights, rewards)) / len(rewards)
    snis_estimate = sum(w * r for w, r in zip(weights, rewards)) / sum(weights)
    ess = sum(weights) ** 2 / sum(w * w for w in weights)
    return is_estimate, snis_estimate, ess

for name, candidate_weights in (("unclipped", weights), ("clipped", clipped)):
    is_estimate, snis_estimate, ess = summarize(candidate_weights, rewards)
    print(
        f"{name}: IS={is_estimate:.3f}; SNIS={snis_estimate:.3f}; "
        f"ESS={ess:.2f}/{len(rewards)}"
    )
unclipped: IS=5.000; SNIS=0.870; ESS=1.31/4
clipped: IS=1.250; SNIS=0.625; ESS=2.29/4

Report the unclipped estimate, the prespecified cap, the clipped sensitivity estimate, and ESS together. The change from 0.870 to 0.625 shows how sensitive the estimate is to the largest weight, so avoid a confident policy-value claim and collect data with better overlap. Bootstrap intervals cannot repair near-zero behavior-policy support, and choosing a cap after seeing the result undermines a prespecified sensitivity analysis.

DR for trajectory-level metrics

The preceding DR formula makes one decision per request. An agent trajectory may contain several decisions, each affecting what happens next. For discounted return \(R(\xi) = \sum_{t=0}^{T} \gamma^t r_t\), a sequential DR estimator combines per-decision weights with predictions for both the observed action and the target policy:

\[\hat{V}_{\text{DR}}^{\text{epi}}(\pi_e) = \frac{1}{N}\sum_{i=1}^{N} \left[ \hat{V}(h_0^{(i)}) + \sum_{t=0}^{T} \gamma^t \rho_{0:t}^{(i)} \left(r_t^{(i)} + \gamma \hat{V}(h_{t+1}^{(i)}) - \hat{Q}(h_t^{(i)},a_t^{(i)})\right) \right],\]

where \(\rho_{0:t}^{(i)}=\prod_{k=0}^{t}\pi_e(a_k^{(i)}\mid h_k^{(i)})/\hat\pi_b(a_k^{(i)}\mid h_k^{(i)})\), \(\hat{Q}(h,a)\) predicts the discounted return after action \(a\), and \(\hat{V}(h)=\sum_a \pi_e(a\mid h)\hat{Q}(h,a)\) averages those predictions under the target policy. Set \(\hat V(h_{T+1})=0\) at the terminal horizon. For continuous actions, use the corresponding expectation or integral instead of the sum. Fit and evaluate value models on separate data or use an appropriate cross-fitting procedure, and check the sequential identification and support assumptions; a trajectory-level formula is not a substitute for them [1].

13.4 Causal Attribution of Agent Failures

Policy-value estimation asks about average outcomes, but an incident review may ask a narrower question: would this particular failure have occurred if the agent had selected another action? A structural causal model (SCM) makes the assumed relationships behind that question explicit.

Definition 21.6 (Structural causal model for agents). One schematic SCM is:

\[ \begin{aligned} S_0 &:= f_0(U_0) \\ A_t &:= \pi(S_t, H_t, U_t) \\ S_{t+1} &:= f_{t+1}(S_t, A_t, U_{t+1}) \\ R_t &:= r(S_t, A_t, U_t) \\ Y &:= g(S_0, A_0, \dots, S_T, A_T, U_Y) \end{aligned} \]

Here \(U\) variables represent factors outside the modeled equations, and \(H_t\) represents the relevant history. The equations are a modeling template, not proof that the listed variables or their relationships are complete.

Definition 21.7 (Counterfactual failure attribution). To ask “what if the model had chosen a different action?”, first use the observed evidence to infer plausible latent conditions (abduction), then replace the relevant action equation with the proposed intervention (action), and finally propagate that change through the model (prediction). Different defensible models or unobserved conditions can produce different answers; a trace alone does not establish the individual counterfactual.

Intervention vs. observation

  • Observational: Conditioning on \(A_t = a\).
  • Interventional: \(\text{do}(A_t = a)\) (we force action \(a\)).

For example, the average effect of changing prompt \(p\) to \(p'\) in a defined population is \(\tau = \mathbb{E}[Y \mid \text{do}(P = p')] - \mathbb{E}[Y \mid \text{do}(P = p)]\). Simply comparing cases where different prompts happened to be used is not the same intervention if those cases also differ in difficulty, users, or rollout conditions.

For standard adjustment from observational data, consistency, conditional exchangeability, and positivity are central assumptions. Other identification strategies can use different assumptions, but no estimator makes the assumptions unnecessary. Moreover, even when an average effect is identifiable, an individual failure’s counterfactual generally requires additional structural assumptions.

13.5 Identification Assumptions

The assumptions connect an observed outcome to the unobserved outcome the team wants to estimate. For a one-step treatment or action \(A\), they can be stated as follows:

Assumption 21.1 (Consistency). If an instance receives action \(a\), its observed outcome is \(Y=Y(a)\), for a well-defined intervention. Applying this to a policy requires a well-defined policy and outcome, with any relevant interference or multiple versions addressed in the design.

Assumption 21.2 (Ignorability / conditional exchangeability). \(Y(a) \perp\!\!\!\perp A \mid X\): after conditioning on recorded pre-action covariates \(X\), action assignment is independent of the potential outcome. This is a causal assumption, not something a good propensity fit alone proves.

Assumption 21.3 (Overlap / positivity). For relevant contexts, \(\pi_b(a \mid X)>0\) whenever \(\pi_e(a \mid X)>0\). The target population itself must also be covered by the logged data, or the analysis needs separately justified transport assumptions.

For sequential decisions, exchangeability and positivity must hold at each relevant history, not merely for the first action. When overlap fails, IS cannot identify the target-policy value from those logs; a prediction for the unsupported region relies on extrapolation or additional data and assumptions. Even small but nonzero probabilities can make estimation practically unreliable.

13.6 Practical Evaluation Protocol

flowchart TB
    subgraph "Estimator Selection"
        A[Which evidence is defensible?]:::decision
        C[Use Direct Method; report model and coverage risk]:::estimator
        D[Use IS; assess weights and ESS]:::estimator
        E[Use DR; qualify both models]:::estimator
        F[Insufficient identification for a target-policy claim]:::decision
    end

    A -->|Defensible outcome model and identification| C
    A -->|Propensities, overlap, and identification| D
    A -->|Both and identification| E
    A -->|Neither| F

    classDef decision fill:#fff3cd,stroke:#333;
    classDef estimator fill:#e1f5e1,stroke:#333;

    linkStyle default stroke:#666,stroke-width:2px

The choice is not just between estimators: first decide whether the evidence can identify the claim. For Juniper’s deployment decision, define the target population, comparison workflow, outcome, and time window; then examine whether the logs cover the users, contexts, and decisions the target policy will encounter.

Step 1 — Record decision evidence responsibly. Capture the relevant pre-action history, actions, observations, outcomes, and behavior-policy probabilities, together with policy and environment versions. Minimize sensitive data and apply appropriate purpose, access, retention, and deletion controls; “more logging” is not a substitute for valid evidence.

Step 2 — Establish behavior probabilities. Prefer correctly recorded probabilities from the actual assignment mechanism when available. Otherwise, estimate \(\hat{\pi}_b(a \mid h)\) from the logs and validate it against known assignment behavior. Even so, a fitted model cannot recover the effect of important unrecorded factors merely by assigning probabilities.

Step 3 — Choose an estimator. The direct method (DM) predicts outcomes for target actions and depends on a defensible outcome model and identification assumptions. IS requires valid behavior propensities and adequate overlap. DR combines both models but still requires identification and appropriate nuisance estimation. A model prediction in an unsupported region is extrapolation, not an identified estimate from those logs. “Well-separated” policies are not a reason to prefer IS: separation often produces extreme weights and high variance.

Step 4 — Assess overlap and uncertainty. Inspect the importance-weight distribution and effective sample size \(\text{ESS} = (\sum w_i)^2 / \sum w_i^2\), together with context coverage and the number of independent units. ESS is a diagnostic, not a guarantee of precision or causal validity. Use an uncertainty method appropriate to the sampling and dependence structure.

Step 5 — Test sensitivity and decide what to do next. Report how results change under plausible deviations from exchangeability, alternative model specifications, or prespecified weight caps; use sensitivity bounds when the required assumptions and inputs can be justified. If identification or precision is inadequate, say so and collect better evidence rather than presenting a point estimate as a decision. A safe, properly designed randomized experiment may be the next step.

13.7 Exercises

  1. (Conceptual) Given logged data showing 70% resolution, and a new agent taking different actions on 30% of cases, explain why 70% is not necessarily a valid estimate of the new agent’s resolution rate.

  2. (Hands-on) Implement IS and DR estimators for a deterministic agent with binary rewards using synthetic data. Compare variance across 1000 simulated datasets.

  3. (Conceptual) The behavior policy only operated during business hours, but the target agent will operate 24/7. Which population-coverage limitation does this create, and what additional evidence or transport assumptions would a 24/7 claim require?

  4. (Discussion) What unmeasured confounders might affect both agent actions and outcomes in your domain?

13.8 Further Reading

  • Bottou et al., “Counterfactual Reasoning and Learning Systems” [2].
  • Dudík et al., “Doubly Robust Policy Evaluation and Learning” [3].
  • Thomas & Brunskill, “Data-efficient Off-policy Policy Evaluation for RL” [1].
  • Pearl, Causality [4].
  • Imbens & Rubin, Causal Inference for Statistics [5].
[1]
P. S. Thomas, G. Theocharous, and M. Ghavamzadeh, “Data-efficient off-policy policy evaluation for reinforcement learning,” in Proceedings of the 22nd international conference on machine learning, 2005, pp. 807–814. doi: 10.1145/1102351.1102458.
[2]
L. Bottou et al., “Counterfactual reasoning and learning systems: The example of computational advertising,” Journal of Machine Learning Research, vol. 14, pp. 3207–3260, 2013.
[3]
M. Dudík, J. Langford, and L. Li, “Doubly robust policy evaluation and learning,” in Proceedings of the 28th international conference on machine learning (ICML), 2011, pp. 1097–1104.
[4]
J. Pearl, Causality: Models, reasoning, and inference, 2nd ed. Cambridge University Press, 2009. doi: 10.1017/CBO9780511803161.
[5]
G. W. Imbens and D. B. Rubin, Causal inference for statistics, social, and biomedical sciences: An introduction. Cambridge University Press, 2015. doi: 10.1017/CBO9781139025751.