Manuscript Offprint
arXiv:2608.23087Closed-Form Predicate-Level Shapley Attribution for Sliding-Window Aggregates
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
ABSTRACT
Streaming engines report sliding-window aggregates in real time, but they do not explain why an aggregate takes its current value. A natural target is the Shapley value from cooperative game theory, which axiomatically distributes an aggregate among the tuples in the window. Practitioners, however, ask predicate-level questions (e.g., how much a region or customer tier contributed to an average or variance spike). Exact Shapley computation is exponential in the window size, and existing estimators discard the massive overlap between consecutive windows.
We show that for SUM, COUNT, AVG, and population/sample variance, exact predicate-level Shapley values admit closed forms in three additively maintained summaries per predicate (count, sum, and sum of squares), with coefficients that depend only on two running harmonic numbers. Attribution therefore reduces to summary updates per slide for registered predicates, with no coalition enumeration. Overlapping and compositional predicates are answered exactly via atomic refinement of Boolean signatures. We further characterize the phenomenon: every moment-polynomial aggregate admits such a form, while MAX, MIN, and quantiles provably do not at any fixed moment order.
Experiments match brute-force Shapley values to floating-point precision on over 10,000 windows, sustain per slide up to ( faster than per-window recomputation of the same formulas), and explain a nighttime fare spike on 2.9M NYC taxi trips at summary updates per second.
Keywords Explainable AI, Data Streaming, Shapley Values, Predicate Attribution, Sliding Windows
1 Introduction
High-velocity data streams, from algorithmic trading and IoT monitoring to real-time cybersecurity, have made Data Stream Management Systems (DSMS) a standard tool. Modern engines such as Apache Flink and Spark Streaming compute continuous aggregate queries over sliding windows efficiently. These systems can instantly report what is happening (e.g., “the average server latency has spiked by 200 ms”), but they cannot explain why it is happening in real time.
Standard root-cause analysis uses ad-hoc manual queries or post-hoc analysis on data warehouses. These approaches introduce unacceptable latency. To automate this, we turn to the Shapley Value (SV), a concept from cooperative game theory. Unlike heuristic feature importance methods, the Shapley Value distributes the “payout” (the aggregate result) among the “players” (the input tuples) axiomatically. It satisfies properties such as Efficiency, Symmetry, Additivity, and the Dummy axiom.
Example 1 (Running Example: Cloud Latency Monitoring). Consider an operations team monitoring request latency for a cloud service. A streaming engine continuously reports AVG and VAR over the most recent requests. When the average latency spikes, the team asks whether the increase is mainly due to requests from region='EU-West', premium customers, a particular service endpoint, or an intersection such as region='EU-West' AND tier='premium'. The
A PREPRINT
relevant explanation must be produced while the window is still active. It should also distinguish a predicate that increases the average from one that merely contributes many near-average tuples. We use this latency-monitoring scenario throughout the paper. Small numerical examples use normalized latency values such as to keep the arithmetic readable.
-
The Re-computation Bottleneck: For a generic cooperative game, exact Shapley computation requires summing over exponentially many coalitions. Sampling-based approximations still require many marginal evaluations. In a sliding-window context, where denotes the active window at time and the next window, the two window states largely overlap. Stateless methods such as Monte Carlo permutation sampling discard useful work from the previous window and repeat many nearly identical computations.
-
The Granularity Mismatch (Tuple vs. Predicate): Existing literature mainly focuses on the Shapley value of individual atomic tuples (row-level attribution). However, in streaming analytics, users rarely ask about a specific raw event. Instead, they require Predicate-Based Attribution. A user is more likely to ask, “How much did Region=’EU-West’ contribute to the variance?” than to query a specific transaction ID. A predicate P is a Boolean condition over tuple attributes. Computing attribution for P treats the dynamic subset of tuples that satisfy P as a coalition. In a streaming context, the cardinality of this subset changes at every slide, complicating standard group-testing approaches. Users also frequently issue compositional questions that involve conjunctions, disjunctions, and negations of multiple predicates. An attribution scheme that only supports single-predicate queries is therefore insufficient.
-
Non-Linearity in Aggregates: Linear aggregates (SUM, COUNT) are trivially decomposable. Non-linear functions such as AVG and VAR introduce interaction effects: the marginal contribution of one tuple depends on the other tuples present in the coalition. The challenge is to show that these interactions can still be summarized exactly for important SQL aggregates whose Shapley game admits a closed form in low-order moments, rather than approximating the full Shapley game.
1.2 Contributions
We derive exact closed-form predicate-level Shapley formulas for sliding-window aggregates whose cooperative game depends only on low-order moments: SUM, COUNT, AVG, population variance, and sample variance. The formulas need only the window's size and its first and second moments, all of which are easy to keep up to date. Once the summaries are updated for tuples entering and leaving the window, attribution is a single formula evaluation. No tuple-level Shapley computation and no coalition enumeration are needed.
Notation preview. We use for the active window at time and for a generic active window when the time index is not important. We use for a user predicate and for the active tuples satisfying . The predicate summaries are , , and , where is the numeric attribute being aggregated. We write for a single-tuple count-window slide and for a time-window slide with outgoing and incoming tuple sets. Full notation is summarized in Table 1.
• Exact Sufficient-Statistics Shapley Formulas: We derive exact closed-form Shapley expressions for SUM, COUNT, AVG, population variance, and sample variance over a finite window. We show that predicate-level attribution for each is a linear function of compact predicate summaries. For a single-relation static database, the tuple-level AVG formula matches an independent result of Standke and Kimelfeld Standke and Kimelfeld [2025] (Section 4.3). The variance formulas, the predicate-level forms, and their windowed maintenance are new. Every attribution coefficient is a simple expression in two harmonic numbers and can be updated in as the window size changes (Section 4.5).
• Predicate Attribution without Tuple Materialization: We show that predicate questions can be answered exactly from together with global summaries, without computing or storing any tuple-level Shapley value.
• Sliding-Window Summary Maintenance: We show how each predicate summary changes under a slide, both for single-tuple count-based deltas and for multi-tuple time-based deltas , avoiding re-evaluation of the full cooperative game on consecutive windows.
• Time-Based Window Generalization: We extend the closed forms to time-based windows where the active cardinality varies, with explicit batched delta-update rules; the harmonic-number coefficients follow at cost.
A PREPRINT
• Overlapping and Compositional Predicates: We support overlapping predicates and arbitrary Boolean combinations of them (intersections, unions, complements, and set differences). We do so via the atomic refinement of their Boolean signatures. Maintaining sufficient statistics per atom yields exact attribution for any compositional query and restores Shapley efficiency over the resulting window partition.
• Additivity Across Disjoint Subsets: The required sufficient statistics are additive across disjoint subsets, so the closed forms compose cleanly with existing pane-based sliding-window aggregation frameworks Li et al. [2005], Tangwongsan et al. [2015], Traub et al. [2021].
• Boundary of the Phenomenon: We prove that the approach extends to every moment-polynomial window game, i.e., any game that is a polynomial in the coalition’s power sums with size-dependent coefficients (Section 7). We also prove the converse boundary: MAX, MIN, and fixed order statistics have no sufficient-statistic representation of any fixed moment order, because windows can match all moments up to order d yet differ in their extreme values.
• Semantics Made Explicit: We show that AVG attribution splits exactly into a group share plus a harmonically weighted group lift (Section 4.4). This reveals that attributions grow logarithmically with window size. On real data, we measure how often the Shapley weighting changes the explanation compared to the naive lift heuristic, and how far the sum-of-members semantics is from the predicate-as-player alternative (Sections 8.7 and 8.6).
• Experimental Evaluation: We validate exactness against brute-force enumeration on 10,010 random windows. We measure constant per-slide latency up to , comparing against per-window recomputation, permutation sampling Castro et al. [2009], and exact enumeration. A case study on 2.9 million NYC taxi trips New York City Taxi and Limousine Commission [2024] explains a nighttime fare spike as long-haul airport traffic while sustaining million summary updates per second in a single-threaded prototype (Section 8).
2 Related Work
The problem of explaining aggregate query results in data streams intersects three research communities: Cooperative Game Theory, Machine Learning (Data Valuation), and Database Provenance. We review the state of the art in each and analyze their limitations regarding the sliding-window predicate-attribution problem.
2.1 Stateless Shapley Approximations
The foundational work by Shapley Shapley [1953] established the axioms of Efficiency, Symmetry, and Additivity. For a generic game represented by a value oracle, exact computation requires summing over exponentially many coalitions. To address this, Castro et al. Castro et al. [2009] introduced sampling-based estimation using the theory of permutations. This approach was unified and popularized in the Machine Learning community by SHAP (Shapley Additive Explanations) Lundberg and Lee [2017]. KernelSHAP, in particular, approximates values by solving a weighted linear regression on perturbed inputs.
Limitation: These methods are designed for static datasets and do not exploit aggregate-specific structure. In a streaming context, a sliding-window transition involves a high degree of data overlap (typically > 99%). Stateless algorithms such as KernelSHAP treat as a completely new dataset, discarding the computational effort spent on . They also operate at the tuple level, so even if applied to a stream they would not directly yield predicate-level answers.
2.2 Variance-Based Sensitivity and Shapley Effects
Variance attribution has also been studied in global sensitivity analysis through Sobol' indices and Shapley effects Owen [2014], Song et al. [2016]. That line of work allocates the variance of a model output among input variables, typically under a probabilistic input model. The structural connection is that both formulations exploit the fact that variance functionals depend on the data only through low-order moments. Our finite-window expressions can be viewed as the discrete, sampling-without-replacement counterpart of the continuous Shapley-effects framework.
Limitation: The players, the object of explanation, and the query type differ from ours. Sobol'/Shapley-effects allocate variance among input variables of a probabilistic model. In contrast, we attribute a database aggregate over a realized finite window to tuples and predicates. Those methods therefore do not yield sliding-window predicate attributions for SQL-style aggregates.
A PREPRINT
2.3 Incremental Shapley and XAI on Streams
Recent work has adapted Shapley-style explanations to streaming or temporal settings. DeltaSHAP Kim et al. [2025] explains prediction evolution in online ML (e.g., patient monitoring). It attributes changes in model predictions over time using Shapley-style reasoning. iSAGE Muschalik et al. [2023] and iPFI Fumagalli et al. [2023] provide incremental feature importance on data streams and handle concept drift.
Limitation: These methods explain model outputs (e.g., risk scores) or which features drive predictions. They do not explain the result of a streaming aggregate query (SUM, AVG, VAR over windows) attributed to predicates (e.g., region, sector). Their maintenance is driven by changes in model predictions, whereas our closed forms are driven by the window delta.
2.4 Incremental Shapley and Data Valuation
Recent work in “Data Valuation” seeks to quantify the value of training data points for ML models. Ghorbani and Zou Ghorbani and Zou [2019] introduced the Data Shapley to identify low-quality data. To avoid expensive model retraining, Jia et al. Jia et al. [2019] proposed efficient incremental algorithms for K-Nearest Neighbors (KNN-Shapley). They later extended this to heuristic approximations for deep learning updates.
Limitation: These methods largely assume an append-only or batch-update setting suitable for model retraining pipelines. They handle the insertion of a new tuple . They are not designed around the eviction phase of a sliding window . Some incremental valuation methods also maintain model- or history-dependent state Yan and Zhang [2021]. Our closed forms instead target aggregate-query windows, where simultaneous insertion and eviction are absorbed by additive updates to bounded predicate summaries.
2.5 Explanations in Data Management
The database community has explored query explanations through provenance, causality, responsibility, group-by-style explanations, and sensitivity analysis. Scorpion Wu and Madden [2013] uses backward tracing and influence-style reasoning to identify tuples responsible for outliers in aggregate queries. MacroBase Bailis et al. [2017] prioritizes attention in fast data by highlighting important and unusual behavior in streams. DIFF Abuzaid et al. [2021] provides a relational interface for large-scale data explanation. TSExplain Chen and Huang [2023] segments aggregated time series so that each segment admits a stable set of top contributors. It targets evolving contributor explanations for KPI curves rather than axiomatic Shapley attribution of a window aggregate to logical predicates. Erebus Palyvos-Giannas et al. [2022] explains divergences between expected and observed streaming query answers (including missing outputs) using provenance-style reasoning under storage limits. It complements forward why-provenance. Glavic et al. Glavic et al. [2013] instrument stream operators to propagate fine-grained tuple lineage in DSMSs, trading off eager versus lazy provenance for overhead. Roy and Suciu Roy and Suciu [2014] formalize explanations for database queries through intervention-style changes. Meliou et al. Meliou et al. [2010] formalized causality and responsibility for query answers and non-answers. More recent work studies Shapley values directly in database query answering. Livshits et al. Livshits et al. [2020] initiated the complexity study of Shapley contributions of tuples to query answers. They established a dichotomy for conjunctive queries and first results for aggregate queries over static databases. Subsequent work develops practical computation via knowledge compilation and model counting Deutch et al. [2022], Kara et al. [2024], Bertossi et al. [2023], tractable alternative responsibility measures Bienvenu et al. [2025], lineage-based algorithms for aggregate queries Abramovich et al. [2025], and a tractability map for aggregate conjunctive queries Standke and Kimelfeld [2025]. Closest to our closed forms, Standke and Kimelfeld Standke and Kimelfeld [2025] derive the tuple-level Shapley value of AVG for a single-relation query over a static database (their Proposition 5.2). This coincides with our Eq. 9; see Section 4.3. That line of work is tuple-level and static. It addresses neither predicate-level attribution, nor variance games, nor maintenance under sliding windows.
Limitation: These works provide important foundations for attribution in databases. They do not directly address the sliding-window predicate-attribution problem studied here. In prior work we studied predicate-level attribution on static tables under partial causal knowledge via Causal Banzhaf Value (CBV) Khani and Assent [2025] and Causally-Constrained Power Indices (CCPI) Khani et al. [2027]. Those methods constrain static power-index explanations; they do not provide closed-form streaming attribution. Causality and sensitivity methods are not generally Shapley-axiomatic. Shapley-based query-answer explanations are formulated for static database instances rather than continuously changing windows. Their complexity results concern worst-case query structure rather than the moment structure of aggregate games that we exploit for constant-time maintenance. Our work targets predicate-level Shapley attribution for streaming aggregate queries. It exploits overlap between consecutive windows in systems such as Apache Flink Carbone et al. [2015].
A PREPRINT
\begin{aligned}W_{t}:&\begin{bmatrix}x_{3}&x_{4}&x_{5}&x_{6}&x_{7}&x_{8}\end{bmatrix}\\\qquad &\downarrow\\x_{out}&=x_{3}\\\end{aligned}\quad x_{in}&=x_{9}\\\quad &\uparrow\\\Delta&= (x_{3}, x_{9})\\W_{t+1}:&\underbrace{x_{4}\quad x_{5}\quad x_{6}\quad x_{7}\quad x_{8}}_{N-1\mathrm{~shared~tuples}}\quad x_{9}\end{aligned}Figure 1: Single-tuple count-based slide. The window advances by evicting and inserting . Of tuples, are shared between consecutive windows. The closed forms below therefore need only update the summaries affected by the two boundary tuples. For time-based windows, and generalize to sets and of arbitrary size.
2.6 Sliding-Window Aggregates, Intermittency, and Shared Maintenance
General-purpose window aggregation frameworks such as panes Li et al. [2005], the Reactive Aggregator Tangwongsan et al. [2015], and Scotty Traub et al. [2021] maintain associative aggregates efficiently under arbitrary window specifications. Our sufficient statistics are associative and slot directly into these frameworks (Corollary 2). Shein and Chrysanthis Shein and Chrysanthis [2022] optimize multi-query plans for incrementally evaluated sliding-window aggregates, sharing work across concurrent window specifications. Zhu and Ravishankar Zhu and Ravishankar [2004] approximate aggregate answers when streams are intermittent, using randomized summaries under burstiness assumptions.
Limitation: These systems target scalable evaluation of window aggregates, not axiomatic explanation of the result. They do not produce Shapley attributions to predicates. Intermittent-stream methods further assume incomplete observations and approximate answers. Our exact formulas require a fully observed active window. Sketch-based or intermittent settings are left to the approximate extensions discussed in our limitations.
3 Background and Preliminaries
In this section, we formalize the data stream model, the semantics of sliding-window aggregation, and the game-theoretic foundations of the Shapley Value. We then extend Shapley attribution from atomic players to logical predicates.
3.1 Data Stream and Sliding Windows
Let be an unbounded stream of tuples. Each tuple consists of a set of features and a timestamp . We consider two window models.
Count-based windows. A count-based window of size contains the most recent tuples:
The transition from to is defined by a delta pair . Here is evicted and is inserted. Cardinality is fixed.
Time-based windows. A time-based window of duration contains all tuples whose timestamp lies in the trailing interval :
The active cardinality varies with the arrival process. The transition from to at the next emit instant is described by a multi-tuple delta
where and . We write . We treat both window types uniformly when possible. We write for an unspecified window of cardinality (or for time-based contexts where the dependence matters). Figure 1 illustrates a single-tuple count-based slide. The time-based case generalizes both arrows to sets.
A PREPRINT
3.2 The Shapley Value
The Shapley Value is a solution concept from cooperative game theory. It assigns a unique distribution of the total surplus generated by a coalition of players. In the context of data attribution, the players are the tuples in the window , and the payout is the aggregate result. Formally, let denote the cooperative game induced by the aggregate. For any coalition , is the value of the aggregate computed on the tuples in (with the convention unless stated otherwise). Concrete instances include , , and defined in Section 4.
For a tuple , the Shapley value is the weighted average of its marginal contributions to all possible subsets :
This formulation satisfies the standard axioms:
• Efficiency: .
• Symmetry: If two tuples contribute equally to all coalitions, then .
• Additivity: For two games .
• Dummy: If a tuple has zero marginal contribution to every coalition, then .
3.3 Predicate-Based Attribution
The classical Shapley literature focuses on the contribution of atomic tuples. Streaming analytics often requires explanations at the level of logical predicates (e.g., “sector = technology”). Let be a boolean predicate. We define the Predicate Coalition as the set of all active tuples satisfying the predicate:
The attribution for the predicate, denoted , is the sum of the atomic Shapley values of its constituents under the same aggregate game :
Partition, overlap, and atomic refinement. By the Efficiency axiom, if a family partitions the window, then . That is, the predicate attributions form an exhaustive, mutually exclusive decomposition of the aggregate. For a single predicate together with its complement , this reduces to . For overlapping predicates, the per-predicate quantity remains the exact aggregate Shapley contribution of . The family no longer sums to , because tuples in multiple predicates are double-counted. We address overlap in Section 5 by working at the level of the atomic refinement of the predicates.
Grand-coalition choice. Throughout the paper, the grand coalition is the active window . Attribution therefore explains the current aggregate relative to the tuples currently retained by the window. Other choices (e.g., all tuples seen so far, or a larger historical horizon) define different cooperative games and yield different Shapley values.
The Challenge. In a sliding window, the composition of is dynamic. Both the player set and the subset change at every slide. Naively recomputing Eq. 6 requires evaluating Eq. 4 for every member of the changing group. This is computationally prohibitive. The goal of the present work is to identify aggregate classes for which can be expressed in closed form from small, additively-maintained summaries.
3.4 Aggregate Classification
The complexity of computing depends on the properties of . We classify streaming aggregates into two categories:
• Linear/Decomposable (e.g., SUM, COUNT): The marginal contribution is independent of the coalition S.
• Sufficient-Statistic Non-Linear (e.g., AVG, VAR): The marginal contribution depends on the tuples in S. However, the expectation over uniformly random predecessor coalitions can be expressed using low-order sufficient statistics of W.
Our results address both decomposable aggregates and non-linear aggregates whose Shapley expressions reduce to incrementally maintained sufficient statistics. They do not cover aggregates such as quantiles, MIN/MAX, or arbitrary user-defined functions. Section 7 makes both sides of this boundary precise.
A PREPRINT
| Symbol | Meaning |
| Active window, generic window, fixed count-window size, and active time-window size | |
| Tuple and its numeric value for SUM/AVG/VAR | |
| Single-tuple count-window slide and multi-tuple time-window slide | |
| Aggregate game and tuple-level Shapley value | |
| Predicate, its active coalition, and predicate attribution | |
| Global sum and squared sum over | |
| Predicate count, sum, and squared sum | |
| First- and second-order harmonic numbers | |
| Auxiliary per-tuple variance quantities defined in Section 4.5 | |
| Predicate-level variance combinations defined in Eq. 21–23 | |
| Population-variance coefficients depending only on | |
| Sample-variance coefficients depending only on | |
| Boolean signature of tuple and corresponding atom |
Table 1: Frequently used notation. Symbols used only locally are defined where they appear.
4 Closed-Form Predicate-Level Shapley Attribution
We now derive exact closed-form predicate-level Shapley attribution for the aggregate classes above. Let the transition from to be defined by the delta . For count-based windows, is the singleton . For time-based windows, it is the set pair . Throughout this section we focus on a single predicate . The multi-predicate and compositional case is treated in Section 5.
4.1 Attribution Semantics
The word “delta” in our framing refers to the maintenance delta of the sliding window. This delta consists of tuples leaving the active state while others enter. The attribution semantics, by contrast, concern the current-window quantity . We do not introduce a separate Shapley game over the change . Defining such a “delta game” would require an additional modeling choice, because and have different player sets. A semantic theory of change attribution is left open (Section 9).
4.2 Decomposable Aggregates: SUM and COUNT
For SUM over a numeric attribute , the cooperative game is . The marginal contribution of tuple is always , independent of the predecessor coalition. Hence . Predicate attribution is simply
COUNT is analogous. Each tuple contributes one unit to the count game, so the attribution of a predicate is the number of active tuples satisfying it: . Both SUM and COUNT are maintained exactly by incrementing the predicate summary for every tuple in and decrementing it for every tuple in .
4.3 Average
AVG is non-additive but admits an exact Shapley expression in terms of simple sufficient statistics. Let denote the value of tuple , let , and let be the -th harmonic number. For the game
the Shapley value of tuple for (using the convention ) is
This harmonic-number form is a direct consequence of the permutation definition (Appendix A.1). It also serves as a baseline non-additive aggregate. The technical value here is that the tuple expression collapses to a predicate-level sufficient-statistics formula.
A PREPRINT
Relation to prior work. For a static database and a single-relation query with all facts endogenous, Eq. 9 was derived independently by Standke and Kimelfeld Standke and Kimelfeld [2025] as their Proposition 5.2. The cross-term sign in their printed statement is a typo. Their proof concludes with the expression equivalent to Eq. 9, and the printed sign would violate Efficiency. Proposition 1 should therefore be read as a restatement of that tuple-level result in the windowed setting. The contribution of this section is the predicate-level form (Eq. 10), its constant-size sufficient statistics, and its role as the base case of the maintenance framework of Sections 4.7–6.
Proposition 1 (Exact AVG Attribution). For , Eq. 9 is the exact Shapley value of . For , define the second term of Eq. 9 to be zero by the convention and the indeterminate 0/0 resolved as 0; then Eq. 9 yields , which agrees with Efficiency. Eq. 10 below is the exact predicate attribution obtained by summing these tuple values over . The formulas hold verbatim for both count-based windows (with constant ) and time-based windows (with , the active cardinality at evaluation time).
The proof follows directly from the permutation definition and is given in Appendix A.1.
For a predicate , let and . Summing Eq. 9 over all tuples satisfying the predicate gives
For a fixed-size count window, exact AVG attribution is therefore determined by four quantities: , , , and . For time-based windows, in Eq. 10 is replaced by (Section 6).
Example 2 (AVG Attribution). Consider and a predicate selecting the tuple with value 10. Here , , , , and . Eq. 10 gives
By the Efficiency axiom, the three tuple-level Shapley values sum to the window average, . Direct evaluation of Eq. 9 gives
which indeed sum to 16/3. The tuple with value 2 receives a negative attribution, -13/18, because its presence lowers the average relative to many coalitions from which it is absent. The tuple with value 4 lies closer to the mean and receives a smaller positive share. In the latency-monitoring reading of the example, the predicate still receives most of the attribution because the selected tuple is well above the global mean.
4.4 Interpretation: Share, Lift, and Scale
Eq. 10 can be rewritten exactly in a form that makes its meaning clear. Let and be the predicate and window means. Then
with . The Shapley value is therefore the group's share of the window mean plus times its lift, where is the Euler–Mascheroni constant. Three consequences follow.
First, for AVG the axioms do not produce a new signal. They fix a specific weighting of two elementary statistics. Each statistic is a poor explanation on its own. Over any partition of W the lifts sum to zero, so they describe deviation from the mean but not the value itself. The shares sum to but ignore whether a group raises or lowers the aggregate. Eq. 13 is the one combination of the two that satisfies the Shapley axioms. Section 8.7 measures how often this weighting changes the explanation compared to ranking by lift alone on real data.
Second, attributions depend on the window size. The weight grows like . Thus, if the composition of the window stays fixed (same , , ), the attribution of a high-lift group keeps growing with even though the aggregate does not change. By Efficiency, other groups shrink by the same amount. Attributions of windows with very different sizes are therefore not directly comparable. This matters for time-based windows, where varies (Section 6). The variance coefficients behave the same way (e.g., below). When comparing across windows, we recommend reporting the share and lift components next to , or comparing only windows of similar size. The case study quantifies the effect on real data (Section 8.6).
A PREPRINT
Third, the decomposition keeps large attributions honest. A headline value such as “ against an aggregate of ” (Section 8.6) splits into a moderate share and a large amplified lift. Reporting both parts avoids over-reading the amplified one.
4.5 Population and Sample Variance
Variance is more challenging than AVG because it depends on both first and second moments. Nevertheless, both population and sample variance admit exact sufficient-statistics representations once the game is defined on all coalitions. Let and .
4.5.1 Population Variance
Define
For a fixed player and a random predecessor set of size drawn uniformly without replacement from , the exact Shapley value reduces, after eliminating empty coalitions, to
The term contributes , because the variance of any singleton is zero and by definition. For , let , , and . Sampling without replacement from gives the moment expressions (derived in Appendix A.2):
These expressions are valid for . The case is handled separately in Appendix A.2 by enumerating the two possible orderings. Substituting these expectations into Eq. 15 and expanding step-by-step (Appendix A.2) yields the closed form
where
and denotes the right-hand side of Eq. 18.
The predicate-level form follows by summing Eq. 20 over all . With , , and , define
These three quantities arise from the predicate-level sums
respectively (Appendix A.2). Summing over and collecting terms (Appendix A.2) gives the exact predicate attribution for population variance:
A PREPRINT
The coefficients arise in Appendix A.2 as finite sums over the coalition size . Partial fractions and telescoping collapse every one of them to a closed form in the harmonic numbers and . Writing ,
So exact population-variance attribution needs only , , , , , and , plus arithmetic on and . Both harmonic numbers update incrementally and ). Thus no precomputation, no lookup table, and no work is needed at any cardinality. Time-based windows evaluate the same expressions at (Section 6). We verified Eqs. 26–27 against direct summation for all .
4.5.2 Sample Variance
Database systems commonly expose sample variance as VAR_SAMP. To make the Shapley game total on all coalitions, we set the singleton and empty values to zero:
This convention reflects the fact that no dispersion is observable from fewer than two tuples. It also avoids undefined game values in the Shapley sum.
The derivation follows the same steps as for population variance and is given in full in Appendix A.2. Only the case needs separate treatment, because a one-tuple predecessor set has game value zero. The result uses the same summaries , , and :
with coefficients that collapse even further than in the population case, to expressions in alone:
Thus sample variance inherits the same incremental coefficient maintenance.
Proposition 2 (Variance). Under the coalition-value definitions above, Eq. 25 and Eq. 29 give exact predicate-level Shapley attribution for population and sample variance. The formulas hold for count-based windows and for time-based windows after substituting .
The proof is given in Appendix A.2.
Empirical Validation. Section 8.2 verifies the closed forms (Eq. 9, Eq. 25, and Eq. 29) against exhaustive coalition enumeration over 10,010 random window configurations. The observed deviations are at double-precision floating-point level.
Sign interpretation. Variance attributions can be negative. A tuple or predicate close to the window mean tends to reduce dispersion relative to coalitions where it is absent. An extreme tuple or predicate tends to increase dispersion. Thus should be read as a stabilizing contribution to the variance aggregate, not as an error.
Example 3 (Variance Attribution). For the same window , the population variance is 104/9. The tuple-level population-variance Shapley values are (3.685, 0.185, 7.685), summing to 104/9. A predicate selecting value 10 receives positive variance attribution because it is the most dispersion-increasing tuple. Under sample variance with the singleton convention above, the Shapley values are (5.444, -1.556, 13.444), summing to 17.333 ≈ 52/3 = . The middle tuple receives negative attribution because it tends to pull coalitions toward the mean.
4.6 Linearity in Predicate Summaries
The structural property that enables predicate-level evaluation is summarized by the following lemma.
A PREPRINT
Lemma 1 (Affine Linearity). For SUM, COUNT, AVG, population variance, and sample variance, once N, , and are fixed, the predicate-level Shapley attribution is an affine function of the predicate summary triple .
Proof. For SUM, . For COUNT, . For AVG, Eq. 10 is affine in . For population and sample variance, the auxiliary quantities , , defined in Eq. 21–23 are themselves linear in once and are fixed; substituting into Eq. 25 or Eq. 29 preserves the affine property.
Given the tuple-level closed forms, Lemma 1 is immediate. Each is affine in with coefficients fixed by , and summation over preserves affinity. The technical content of this section therefore lies in the tuple-level derivations (Eq. 9 and Appendix A.2) and in the coefficient closed forms. The lemma itself is the simple but load-bearing observation that converts them into predicate-level answers without ever materializing tuple-level Shapley values. It also enables the additivity-across-subsets corollary used by pane-based maintenance frameworks (Section 4.8). Finally, it makes sampling-based approximation of for ad-hoc predicates well posed as estimation of an affine functional of maintained summaries.
4.7 Summary Maintenance Under Slides
The pane-level summaries for a predicate P are updated by the window delta. For a count-based slide and numeric attribute y:
For a multi-tuple time-based delta the same updates apply tuple-by-tuple over both sets, so the cost is per affected predicate. Global summaries (or ), , and are updated analogously.
Numerical stability. Long-running streams expose two floating-point issues. The first is cancellation in the variance formulas. Terms such as and the part of subtract nearly equal quantities. When the mean is much larger than the spread, most significant digits cancel and the result is dominated by rounding noise. This is the same failure mode as classical one-pass variance. A standard remedy is to center the values first, for a coarse location estimate . AVG attribution is recovered by adding back , and VAR attribution is invariant to the shift. The second issue is drift from repeated updates. Adding and subtracting millions of increments into the same summaries slowly loses low-order bits. Pane-based maintenance (Corollary 2) avoids most of this for free. Each pane keeps its own partial sums, and the window summary is rebuilt by adding a few pane totals rather than a long history of tiny updates. Compensated summation (which carries a small correction for bits lost at each add) can shrink whatever drift remains. Empirically, the hard case is the one that needs the shift. With , values , and slides of plain additive updates, unshifted variance attribution drifted to 23% relative error. The same run with stayed accurate to . On our month-long taxi case study, where the fare mean is comparable to its spread (Section 8.6), ordinary double-precision updates already kept the Efficiency identity within relative deviation. No special mitigation was required.
Combined with Lemma 1, the additive update rules above give the following corollary.
Corollary 1 (Per-Slide Cost). For SUM, COUNT, AVG, population variance, and sample variance, the predicate attribution can be evaluated in from the maintained summaries and the running harmonic numbers , (Eqs. 26–31). The per-slide summary update cost is per affected predicate for count-based windows and for time-based windows; no coefficient precomputation or caching is required.
Table 2 contrasts this with naive recomputation per window.
4.8 Additivity Across Disjoint Subsets
The summaries , , , , are all sums of per-tuple quantities. They are therefore additive over disjoint partitions of W. The following corollary captures this systems-relevant consequence.
A PREPRINT
Algorithm 1 Per-slide summary maintenance
1: Input: delta (for count-based slides, take and ), set of predicates whose summaries are maintained
2: Update global summaries (or ), , over all tuples in
3: for all tuples do
4: for all with do
5: Update using Eqs. 32–34
6: end for
7: end for
8: if (or ) changed since last evaluation then
9: Update running , (or , ) and evaluate the coefficient closed forms Eqs. 26–31
10: end if
11: On query, evaluate the requested closed-form attribution
| Aggregate Type | Recompute per Window | Closed-Form Maintenance |
|---|---|---|
| Count-based windows (constant ) | ||
| SUM/COUNT | exact update | |
| AVG | exact update | |
| VAR_POP/VAR_SAMP | exact update | |
| Time-based windows (variable , delta size ) | ||
| SUM/COUNT | exact update | |
| AVG | exact update | |
| VAR_POP/VAR_SAMP | exact update | |
Table 2: Exact maintenance cost per affected predicate. Constant-time entries assume (i) the predicate summaries are maintained and (ii) that tuple-membership tests are . All attribution coefficients are closed forms in the running harmonic numbers and (Eqs. 26–31). Coefficient access is therefore for both window types with no precomputation.
Corollary 2 (Pane Compatibility). Let be any partition of . Then
and analogously for . Consequently, the closed forms Eq. 10, Eq. 25, and Eq. 29 can be evaluated from per-pane summaries via additive merging, without merging local Shapley vectors or applying any global correction.
This makes the closed forms drop-in compatible with existing pane-based sliding-window aggregation frameworks Li et al. [2005], Tangwongsan et al. [2015]. The Shapley statistics are added to the standard set of per-pane aggregates, and the closed-form formula is evaluated once after pane merging.
Toward a characterization. All aggregates treated here share one property. Once a few window-level statistics are fixed, the expected Shapley marginal contribution of a tuple, or of a predicate coalition, depends only on its low-order moments. Section 7 makes this precise in both directions. It gives a sufficiency theorem covering every moment-polynomial game and an impossibility result showing that order statistics escape every fixed moment order.
5 Compositional Predicates via Atomic Refinement
When the system maintains predicates , two phenomena complicate the per-predicate maintenance described above. First, predicates may overlap: a tuple can satisfy several at once. The family then counts those tuples multiple times and does not sum to . Second, users frequently issue compositional queries (intersections, unions, complements, set-differences). For these queries, a single per-predicate summary is insufficient. We address both by maintaining sufficient statistics on the atomic refinement of the predicates.
5.1 Signatures and Atoms
Assign to each active tuple a Boolean signature
A PREPRINT
For each , define the atom . The family partitions . Let be the set of active signatures; . For each active signature , we maintain
Each atom is itself a coalition of active tuples. The closed forms Eq. 10, Eq. 25, and Eq. 29 therefore apply with replaced by . We denote the resulting atom attribution by .
5.2 Compositional Queries
For any Boolean combination of , let , where denotes the truth value of on a tuple with signature . The coalition is then a disjoint union of atoms, and the attribution decomposes additively:
Standard cases include
• Single predicate: .
• Intersection: .
• Complement: .
• Set-difference: .
• Union (inclusion-exclusion): , equivalently .
Answering a compositional query costs one closed-form evaluation per active atom satisfying , i.e., time. This cost is at most . In practice, it tracks the number of signatures that actually occur (Section 8.5). Alternatively, summaries of the participating atoms can be added first and the closed form evaluated once on the merged summary, by Corollary 2.
5.3 Restoration of Efficiency
Because partitions ,
For any partition of into Boolean combinations, the family of compositional attributions inherits the same partition property: . In particular, for any . Under overlap, is not a defect of the closed forms. It is a consequence of double-counting tuples that satisfy multiple predicates. The atom decomposition makes this phenomenon transparent and corrects it.
5.4 Maintenance Under Slides
Atom summaries are updated by the same delta rules as predicate summaries (Eqs. 32–34), applied to the atom selected by the tuple’s signature. For each , the engine evaluates the predicates, forms in time, and updates the summaries of the corresponding atom. New signatures are allocated lazily, and atoms whose count drops to zero are reclaimed. Per-tick maintenance cost is therefore across all atoms, and the state is . In practice, the predicate tests are compiled into a -bit mask per tuple. Signature evaluation then behaves like any vectorized filter operator rather than scattered branches.
5.5 State Growth in Practice
The upper bound on is rarely tight. Categorical attributes with mutually exclusive values (e.g., region='EU' vs. region='US') allow at most one of the corresponding bits to be set, so impossible signatures never appear. When predicates target disjoint dimensions (region, tier, service), grows with the product of the per-dimension cardinalities rather than with . Lazy allocation keeps only the signatures that actually occur. If the exact atom state still grows too large for memory, bounded-memory fallbacks apply. These include sketching or heavy-hitter tracking on signatures, partial materialization of atoms, or maintaining summaries only for explicitly enumerated intersections and answering the remaining compositional queries by inclusion-exclusion over those.
A PREPRINT
Example 4 (Compositional Predicate Attribution). For with and , the four signatures yield atoms (US, basic), (US, premium), (EU, basic), (EU, premium). From their summaries, “EU contribution” = ; “premium contribution” = ; “EU and premium” = ; “EU but not premium” = ; “EU or premium” = ; all answered exactly, with .
Proposition 3 (Compositional Predicate Attribution). Fix predicates and let be their atomic refinement on the active window. For any Boolean combination of the predicates, the predicate attribution is given exactly by Eq. 38, with each atom attribution computed from and the global summaries via Eq. 10, Eq. 25, or Eq. 29. Per-tick maintenance is , and the state is . The atom decomposition restores Shapley efficiency over the window: .
Proof. Atoms partition by construction, so is a disjoint union of atoms and . Each closed form was derived for an arbitrary subset of the window using only that subset's and the global summaries, and atoms are such subsets. The maintenance cost holds because each slide tuple needs predicate evaluations to form its signature and one atom-summary update. Efficiency follows from the Efficiency axiom applied to the partition .
6 Time-Based Windows
The closed forms Eq. 9, Eq. 10, Eq. 25, and Eq. 29 were derived without using the count-based fixed-cardinality assumption. They depend on the window only through its cardinality and the additive moments , (and the corresponding predicate or atom summaries). For time-based windows we therefore evaluate the same formulas with replaced by the current active cardinality . Two practical concerns arise that did not arise in the count-based case: (i) the per-tick delta is multi-tuple, and (ii) the -dependent coefficients must track . By the closed forms of Section 4.5, the latter reduces to maintaining the two running harmonic numbers.
6.1 Multi-Tuple Deltas
For a time-based slide , the per-tick maintenance cost is for each affected predicate, because all summary updates are additive (Algorithm 1). Under stationary arrivals with rate and tick interval , the expected delta size is in steady state, because the expected insert and expiration rates match. Thus, for a fixed emit interval, the expected update work is controlled by the number of arrivals and expirations in that interval rather than by the full window cardinality.
6.2 N-Dependent Coefficient Updates
The coefficients depend on the window only through and (Eqs. 26–31). Both update incrementally,
When jumps by more than one within a tick, extending the pair by steps costs . This cost is already dominated by the summary updates of the same tick. In practice, one keeps the prefix arrays and , extended lazily to the largest cardinality seen. Coefficient maintenance is therefore free in both asymptotic and practical terms, for any pattern of cardinality variation, with no precomputation and no assumptions on .
6.3 Edge Cases and Out-of-Order Arrivals
Edge cases. When the window is empty and all attributions are undefined; we emit a sentinel and continue. When , by Efficiency . The AVG closed form (Eq. 9) reduces correctly because , giving . The variance games are zero on singletons by definition. When shrinks across a tick because more tuples expire than arrive, the same updates apply with the corresponding .
Out-of-order arrivals. The analysis above assumes that within a tick all tuple insertions and expirations are determined unambiguously by event-time watermarks. Late arrivals, meaning tuples whose timestamp falls inside an already-emitted window, require either watermark-based reordering of the stream or retroactive correction of the affine
A PREPRINT
attribution form. We treat full out-of-order support as future work. In practice, watermark policies in Flink and similar engines bound the out-of-order delay so that retroactive corrections, if needed, are applied to a small constant number of recent emit ticks.
Retractions and corrections. Engines that model corrections with retractions (e.g., an explicit delete or negated update followed by an inserted replacement) pair cleanly with the maintenance story in this paper. Predicate and global summaries are affine in the per-tuple increments in Eqs. 32–34. Cancelling an erroneous tuple therefore reapplies the same updates with opposite sign, and inserting the corrected tuple applies them forward again.
Proposition 4 (Time-Based Maintenance). For a time-based window with stochastic cardinality and per-tick delta , the predicate attributions Eq. 10, Eq. 25, and Eq. 29 are exact at every emit tick once is substituted for . The per-tick cost is summary updates; coefficient maintenance is amortized via the harmonic-number closed forms Eqs. 26–31.
Proof. The closed forms use only the cardinality and the additive moments of the current window, so substituting preserves the derivations. The cost bounds follow from Algorithm 1 applied to multi-tuple deltas and from the incremental harmonic-number updates of Section 6.
7 The Boundary of Sufficient-Statistic Attribution
The five aggregates of Section 4 are instances of one structural phenomenon. This section describes its boundary from both sides. A sufficiency theorem identifies a broad class of games whose predicate attribution is affine in maintained power sums. An impossibility result shows that order statistics fall outside every fixed moment order.
7.1 Sufficiency: Moment-Polynomial Games
For a coalition and , let denote the -th power sum, with . Note and in the earlier notation.
Definition 1 (Moment-polynomial game). Fix integers and . A window game is a moment-polynomial game of order if there exist coefficient functions , indexed by multi-indices with , such that for every ,
All five aggregates of Section 4 are moment-polynomial: SUM is (order ); COUNT is (order ); AVG is with for (order ); population variance is (order ); sample variance is analogous with factors. The class also contains, e.g., the q-th central-moment numerator for any fixed , and sums of fixed polynomials of the values.
Theorem 1 (Sufficiency). Let be a moment-polynomial game of order and let . Then:
(i) There exist coefficients , each a polynomial in the global power sums whose coefficients depend only on (and on the ), such that for every .
(ii) For every predicate , , where and ; that is, is affine in the predicate power-sum vector, generalizing Lemma 1.
(iii) All required summaries are additive over disjoint subsets. Consequently, for fixed , Corollaries 1 and 2 extend verbatim with summaries per predicate or atom: per-slide maintenance is per affected predicate and queries evaluate in given coefficients that depend only on N and the global power sums.
The proof (Appendix A.3) rests on two classical facts. First, over a uniformly random -subset drawn without replacement, the probability that fixed distinct tuples are jointly included is the falling-factorial ratio . Second, products of power sums expand into sums over distinct-index tuples that are again polynomials in power sums. The degree bound is not tight for specific games. For the variance games, cancellations reduce the required predicate summaries to as in Section 4.5.
A PREPRINT
Remark 1 (Multivariate extension). If tuples carry a value vector and Eq. 41 is stated over mixed power sums , the proof carries over unchanged. This covers, e.g., the covariance game . Its predicate attribution is therefore affine in the predicate summaries .
7.2 Impossibility: Order Statistics
The MAX game is for and .
Proposition 5 (No finite-moment representation for order statistics). For every there exist windows , with and for all , but . Consequently, no attribution rule computed from and per-predicate power sums up to order can satisfy the Efficiency axiom for the MAX game: the totals it must reproduce already differ on inputs it cannot distinguish. The same holds for MIN and for any fixed order statistic, hence for quantiles and the median.
For an explicit witness is and : both have , , and , yet . The general construction (Appendix A.3) perturbs a window with distinct values along the kernel of the moment map, which has dimension whenever . Some moment-preserving perturbation therefore moves any chosen order statistic.
Proposition 5 explains why the operators excluded in Section 4 are excluded. The problem is not a missing derivation. Bounded-order moments simply do not carry enough information. Between the two regimes lies an open strip. Games that depend on moments, but not polynomially (e.g., standardized skewness, which divides a moment-polynomial numerator by a fractional power of the variance), can use the same summaries but have, to our knowledge, no exact Shapley closed form. Mapping this strip precisely remains future work.
8 Experimental Evaluation
We evaluate five questions. RQ1: Do the closed forms match exact Shapley values computed by exhaustive coalition enumeration? RQ2: How does per-slide attribution cost scale with window size N, compared to per-window recomputation, permutation sampling, and enumeration? RQ3: What accuracy does the sampling alternative buy at what cost, for ad-hoc predicates? RQ4: How do maintenance cost and state behave under many predicates and on real data at full stream rate? RQ5: Does the axiomatic weighting change the resulting explanations, relative to the naive lift heuristic and to the predicate-as-player meta-game semantics, on real data?
8.1 Setup
All experiments run single-threaded on an Apple M2 Pro (16 GB RAM) using a Python 3.12/NumPy 2.4 prototype. No compiled kernels are used, so absolute latencies are conservative. The meaningful quantity is the comparison across methods, which share data structures and predicate-evaluation code. The implementation and all experiment scripts are included with the submission. We compare four methods that answer the same query, namely the predicate attribution of a fixed predicate (selectivity 0.3) for AVG and VAR_POP at every slide of a count-based window:
• Incremental (ours): incremental summary maintenance (Algorithm 1) plus closed-form evaluation; coefficients evaluated in from the running harmonic numbers and (constant for fixed count-window size ).
• Per-window scan: closed-form evaluation with summaries recomputed from scratch by a vectorized scan per window; the same harmonic-number coefficients. This isolates the value of incremental maintenance given our formulas.
• MC (M): stateless permutation sampling Castro et al. [2009] with M permutations per window; each permutation is walked once with incrementally maintained ( ), i.e., per window, which is the strongest sampling variant for these games. Figure 2 reports the case M = 100.
• Enumeration : exact enumeration of all predecessor coalitions per tuple via Eq. 4.
MC and Enumeration are generic methods that only see the game through its value function and do not exploit aggregate structure. We include them to show what the stateless alternatives cost, not as competitive baselines. The like-for-like comparison that isolates our contribution is Incremental versus Per-window scan: both use the same closed forms and differ only in how summaries are obtained. Explanation systems such as Scorpion Wu and Madden [2013],
A PREPRINT
| Aggregate | Distribution | Max Abs Dev | Max Rel Dev |
|---|---|---|---|
| AVG | |||
| AVG | Uniform | ||
| VAR_POP | |||
| VAR_POP | Uniform | ||
| VAR_SAMP | |||
| VAR_SAMP | Uniform |
Table 3: RQ1: maximum deviation between the closed forms and exhaustive coalition enumeration over 10,010 random windows (; tuple- and predicate-level values both checked). All deviations are attributable to double-precision floating-point rounding in either method.
DIFF Abuzaid et al. [2021], and TSExplain Chen and Huang [2023] answer related but non-axiomatic explanation queries. RQ5 therefore compares against the semantic alternatives (the lift heuristic and the meta-game), which target the same quantity as we do. System-level comparisons on shared workloads are left to future work.
8.2 RQ1: Exactness
We compare closed-form outputs against Enumeration on a grid spanning , predicate selectivities , and value distributions and Uniform. This yields 10,010 random windows and 30,030 aggregate comparisons, checking every tuple-level value and the predicate-level attribution. We cap at 12 because enumeration costs . The closed forms are exact for all by Propositions 1 and 2, so RQ1 validates the implementation. Table 3 reports the maxima. All deviations are at double-precision rounding level. The larger absolute deviations for the variance games under Uniform simply reflect the -scale second moments involved. Relative deviations stay below . The atomic-refinement Efficiency identity (Section 5), checked with random overlapping predicates on every window with , holds to a maximum normalized deviation of .
8.3 RQ2: Attribution Latency vs. Window Size
Figure 2 reports median per-slide latency as grows from to (stream of standard-normal values; 2,000 slides per configuration for Incremental and Per-window scan). Incremental is flat at per slide across four orders of magnitude of , matching Corollary 1. Per-window scan grows linearly from to ms. At , Incremental is already faster than recomputing summaries per window with the same closed forms. The stateless baselines are orders of magnitude further away. MC () costs ms per window at and ms at ( Incremental). Enumeration costs ms at , s at , and s at . Neither is viable at streaming rates even for small windows.
8.4 RQ3: The Cost of Approximation
Because ad-hoc predicates unknown at maintenance time require either a scan or sampling (Section 9), we quantify the sampling route. Figure 3 shows the accuracy–latency tradeoff of MC as varies, at with values from , so that AVG () and VAR_POP () both have scale. Errors are means over 20 runs, relative to the aggregate value. The error decays as the expected . Reaching relative error requires permutations and s per window, roughly times the cost at which Incremental delivers the exact answer for maintained predicates. Sampling is thus a fallback for ad-hoc queries, not a competitor for registered ones.
8.5 RQ4a: Scaling in the Number of Predicates
Table 4 scales the atomic-refinement state (Section 5) to registered predicates over categorical dimensions of cardinality slides). Per-slide maintenance grows only from to . Each slide touches exactly one atom per boundary tuple regardless of (the signature evaluation is a bit-packed vectorized step). The active-atom count stays far below and saturates at its other bound , as predicted in Section 5. The cost of decomposing the full window into all atom attributions scales with , not with . The row also marks the honest boundary of the approach. With , the atom state amounts to one summary triple per active tuple, so the “no tuple materialization” advantage has been spent on predicate coverage. The framework targets moderate
A PREPRINT

Figure 2: RQ2: median per-slide latency for answering the same predicate-attribution query (AVG and VAR_POP) as a function of window size (log–log). The closed-form incremental method is constant at ; per-window scanning grows linearly; sampling and enumeration are orders of magnitude slower and infeasible at streaming rates.

Figure 3: RQ3: accuracy–latency tradeoff of permutation sampling for predicate attribution (, values , mean of 20 runs). Errors decay as ; the exact incremental closed form answers in .
A PREPRINT
| K | slide | all-atom query | ||
|---|---|---|---|---|
| 1 | 2 | 2 | 0.88 | 2.5 |
| 4 | 5 | 16 | 0.88 | 2.2 |
| 8 | 8 | 256 | 0.88 | 3.2 |
| 16 | 64 | 0.96 | 25.9 | |
| 32 | 3,740 | 1.00 | 1,237 | |
| 64 | 9,994 | 1.35 | 3,323 |
Table 4: RQ4a: atomic-refinement scaling with the number of registered predicates (). Maintenance stays near-constant; state and full-decomposition query cost track the active signatures , not the worst case.
numbers of registered dimensions. Predicate search over unregistered candidates belongs to the ad-hoc regime of RQ3 (see also Section 9).
8.6 RQ4b: Case Study on NYC Taxi Data
We stream all 2,926,220 yellow-taxi trips of January 2024 from the NYC TLC trip records New York City Taxi and Limousine Commission [2024] (fares filtered to (0, 500] dollars), through a time-based window of 1 hour emitting every 5 minutes, with registered predicates: airport (pickup at JFK, LaGuardia, or Newark), manhattan (pickup in Manhattan), and longtrip (distance > 10 miles, overlapping both).
Throughput and state. The full month (8,928 emit ticks; between 151 and 9,199, mean 3,931) is processed end-to-end in 3.4 s single-threaded. Summary updates take 3.3 s, i.e., million updates per second. Each emit tick then needs for the full atom decomposition under both AVG and VAR_POP, of which is coefficient maintenance via the harmonic-number closed forms (Eqs. 26–27). There is no coefficient precomputation, no cache, and no step anywhere in the loop. Of the possible signatures, at most 6 atoms are ever active. The two signatures that would require an airport pickup inside Manhattan are impossible, exactly the state collapse anticipated in Section 5. Across all 8,928 real windows, the Efficiency identity holds to a relative deviation of at most despite a month of purely additive updates.
Explaining a fare spike. Figure 4 shows 24 hours starting 2024-01-09 18:00, with the active cardinality shown below so that scale effects (Section 4.4) are visible next to the attributions. Between 02:00 and 06:00 the windowed average fare rises from a daytime level of to a peak ofN_{t} = 289\Phi_{airport}^{AVG} = +35.73. Nighttime Manhattan traffic is cheap and pulls the average down. The spike exists only because expensive airport trips dominate the thin overnight window. The share-lift decomposition (Eq. 13) keeps this headline honest. With60.1 and, the +26.6 share and a N_{t}\approx 7,000\approx 300w(N_{t})\Phi\ln N\Phi_{airport \land longtrip} =\Phi_{airport \land -longtrip} =^{2}^{2}^{2}$. All quantities are exact Shapley attributions computed from the maintained summaries at emit time, with no access to individual tuples.
8.7 RQ5: Does the Axiomatic Weighting Matter?
Section 4.4 shows that AVG attribution combines share and lift with a weight. Does the Shapley value ever disagree with simply ranking groups by lift? We compare the two on all 8,928 real windows, for the three pickup groups (Figure 5, top). They are highly correlated (Pearson ) and agree on the complete ranking in of windows, so the axioms mostly confirm the practitioner's heuristic, as one should hope. The disagreements, however, are not noise. In 522 windows () the top-ranked group differs, mostly in mid-size windows (median among disagreements). The cause is exactly the share term of Eq. 13. For example, at 04:50 on 2024-01-02 (, \nu = \34.73\ell = +$1.48\Phi = $21.5234.73 total$). Here 186 of the 239 trips are Manhattan pickups, and they carry most of the aggregate's value despite below-average fares. The two answers address different questions. Lift asks "who pushed the average above baseline?"; Shapley asks "how does the current value distribute over groups?". Only the latter satisfies Efficiency: over any partition the lifts sum to zero, so the heuristic cannot account for the value
A PREPRINT


Figure 4: RQ4b: 24 hours of NYC yellow-taxi fares (1 h window, 5 min emit). Top: windowed AVG fare and its exact Shapley decomposition into airport, Manhattan, and other pickups; the 02:00–06:00 spike (shaded) is driven by airport traffic, whose attribution exceeds the aggregate while Manhattan’s is negative. Middle: the same decomposition for the VAR_POP game; Manhattan trips stabilize the nighttime variance while dispersed outer-borough trips drive it. Bottom: active cardinality (log scale), overlaid because attributions carry a -weighted lift component (Section 4.4).
itself. Figure 5 (bottom) completes the scale story of Section 4.4. At the fixed peak-window composition, grows from 58.8 to 88.1 as N ranges over the observed cardinalities, while the share component stays constant. This is why Figure 4 shows alongside the attribution curves.
Sum-of-members vs. predicate-as-player. We also computed, at every emit tick, the meta-game semantics discussed in Section 9: the three groups act as three players and is evaluated on unions of their coalitions (exact via 3! permutations over merged summaries; 3.4 s per tick). The two semantics correlate ( ) and agree on the top contributor in 93.2% of windows, but their magnitudes differ substantially. The mean absolute deviation is 8.04 per group (39% of the aggregate value on average) and the maximum is 62.26. At the spike peak, the meta-game assigns airport +25.97 instead of +63.44 and Manhattan -6.34 instead of -35.73. With only three coarse players, each group's marginal contribution is evaluated against far larger coalitions, which compresses the attributions. Which semantics is preferable depends on the application. The sum-of-members semantics refines consistently under drill-down (Eq. 38) and is the one with constant-time maintenance. The meta-game depends on the chosen predicate granularity and costs per query for groups, exponential in general. Either way, the measured gap shows the choice is consequential, not cosmetic.
A PREPRINT

window size N (fixed peak-window composition)
Figure 5: RQ5. Top: exact Shapley attribution vs. naive lift for the three pickup groups over all 8,928 real windows (2,500 points sampled per group). The two agree broadly (r = 0.962) but name a different top contributor in 5.8% of windows. Bottom: at fixed (peak-window) composition as a function of N: the share component is constant while the harmonically weighted lift grows like across the observed cardinality range (shaded).
9 Limitations and Future Work
The closed forms above give exact sufficient-statistics attribution for the aggregate games treated in this paper. Keeping the scope this narrow avoids unproved approximation assumptions. It also makes the limits of the results explicit.
-
Aggregate scope. Our exact-maintenance results cover SUM, COUNT, AVG, both variance games, and, by Theorem 1, any moment-polynomial aggregate (including covariance and fixed central moments; Remark 1). They do not cover quantiles, MIN/MAX (impossible by Proposition 5), joins, or arbitrary user-defined functions. The territory between the two regimes is not fully mapped. Games that depend on moments non-polynomially (e.g., standardized skewness), ratio-of-moment statistics, DISTINCT-style aggregates, regression aggregates, and model-inference queries need new aggregate-specific arguments.
-
Attribution semantics. Two semantic questions remain open. First, the closed forms attribute the current aggregate value. Attributing the change axiomatically would need a Shapley game over a common player set spanning both windows, which is an extra modeling choice. Second, an alternative to our sum-of-members semantics treats the predicates themselves as players in a meta-game over unions of their coalitions. Section 8.7 measures the gap between the two on real data (high rank agreement, but magnitudes differing by 39% of the aggregate on average). The
A PREPRINT
meta-game is computable from the same atom summaries for small K but exponential in general. When it is the better choice, and how to maintain it at scale, is left to future work.
-
Registered and ad-hoc predicates. The constant-time guarantees assume that predicates (or dimensions) of interest are registered in advance so that their summaries are maintained as the stream evolves. Predicates that first appear at query time need scans, indexes, or sampling instead. Lemma 1 makes such approaches well-defined in principle, and Section 8.4 shows how expensive the sampling route is. With very many registered predicates the atom state can also approach one summary per active tuple (Section 8.5). A full systems treatment of ad-hoc predicates, indexing, and predicate promotion is left to future work.
-
Temporal structure. The time-based analysis assumes that watermarks fix all insertions and expirations within each emit tick. Late arrivals need reordering or retroactive correction, which we do not formalize. More broadly, the window is treated as a bag of records. The temporal order of tuples plays no role beyond entry and exit, and extending the axioms to time-ordered Shapley values is a natural next step. Finally, Shapley attribution is not causal explanation. It divides the realized aggregate among tuples or atoms, but it does not identify a causal graph. If EU traffic drives premium-tier latency through a hidden dependency, both atoms can receive large variance attribution without the framework saying which caused which.
10 Conclusion
Explaining a streaming aggregate should not cost more than computing it. This paper showed that for SUM, COUNT, AVG, and both variance games, exact predicate-level Shapley attribution collapses to an affine function of three additively maintained summaries per predicate. Every attribution coefficient is a closed form in two running harmonic numbers. Arbitrary Boolean combinations of overlapping predicates are answered exactly from the atomic refinement, which also restores Efficiency. The phenomenon has a boundary on both sides: every moment-polynomial game admits such a closed form, while order statistics provably admit none of any fixed moment order. The share–lift decomposition makes the resulting numbers easy to interpret, including their logarithmic dependence on window size. Empirically, the attribution is exact to floating-point precision and costs a constant per slide, independent of window size, in an unoptimized single-threaded prototype. This is faster than per-window recomputation with the same formulas at , with stateless sampling and enumeration further orders of magnitude away. On real data it agrees with the naive lift heuristic on most windows but overturns its top-ranked explanation on 5.8% of them. It also turns a real fare-spike anomaly on 2.9 million taxi trips into a quantitative, axiomatically grounded explanation at stream rate. Because the maintained state consists of ordinary associative aggregates, the method plugs into existing window-aggregation infrastructure. We believe it provides a practical foundation for always-on, explanation-aware stream processing.
A Proof Details
A.1 AVG
In the permutation view of the Shapley value, each position of is equally likely. If appears first, the marginal contribution is . If appears after predecessors, the predecessor set is a uniformly random size- subset of , and since ,
Averaging over and using gives Eq. 9. Summing over yields Eq. 10. The derivation uses only the cardinality and the additive sum of the current window, so it transfers verbatim to time-based windows once is replaced by . (This computation also appears, for static single-relation queries, in the proof of Proposition 5.2 of Standke and Kimelfeld [2025].)
A.2 Variance
Moment expressions. For a fixed player and a uniformly random size- subset drawn without replacement, each remaining tuple is included with probability . Any pair with is jointly included with probability , where . Therefore,
A PREPRINT
For the second moment of ,
(44)
so
(45)
where the last step uses over .
case. When , only the orderings and are possible, with the unique other tuple. Both predecessor sets give zero population variance (one is empty, the other is a singleton). The marginal contribution of averaged over the two positions is therefore . This matches Eq. 19 evaluated at using the convention that the term vanishes when .
Population variance Shapley value. We expand the marginal contribution step-by-step:
Taking the expectation over random predecessor coalitions of size , we substitute , , and , and simplify using . Substituting these into the four terms above yields the expected marginal contribution :
(47)
This matches Eq. 20. Summing over and over uses
(48)
where , , and are defined in Eq. 21–Eq. 23. Substituting gives the predicate-level sum form
A PREPRINT
with
(50)
Collecting the -dependent factors yields Eq. 25 with
(51)
Partial fractions reduce each sum to harmonic numbers. For example, , so telescopes to . The same treatment of the remaining sums gives the closed forms Eq. 26–Eq. 27.
Sample variance. For sample variance and ,
(52)
Taking expectations and again grouping terms by their dependence on gives, for ,
The case is handled separately because by definition for . The expected marginal contribution of adding to a one-tuple predecessor set is
The exact tuple-level Shapley value is
Summing over tuple positions and over using the same predicate-summary identities as above gives Eq. 29 with
(56)
The identity cancels the leading term of outright. The remaining sums telescope to the closed forms Eq. 30–Eq. 31.
A PREPRINT
sanity check. With , only contributes. For with , and , giving , so . By symmetry, . The two values sum to , verifying Efficiency.
A.3 Sufficiency and Impossibility
Proof of Theorem 1. Fix and let , . In the permutation view, conditioned on arriving after predecessors, the predecessor set is a uniformly random -subset of , and
By Eq. 41 and , both and are polynomials in the variables and , of total weighted degree at most (each factor or carrying weight , each monomial in Eq. 41 having weight at most ), with coefficients or depending only on . It therefore suffices to show that for any exponents ,
is a polynomial in the power sums with coefficients depending only on and . Expand the product into a sum over tuples of indices , , of monomials with , each multiplied by . Group the tuples by the set partition induced by equality of indices. A tuple whose distinct indices are (with merged exponents , ) contributes . Under sampling without replacement,
(59)
a constant depending only on . The remaining sum over distinct is, by inclusion-exclusion over the partition lattice (the standard expansion of augmented monomial symmetric functions in terms of power sums), a polynomial with integer coefficients in for . Finally, , so every term is a polynomial in (degree ) and the global power sums . Averaging over with weights and coefficients preserves this structure, proving (i). Part (ii) follows by summing (i) over , since the coefficients do not depend on . Part (iii) is immediate because power sums are sums of per-tuple quantities.
Proof of Proposition 5. Fix and let . Consider the moment map , with . Its Jacobian has rows . At any point with pairwise distinct coordinates it has full rank (a generalized Vandermonde submatrix on any distinct coordinates is nonsingular), so has dimension . Fix a target index (for MAX, the argmax; for a general order statistic, the coordinate holding that rank). The subspace has dimension at least 1 less, i.e., at most , so some has . Since is a submersion at , the fiber is locally a smooth 2-manifold containing a curve with and . For sufficiently small , the coordinates of remain pairwise distinct and retain their ordering. The value of the chosen order statistic therefore equals , which is non-constant in because . Taking and for small yields two windows with identical and moments but different order-statistic values. If an attribution rule for the corresponding game were computed from and predicate moments alone, its total over any partition would agree on and (take the trivial single-predicate partition, whose predicate moments coincide with the global ones). This contradicts Efficiency, which forces the totals . Windows of any larger size follow by padding both windows with the same values.
References
Christoph Standke and Benny Kimelfeld. Tractability frontiers of the Shapley value for aggregate conjunctive queries. Proceedings of the ACM on Management of Data, 3, 2025. doi:10.1145/3767720.
A PREPRINT
Jin Li, David Maier, Kristin Tufte, Vassilis Papadimos, and Peter A. Tucker. No pane, no gain: Efficient evaluation of sliding-window aggregates over data streams. ACM SIGMOD Record, 34(1):39–44, 2005.
Kanat Tangwongsan, Martin Hirzel, Scott Schneider, and Kun-Lung Wu. General incremental sliding-window aggregation. Proceedings of the VLDB Endowment, 8(7):702–713, 2015.
Jonas Traub, Philipp Marian Grulich, Alejandro Rodríguez Cuéllar, Sebastian Breß, Asterios Katsifodimos, Tilmann Rabl, and Volker Markl. Scotty: General and efficient open-source window aggregation for stream processing systems. ACM Transactions on Database Systems, 46(1):1:1–1:46, 2021. doi:10.1145/3433675.
Javier Castro, Daniel Gómez, and Juan Tejada. Polynomial calculation of the shapley value based on sampling. Computers & Operations Research, 36(5):1726–1730, 2009.
New York City Taxi and Limousine Commission. TLC trip record data: Yellow taxi trip records, january 2024. https://www.nyc.gov/site/tlc/about/tlc-trip-record-data.page, 2024. Accessed July 2026.
Lloyd S Shapley. A value for n-person games. In Contributions to the Theory of Games (AM-28), volume 2, pages 307–317. Princeton University Press, 1953.
Scott M Lundberg and Su-In Lee. A unified approach to interpreting model predictions. In Proceedings of the 31st International Conference on Neural Information Processing Systems, pages 4768–4777, 2017.
Art B. Owen. Sobol' indices and shapley value. SIAM/ASA Journal on Uncertainty Quantification, 2(1):245–251, 2014.
Eunhye Song, Barry L. Nelson, and Jeremy Staum. Shapley effects for global sensitivity analysis: Theory and computation. SIAM/ASA Journal on Uncertainty Quantification, 4(1):1060–1083, 2016.
Changhun Kim, Yechan Mun, Sangchul Hahn, and Eunho Yang. Deltashap: Explaining prediction evolutions in online patient monitoring with shapley values. arXiv preprint arXiv:2507.02342, 2025. ICML Workshop on Actionable Interpretability.
Maximilian Muschalik, Fabian Fumagalli, Barbara Hammer, and Eyke Hüllermeier. isage: An incremental version of sage for online explanation on data streams. In European Conference on Machine Learning and Principles and Practice of Knowledge Discovery in Databases (ECML PKDD), pages 395–410. Springer, 2023.
Fabian Fumagalli, Maximilian Muschalik, Eyke Hüllermeier, and Barbara Hammer. Incremental permutation feature importance (ipfi): Towards online explanations on data streams. Machine Learning, 112(12):4863–4892, 2023.
Amirata Ghorbani and James Zou. Data shapley: Equitable valuation of data for machine learning. In International Conference on Machine Learning (ICML), pages 2242–2251. PMLR, 2019.
Ruoxi Jia, David Dao, Boxin Wang, Frances Ann Hubis, Nick Hynes, Nezihe Merve Gürel, Bo Li, Ce Zhang, Dawn Song, and Costas J Spanos. Efficient task-specific data valuation for nearest neighbor algorithms. Proceedings of the VLDB Endowment, 12(11):1610–1623, 2019.
Tom Yan and Ce Zhang. Monitoring data quality for machine learning with shapley value. In Proceedings of the 2021 International Conference on Management of Data (SIGMOD), 2021.
Eugene Wu and Samuel Madden. Scorpion: Explaining away outliers in aggregate queries. Proceedings of the VLDB Endowment, 6(8):553–564, 2013.
Peter Bailis, Edward Gan, Samuel Madden, Deepak Narayanan, Kexin Rong, and Sahaana Suri. Macrobase: Prioritizing attention in fast data. In Proceedings of the 2017 ACM International Conference on Management of Data, pages 541–556, 2017.
Firas Abuzaid, Peter Kraft, Sahaana Suri, Edward Gan, Eric Xu, Atul Shenoy, Asvin Ananthanarayan, John Sheu, Erik Meijer, Xi Wu, Jeff Naughton, Peter Bailis, and Matei Zaharia. Diff: A relational interface for large-scale data explanation. The VLDB Journal, 30:45–70, 2021.
Yiru Chen and Silu Huang. TSExplain: Explaining aggregated time series by surfacing evolving contributors. In Proceedings of the 39th IEEE International Conference on Data Engineering (ICDE), pages 708–720. IEEE, 2023. doi:10.1109/ICDE55515.2023.00060.
Dimitris Palyvos-Giannas, Katerina Tzompanaki, Marina Papatriantaflou, and Vincenzo Gulisano. Erebus: Explaining the outputs of data streaming queries. Proceedings of the VLDB Endowment, 16(2):230–242, 2022. doi:10.14778/3565816.3565825.
Boris Glavic, Kyumars Sheykh Esmaili, Peter M. Fischer, and Nesime Tatbul. Ariadne: Managing fine-grained provenance on data streams. In Proceedings of the 7th ACM International Conference on Distributed Event-Based Systems (DEBS), pages 291–320, Arlington, TX, USA, 2013. ACM. doi:10.1145/2488222.2488256.
A PREPRINT
Sudeepa Roy and Dan Suciu. A formal approach to finding explanations for database queries. In Proceedings of the 2014 ACM SIGMOD International Conference on Management of Data, pages 1579–1590, New York, NY, USA, 2014. Association for Computing Machinery.
Alexandra Meliou, Wolfgang Gatterbauer, Katherine F Moore, and Dan Suciu. The complexity of causality and responsibility for query answers and non-answers. Proceedings of the VLDB Endowment, 4(1):34–45, 2010.
Ester Livshits, Leopoldo Bertossi, Benny Kimelfeld, and Moshe Sebag. The Shapley value of tuples in query answering. In 23rd International Conference on Database Theory (ICDT 2020), volume 155 of Leibniz International Proceedings in Informatics (LIPIcs), pages 20:1–20:19. Schloss Dagstuhl–Leibniz-Zentrum für Informatik, 2020. doi:10.4230/LIPIcs.ICDT.2020.20.
Daniel Deutch, N. Frost, Benny Kimelfeld, and Mikael Monet. Computing the shapley value of facts in query answering. In Proceedings of the 2022 International Conference on Management of Data, pages 1570–1583, New York, NY, USA, 2022. Association for Computing Machinery.
Ahmet Kara, Dan Olteanu, and Dan Suciu. From Shapley value to model counting and back. Proceedings of the ACM on Management of Data, 2(2):79:1–79:23, 2024.
Leopoldo Bertossi, Benny Kimelfeld, Ester Livshits, and Mikael Monet. The shapley value in database management. SIGMOD Record, 52(2):7–18, 2023.
Meghyn Bienvenu, Diego Figueira, and Pierre Lafourcade. Shapley revisited: Tractable responsibility measures for query answers. arXiv preprint arXiv:2503.22358, 2025.
Omer Abramovich, Daniel Deutch, Nave Frost, Ahmet Kara, and Dan Olteanu. Advancing fact attribution for query answering: Aggregate queries and novel algorithms. Proceedings of the VLDB Endowment, 18, 2025. doi:10.14778/3749646.3749670.
Pouya Khani and Ira Assent. Causal banzhaf value for aggregate query explanations. In DOLAP 27th International Workshop on Design, Optimization, Languages and Analytical Processing of Big Data, pages 54–58, 2025.
Pouya Khani, Yuchen Zhang, and Ira Assent. Causally-constrained power indices: Predicate attribution for aggregate query explanations. In Big Data Analytics and Knowledge Discovery, pages 302–317, Cham, 2027. Springer Nature Switzerland. doi:10.1007/978-3-032-34896-8_24.
Paris Carbone, Asterios Katsifodimos, Stephans Ewen, Volker Markl, Seif Haridi, and Kostas Tzoumas. Apache flink: Stream and batch processing in a single engine. Bulletin of the IEEE Computer Society Technical Committee on Data Engineering, 36(4), 2015.
Anatoli U. Shein and Panos K. Chrysanthis. Multi-query optimization of incrementally evaluated sliding-window aggregations. IEEE Transactions on Knowledge and Data Engineering, 34(8):3899–3911, 2022. doi:10.1109/TKDE.2020.3029770.
Shanzhong Zhu and Chinya V. Ravishankar. A scalable approach to approximating aggregate queries over intermittent streams. In Proceedings of the 16th International Conference on Scientific and Statistical Database Management (SSDBM), pages 85–94, Santorini, Greece, 2004. IEEE Computer Society. doi:10.1109/SSDBM.2004.1311196.