An open source alternative to Tableau. Embeddable visual analytic
TypeScript bidatadata-analysisdata-miningdata-visualizationedak6skanarieslow-codepivot-tablereacttableautableau-alternativetypescriptvegavega-litevisualization
feat(explain): statistical kernel, engine, and A/D-class explainers (K-1..K-5)
Elwynn Chen3b85a9cf27e4
diff --git a/docs/explain-data-redesign.md b/docs/explain-data-redesign.mdnew file mode 100644index 00000000..02f4b34d--- /dev/null+++ b/docs/explain-data-redesign.md@@ -0,0 +1,351 @@+# Explain Data 重构方案++> 状态:设计提案(待评审)+> 日期:2026-07-07+> 关联:[dsl-design-review.md](./dsl-design-review.md)、[internal_docs/explain-data-explained/README.md](../internal_docs/explain-data-explained/README.md)(Tableau Explain Data 原理参考)++## 1. 背景与现状复盘++Explain Data 模块允许用户点击图表中的一个标记(mark),由系统给出该标记"为什么值得注意"的解释。当前实现的调用链:++- 触发:右键标记 → 嵌入菜单 `data_interpretation`(`components/embedMenu.tsx`)→ 选中标记的维度值存入 `selectedMarkObject`(`renderer/index.tsx`)→ 打开 `components/explainData/index.tsx` 对话框。+- 算法:`lib/insights/explainBySelection.ts`。对每个「未可视化维度 × 视图度量」组合跑两次聚合查询(总体分布、选中标记分布),归一化后用 Jensen–Shannon 散度变体打分(`utils/normalization.ts#compareDistributionJS`),按分数降序展示。++按 Tableau 的四分类,现状只覆盖了 **unique about this mark**(标记的独特之处)一类,且存在以下问题:++### 1.1 数学层++| # | 问题 | 位置 | 后果 |+|---|------|------|------|+| 1 | JS 散度跳过任一侧占比为 0 的类别(`if (p === 0 \|\| q === 0) continue`),但 JS 散度对零概率有良好定义 | `normalization.ts#compareDistributionJS` | "只集中在某类别 / 完全缺失某类别"这种最强信号被丢弃 |+| 2 | 最终分数乘以类别覆盖率权重(匹配类别数 / 总体类别数),分布越集中权重越低 | 同上 | 系统性压低最独特的候选,**排序方向与洞察价值相反** |+| 3 | 归一化对度量取绝对值求和 | `normalization.ts#normalizeWithParent` | 可正可负的度量(利润等)份额概念不成立,结果无意义 |+| 4 | 比较基线是"含自身的总体"(child vs parent),而非"其余标记"(siblings) | `explainBySelection.ts` | 大占比标记与包含自己的总体比,差异被自我稀释 |++### 1.2 统计层++- 无最小样本量要求:只有两三行数据的标记分布必然极端,散度必然高,**排最前的往往最不可信**。+- 无基数校正:高基数维度(城市 200 值)与低基数维度(性别 2 值)的分数不可比却混排。+- 数值维度等宽 10 箱,一个极端值即可把其余 9 箱压空,分箱本身制造假差异。+- 无显著性判断、无分数阈值:**永远输出一个排好序的列表**,不管有没有真实信号。++### 1.3 工程层++- 查询完全串行,共 `2 × 候选维度数 × 度量数` 次往返;总体分布查询按度量重复执行。+- `explainValue.ts`、`explainByChildren.ts` 为死代码(无任何引用);前者还有 key 错位 bug(聚合结果 key 为 `getMeaAggKey` 形式,读取时却用裸 `fid`,恒为 `undefined`)。++### 1.4 呈现层++- 返回值命名为 `normalizedData` 实际是未归一化的原始聚合值,图表靠双独立 y 轴硬拗成可比。+- 结果标签为 `字段名 + 裸分数`,用户无法解读;多度量时不可区分;标题硬编码英文未走 i18n。+- 全部计算完成前只有 loading,无渐进展示;无空状态。++**一句话结论:现状是"用一个实现有误的信息论指标,近似回答了一个错误的问题"。** 用户问"为什么这个值高/低",系统回答"这个标记的构成有何不同",且在这个降级问题上排序也不可信。好在查询走标准 workflow 抽象、标记级聚合数据量小,重构的工程障碍不大。++## 2. 架构约束与总设计原则++### 2.1 计算架构约束(硬性)++Graphic Walker 的计算既可在浏览器端执行,也可下发服务端,**唯一下发通道是 workflow DSL**(`IDataQueryWorkflowStep[]`,经 `dataQuery(computation, workflow)` 执行)。DSL 能力清单(`interfaces.ts`):++| 能力 | 形态 | 备注 |+|------|------|------|+| 过滤 | `{type:'filter', filters:[{fid, rule}]}` | rule 支持 `one of` / `not in` / `range` / `temporal range` / `regexp` → **标记谓词可下推** |+| 派生列 | `{type:'transform', transform:[{key, expression}]}` | 表达式 op:`bin` / `binCount` / `log2` / `log10` / `log` / `one` / `dateTimeDrill` / `dateTimeFeature` / `expr` |+| 聚合 | `{type:'view', query:[{op:'aggregate', groupBy, measures}]}` | 聚合器:`sum` / `count` / `mean` / `median` / `variance` / `stdev` / `max` / `min` / `distinctCount` |+| 行级取数 | `{type:'view', query:[{op:'raw', fields}]}` + payload `limit` | **极端值检测的关键依赖** |+| 排序 | `{type:'sort', sort, by}` | 配合 limit 可做 top-N |++**没有的能力**:分位数聚合(无 q1/q3)、窗口函数、join、采样。方案设计不得依赖这些;确需分位数时用 `raw` 取回单列客户端计算(见 3.1)。++### 2.2 总原则:DSL 做数据归约,客户端做统计++所有解释类型统一遵循一个两段式契约:++```+阶段一(可下发):workflow DSL 把原始数据归约为「标记级 / 类别级聚合表」或「受限行级样本」+ —— 结果规模 = O(标记数 × 类别数),与原始行数无关+阶段二(客户端):在归约结果上做统计计算(散度、IQR、ridge 回归、打分)+ —— 纯函数、无 IO、可单测+```++这与 Tableau 的架构一致(模型拟合发生在标记级聚合上,而非原始行)。它保证:服务端只需要已有的 DSL 语义,不新增任何自定义算子;统计层在两种计算模式下行为完全一致。++**派生原则**:所有聚合查询一律请求 `sum` + `count`(而非直接请求 `mean`),客户端按需派生均值与份额。这带来两个关键收益:++1. sum/count 可加,**siblings(其余标记)分布可以从「视图维度 + 候选维度」一次查询的结果中直接减出来**,不需要单独的总体查询——查询数减半;+2. 均值、占比、方差贡献等都能在客户端一致地推导,避免非可加聚合(mean/median)无法跨层合成的问题。++例外:视图度量本身用了 `median` / `variance` 等非可加聚合时,该度量的总体/兄弟分布需单独一次查询(见 6.1)。++### 2.3 共享查询编排++四类解释器的查询高度重叠,引擎层统一去重:++- 以 workflow 的稳定序列化哈希为 key,同一查询只执行一次,多个解释器共享结果;+- `Promise.all` + 并发上限(默认 4)并行执行;+- 结果以流式(`onResult` 回调 / AsyncGenerator)交付 UI,先算完的先展示。++**查询预算对比**(k = 候选维度数,m = 视图度量数):++| | 现状 | 重构后 |+|---|---|---|+| 查询次数 | 2·k·m(串行) | ≈ k + 3(并行,B/D 两类共享同一批查询) |+| 单查询度量数 | 1 | 全部度量合批 |++## 3. 四大类解释的实现方案++以下统一记号:视图维度集 `Dims`(定义了标记的 LOD)、视图度量 `M`(目标度量,聚合器 `agg`)、选中标记谓词 `P`(`Dims` 上的等值条件,DSL 表达为 `one of` 过滤)、候选维度 `d`、候选度量 `m`。++### 3.1 A 类 · 极端值(Extreme Values)++**回答的问题**:选中标记的聚合值是否被少数行级极端记录扭曲?(Tableau 开篇的 10000 秒 L-sit 例子)++**适用条件**:`agg ∈ {mean, sum, stdev, variance}`(对极值敏感);`count` / `distinctCount` 不适用。++**查询计划**(两段,均为标准 DSL):++第一步·预筛(1 次查询,结果 1 行)——判断有没有必要拉行级数据:++```jsonc+[+ { "type": "filter", "filters": [/* 视图过滤器 + 标记谓词 P(one of) */] },+ { "type": "view", "query": [{+ "op": "aggregate", "groupBy": [],+ "measures": [+ { "field": "M", "agg": "count", "asFieldKey": "M_count" },+ { "field": "M", "agg": "mean", "asFieldKey": "M_mean" },+ { "field": "M", "agg": "median", "asFieldKey": "M_median" },+ { "field": "M", "agg": "stdev", "asFieldKey": "M_stdev" },+ { "field": "M", "agg": "min", "asFieldKey": "M_min" },+ { "field": "M", "agg": "max", "asFieldKey": "M_max" }+ ]+ }]}+]+```++预筛条件:`count ≥ 5` 且(`|mean − median| > 0.5·stdev` 或 `max − median > 3·stdev` 或 `median − min > 3·stdev`)。均值与中位数的显著偏离是存在极端值的廉价信号;不满足则直接跳过该类,省掉行级查询。++第二步·行级取数(1 次查询)——DSL 没有分位数聚合,用 `raw` 拉取该标记的度量列,客户端算 IQR:++```jsonc+// payload: { workflow: [...], limit: 20000 }+[+ { "type": "filter", "filters": [/* 同上 */] },+ { "type": "view", "query": [{ "op": "raw", "fields": ["M", /* 其他视图度量 */] }] }+]+```++**客户端计算**:++1. 排序求 q1/q3,`IQR = q3 − q1`,离群 = 超出 `[q1 − 1.5·IQR, q3 + 1.5·IQR]` 的记录;+2. **影响力评估**(核心打分):`impact = |agg(全部) − agg(剔除离群行)| / |agg(全部)|`。只有 impact 超过阈值(建议 10%)才作为解释输出——"存在离群值"本身不是洞察,"离群值扭曲了你看到的聚合结果"才是;+3. 行数超过 limit 时降级:仅基于预筛统计量给出弱提示("该标记的均值显著偏离中位数,可能存在极端记录"),不列具体行。++**证据呈现**:该标记度量值的直方图(客户端已有全部行值,直接分箱)+ 高亮离群区间 + 文案"剔除 n 条极端记录后,`mean(M)` 从 X 变为 Y(变化 Z%)"。若需要展示离群行明细,用第二步已取回的其他字段。++**护栏**:`count ≥ 5`;impact ≥ 10%;离群行数占比 ≤ 20%(超过说明是双峰/长尾分布而非个别异常,改用"分布形态"话术)。++### 3.2 B 类 · 贡献维度(Contributing Dimensions)++**回答的问题**:某个未可视化维度的取值构成,能否**帮助预测**各标记的度量值——而不只是"这个标记的构成不一样"(那是 D 类)。++**方法**(Tableau 的 base/explain model 框架):++- **base model**:以视图维度 one-hot 为特征,ridge 回归拟合各标记的 `M` 值;+- **explain model**:base 特征 + 候选维度 `d` 的 **top-K 取值占比**(rates)作为附加特征;+- 训练时**留出选中标记**,打分 = 对其余标记的拟合改善 + 对留出标记的预测误差改善 − 过拟合惩罚。++**查询计划**(每个候选维度 1 次查询;数值型候选先 transform bin):++```jsonc+[+ { "type": "filter", "filters": [/* 仅视图过滤器,不含标记谓词 —— 需要所有标记 */] },+ // 数值型候选维度:先分箱+ { "type": "transform", "transform": [{+ "key": "d_bin",+ "expression": { "op": "bin", "as": "d_bin", "num": 10,+ "params": [{ "type": "field", "value": "d" }] }+ }]},+ { "type": "view", "query": [{+ "op": "aggregate",+ "groupBy": [/* ...Dims, */ "d_bin"],+ "measures": [+ { "field": "M", "agg": "sum", "asFieldKey": "M_sum" },+ { "field": "M", "agg": "count", "asFieldKey": "M_count" },+ { "field": "*", "agg": "count", "asFieldKey": "row_count" }+ ]+ }]}+]+```++> 这批查询**与 D 类完全同构**——引擎层同一次查询同时喂 B、D 两个解释器,这是查询预算从 2km 降到 k 的关键。++**客户端计算**:++1. 从查询结果统计 `d` 的全局 top-K 取值(K = 10,按行数),其余归入 `__other__`;+2. pivot 成「标记 × (top-K 占比)」特征矩阵,占比 = 该标记内取值行数 / 该标记总行数;+3. 目标向量 y = 各标记的 `M` 聚合值(sum/count 派生),标准化;+4. ridge 闭式解 `β = (XᵀX + λI)⁻¹Xᵀy`。特征维度 ≤ |Dims one-hot| + K + 1 ≈ 20,标记数通常几十,纯 JS 实现(高斯消元求逆)几十行,无新依赖;+5. 打分:+ - `fitGain = R²_explain − R²_base`(在非留出标记上,λ 经 LOO 交叉验证选取);+ - `predGain = |ŷ_base(mark) − y(mark)| − |ŷ_explain(mark) − y(mark)|`,归一化到 y 的尺度;+ - `penalty`:自由度惩罚(特征数增量 / 标记数)+ "幸运预测"检查——对候选特征做若干次随机置换(种子固定,保证可复现),若真实 predGain 未显著超过置换分布,判为侥幸,丢弃;+ - `score = w₁·fitGain + w₂·predGain − penalty`,仅 score > 阈值者输出。++**证据呈现**:Tableau 式双图——上图为各标记的实际值 vs base model 预测带 vs explain model 预测带(选中标记高亮);下图为该候选维度 top 取值占比与 `M` 的关系。文案统一用关联性措辞:"`d` 的构成**有助于预测** `M`",禁用因果表述。++**护栏**:标记数 ≥ 8 才启用模型类(不足时该类整体禁用,UI 说明原因);候选维度基数 ≥ 2;`__other__` 占比 > 80% 的高基数维度跳过。++### 3.3 C 类 · 贡献度量(Contributing Measures)++**回答的问题**:某个未可视化**度量**在标记 LOD 上的聚合值,能否帮助预测目标度量?(攀岩例子里的指力、训练年限)++**查询计划**(**全部候选度量合并为 1 次查询**):++```jsonc+[+ { "type": "filter", "filters": [/* 仅视图过滤器 */] },+ { "type": "view", "query": [{+ "op": "aggregate",+ "groupBy": [/* Dims */],+ "measures": [+ { "field": "M", "agg": "sum", "asFieldKey": "M_sum" },+ { "field": "M", "agg": "count", "asFieldKey": "M_count" },+ // 每个候选度量 m:+ { "field": "m1", "agg": "sum", "asFieldKey": "m1_sum" },+ { "field": "m1", "agg": "count", "asFieldKey": "m1_count" },+ { "field": "m2", "agg": "sum", "asFieldKey": "m2_sum" }+ // ...+ ]+ }]}+]+```++结果规模 = 标记数 × 字段数,极小。++**客户端计算**:与 B 类共用同一 ridge 框架,差异仅在特征构造:++1. 候选度量 `m` 在标记 LOD 上取 mean(sum/count 派生),标准化;+2. 特征 = base 特征 + `m̃` + `m̃²`(二阶项,对应 Tableau 的 second-order modeling,捕捉非线性);+3. 打分、置换检验、护栏与 B 类完全一致。++**证据呈现**:散点图(x = 候选度量的标记级均值,y = 目标度量,选中标记高亮)+ explain model 拟合曲线。文案额外遵循 Tableau 文章的提醒:**只陈述关联,不暗示可控性**("臂展有助于区分,但不可改变"这类判断留给用户;后续可让用户给字段打 可控/固定/忽略/敏感 标签,见 M3)。++### 3.4 D 类 · 标记独特性(Unique About This Mark)——修复现有实现++**回答的问题**:这个标记的人群构成,在哪个未可视化维度上与**其余标记**最不一样?定位为"探索线索",UI 上明确降级于 A/B/C(Tableau 原文:"clues, not conclusions")。++**查询计划**:与 B 类共享同一批查询(3.2 的 workflow),零额外查询。选中标记的分布 = 谓词过滤后的行;siblings 分布 = 全量减去选中标记(sum/count 可加,客户端直接减)。++**客户端计算**(替换 `compareDistributionJS`):++1. 分布构造:对 count 类比较用行数占比;对度量比较用 `sum` 份额(**负值处理**:存在负值时自动切换为行数占比模式并在文案中注明,不再取绝对值硬算);+2. 平滑:两侧分布各加 Laplace 伪计数(α = 0.5),消除小样本的伪极端;+3. 打分 = **完整 JS 距离** `√(JSD)`:零概率类别按定义计入(`0·log 0 = 0`,单侧为零时贡献 `0.5·p`),**不再乘覆盖率权重**。JS 距离有界于 [0,1],跨维度天然可比,高基数无需额外归一;+4. 显著性:对行数分布做 G 检验(`G = 2N·KL(mark‖siblings)`,渐近 `χ²(k−1)`),p < 0.01 且 JS 距离 > 0.15 才输出;对度量份额分布无严格检验,用样本量下限 + 更高的距离阈值(0.25)兜底,并在 UI 标注为启发式结果。++**证据呈现**:修复现状图表——选中标记与 siblings **共用同一 y 轴**,均以份额(%)呈现;不再返回挂着 `normalized` 名字的原始值。++**护栏**:标记行数 ≥ 20;候选维度在平滑后有效类别数 ≥ 2;每维度只保留该维度下的最优结果,全局最多输出 top 5。++### 3.5 跨类型排序与展示++各类分数量纲不同,**不做跨类型统一排序**。UI 按固定优先级分组展示:A(数据质量,最可行动)→ B/C(模型证据)→ D(探索线索),组内按各自分数排序;每条解释映射为三档定性强度(强 / 中 / 弱提示),裸分数仅在开发者模式展示。所有类别都可能为空——空状态明确显示"未发现显著模式",这是**特性而非缺陷**。++## 4. 推荐改造方案:架构层保留,算法层重写++明确回答"从零重写还是基于现有修改":**分层回答**。++### 4.1 保留(复用现有资产)++| 资产 | 位置 | 理由 |+|------|------|------|+| 触发链路 | `embedMenu.tsx` → `selectedMarkObject` → 谓词构造 | 标记→谓词的映射逻辑正确,含 temporal 特判 |+| workflow 编排与计算抽象 | `utils/workflow.ts#toWorkflow`、`computation/index.ts#dataQuery` | 这正是"适配双端计算"的根基,方案的全部查询都经由它 |+| 对话框与图表基建 | Dialog / vega-embed / 主题系统 | 壳可用,换内容 |++### 4.2 重写(废弃后新建)++| 废弃 | 理由 |+|------|------|+| `lib/insights/explainBySelection.ts` | 打分逻辑重写后所剩无几,查询编排移入引擎层 |+| `lib/insights/explainValue.ts`、`explainByChildren.ts` | 死代码 + bug,git 历史可查,直接删除 |+| `utils/normalization.ts` 中的 `compareDistribution*` 系列 | 数学错误的修复量 ≈ 重写量,且现有代码零测试覆盖;`normalizeWithParent` 等如无他处引用一并清理 |+| `components/explainData/index.tsx` 内容区 | 从"分数列表 + 单图"改为"按类分组的解释卡片 + 渐进加载" |++理由汇总:算法层总共约 300 行、无测试、其中三分之二是死代码,"原地修" 与 "重写" 工作量几乎相同,但重写能一步到位建立四类解释器的统一接口与测试基线。++### 4.3 新模块设计++```+lib/explain/+├── engine.ts // 编排:查询去重(workflow 哈希)、并发执行、流式交付、跨类护栏+├── types.ts // IExplainer / IExplanation / ExplainContext+├── explainers/+│ ├── extremeValue.ts // A 类+│ ├── contributingDim.ts // B 类+│ ├── contributingMeasure.ts // C 类+│ └── uniqueMark.ts // D 类+├── stats/+│ ├── divergence.ts // JS 距离(完整零处理 + 平滑)、G 检验+│ ├── quantile.ts // q1/q3/IQR+│ └── ridge.ts // 闭式解 ridge + LOO λ 选择 + 置换检验(种子固定)+└── __tests__/ // 纯函数单测 + 合成数据金标准+```++核心接口:++```ts+interface IExplainer {+ type: 'extreme-value' | 'contributing-dimension' | 'contributing-measure' | 'unique-mark';+ isApplicable(ctx: ExplainContext): boolean; // 聚合类型、标记数等前置检查+ plan(ctx: ExplainContext): IDataQueryPayload[]; // 只产出 workflow DSL,不执行+ analyze(ctx: ExplainContext, results: IRow[][]): IExplanation[]; // 纯函数,客户端统计+}++interface IExplanation {+ type: IExplainer['type'];+ score: number;+ strength: 'strong' | 'moderate' | 'weak';+ field: IField; // 解释字段(+ 度量上下文)+ descriptionKey: string; // i18n key,参数化,不硬编码文案+ descriptionParams: Record<string, string | number>;+ evidence: { chartSpec: object; rows?: IRow[] }; // vega-lite spec + 可选明细行+}+```++`plan / analyze` 分离是适配双端计算的结构性保证:**explainer 只会通过 DSL 表达数据需求**,任何绕过 DSL 的取数在接口上就不可能发生;engine 对 `plan` 产出做哈希去重后统一执行(B/D 共享查询即由此自动达成)。`analyze` 是纯函数,单测直接喂查询结果 fixture,无需 mock 计算层。++对外暴露 headless API(供 host 应用/未来 LLM 叙述层消费):++```ts+explainMark(ctx): AsyncGenerator<IExplanation>+```++现有 `<ExplainData>` 组件变为该 API 的默认 UI 消费者。++### 4.4 测试策略++- `stats/` 全部纯函数单测(散度零值边界、G 检验临界值、ridge 与解析解对拍);+- 合成数据金标准:构造已知答案的数据集(植入一条极端记录 / 一个强相关隐藏度量 / 一个构成差异维度),断言对应解释以 `strong` 强度被找到、且无关字段不产生解释(控误报);+- 双端一致性:同一合成数据集分别走客户端计算与服务端计算(CI 里用 DuckDB-WASM 模拟),断言 `analyze` 输入一致。++## 5. 里程碑++| 阶段 | 内容 | 规模 | 可独立发布 |+|------|------|------|-----------|+| **M0 · 止损** | 在现有代码上最小修复:JS 散度零值处理、删覆盖率权重、siblings 基线、样本量/阈值/空状态、查询合批并行、UI 同轴份额化 | 2–3 天 | ✅ 立即改善现有功能可信度 |+| **M1 · 引擎 + A 类** | `lib/explain/` 骨架落地;极端值解释器;D 类迁入引擎;卡片式分组 UI + 渐进加载;删除死代码 | ~1 周 | ✅ |+| **M2 · 模型类** | `stats/ridge.ts`;B、C 解释器;置换检验;i18n 文案体系(关联性措辞规范) | ~2 周 | ✅ |+| **M3 · 产品层** | headless API 定稿;行动按钮(将解释字段加入视图 / 过滤到该段 / 排除离群行);字段元数据标注(可控/固定/忽略/敏感);LLM 叙述接口预留 | 按需 | — |++M0 与 M1+ 并不冲突:M0 的散度修复代码即 M1 `stats/divergence.ts` 的雏形,工作量不浪费。++## 6. 风险与开放问题++1. **非可加聚合的 siblings 派生**:视图度量为 `median` / `variance` 时无法从标记级 sum/count 合成总体分布,D 类需为此类度量单独多跑一次总体查询(回到现状的查询形态,但仍合批并行)。+2. **`raw` 查询的规模上限**:A 类依赖行级取数,单标记行数极大时受 `limit` 约束降级为弱提示。若未来服务端 DSL 扩展分位数聚合(`q1`/`q3`),A 类可完全免除行级查询——建议作为 DSL 演进的候选项记入 [dsl-design-review.md](./dsl-design-review.md) 的行动清单,但**本方案不依赖它**。+3. **temporal 维度作为候选**:需选择 drill 粒度(year/month/…)。M1 先用 `dateTimeDrill` 固定 month 粒度,后续依据视图时间轴粒度自适应。+4. **置换检验的确定性**:浏览器端随机置换需固定种子以保证"同一视图状态产出同一解释"(Tableau 文章强调的可复现性);`stats/ridge.ts` 内置 PRNG,不使用 `Math.random`。+5. **候选字段规模**:宽表(>50 个候选字段)下 k+3 次查询仍可能偏多。缓解:按字段元信息预排序(基数适中优先),首屏只跑 top 20 候选,其余"继续分析"按需触发。diff --git a/docs/explain-data-worklog.md b/docs/explain-data-worklog.mdnew file mode 100644index 00000000..2cc764ec--- /dev/null+++ b/docs/explain-data-worklog.md@@ -0,0 +1,102 @@+# Explain Data 重构 · 分工与进度跟踪++> 性质:临时工作文档(重构完成后归档或删除)+> 方案依据:[explain-data-redesign.md](./explain-data-redesign.md)(本文件不重复方案细节,只管分工与进度)+> 创建:2026-07-07++## 1. 协作模型++两个角色:++| 角色 | 承担者 | 职责 |+|------|--------|------|+| **Kernel**(内核/架构) | Fable(主 agent) | 数学与统计内核、打分公式、架构接口、engine 编排语义、评审执行方产出 |+| **Executor**(工程执行) | 执行 agent(handoff) | 解释器接线、UI 重写、i18n、测试 fixture、死代码清理、构建与回归验证 |++**分工原则(判断任何新任务归属时用这条)**:++> 错误会**静默污染结果**的代码 → Kernel。错误会**被测试或肉眼立刻发现**的代码 → Executor。++具体地:一个写错的 JS 散度会产出"看起来合理但排序全错"的解释列表,没人能靠观察发现,所以它必须由 Kernel 写并配单测锁死;一个写错的卡片组件会直接渲染坏掉,验收标准就能兜住,交给 Executor。++**冻结边界(Executor 必须遵守)**:++- `lib/explain/stats/**` 与各 explainer 的 `analyze()` 打分逻辑为 **frozen**:Executor 只可调用,不可修改。发现问题 → 记录到 §5 进度日志并升级给 Kernel,不要自行"顺手修"。+- `lib/explain/types.ts` 的接口签名为 frozen:需要加字段时先在日志中提出。+- 所有取数必须走 `plan(): IDataQueryPayload[]`(workflow DSL)。任何直接访问原始数据源的代码都是违规,评审时一票否决。++**升级触发条件**(Executor 遇到以下情况停下并记日志,等 Kernel 决策):++1. stats 单测失败,或金标准测试(E6)找不到植入的信号 / 产生误报;+2. 规格有歧义、或实现中发现方案文档没覆盖的分支;+3. 需要修改任何 frozen 文件才能继续;+4. 双端计算(客户端 vs DuckDB-WASM)结果不一致。++**评审节奏**:Executor 每完成一个 E 任务,在 §5 追加一行日志(任务号、改动文件、验证方式、遗留问题);每个里程碑收口时 Kernel 过一遍 diff 再进入下一阶段。++## 2. 任务清单++任务编号:`K-*` = Kernel,`E-*` = Executor。状态:`[ ]` 未开始 / `[~]` 进行中 / `[x]` 完成 / `[!]` 阻塞。++### 阶段一 · M0 止损(可独立发布)++| # | 任务 | 状态 | 说明 / 验收标准 |+|---|------|------|----------------|+| K-1 | 修复散度打分:完整 JS 距离(零概率按定义计入)+ Laplace 平滑 + 删除覆盖率权重,先以独立纯函数落在 `lib/explain/stats/divergence.ts`(M0 阶段由旧代码引用) | [ ] | 单测覆盖:零值边界、单类别集中分布得高分、对称性、有界 [0,1] |+| K-2 | siblings 基线:从「视图维度+候选维度」查询结果减出其余标记分布(sum/count 派生),替换现在的 child-vs-parent 比较 | [ ] | 单测:大占比标记不再被自我稀释 |+| E-1 | 查询合批与并行:overall 查询按候选维度合并全部度量(2km→2k),`Promise.all` 并发上限 4 | [ ] | 现有功能行为不变,网络往返次数可在 devtools 验证 |+| E-2 | M0 UI 修正:选中标记与 siblings 同 y 轴、以份额(%)呈现;样本量 <20 或分数 < 阈值不展示;空状态文案"未发现显著模式" | [ ] | 阈值常量从 K-1 模块导入,不自定义 |++### 阶段二 · M1 引擎骨架 + 极端值++| # | 任务 | 状态 | 说明 / 验收标准 |+|---|------|------|----------------|+| K-3 | `lib/explain/types.ts` + `engine.ts`:IExplainer/IExplanation/ExplainContext 定稿;查询哈希去重、并发执行、AsyncGenerator 流式交付 | [ ] | engine 单测:同构 workflow 只执行一次;B/D 共享查询自动成立 |+| K-4 | `stats/quantile.ts`(q1/q3/IQR)+ A 类解释器 `explainers/extremeValue.ts` 完整实现(预筛条件、impact 打分、降级路径) | [ ] | 金标准:植入单条极端记录的合成数据集被以 strong 检出 |+| K-5 | D 类解释器 `explainers/uniqueMark.ts`:基于 K-1/K-2 内核 + G 检验门槛,迁入 engine | [ ] | 与 M0 修复后的旧路径结果一致后,旧路径下线 |+| E-3 | UI 重写:按类分组的解释卡片(A → B/C → D 固定顺序)、三档强度标签、渐进加载(AsyncGenerator 消费)、证据图渲染 | [ ] | 裸分数仅开发者模式可见;vega spec 由 explainer 的 `evidence.chartSpec` 提供,UI 不自行拼 spec |+| E-4 | 删除死代码:`lib/insights/explainValue.ts`、`explainByChildren.ts`、`utils/normalization.ts` 中不再被引用的 `compareDistribution*` / `normalizeWithParent` 等;`lib/insights/` 目录清空后移除 | [ ] | 全仓 grep 无残留引用,build + 现有测试通过 |+| E-5 | i18n:所有解释文案走 `descriptionKey` + 参数,补齐 en-US / zh-CN / ja-JP 三份 locale;文案遵循关联性措辞规范("有助于预测/与…相关",禁用因果词) | [ ] | 硬编码英文标题全部清除 |+| E-6 | 金标准测试基建:按 Kernel 提供的规格生成合成数据集 fixture(植入极端记录 / 强相关度量 / 构成差异维度 / 纯噪声对照组),接入 vitest | [ ] | 噪声对照组必须零解释输出(控误报) |++### 阶段三 · M2 模型类++| # | 任务 | 状态 | 说明 / 验收标准 |+|---|------|------|----------------|+| K-6 | `stats/ridge.ts`:闭式解 ridge、标准化、LOO λ 选择、固定种子置换检验(内置 PRNG,禁用 Math.random) | [ ] | 与解析解对拍;同输入必同输出(可复现性) |+| K-7 | B 类 `contributingDim.ts` + C 类 `contributingMeasure.ts`:特征构造(top-K rates / 二阶项)、holdout 打分、护栏,完整实现 | [ ] | 金标准:植入的相关字段 strong 检出,无关字段不出现 |+| E-7 | B/C 证据图:base vs explain 预测带图、候选度量散点图(按 Kernel 给的 spec 模板接线) | [ ] | 选中标记高亮,暗色主题正常 |+| E-8 | 双端一致性 CI:同一 fixture 分别走客户端计算与 DuckDB-WASM 服务端模拟,断言 explainer 的 `analyze` 输入一致 | [ ] | 接入 CI,失败即阻塞合并 |+| E-9 | 性能护栏:宽表候选字段 >20 时按基数预排序取 top 20,UI 提供"继续分析"按需触发 | [ ] | 50 字段宽表首屏查询数 ≤ 23 |++### 阶段四 · M3 产品层(进入前重新评估分工)++| # | 任务 | 状态 | 说明 |+|---|------|------|------|+| K-8 | headless API `explainMark(ctx): AsyncGenerator<IExplanation>` 定稿并导出 | [ ] | 含 API 文档 |+| E-10 | 行动按钮:解释字段加入视图 / 过滤到该段 / 排除离群行 | [ ] | 复用 vizStore 现有 action |+| E-11 | 字段元数据标注(可控/固定/忽略/敏感)与解释文案联动 | [ ] | 待 K-8 后细化 |++## 3. Handoff 交接物清单++进入每个阶段的工程执行前,Kernel 必须交付齐以下内容,Executor 才开工:++- [ ] 对应 K 任务代码合入,`stats/` 单测绿;+- [ ] 一个**端到端参考实现**可运行(M1 阶段 = A 类 + D 类完整跑通 engine),Executor 照此模式接线,不需要理解统计内部;+- [ ] 金标准数据集的**生成规格**(字段结构、植入信号的参数、期望输出),E-6 据此实现 fixture;+- [ ] 证据图的 vega-lite spec 模板(E-3/E-7 只做接线与主题适配);+- [ ] 本文档 §2 中该阶段 E 任务的验收标准无歧义(Executor 开工前先通读,有疑问先提)。++## 4. Executor 工作守则++1. **改动范围**:只动本阶段 E 任务列出的文件域;顺手发现的其他问题记日志,不动手。+2. **验证闭环**:每个 E 任务完成后依次跑 ① 相关单测 ② `npm build`(graphic-walker 包) ③ playground 目视验证。注意 playground 引用的是**构建产物**:需重新 build graphic-walker 并清除 playground 的 `.vite` 缓存才能看到改动。+3. **提交粒度**:一个 E 任务一个 commit,message 前缀 `feat(explain)` / `refactor(explain)` / `test(explain)`,正文引用任务号。+4. **不确定就停**:满足 §1 任一升级触发条件时,停止该任务、记日志、切换到其他不受阻塞的 E 任务。+5. **日志格式**:见 §5 表头,append-only,不改写历史行。++## 5. 进度日志(append-only)++| 日期 | 角色 | 任务 | 记录 |+|------|------|------|------|+| 2026-07-07 | Kernel | — | 方案文档与本分工文档创建;等待方案评审后启动 K-1 |diff --git a/packages/graphic-walker/jest.config.js b/packages/graphic-walker/jest.config.jsindex 0c0e996f..0855789b 100644--- a/packages/graphic-walker/jest.config.js+++ b/packages/graphic-walker/jest.config.js@@ -4,6 +4,7 @@ module.exports = {testEnvironment: 'node',moduleNameMapper: {'^@/(.*)$': '<rootDir>/src/$1',+ '^nanoid$': '<rootDir>/../../node_modules/nanoid/index.cjs',},testPathIgnorePatterns: ['<rootDir>/dist/'],};diff --git a/packages/graphic-walker/src/lib/explain/engine.test.ts b/packages/graphic-walker/src/lib/explain/engine.test.tsnew file mode 100644index 00000000..f7297274--- /dev/null+++ b/packages/graphic-walker/src/lib/explain/engine.test.ts@@ -0,0 +1,99 @@+import type { IDataQueryPayload, IRow } from '../../interfaces';+import { explainMarkAll, explainMark } from './engine';+import type { IExplainContext, IExplainer } from './types';++const CTX = { allFields: [], viewDimensions: [], viewMeasures: [], viewFilters: [], selectedMark: {} } as unknown as IExplainContext;++const PAYLOAD_A: IDataQueryPayload = { workflow: [{ type: 'view', query: [{ op: 'raw', fields: ['a'] }] }] };+// structurally identical to A but constructed separately (different key order paths)+const PAYLOAD_A_CLONE: IDataQueryPayload = JSON.parse(JSON.stringify(PAYLOAD_A));+const PAYLOAD_B: IDataQueryPayload = { workflow: [{ type: 'view', query: [{ op: 'raw', fields: ['b'] }] }] };++function makeExplainer(type: string, payloads: IDataQueryPayload[], opts?: { applicable?: boolean; analyzeDelay?: number; throwOnAnalyze?: boolean }): IExplainer {+ return {+ type: type as IExplainer['type'],+ isApplicable: () => ({ applicable: opts?.applicable ?? true, reason: 'test.reason' }),+ plan: () => payloads,+ analyze: (_ctx, results) => {+ if (opts?.throwOnAnalyze) throw new Error('analyze boom');+ return results.map((rows, i) => ({+ type: type as IExplainer['type'],+ score: rows.length + i,+ strength: 'weak' as const,+ field: { fid: 'f', name: 'f', analyticType: 'dimension', semanticType: 'nominal' } as never,+ descriptionKey: 'test',+ descriptionParams: {},+ evidence: {},+ }));+ },+ };+}++describe('explain engine', () => {+ it('dedupes structurally identical payloads across explainers', async () => {+ const calls: IDataQueryPayload[] = [];+ const computation = async (payload: IDataQueryPayload): Promise<IRow[]> => {+ calls.push(payload);+ return [{ x: 1 }];+ };+ const e1 = makeExplainer('unique-mark', [PAYLOAD_A, PAYLOAD_B]);+ const e2 = makeExplainer('contributing-dimension', [PAYLOAD_A_CLONE]);+ const results = await explainMarkAll(CTX, computation, [e1, e2]);+ expect(calls).toHaveLength(2); // A executed once, B once+ expect(results.every((r) => r.status === 'ok')).toBe(true);+ });++ it('respects the concurrency cap', async () => {+ let active = 0;+ let maxActive = 0;+ const computation = async (): Promise<IRow[]> => {+ active++;+ maxActive = Math.max(maxActive, active);+ await new Promise((r) => setTimeout(r, 10));+ active--;+ return [];+ };+ const payloads = Array.from({ length: 8 }, (_, i) => ({+ workflow: [{ type: 'view' as const, query: [{ op: 'raw' as const, fields: [`f${i}`] }] }],+ }));+ const explainer = makeExplainer('unique-mark', payloads);+ await explainMarkAll(CTX, computation, [explainer], { concurrency: 2 });+ expect(maxActive).toBeLessThanOrEqual(2);+ });++ it('yields skipped results for inapplicable explainers without querying', async () => {+ const computation = jest.fn(async (): Promise<IRow[]> => []);+ const explainer = makeExplainer('extreme-value', [PAYLOAD_A], { applicable: false });+ const results = await explainMarkAll(CTX, computation, [explainer]);+ expect(results[0].status).toBe('skipped');+ expect(results[0].reason).toBe('test.reason');+ expect(computation).not.toHaveBeenCalled();+ });++ it('isolates explainer errors: one failure does not poison the rest', async () => {+ const computation = async (): Promise<IRow[]> => [{ x: 1 }];+ const bad = makeExplainer('extreme-value', [PAYLOAD_A], { throwOnAnalyze: true });+ const good = makeExplainer('unique-mark', [PAYLOAD_B]);+ const results = await explainMarkAll(CTX, computation, [bad, good]);+ const byType = Object.fromEntries(results.map((r) => [r.explainer, r]));+ expect(byType['extreme-value'].status).toBe('error');+ expect(byType['extreme-value'].reason).toContain('analyze boom');+ expect(byType['unique-mark'].status).toBe('ok');+ expect(byType['unique-mark'].explanations).toHaveLength(1);+ });++ it('streams results in completion order, not registration order', async () => {+ const computation = async (payload: IDataQueryPayload): Promise<IRow[]> => {+ const isSlow = JSON.stringify(payload).includes('slow');+ await new Promise((r) => setTimeout(r, isSlow ? 50 : 5));+ return [];+ };+ const slow = makeExplainer('contributing-measure', [{ workflow: [{ type: 'view', query: [{ op: 'raw', fields: ['slow'] }] }] }]);+ const fast = makeExplainer('unique-mark', [{ workflow: [{ type: 'view', query: [{ op: 'raw', fields: ['fast'] }] }] }]);+ const order: string[] = [];+ for await (const result of explainMark(CTX, computation, [slow, fast])) {+ order.push(result.explainer);+ }+ expect(order).toEqual(['unique-mark', 'contributing-measure']);+ });+});diff --git a/packages/graphic-walker/src/lib/explain/engine.ts b/packages/graphic-walker/src/lib/explain/engine.tsnew file mode 100644index 00000000..763ad93c--- /dev/null+++ b/packages/graphic-walker/src/lib/explain/engine.ts@@ -0,0 +1,110 @@+import type { IComputationFunction, IRow } from '../../interfaces';+import type { IExplainContext, IExplainOptions, IExplainer, IExplainerResult } from './types';+import { stableStringify } from './queries';++/**+ * Explain Data engine: executes explainers against a computation service.+ *+ * - every payload produced by `plan()` is deduplicated by structural hash,+ * so explainers sharing a query (contributing-dimension / unique-mark)+ * trigger a single execution;+ * - query execution is capped by a concurrency limiter;+ * - results stream out per explainer as soon as its queries settle, in+ * completion order — the UI renders progressively.+ */++const DEFAULT_CONCURRENCY = 4;++type Limiter = <T>(fn: () => Promise<T>) => Promise<T>;++function createLimiter(max: number): Limiter {+ let active = 0;+ const waiters: (() => void)[] = [];+ return async function run<T>(fn: () => Promise<T>): Promise<T> {+ if (active >= max) {+ await new Promise<void>((resolve) => waiters.push(resolve));+ }+ active++;+ try {+ return await fn();+ } finally {+ active--;+ waiters.shift()?.();+ }+ };+}++export async function* explainMark(+ ctx: IExplainContext,+ computation: IComputationFunction,+ explainers: IExplainer[],+ options?: IExplainOptions+): AsyncGenerator<IExplainerResult> {+ const limiter = createLimiter(options?.concurrency ?? DEFAULT_CONCURRENCY);+ const queryCache = new Map<string, Promise<IRow[]>>();++ const runQuery = (payloadKey: string, payload: Parameters<IComputationFunction>[0]): Promise<IRow[]> => {+ const cached = queryCache.get(payloadKey);+ if (cached) return cached;+ const promise = limiter(async () => (await computation(payload)) as IRow[]);+ queryCache.set(payloadKey, promise);+ return promise;+ };++ const pending: Promise<IExplainerResult>[] = [];++ for (const explainer of explainers) {+ const applicability = explainer.isApplicable(ctx);+ if (!applicability.applicable) {+ pending.push(+ Promise.resolve({+ explainer: explainer.type,+ status: 'skipped',+ reason: applicability.reason,+ explanations: [],+ })+ );+ continue;+ }+ pending.push(+ (async (): Promise<IExplainerResult> => {+ try {+ const payloads = explainer.plan(ctx);+ const results = await Promise.all(payloads.map((p) => runQuery(stableStringify(p), p)));+ const explanations = explainer.analyze(ctx, results);+ return { explainer: explainer.type, status: 'ok', explanations };+ } catch (err) {+ return {+ explainer: explainer.type,+ status: 'error',+ reason: err instanceof Error ? err.message : String(err),+ explanations: [],+ };+ }+ })()+ );+ }++ // yield in completion order+ const tagged = pending.map((p, i) => p.then((result) => ({ i, result })));+ const remaining = new Map(tagged.map((p, i) => [i, p]));+ while (remaining.size > 0) {+ const { i, result } = await Promise.race(remaining.values());+ remaining.delete(i);+ yield result;+ }+}++/** convenience wrapper: run all explainers to completion and collect results */+export async function explainMarkAll(+ ctx: IExplainContext,+ computation: IComputationFunction,+ explainers: IExplainer[],+ options?: IExplainOptions+): Promise<IExplainerResult[]> {+ const results: IExplainerResult[] = [];+ for await (const result of explainMark(ctx, computation, explainers, options)) {+ results.push(result);+ }+ return results;+}diff --git a/packages/graphic-walker/src/lib/explain/explainers/extremeValue.ts b/packages/graphic-walker/src/lib/explain/explainers/extremeValue.tsnew file mode 100644index 00000000..eb7b18a6--- /dev/null+++ b/packages/graphic-walker/src/lib/explain/explainers/extremeValue.ts@@ -0,0 +1,169 @@+import type { IRow, IViewField } from '../../../interfaces';+import { getMeaAggKey } from '../../../utils';+import { detectIqrOutliers, outlierImpact, type ISensitiveAggregator } from '../stats/quantile';+import { EXPLAIN_COUNT_KEY, markPrescreenQuery, markRawQuery } from '../queries';+import type { IExplainContext, IExplainer, IExplanation, IExplanationStrength } from '../types';++/**+ * A-class explainer: extreme values.+ *+ * "Is the aggregate you are looking at distorted by a handful of extreme+ * row-level records?" — the most actionable explanation type: the evidence+ * is the suspicious rows themselves.+ *+ * Plan: [0] cheap pre-screen aggregate over the selected mark,+ * [1] row-level fetch of the mark's measure values (bounded by limit).+ *+ * SCORING-FROZEN for the executor agent (see docs/explain-data-worklog.md §1).+ */++export const RAW_LIMIT = 20000;+const MIN_ROWS = 5;+const MAX_OUTLIER_SHARE = 0.2;+const MIN_IMPACT = 0.1;+const MAX_EVIDENCE_ROWS = 20;+const MAX_HISTOGRAM_POINTS = 1000;++const SENSITIVE_AGGS: ReadonlySet<string> = new Set<ISensitiveAggregator>(['mean', 'sum', 'stdev', 'variance']);++function sensitiveMeasures(ctx: IExplainContext): IViewField[] {+ const seen = new Set<string>();+ return ctx.viewMeasures.filter((m) => {+ const key = getMeaAggKey(m.fid, m.aggName ?? 'sum');+ if (seen.has(key)) return false;+ seen.add(key);+ return SENSITIVE_AGGS.has(m.aggName ?? 'sum');+ });+}++function strengthOf(impact: number): IExplanationStrength {+ if (impact >= 0.3) return 'strong';+ if (impact >= 0.15) return 'moderate';+ return 'weak';+}++/** deterministic downsample preserving outliers: every k-th value + all outliers */+function sampleForHistogram(values: number[], outlierIndices: Set<number>): number[] {+ if (values.length <= MAX_HISTOGRAM_POINTS) return values;+ const step = Math.ceil(values.length / MAX_HISTOGRAM_POINTS);+ const sampled: number[] = [];+ for (let i = 0; i < values.length; i++) {+ if (i % step === 0 || outlierIndices.has(i)) sampled.push(values[i]);+ }+ return sampled;+}++function histogramSpec(values: number[], lowerFence: number, upperFence: number, measureName: string): Record<string, unknown> {+ return {+ width: 320,+ height: 160,+ data: { values: values.map((v) => ({ value: v })) },+ layer: [+ {+ mark: { type: 'bar', opacity: 0.85 },+ encoding: {+ x: { field: 'value', bin: { maxbins: 30 }, type: 'quantitative', title: measureName },+ y: { aggregate: 'count', type: 'quantitative', title: null },+ },+ },+ { mark: { type: 'rule', strokeDash: [4, 4] }, encoding: { x: { datum: lowerFence } } },+ { mark: { type: 'rule', strokeDash: [4, 4] }, encoding: { x: { datum: upperFence } } },+ ],+ };+}++export const extremeValueExplainer: IExplainer = {+ type: 'extreme-value',++ isApplicable(ctx) {+ if (Object.keys(ctx.selectedMark).length === 0) {+ return { applicable: false, reason: 'explain.skip.noMark' };+ }+ if (ctx.viewDimensions.some((d) => d.semanticType === 'temporal')) {+ // temporal marks need drill-aware equality filters; out of scope for now+ return { applicable: false, reason: 'explain.skip.temporalMark' };+ }+ if (sensitiveMeasures(ctx).length === 0) {+ return { applicable: false, reason: 'explain.skip.noSensitiveAgg' };+ }+ return { applicable: true };+ },++ plan(ctx) {+ const fids = sensitiveMeasures(ctx).map((m) => m.fid);+ return [markPrescreenQuery(ctx, fids), markRawQuery(ctx, [...new Set(fids)], RAW_LIMIT)];+ },++ analyze(ctx, results) {+ const [prescreenRows, rawRows] = results;+ const stats = prescreenRows?.[0];+ if (!stats) return [];+ const n = Number(stats[EXPLAIN_COUNT_KEY]);+ if (!Number.isFinite(n) || n < MIN_ROWS) return [];+ const truncated = rawRows.length >= RAW_LIMIT;++ const explanations: IExplanation[] = [];+ for (const measure of sensitiveMeasures(ctx)) {+ const agg = (measure.aggName ?? 'sum') as ISensitiveAggregator;+ const mean = Number(stats[getMeaAggKey(measure.fid, 'mean')]);+ const median = Number(stats[getMeaAggKey(measure.fid, 'median')]);+ const stdev = Number(stats[getMeaAggKey(measure.fid, 'stdev')]);+ const maxV = Number(stats[getMeaAggKey(measure.fid, 'max')]);+ const minV = Number(stats[getMeaAggKey(measure.fid, 'min')]);+ const signaled =+ Number.isFinite(stdev) &&+ stdev > 0 &&+ (Math.abs(mean - median) > 0.5 * stdev || maxV - median > 3 * stdev || median - minV > 3 * stdev);+ if (!signaled) continue;++ if (truncated) {+ explanations.push({+ type: 'extreme-value',+ score: Math.abs(mean - median) / stdev,+ strength: 'weak',+ field: measure,+ measure,+ descriptionKey: 'explain.extremeValue.truncated',+ descriptionParams: { measure: measure.name ?? measure.fid, rowCount: n },+ evidence: {},+ });+ continue;+ }++ const valueRows: { value: number; row: IRow }[] = rawRows+ .map((row) => ({ value: Number(row[measure.fid]), row }))+ .filter((x) => Number.isFinite(x.value));+ if (valueRows.length < MIN_ROWS) continue;+ const values = valueRows.map((x) => x.value);+ const { lowerFence, upperFence, outlierIndices } = detectIqrOutliers(values);+ if (outlierIndices.length === 0) continue;+ if (outlierIndices.length / values.length > MAX_OUTLIER_SHARE) continue; // long tail, not "a few bad rows"+ const { aggregateAll, aggregateWithout, impact } = outlierImpact(values, outlierIndices, agg);+ if (!Number.isFinite(impact) || impact < MIN_IMPACT) continue;++ const outlierSet = new Set(outlierIndices);+ explanations.push({+ type: 'extreme-value',+ score: impact,+ strength: strengthOf(impact),+ field: measure,+ measure,+ descriptionKey: 'explain.extremeValue.desc',+ descriptionParams: {+ measure: measure.name ?? measure.fid,+ agg,+ outlierCount: outlierIndices.length,+ rowCount: values.length,+ before: aggregateAll,+ after: aggregateWithout,+ changePercent: Math.round(impact * 1000) / 10,+ },+ evidence: {+ rows: outlierIndices.slice(0, MAX_EVIDENCE_ROWS).map((i) => valueRows[i].row),+ chartSpec: histogramSpec(sampleForHistogram(values, outlierSet), lowerFence, upperFence, measure.name ?? measure.fid),+ },+ });+ }+ return explanations.sort((a, b) => b.score - a.score);+ },+};diff --git a/packages/graphic-walker/src/lib/explain/explainers/uniqueMark.ts b/packages/graphic-walker/src/lib/explain/explainers/uniqueMark.tsnew file mode 100644index 00000000..0dc6d309--- /dev/null+++ b/packages/graphic-walker/src/lib/explain/explainers/uniqueMark.ts@@ -0,0 +1,238 @@+import type { IRow, IViewField } from '../../../interfaces';+import { getMeaAggKey } from '../../../utils';+import { gTestPValue, jsDistance, laplaceSmooth, subtractMass } from '../stats/divergence';+import { ADDITIVE_SAFE_AGGS, EXPLAIN_COUNT_KEY, complementaryDimensions, isMarkRow, markLevelQuery } from '../queries';+import type { IExplainContext, IExplainer, IExplanation, IExplanationStrength } from '../types';++/**+ * D-class explainer: what is unique about this mark?+ *+ * Compares the selected mark's composition over each unvisualized dimension+ * against the SIBLINGS (all other marks), not the parent that contains the+ * mark itself. Framed as an exploratory clue, ranked below A/B/C evidence.+ *+ * Shares its per-candidate queries with the contributing-dimension explainer+ * (same markLevelQuery builder → engine-level dedup).+ *+ * SCORING-FROZEN for the executor agent (see docs/explain-data-worklog.md §1).+ */++const MIN_MARK_ROWS = 20;+const MAX_CATEGORIES = 12; // collapse the tail into __other__ beyond this+const COUNT_P_THRESHOLD = 0.01;+const COUNT_JS_THRESHOLD = 0.15;+const MEASURE_JS_THRESHOLD = 0.25;+const MAX_RESULTS = 5;+const SMOOTH_ALPHA = 0.5;+/**+ * Guard against row-level outlier leakage: if one category's per-row mean is+ * this many times the median per-row mean, the mass concentration is likely+ * driven by a few extreme records — that is the extreme-value explainer's+ * territory, and reporting it here as "unique composition" would be a false+ * insight on every unrelated dimension.+ */+const ROW_DOMINANCE_RATIO = 10;+export const OTHER_CATEGORY = '__other__';++interface ICandidateComposition {+ categories: (string | number)[];+ markCounts: number[];+ siblingCounts: number[];+ /** per view-measure fid: additive sum masses */+ markSums: Map<string, number[]>;+ siblingSums: Map<string, number[]>;+}++function formatCategory(value: unknown): string | number {+ if (Array.isArray(value) && value.length === 2 && typeof value[0] === 'number') {+ // bin transform emits [lo, hi]+ return `${Number(value[0].toFixed(2))}–${Number(value[1].toFixed(2))}`;+ }+ return value as string | number;+}++function buildComposition(ctx: IExplainContext, rows: IRow[], candidateKey: string, measureFids: string[]): ICandidateComposition | null {+ type Bucket = { total: number; mark: number; totalSums: number[]; markSums: number[] };+ const buckets = new Map<string | number, Bucket>();+ for (const row of rows) {+ const category = formatCategory(row[candidateKey]);+ if (category === undefined || category === null) continue;+ let bucket = buckets.get(category);+ if (!bucket) {+ bucket = { total: 0, mark: 0, totalSums: measureFids.map(() => 0), markSums: measureFids.map(() => 0) };+ buckets.set(category, bucket);+ }+ const rowCount = Number(row[EXPLAIN_COUNT_KEY]) || 0;+ const mark = isMarkRow(row, ctx);+ bucket.total += rowCount;+ if (mark) bucket.mark += rowCount;+ measureFids.forEach((fid, i) => {+ const v = Number(row[getMeaAggKey(fid, 'sum')]) || 0;+ bucket!.totalSums[i] += v;+ if (mark) bucket!.markSums[i] += v;+ });+ }+ if (buckets.size < 2) return null;++ // collapse the tail into __other__ so high-cardinality candidates stay comparable+ const entries = [...buckets.entries()].sort((a, b) => b[1].total - a[1].total);+ const kept = entries.slice(0, MAX_CATEGORIES);+ const tail = entries.slice(MAX_CATEGORIES);+ if (tail.length > 0) {+ const other: Bucket = { total: 0, mark: 0, totalSums: measureFids.map(() => 0), markSums: measureFids.map(() => 0) };+ for (const [, b] of tail) {+ other.total += b.total;+ other.mark += b.mark;+ b.totalSums.forEach((v, i) => (other.totalSums[i] += v));+ b.markSums.forEach((v, i) => (other.markSums[i] += v));+ }+ kept.push([OTHER_CATEGORY, other]);+ }++ const categories = kept.map(([c]) => c);+ const markCounts = kept.map(([, b]) => b.mark);+ const totalCounts = kept.map(([, b]) => b.total);+ const siblingCounts = subtractMass(totalCounts, markCounts);+ const markSums = new Map<string, number[]>();+ const siblingSums = new Map<string, number[]>();+ measureFids.forEach((fid, i) => {+ const mark = kept.map(([, b]) => b.markSums[i]);+ const total = kept.map(([, b]) => b.totalSums[i]);+ markSums.set(fid, mark);+ // negative sums make "share of mass" meaningless — flag by storing null-ish+ if (mark.some((v) => v < 0) || total.some((v, j) => v - mark[j] < -1e-9)) {+ siblingSums.set(fid, []);+ } else {+ siblingSums.set(fid, subtractMass(total, mark));+ }+ });+ return { categories, markCounts, siblingCounts, markSums, siblingSums };+}++function strengthOf(js: number): IExplanationStrength {+ if (js >= 0.4) return 'strong';+ if (js >= 0.25) return 'moderate';+ return 'weak';+}++function compositionSpec(+ categories: (string | number)[],+ markShares: number[],+ siblingShares: number[],+ candidateName: string+): Record<string, unknown> {+ const values = categories.flatMap((category, i) => [+ { category: String(category), group: 'selected', share: markShares[i] },+ { category: String(category), group: 'siblings', share: siblingShares[i] },+ ]);+ return {+ width: 320,+ height: 180,+ data: { values },+ mark: { type: 'bar' },+ encoding: {+ x: { field: 'category', type: 'nominal', title: candidateName, sort: null },+ xOffset: { field: 'group' },+ y: { field: 'share', type: 'quantitative', title: 'share', axis: { format: '.0%' } },+ color: { field: 'group', type: 'nominal', legend: { orient: 'bottom', title: null } },+ },+ };+}++export const uniqueMarkExplainer: IExplainer = {+ type: 'unique-mark',++ isApplicable(ctx) {+ if (Object.keys(ctx.selectedMark).length === 0 || ctx.viewDimensions.length === 0) {+ return { applicable: false, reason: 'explain.skip.noMark' };+ }+ if (complementaryDimensions(ctx).length === 0) {+ return { applicable: false, reason: 'explain.skip.noCandidates' };+ }+ return { applicable: true };+ },++ plan(ctx) {+ return complementaryDimensions(ctx).map((candidate) => markLevelQuery(ctx, candidate).payload);+ },++ analyze(ctx, results) {+ const candidates = complementaryDimensions(ctx);+ const measureFids = [+ ...new Set(ctx.viewMeasures.filter((m) => ADDITIVE_SAFE_AGGS.has(m.aggName ?? 'sum')).map((m) => m.fid)),+ ];+ const explanations: IExplanation[] = [];++ candidates.forEach((candidate, index) => {+ const rows = results[index];+ if (!rows || rows.length === 0) return;+ const { candidateKey } = markLevelQuery(ctx, candidate);+ const composition = buildComposition(ctx, rows, candidateKey, measureFids);+ if (!composition) return;+ const { categories, markCounts, siblingCounts, markSums, siblingSums } = composition;+ const markN = markCounts.reduce((a, b) => a + b, 0);+ const siblingN = siblingCounts.reduce((a, b) => a + b, 0);+ if (markN < MIN_MARK_ROWS || siblingN < MIN_MARK_ROWS) return;++ const markProbs = laplaceSmooth(markCounts, SMOOTH_ALPHA);+ const siblingProbs = laplaceSmooth(siblingCounts, SMOOTH_ALPHA);++ let best: IExplanation | null = null;++ // count-based composition: statistically testable, preferred+ const countJs = jsDistance(markProbs, siblingProbs);+ const p = gTestPValue(markCounts, siblingProbs);+ if (p < COUNT_P_THRESHOLD && countJs > COUNT_JS_THRESHOLD) {+ const topIdx = markProbs.reduce((maxI, v, i) => (v - siblingProbs[i] > markProbs[maxI] - siblingProbs[maxI] ? i : maxI), 0);+ best = {+ type: 'unique-mark',+ score: countJs,+ strength: strengthOf(countJs),+ field: candidate,+ descriptionKey: 'explain.uniqueMark.countDesc',+ descriptionParams: {+ dimension: candidate.name ?? candidate.fid,+ topCategory: String(categories[topIdx]),+ markShare: Math.round(markProbs[topIdx] * 1000) / 10,+ siblingShare: Math.round(siblingProbs[topIdx] * 1000) / 10,+ pValue: p < 1e-4 ? '<0.0001' : String(Math.round(p * 10000) / 10000),+ },+ evidence: { chartSpec: compositionSpec(categories, markProbs, siblingProbs, candidate.name ?? candidate.fid) },+ };+ }++ // measure-mass composition: heuristic (no significance test), higher bar+ for (const fid of measureFids) {+ const markMass = markSums.get(fid) ?? [];+ const siblingMass = siblingSums.get(fid) ?? [];+ if (markMass.length === 0 || siblingMass.length === 0) continue; // negative-mass fallback+ // row-dominance guard: per-category per-row means within the mark+ const perRowMeans = markMass.map((v, i) => (markCounts[i] > 0 ? v / markCounts[i] : NaN)).filter((v) => Number.isFinite(v));+ if (perRowMeans.length >= 2) {+ const sortedMeans = [...perRowMeans].sort((a, b) => a - b);+ const medianMean = sortedMeans[Math.floor(sortedMeans.length / 2)];+ if (medianMean > 0 && Math.max(...perRowMeans) / medianMean > ROW_DOMINANCE_RATIO) continue;+ }+ const pm = laplaceSmooth(markMass, SMOOTH_ALPHA);+ const qm = laplaceSmooth(siblingMass, SMOOTH_ALPHA);+ const js = jsDistance(pm, qm);+ if (js <= MEASURE_JS_THRESHOLD || js <= (best?.score ?? 0)) continue;+ const measure = ctx.viewMeasures.find((m) => m.fid === fid)!;+ best = {+ type: 'unique-mark',+ score: js,+ strength: strengthOf(js),+ field: candidate,+ measure,+ descriptionKey: 'explain.uniqueMark.measureDesc',+ descriptionParams: { dimension: candidate.name ?? candidate.fid, measure: measure.name ?? fid },+ evidence: { chartSpec: compositionSpec(categories, pm, qm, candidate.name ?? candidate.fid) },+ };+ }++ if (best) explanations.push(best);+ });++ return explanations.sort((a, b) => b.score - a.score).slice(0, MAX_RESULTS);+ },+};diff --git a/packages/graphic-walker/src/lib/explain/golden.test.ts b/packages/graphic-walker/src/lib/explain/golden.test.tsnew file mode 100644index 00000000..7c7f8c31--- /dev/null+++ b/packages/graphic-walker/src/lib/explain/golden.test.ts@@ -0,0 +1,138 @@+import type { IRow, IViewField } from '../../interfaces';+import { getTestComputation as getComputation } from './testUtils';+import { explainMarkAll } from './engine';+import { extremeValueExplainer } from './explainers/extremeValue';+import { uniqueMarkExplainer } from './explainers/uniqueMark';+import type { IExplainContext } from './types';++/**+ * Golden-standard end-to-end tests: synthetic datasets with PLANTED signals,+ * executed through the real workflow-DSL client computation+ * (plan → dataQueryClient → analyze). The noise-control suite asserts zero+ * output on clean data — thresholds must not be relaxed to make signals pass.+ */++const field = (fid: string, analyticType: 'dimension' | 'measure', semanticType: 'nominal' | 'quantitative', aggName?: string): IViewField =>+ ({ fid, name: fid, analyticType, semanticType, aggName } as unknown as IViewField);++const REGION = field('region', 'dimension', 'nominal');+const CHANNEL = field('channel', 'dimension', 'nominal');+const NOISE_DIM = field('noise_dim', 'dimension', 'nominal');+const AGE = field('age', 'dimension', 'quantitative');+const SALES = field('sales', 'measure', 'quantitative', 'mean');++const ALL_FIELDS = [REGION, CHANNEL, NOISE_DIM, AGE, SALES];++const REGIONS = ['A', 'B', 'C', 'D'];+const ROWS_PER_REGION = 50;++/**+ * Deterministic dataset, 200 rows.+ * Planted signals (only when `planted` is true):+ * - region B row #0 has sales = 10000 (extreme value distorting mean)+ * - region B is 80% online channel; other regions 30% (unique composition)+ * Uniform everywhere (must never trigger):+ * - noise_dim cycles 5 values identically in every region+ * - age cycles 21..60 identically in every region+ */+function makeDataset(planted: boolean): IRow[] {+ const rows: IRow[] = [];+ for (const region of REGIONS) {+ for (let i = 0; i < ROWS_PER_REGION; i++) {+ const onlineShare = planted && region === 'B' ? 0.8 : 0.3;+ rows.push({+ region,+ channel: i < ROWS_PER_REGION * onlineShare ? 'online' : 'offline',+ noise_dim: `n${i % 5}`,+ age: 21 + (i % 40),+ sales: planted && region === 'B' && i === 0 ? 10000 : 50 + (i % 20),+ });+ }+ }+ return rows;+}++function makeContext(mark: string): IExplainContext {+ return {+ allFields: ALL_FIELDS,+ viewDimensions: [REGION],+ viewMeasures: [SALES],+ viewFilters: [],+ selectedMark: { region: mark },+ };+}++const EXPLAINERS = [extremeValueExplainer, uniqueMarkExplainer];++describe('golden: planted signals are found', () => {+ const computation = getComputation(makeDataset(true));++ it('extreme value: the 10000-sales record distorting region B mean is detected as strong', async () => {+ const results = await explainMarkAll(makeContext('B'), computation, EXPLAINERS);+ const extreme = results.find((r) => r.explainer === 'extreme-value')!;+ expect(extreme.status).toBe('ok');+ expect(extreme.explanations).toHaveLength(1);+ const ex = extreme.explanations[0];+ expect(ex.strength).toBe('strong');+ expect(ex.evidence.rows?.some((r) => r.sales === 10000)).toBe(true);+ // removing the bad record must restore a plausible mean+ expect(Number(ex.descriptionParams.after)).toBeLessThan(100);+ expect(Number(ex.descriptionParams.before)).toBeGreaterThan(200);+ });++ it('unique mark: region B channel composition (80% vs 30% online) is detected', async () => {+ const results = await explainMarkAll(makeContext('B'), computation, EXPLAINERS);+ const unique = results.find((r) => r.explainer === 'unique-mark')!;+ expect(unique.status).toBe('ok');+ const channelExp = unique.explanations.find((e) => e.field.fid === 'channel');+ expect(channelExp).toBeDefined();+ expect(['strong', 'moderate']).toContain(channelExp!.strength);+ });++ it('uniform fields never appear as explanations (false-positive control)', async () => {+ const results = await explainMarkAll(makeContext('B'), computation, EXPLAINERS);+ const unique = results.find((r) => r.explainer === 'unique-mark')!;+ const fids = unique.explanations.map((e) => e.field.fid);+ expect(fids).not.toContain('noise_dim');+ expect(fids).not.toContain('age');+ });+});++describe('golden: clean data produces zero explanations (noise control)', () => {+ const computation = getComputation(makeDataset(false));++ it.each(REGIONS)('region %s: no explanations of any type', async (region) => {+ const results = await explainMarkAll(makeContext(region), computation, EXPLAINERS);+ for (const result of results) {+ expect(result.status).toBe('ok');+ expect(result.explanations).toHaveLength(0);+ }+ });+});++describe('golden: guardrails', () => {+ it('marks with too few rows produce no unique-mark explanations', async () => {+ // 10 rows per region: below MIN_MARK_ROWS+ const tiny: IRow[] = [];+ for (const region of REGIONS) {+ for (let i = 0; i < 10; i++) {+ tiny.push({ region, channel: region === 'B' ? 'online' : 'offline', noise_dim: `n${i % 5}`, age: 30, sales: 50 + i });+ }+ }+ const results = await explainMarkAll(makeContext('B'), getComputation(tiny), EXPLAINERS);+ const unique = results.find((r) => r.explainer === 'unique-mark')!;+ expect(unique.explanations).toHaveLength(0);+ });++ it('temporal marks skip the extreme-value explainer with a reason', async () => {+ const TEMPORAL_DIM = { ...REGION, fid: 'date', name: 'date', semanticType: 'temporal' } as unknown as IViewField;+ const ctx: IExplainContext = {+ ...makeContext('B'),+ viewDimensions: [TEMPORAL_DIM],+ selectedMark: { date: '2024-01-01' },+ };+ const results = await explainMarkAll(ctx, getComputation(makeDataset(true)), [extremeValueExplainer]);+ expect(results[0].status).toBe('skipped');+ expect(results[0].reason).toBe('explain.skip.temporalMark');+ });+});diff --git a/packages/graphic-walker/src/lib/explain/index.ts b/packages/graphic-walker/src/lib/explain/index.tsnew file mode 100644index 00000000..120f5d06--- /dev/null+++ b/packages/graphic-walker/src/lib/explain/index.ts@@ -0,0 +1,15 @@+export * from './types';+export { explainMark, explainMarkAll } from './engine';+export { extremeValueExplainer } from './explainers/extremeValue';+export { uniqueMarkExplainer } from './explainers/uniqueMark';++import type { IExplainer } from './types';+import { extremeValueExplainer } from './explainers/extremeValue';+import { uniqueMarkExplainer } from './explainers/uniqueMark';++/**+ * Registered explainers in display-priority order:+ * data-quality evidence first, exploratory clues last.+ * (M2 adds contributing-dimension / contributing-measure between them.)+ */+export const defaultExplainers: IExplainer[] = [extremeValueExplainer, uniqueMarkExplainer];diff --git a/packages/graphic-walker/src/lib/explain/queries.ts b/packages/graphic-walker/src/lib/explain/queries.tsnew file mode 100644index 00000000..d0161502--- /dev/null+++ b/packages/graphic-walker/src/lib/explain/queries.ts@@ -0,0 +1,200 @@+import type { IDataQueryPayload, IDataQueryWorkflowStep, IExpression, IRow, IViewField, IVisFilter } from '../../interfaces';+import { COUNT_FIELD_ID, MEA_KEY_ID, MEA_VAL_ID, PAINT_FIELD_ID } from '../../constants';+import { getMeaAggKey } from '../../utils';+import { addFilterForQuery, addTransformForQuery, createFilter, processExpression } from '../../utils/workflow';+import type { IExplainContext } from './types';++/**+ * Shared workflow-DSL query builders for all explainers.+ *+ * Explainers MUST build queries through these helpers: the engine dedupes+ * structurally identical payloads, so two explainers using the same builder+ * automatically share one query execution (this is how the contributing-+ * dimension and unique-mark explainers split a single scan per candidate).+ */++/** aggregate result key for the per-group row count */+export const EXPLAIN_COUNT_KEY = '__explain_row_count';++/** derived-field key used when a quantitative candidate dimension is binned */+export const explainBinKey = (fid: string) => `${fid}__explain_bin`;++const SPECIAL_FIDS = new Set<string>([COUNT_FIELD_ID, MEA_KEY_ID, MEA_VAL_ID, PAINT_FIELD_ID]);++export const QUANT_BIN_NUM = 10;++/** measure aggregators whose mass composition is meaningful for D/B class analysis */+export const ADDITIVE_SAFE_AGGS = new Set(['sum', 'mean', 'count']);++/**+ * Candidate dimensions for composition-based explainers: every dimension+ * field not in the view. Temporal candidates are excluded for now (drill+ * granularity selection is an open question, worklog §6.3).+ */+export function complementaryDimensions(ctx: IExplainContext): IViewField[] {+ const inView = new Set(ctx.viewDimensions.map((f) => f.fid));+ return ctx.allFields.filter(+ (f) => f.analyticType === 'dimension' && !inView.has(f.fid) && !SPECIAL_FIDS.has(f.fid) && f.semanticType !== 'temporal'+ );+}++/** transform entries for all computed fields the queries may reference */+function computedFieldTransforms(ctx: IExplainContext): { key: string; expression: IExpression }[] {+ return ctx.allFields+ .filter((f) => f.computed && f.expression && !(f.expression.op === 'expr' && f.aggName === 'expr'))+ .map((f) => ({+ key: f.fid,+ expression: processExpression(f.expression!, ctx.allFields, { timezoneDisplayOffset: ctx.timezoneDisplayOffset }),+ }));+}++/** resolved row-level view filters (aggregate-level filters are not supported here) */+function resolvedViewFilters(ctx: IExplainContext): IVisFilter[] {+ return ctx.viewFilters.filter((f) => f.rule && !f.enableAgg).map(createFilter);+}++/** equality filters pinning the selected mark, over the view dimensions */+export function markFilters(ctx: IExplainContext): IVisFilter[] {+ return ctx.viewDimensions+ .filter((d) => ctx.selectedMark[d.fid] !== undefined)+ .map((d) => ({ fid: d.fid, rule: { type: 'one of', value: [ctx.selectedMark[d.fid]] } }));+}++/** wrap a view step into a full payload: transforms first, then filters, then the view */+function assemble(ctx: IExplainContext, viewStep: IDataQueryWorkflowStep, opts?: { extraTransforms?: { key: string; expression: IExpression }[]; extraFilters?: IVisFilter[]; limit?: number }): IDataQueryPayload {+ let payload: IDataQueryPayload = { workflow: [viewStep] };+ if (opts?.limit) payload = { ...payload, limit: opts.limit };+ payload = addFilterForQuery(payload, [...resolvedViewFilters(ctx), ...(opts?.extraFilters ?? [])]);+ payload = addTransformForQuery(payload, [...computedFieldTransforms(ctx), ...(opts?.extraTransforms ?? [])]);+ return payload;+}++export interface IMarkLevelQuery {+ payload: IDataQueryPayload;+ /** the group-by key holding the candidate dimension's (possibly binned) value */+ candidateKey: string;+}++/**+ * The workhorse query shared by the contributing-dimension and unique-mark+ * explainers: group by [view dimensions..., candidate] over ALL marks,+ * fetching row counts plus per-measure sums. Sums and counts are additive,+ * so mark / siblings / totals are all derivable client-side from this one+ * result set.+ */+export function markLevelQuery(ctx: IExplainContext, candidate: IViewField): IMarkLevelQuery {+ const isQuant = candidate.semanticType === 'quantitative';+ const candidateKey = isQuant ? explainBinKey(candidate.fid) : candidate.fid;+ const extraTransforms = isQuant+ ? [+ {+ key: candidateKey,+ expression: {+ op: 'bin',+ as: candidateKey,+ num: QUANT_BIN_NUM,+ params: [{ type: 'field', value: candidate.fid }],+ } as unknown as IExpression,+ },+ ]+ : [];+ const measureFids = [...new Set(ctx.viewMeasures.filter((m) => m.fid !== COUNT_FIELD_ID && m.aggName !== 'expr').map((m) => m.fid))];+ const viewStep: IDataQueryWorkflowStep = {+ type: 'view',+ query: [+ {+ op: 'aggregate',+ groupBy: [...ctx.viewDimensions.map((d) => d.fid), candidateKey],+ measures: [+ { field: '*', agg: 'count', asFieldKey: EXPLAIN_COUNT_KEY },+ ...measureFids.map((fid) => ({ field: fid, agg: 'sum' as const, asFieldKey: getMeaAggKey(fid, 'sum') })),+ ],+ },+ ],+ };+ return { payload: assemble(ctx, viewStep, { extraTransforms }), candidateKey };+}++/**+ * Pre-screen aggregates for the selected mark: cheap distribution statistics+ * that decide whether fetching row-level data is worthwhile.+ */+export function markPrescreenQuery(ctx: IExplainContext, measureFids: string[]): IDataQueryPayload {+ const viewStep: IDataQueryWorkflowStep = {+ type: 'view',+ query: [+ {+ op: 'aggregate',+ groupBy: [],+ measures: [+ { field: '*', agg: 'count', asFieldKey: EXPLAIN_COUNT_KEY },+ ...measureFids.flatMap((fid) =>+ (['mean', 'median', 'stdev', 'min', 'max'] as const).map((agg) => ({+ field: fid,+ agg,+ asFieldKey: getMeaAggKey(fid, agg),+ }))+ ),+ ],+ },+ ],+ };+ return assemble(ctx, viewStep, { extraFilters: markFilters(ctx) });+}++/** row-level values of the selected mark, for IQR outlier analysis */+export function markRawQuery(ctx: IExplainContext, fields: string[], limit: number): IDataQueryPayload {+ const viewStep: IDataQueryWorkflowStep = {+ type: 'view',+ query: [{ op: 'raw', fields }],+ };+ return assemble(ctx, viewStep, { extraFilters: markFilters(ctx), limit });+}++/**+ * Marks-level aggregation at the view's level of detail, carrying the view+ * measures plus candidate (unvisualized) measures — the single query behind+ * the contributing-measure explainer.+ */+export function marksWithMeasuresQuery(ctx: IExplainContext, candidateMeasureFids: string[]): IDataQueryPayload {+ const viewMeasureFids = [...new Set(ctx.viewMeasures.filter((m) => m.fid !== COUNT_FIELD_ID && m.aggName !== 'expr').map((m) => m.fid))];+ const fids = [...new Set([...viewMeasureFids, ...candidateMeasureFids])];+ const viewStep: IDataQueryWorkflowStep = {+ type: 'view',+ query: [+ {+ op: 'aggregate',+ groupBy: ctx.viewDimensions.map((d) => d.fid),+ measures: [+ { field: '*', agg: 'count', asFieldKey: EXPLAIN_COUNT_KEY },+ ...fids.map((fid) => ({ field: fid, agg: 'sum' as const, asFieldKey: getMeaAggKey(fid, 'sum') })),+ ],+ },+ ],+ };+ return assemble(ctx, viewStep);+}++/** does this aggregated row belong to the selected mark? */+export function isMarkRow(row: IRow, ctx: IExplainContext): boolean {+ return ctx.viewDimensions.every((d) => {+ const expected = ctx.selectedMark[d.fid];+ if (expected === undefined) return true;+ const actual = row[d.fid];+ // grouped values may come back as numbers vs strings depending on the+ // computation backend; compare loosely via string form+ return actual === expected || String(actual) === String(expected);+ });+}++/** stable stringify with sorted object keys — the engine's dedup key */+export function stableStringify(value: unknown): string {+ if (Array.isArray(value)) {+ return `[${value.map(stableStringify).join(',')}]`;+ }+ if (value && typeof value === 'object') {+ const keys = Object.keys(value as Record<string, unknown>).sort();+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify((value as Record<string, unknown>)[k])}`).join(',')}}`;+ }+ return JSON.stringify(value);+}diff --git a/packages/graphic-walker/src/lib/explain/stats/divergence.test.ts b/packages/graphic-walker/src/lib/explain/stats/divergence.test.tsnew file mode 100644index 00000000..e72f1f3b--- /dev/null+++ b/packages/graphic-walker/src/lib/explain/stats/divergence.test.ts@@ -0,0 +1,103 @@+import { laplaceSmooth, jsDivergence, jsDistance, subtractMass, chiSquareUpperTail, gTestPValue, logGamma } from './divergence';++describe('laplaceSmooth', () => {+ it('normalizes to a probability vector', () => {+ const p = laplaceSmooth([10, 20, 30]);+ expect(p.reduce((a, b) => a + b, 0)).toBeCloseTo(1, 10);+ });+ it('gives zero-mass categories non-zero probability', () => {+ const p = laplaceSmooth([0, 100]);+ expect(p[0]).toBeGreaterThan(0);+ expect(p[0]).toBeLessThan(p[1]);+ });+ it('handles an all-zero vector as uniform', () => {+ const p = laplaceSmooth([0, 0, 0, 0], 0);+ expect(p).toEqual([0.25, 0.25, 0.25, 0.25]);+ });+});++describe('jsDivergence / jsDistance', () => {+ it('is 0 for identical distributions', () => {+ expect(jsDivergence([0.2, 0.3, 0.5], [0.2, 0.3, 0.5])).toBeCloseTo(0, 10);+ });+ it('is 1 for disjoint distributions (bounded above)', () => {+ expect(jsDivergence([1, 0], [0, 1])).toBeCloseTo(1, 10);+ });+ it('counts single-sided zero categories by definition (the old implementation skipped them)', () => {+ // mark concentrated in a category siblings never hit: strong signal+ const withZeros = jsDivergence([0.9, 0.1, 0], [0, 0.1, 0.9]);+ expect(withZeros).toBeGreaterThan(0.8);+ });+ it('is symmetric', () => {+ const p = [0.7, 0.2, 0.1];+ const q = [0.1, 0.3, 0.6];+ expect(jsDivergence(p, q)).toBeCloseTo(jsDivergence(q, p), 12);+ });+ it('is bounded in [0, 1] for arbitrary inputs', () => {+ for (let trial = 0; trial < 50; trial++) {+ // deterministic pseudo-random via simple LCG+ let seed = trial * 2654435761 + 1;+ const next = () => ((seed = (seed * 1664525 + 1013904223) >>> 0), seed / 2 ** 32);+ const raw1 = Array.from({ length: 6 }, next);+ const raw2 = Array.from({ length: 6 }, next);+ const p = laplaceSmooth(raw1, 0);+ const q = laplaceSmooth(raw2, 0);+ const d = jsDivergence(p, q);+ expect(d).toBeGreaterThanOrEqual(0);+ expect(d).toBeLessThanOrEqual(1);+ }+ });+ it('a concentrated distribution scores HIGHER than a mildly different one (regression for the coverage-weight bug)', () => {+ const siblings = laplaceSmooth([25, 25, 25, 25], 0);+ const concentrated = laplaceSmooth([100, 0, 0, 0], 0);+ const mild = laplaceSmooth([30, 26, 24, 20], 0);+ expect(jsDistance(concentrated, siblings)).toBeGreaterThan(jsDistance(mild, siblings));+ });+});++describe('subtractMass', () => {+ it('derives siblings from totals', () => {+ expect(subtractMass([10, 20, 30], [1, 20, 5])).toEqual([9, 0, 25]);+ });+ it('clamps float noise at zero', () => {+ expect(subtractMass([1], [1.0000001])[0]).toBe(0);+ });+});++describe('logGamma', () => {+ it('matches known factorials', () => {+ expect(Math.exp(logGamma(5))).toBeCloseTo(24, 6); // Γ(5) = 4!+ expect(Math.exp(logGamma(1))).toBeCloseTo(1, 10);+ expect(Math.exp(logGamma(0.5))).toBeCloseTo(Math.sqrt(Math.PI), 8);+ });+});++describe('chiSquareUpperTail', () => {+ it('matches standard critical values', () => {+ // classic table values+ expect(chiSquareUpperTail(3.841, 1)).toBeCloseTo(0.05, 3);+ expect(chiSquareUpperTail(5.991, 2)).toBeCloseTo(0.05, 3);+ expect(chiSquareUpperTail(16.919, 9)).toBeCloseTo(0.05, 3);+ expect(chiSquareUpperTail(6.635, 1)).toBeCloseTo(0.01, 3);+ });+ it('is 1 at x = 0 and decreasing in x', () => {+ expect(chiSquareUpperTail(0, 3)).toBe(1);+ expect(chiSquareUpperTail(1, 3)).toBeGreaterThan(chiSquareUpperTail(5, 3));+ });+});++describe('gTestPValue', () => {+ it('is non-significant when the mark matches the reference composition', () => {+ const p = gTestPValue([25, 25, 25, 25], [0.25, 0.25, 0.25, 0.25]);+ expect(p).toBeGreaterThan(0.9);+ });+ it('is highly significant for a strongly skewed mark with adequate sample size', () => {+ const p = gTestPValue([90, 5, 5, 0], [0.25, 0.25, 0.25, 0.25]);+ expect(p).toBeLessThan(1e-6);+ });+ it('does not flag tiny samples (guards the "2-row mark" failure mode)', () => {+ // 3 observations can look extreme but must not reach p < 0.01+ const p = gTestPValue([3, 0, 0, 0], [0.25, 0.25, 0.25, 0.25]);+ expect(p).toBeGreaterThan(0.01);+ });+});diff --git a/packages/graphic-walker/src/lib/explain/stats/divergence.ts b/packages/graphic-walker/src/lib/explain/stats/divergence.tsnew file mode 100644index 00000000..40cc54e6--- /dev/null+++ b/packages/graphic-walker/src/lib/explain/stats/divergence.ts@@ -0,0 +1,165 @@+/**+ * Statistical kernel for the Explain Data module.+ *+ * FROZEN for the executor agent: do not modify scoring logic here.+ * See docs/explain-data-worklog.md §1.+ */++/**+ * Laplace-smooth a non-negative mass vector into a probability vector.+ * alpha adds pseudo-mass to every category so small samples do not+ * produce spuriously extreme distributions.+ */+export function laplaceSmooth(mass: number[], alpha = 0.5): number[] {+ const total = mass.reduce((acc, v) => acc + v, 0) + alpha * mass.length;+ if (total <= 0) {+ return mass.map(() => 1 / Math.max(mass.length, 1));+ }+ return mass.map((v) => (v + alpha) / total);+}++/**+ * Jensen–Shannon divergence (base 2) between two aligned probability vectors.+ * Zero-probability categories contribute by definition (0·log0 = 0; the+ * non-zero side contributes 0.5·p). Bounded in [0, 1].+ */+export function jsDivergence(p: number[], q: number[]): number {+ if (p.length !== q.length) {+ throw new Error(`jsDivergence: length mismatch (${p.length} vs ${q.length})`);+ }+ let score = 0;+ for (let i = 0; i < p.length; i++) {+ const pi = p[i];+ const qi = q[i];+ if (pi === 0 && qi === 0) continue;+ const m = 0.5 * (pi + qi);+ if (pi > 0) score += 0.5 * pi * Math.log2(pi / m);+ if (qi > 0) score += 0.5 * qi * Math.log2(qi / m);+ }+ // clamp numeric noise+ return Math.min(1, Math.max(0, score));+}++/**+ * Jensen–Shannon distance: sqrt of the divergence. A proper metric,+ * bounded in [0, 1] and comparable across candidate dimensions of+ * different cardinalities.+ */+export function jsDistance(p: number[], q: number[]): number {+ return Math.sqrt(jsDivergence(p, q));+}++/**+ * Element-wise `total − part`, clamped at 0 (guards float noise).+ * Used to derive the siblings distribution from the all-marks totals+ * without an extra query; valid for additive masses (counts, sums).+ */+export function subtractMass(total: number[], part: number[]): number[] {+ if (total.length !== part.length) {+ throw new Error(`subtractMass: length mismatch (${total.length} vs ${part.length})`);+ }+ return total.map((t, i) => Math.max(0, t - part[i]));+}++const LANCZOS_G = 7;+const LANCZOS_COEFFS = [+ 0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012,+ 9.9843695780195716e-6, 1.5056327351493116e-7,+];++/** log Γ(x) via Lanczos approximation, x > 0. */+export function logGamma(x: number): number {+ if (x < 0.5) {+ // reflection formula+ return Math.log(Math.PI / Math.sin(Math.PI * x)) - logGamma(1 - x);+ }+ const z = x - 1;+ let acc = LANCZOS_COEFFS[0];+ for (let i = 1; i < LANCZOS_G + 2; i++) {+ acc += LANCZOS_COEFFS[i] / (z + i);+ }+ const t = z + LANCZOS_G + 0.5;+ return 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(acc);+}++const MAX_ITER = 300;+const EPS = 1e-12;++/** Regularized lower incomplete gamma P(a, x) by series expansion (x < a + 1). */+function lowerGammaSeries(a: number, x: number): number {+ let term = 1 / a;+ let sum = term;+ for (let n = 1; n < MAX_ITER; n++) {+ term *= x / (a + n);+ sum += term;+ if (Math.abs(term) < Math.abs(sum) * EPS) break;+ }+ return sum * Math.exp(-x + a * Math.log(x) - logGamma(a));+}++/** Regularized upper incomplete gamma Q(a, x) by continued fraction (x ≥ a + 1). */+function upperGammaCF(a: number, x: number): number {+ let b = x + 1 - a;+ let c = 1 / 1e-300;+ let d = 1 / b;+ let h = d;+ for (let i = 1; i < MAX_ITER; i++) {+ const an = -i * (i - a);+ b += 2;+ d = an * d + b;+ if (Math.abs(d) < 1e-300) d = 1e-300;+ c = b + an / c;+ if (Math.abs(c) < 1e-300) c = 1e-300;+ d = 1 / d;+ const del = d * c;+ h *= del;+ if (Math.abs(del - 1) < EPS) break;+ }+ return h * Math.exp(-x + a * Math.log(x) - logGamma(a));+}++/**+ * Upper-tail probability of the chi-square distribution:+ * P(X ≥ x) for X ~ χ²(df).+ */+export function chiSquareUpperTail(x: number, df: number): number {+ if (x <= 0) return 1;+ if (df <= 0) throw new Error('chiSquareUpperTail: df must be positive');+ const a = df / 2;+ const half = x / 2;+ if (half < a + 1) {+ return Math.min(1, Math.max(0, 1 - lowerGammaSeries(a, half)));+ }+ return Math.min(1, Math.max(0, upperGammaCF(a, half)));+}++/**+ * G-test of goodness of fit: are the observed category counts consistent+ * with the expected probabilities?+ *+ * @param observed raw counts for the selected mark, aligned with expectedProbs+ * @param expectedProbs probability vector (e.g. smoothed sibling shares)+ * @returns p-value; small p ⇒ the mark's composition differs significantly+ */+export function gTestPValue(observed: number[], expectedProbs: number[]): number {+ if (observed.length !== expectedProbs.length) {+ throw new Error(`gTestPValue: length mismatch (${observed.length} vs ${expectedProbs.length})`);+ }+ const n = observed.reduce((acc, v) => acc + v, 0);+ if (n <= 0 || observed.length < 2) return 1;+ let g = 0;+ for (let i = 0; i < observed.length; i++) {+ const obs = observed[i];+ if (obs <= 0) continue;+ const expected = expectedProbs[i] * n;+ if (expected <= 0) {+ // observed mass where the reference assigns none: infinitely surprising+ // under the model; cap via a tiny expected mass instead of Infinity.+ g += 2 * obs * Math.log(obs / (EPS * n));+ continue;+ }+ g += 2 * obs * Math.log(obs / expected);+ }+ const df = observed.length - 1;+ return chiSquareUpperTail(Math.max(0, g), df);+}diff --git a/packages/graphic-walker/src/lib/explain/stats/quantile.test.ts b/packages/graphic-walker/src/lib/explain/stats/quantile.test.tsnew file mode 100644index 00000000..c09df91a--- /dev/null+++ b/packages/graphic-walker/src/lib/explain/stats/quantile.test.ts@@ -0,0 +1,60 @@+import { quantileSorted, detectIqrOutliers, computeAggregate, outlierImpact } from './quantile';++describe('quantileSorted', () => {+ it('computes exact quartiles on aligned data', () => {+ const sorted = [1, 2, 3, 4, 5];+ expect(quantileSorted(sorted, 0.25)).toBe(2);+ expect(quantileSorted(sorted, 0.5)).toBe(3);+ expect(quantileSorted(sorted, 0.75)).toBe(4);+ });+ it('interpolates between values (type-7)', () => {+ expect(quantileSorted([1, 2, 3, 4], 0.5)).toBeCloseTo(2.5, 10);+ });+ it('handles boundaries and empty input', () => {+ expect(quantileSorted([7, 9], 0)).toBe(7);+ expect(quantileSorted([7, 9], 1)).toBe(9);+ expect(Number.isNaN(quantileSorted([], 0.5))).toBe(true);+ });+});++describe('detectIqrOutliers', () => {+ it('finds a planted extreme record', () => {+ const values = [...Array.from({ length: 40 }, (_, i) => 10 + (i % 5)), 10000];+ const res = detectIqrOutliers(values);+ expect(res.outlierIndices).toEqual([40]);+ });+ it('finds nothing on clean data', () => {+ const values = Array.from({ length: 50 }, (_, i) => 100 + (i % 10));+ expect(detectIqrOutliers(values).outlierIndices).toHaveLength(0);+ });+ it('detects low-side outliers too', () => {+ const values = [-5000, ...Array.from({ length: 40 }, (_, i) => 10 + (i % 5))];+ expect(detectIqrOutliers(values).outlierIndices).toEqual([0]);+ });+});++describe('computeAggregate', () => {+ it('matches hand-computed values', () => {+ expect(computeAggregate([1, 2, 3, 4], 'sum')).toBe(10);+ expect(computeAggregate([1, 2, 3, 4], 'mean')).toBe(2.5);+ expect(computeAggregate([2, 4, 4, 4, 5, 5, 7, 9], 'stdev')).toBeCloseTo(2.138, 3);+ expect(computeAggregate([2, 4, 4, 4, 5, 5, 7, 9], 'variance')).toBeCloseTo(4.571, 3);+ });+});++describe('outlierImpact', () => {+ it('quantifies how one extreme record distorts a mean (the Tableau L-sit example)', () => {+ const values = [...Array.from({ length: 40 }, () => 60), 10000];+ const { outlierIndices } = detectIqrOutliers(values);+ const { aggregateAll, aggregateWithout, impact } = outlierImpact(values, outlierIndices, 'mean');+ expect(aggregateWithout).toBeCloseTo(60, 6);+ expect(aggregateAll).toBeGreaterThan(290);+ expect(impact).toBeGreaterThan(0.5);+ });+ it('reports near-zero impact when outliers barely move the aggregate', () => {+ const values = [...Array.from({ length: 1000 }, (_, i) => 100 + (i % 7)), 160];+ const { outlierIndices } = detectIqrOutliers(values);+ const { impact } = outlierImpact(values, outlierIndices, 'sum');+ expect(impact).toBeLessThan(0.01);+ });+});diff --git a/packages/graphic-walker/src/lib/explain/stats/quantile.ts b/packages/graphic-walker/src/lib/explain/stats/quantile.tsnew file mode 100644index 00000000..e5729d43--- /dev/null+++ b/packages/graphic-walker/src/lib/explain/stats/quantile.ts@@ -0,0 +1,89 @@+/**+ * Quantile / IQR utilities for the extreme-value explainer.+ *+ * FROZEN for the executor agent: do not modify scoring logic here.+ * See docs/explain-data-worklog.md §1.+ */++/** Type-7 (linear interpolation) quantile of a pre-sorted ascending array. */+export function quantileSorted(sorted: number[], p: number): number {+ if (sorted.length === 0) return NaN;+ if (p <= 0) return sorted[0];+ if (p >= 1) return sorted[sorted.length - 1];+ const h = (sorted.length - 1) * p;+ const lo = Math.floor(h);+ const hi = Math.ceil(h);+ if (lo === hi) return sorted[lo];+ return sorted[lo] + (h - lo) * (sorted[hi] - sorted[lo]);+}++export interface IIqrOutlierResult {+ q1: number;+ q3: number;+ iqr: number;+ lowerFence: number;+ upperFence: number;+ /** indices into the ORIGINAL (unsorted) values array */+ outlierIndices: number[];+}++/** Tukey's fences: values beyond q1/q3 ± 1.5·IQR. */+export function detectIqrOutliers(values: number[], k = 1.5): IIqrOutlierResult {+ const sorted = [...values].sort((a, b) => a - b);+ const q1 = quantileSorted(sorted, 0.25);+ const q3 = quantileSorted(sorted, 0.75);+ const iqr = q3 - q1;+ const lowerFence = q1 - k * iqr;+ const upperFence = q3 + k * iqr;+ const outlierIndices: number[] = [];+ for (let i = 0; i < values.length; i++) {+ if (values[i] < lowerFence || values[i] > upperFence) {+ outlierIndices.push(i);+ }+ }+ return { q1, q3, iqr, lowerFence, upperFence, outlierIndices };+}++export type ISensitiveAggregator = 'sum' | 'mean' | 'stdev' | 'variance';++export function computeAggregate(values: number[], agg: ISensitiveAggregator): number {+ const n = values.length;+ if (n === 0) return NaN;+ const total = values.reduce((acc, v) => acc + v, 0);+ if (agg === 'sum') return total;+ const avg = total / n;+ if (agg === 'mean') return avg;+ const sq = values.reduce((acc, v) => acc + (v - avg) * (v - avg), 0);+ const variance = n > 1 ? sq / (n - 1) : 0;+ if (agg === 'variance') return variance;+ return Math.sqrt(variance);+}++export interface IOutlierImpact {+ /** aggregate over all values */+ aggregateAll: number;+ /** aggregate with outlier values removed */+ aggregateWithout: number;+ /** relative change in the aggregate caused by the outliers, in [0, ∞) */+ impact: number;+}++/**+ * How much do the outlier rows distort the aggregate the user is looking at?+ * `impact` is relative to the full aggregate; when the full aggregate is ~0,+ * the change is scaled by the values' dispersion instead so the ratio stays+ * meaningful.+ */+export function outlierImpact(values: number[], outlierIndices: number[], agg: ISensitiveAggregator): IOutlierImpact {+ const excluded = new Set(outlierIndices);+ const kept = values.filter((_, i) => !excluded.has(i));+ const aggregateAll = computeAggregate(values, agg);+ const aggregateWithout = kept.length > 0 ? computeAggregate(kept, agg) : NaN;+ let impact = 0;+ if (Number.isFinite(aggregateAll) && Number.isFinite(aggregateWithout)) {+ const change = Math.abs(aggregateAll - aggregateWithout);+ const denom = Math.abs(aggregateAll) > 1e-12 ? Math.abs(aggregateAll) : computeAggregate(values, 'stdev') || 1;+ impact = change / denom;+ }+ return { aggregateAll, aggregateWithout, impact };+}diff --git a/packages/graphic-walker/src/lib/explain/testUtils.ts b/packages/graphic-walker/src/lib/explain/testUtils.tsnew file mode 100644index 00000000..058cd8d4--- /dev/null+++ b/packages/graphic-walker/src/lib/explain/testUtils.ts@@ -0,0 +1,41 @@+import type { IComputationFunction, IDataQueryPayload, IRow } from '../../interfaces';+import { filter as applyFilter } from '../filter';+import { transformData } from '../transform';+import { queryView } from '../viewQuery';+import { sortBy } from '../sort';++/**+ * Worker-free computation function mirroring `dataQueryClient` semantics,+ * for tests only (the production client computation goes through vite+ * `?worker&inline` imports that jest cannot resolve).+ *+ * Keep step semantics in sync with computation/clientComputation.ts.+ */+export const getTestComputation = (rawData: IRow[]): IComputationFunction => {+ return async (payload: IDataQueryPayload) => {+ let res = rawData;+ for (const step of payload.workflow) {+ switch (step.type) {+ case 'filter':+ res = applyFilter(+ res,+ step.filters.map((f) => ({ fid: f.fid, rule: f.rule }))+ );+ break;+ case 'transform':+ res = await transformData(res, step.transform);+ break;+ case 'view':+ for (const job of step.query) {+ res = queryView(res, job);+ }+ break;+ case 'sort':+ res = sortBy(res, step.by, step.sort);+ break;+ }+ }+ const offset = payload.offset ?? 0;+ return res.slice(offset, payload.limit && payload.limit > 0 ? offset + payload.limit : undefined);+ };+};diff --git a/packages/graphic-walker/src/lib/explain/types.ts b/packages/graphic-walker/src/lib/explain/types.tsnew file mode 100644index 00000000..4c0ca216--- /dev/null+++ b/packages/graphic-walker/src/lib/explain/types.ts@@ -0,0 +1,94 @@+import type { IComputationFunction, IDataQueryPayload, IField, IFilterField, IRow, IViewField } from '../../interfaces';++/**+ * Explain Data module — shared contracts.+ *+ * INTERFACE-FROZEN for the executor agent: propose signature changes in+ * docs/explain-data-worklog.md §5 instead of editing this file.+ *+ * Architecture rule: explainers declare ALL data needs as workflow DSL+ * payloads via `plan()`; `analyze()` is a pure function of the query+ * results. No explainer may touch a data source directly — this is what+ * keeps the module working against both the in-browser computation and a+ * server-side computation service.+ */++export type IExplanationType = 'extreme-value' | 'contributing-dimension' | 'contributing-measure' | 'unique-mark';++export type IExplanationStrength = 'strong' | 'moderate' | 'weak';++export interface IExplainContext {+ /** all dataset fields (including ones not in the view) */+ allFields: IViewField[];+ /** dimensions currently in the view — these define the mark's level of detail */+ viewDimensions: IViewField[];+ /** measures currently in the view */+ viewMeasures: IViewField[];+ /** active view filters */+ viewFilters: IFilterField[];+ /** the clicked mark: view-dimension fid → value */+ selectedMark: Record<string, string | number>;+ timezoneDisplayOffset?: number;+}++export interface IExplanationEvidence {+ /** vega-lite spec, self-contained (inline data values); UI applies theme config only */+ chartSpec?: Record<string, unknown>;+ /** supporting rows, e.g. the outlier records */+ rows?: IRow[];+}++export interface IExplanation {+ type: IExplanationType;+ /** type-specific score; NOT comparable across types — rank within a type only */+ score: number;+ strength: IExplanationStrength;+ /** the explaining field */+ field: IField;+ /** the measure being explained, when applicable */+ measure?: IField;+ /** i18n key; UI must not hardcode explanation copy */+ descriptionKey: string;+ descriptionParams: Record<string, string | number>;+ evidence: IExplanationEvidence;+}++export interface IApplicability {+ applicable: boolean;+ /** i18n key explaining why the explainer was skipped */+ reason?: string;+}++export interface IExplainer {+ type: IExplanationType;+ isApplicable(ctx: IExplainContext): IApplicability;+ /**+ * Declare data needs as workflow DSL payloads. Must be deterministic for+ * a given context (the engine dedupes structurally identical payloads+ * across explainers). Build shared queries through `queries.ts` helpers+ * so deduplication actually fires.+ */+ plan(ctx: IExplainContext): IDataQueryPayload[];+ /**+ * Pure function: `results[i]` is the result set of `plan(ctx)[i]`.+ * Never issues queries of its own.+ */+ analyze(ctx: IExplainContext, results: IRow[][]): IExplanation[];+}++export interface IExplainerResult {+ explainer: IExplanationType;+ status: 'ok' | 'skipped' | 'error';+ /** i18n key when skipped; error message when errored */+ reason?: string;+ explanations: IExplanation[];+}++export interface IExplainOptions {+ /** max concurrent queries, default 4 */+ concurrency?: number;+ /** override the explainer set (defaults to all registered explainers) */+ explainers?: IExplainer[];+}++export type { IComputationFunction, IDataQueryPayload };