An open source alternative to Tableau. Embeddable visual analytic
TypeScript bidatadata-analysisdata-miningdata-visualizationedak6skanarieslow-codepivot-tablereacttableautableau-alternativetypescriptvegavega-litevisualization
feat: add workflow conformance suite
Elwynn Chen933d8d9eafe0
diff --git a/computation.md b/computation.mdindex ac6c9922..5dc5baaa 100644--- a/computation.md+++ b/computation.md@@ -1,518 +1,229 @@-# GraphicWalker View Data Computation+# Graphic Walker Workflow Computation Specification-Before the renderer generates the visualization, GraphicWalker applies an asynchronous workflow to compute the data to the view data which is directly used by the renderer. The computation workflow consists of a series of data queries, that describe how to compute the view data from the raw data. The computation workflow is not only used in the rendering phase, but also used in cases such as preview table, and filter editor when GraphicWalker requires the necessary statistics from the raw data.+This document is the normative specification for Graphic Walker view-data computation. An implementation is conforming when it evaluates every valid `IDataQueryPayload` according to the semantics below, independent of whether the backend is the client-side JavaScript executor or SQL generated by `@kanaries/gw-dsl-parser`.-## Computation Workflow+The workflow DSL is an execution IR, not a user authoring format. UI specs and future shorthand formats compile into this IR before computation starts.-The computation workflow contains 4 types of queries: filter query, transform query, view query, and sort query.--### Filter Query (optional)--The filter query is used to filter the raw data. It contains a list of filter fields, each of which contains a filter rule.+## 1. Request Model```ts-type IFilterRule = (- | {- type: 'range';- value: readonly [number, number];- }- | {- type: 'temporal range';- value: readonly [number, number];- }- | {- type: 'one of';- value: Array<any>;- }- | {- type: 'not in';- value: Array<any>;- }-);--interface IFilterField {- fid: string;- rule: IFilterRule;+export interface IDataQueryPayload {+ workflow: IDataQueryWorkflowStep[];+ tag?: string;+ limit?: number;+ offset?: number;}+```++A payload is evaluated against an ordered array of rows. Each row is a record keyed by field id (`fid`). Workflow steps are evaluated strictly in array order. The output of each step becomes the input to the next step.++`offset` and `limit` are applied after all workflow steps, including `sort`. `offset` defaults to `0`. A missing `limit`, `undefined`, `0`, or a negative UI sentinel means no upper bound. When `limit > 0`, the final slice is `[offset, offset + limit)`.++Workflow steps may include multiple `view` steps. They cascade exactly like any other step: the rows produced by the first `view` step are the rows consumed by the next step.++## 2. Value And Type Semantics++Missing fields evaluate to `undefined`. `null` and `undefined` are nullish values. Unless a rule below says otherwise, nullish input propagates to a nullish or failed result rather than being coerced to a useful value.-interface IFilterQuery {+Numeric operators coerce with JavaScript `Number(value)` semantics for strings and booleans when the value is explicitly converted by the workflow builder. Direct executor comparisons use the stored value; relational comparisons with nullish values fail. SQL backends must match these observable results, including numeric strings that participate in numeric arithmetic.++Boolean values used in numeric contexts coerce to `1` for `true` and `0` for `false`. Date strings are parsed by the offset-date model in section 4 when used by temporal operators. ISO strings with explicit timezone offsets are absolute instants. Date-only strings (`YYYY`, `YYYY-MM`, `YYYY-MM-DD`) are interpreted in the supplied parse offset, not as host-local dates.++Floating point comparisons in conformance tests use an absolute tolerance of `1e-9`. This tolerance covers IEEE-754 arithmetic and DuckDB decimal/float conversion differences; it is not large enough to hide different bin boundaries, different timestamps, or different aggregate formulas.++## 3. Filter Step++```ts+export interface IFilterWorkflowStep {type: 'filter';- filters: Array<IFilterField>;+ filters: IVisFilter[];}```-The schema of the filter query is--```json-{- "$schema": "http://json-schema.org/draft-07/schema#",- "type": "object",- "properties": {- "type": {- "type": "string",- "enum": [- "filter"- ]- },- "filters": {- "type": "array",- "items": {- "type": "object",- "properties": {- "fid": {- "type": "string"- },- "rule": {- "type": "object",- "oneOf": [- {- "properties": {- "type": {- "type": "string",- "enum": [- "range",- "temporal range"- ]- },- "value": {- "type": "array",- "items": {- "type": "number"- },- "minItems": 2,- "maxItems": 2- }- },- "required": [- "type",- "value"- ]- },- {- "properties": {- "type": {- "type": "string",- "enum": [- "one of",- "not in"- ]- },- "value": {- "type": "array",- "items": {- "oneOf": [- {- "type": "string"- },- {- "type": "number"- }- ]- }- }- },- "required": [- "type",- "value"- ]- }- ]- }- },- "required": [- "fid",- "rule"- ]- }- }- },- "required": [- "type",- "filters"- ]-}-```+All filters in a filter step are combined with logical AND. Input row order is preserved for rows that pass.-### Transform Query (optional)+### `range`-The transform query is used to resolve the field calculations. It contains a list of transform fields, each of which contains an expression.+`{ type: 'range', value: [min, max] }` passes a row when:```ts-type IExpParameter = (- | {- type: 'field';- value: string;- }- | {- type: 'value';- value: any; //- }- | {- type: 'expression';- value: IExpression;- }- | {- type: 'constant';- value: any;- }-);--interface IExpression {- op: 'bin' | 'one' | 'binCount'|'log';- params: IExpParameter[];- as: string;- num?:number;-}+(min ?? -Infinity) <= row[fid] && row[fid] <= (max ?? Infinity);+```-interface ITransformField {- key: string;- expression: IExpression;-}+Bounds are inclusive. A nullish row value fails the predicate. A null bound is open on that side.-interface ITransformQuery {- type: 'transform';- transform: Array<ITransformField>;-}-```+### `temporal range`-The schema of the transform query is--```json-{- "$schema": "http://json-schema.org/draft-07/schema#",- "type": "object",- "properties": {- "type": {- "type": "string",- "enum": [- "transform"- ]- },- "transform": {- "type": "array",- "items": {- "type": "object",- "properties": {- "key": {- "type": "string"- },- "expression": {- "type": "object",- "properties": {- "op": {- "type": "string",- "enum": [- "bin",- "log2",- "log10",- "one",- "binCount"- ]- },- "params": {- "type": "array",- "items": {- "type": "object",- "oneOf": [- {- "properties": {- "type": {- "type": "string",- "enum": [- "field"- ]- },- "value": {- "type": "string"- }- },- "required": [- "type",- "value"- ]- },- {- "properties": {- "type": {- "type": "string",- "enum": [- "value",- "constant"- ]- },- "value": {}- },- "required": [- "type",- "value"- ]- },- {- "properties": {- "type": {- "type": "string",- "enum": [- "expression"- ]- },- "value": {- "$ref": "#/properties/transform/items/properties/expression"- }- },- "required": [- "type",- "value"- ]- }- ]- }- },- "as": {- "type": "string"- }- },- "required": [- "op",- "params",- "as"- ]- }- },- "required": [- "key",- "expression"- ]- }- }- },- "required": [- "type",- "transform"- ]-}-```+`{ type: 'temporal range', value: [min, max], offset?, format? }` parses the row value with `newOffsetDate(offset)`, compares the resulting epoch milliseconds to inclusive bounds, and passes when the timestamp is inside the range. A nullish or unparseable row value fails. `format` is metadata and does not change runtime parsing.++### `one of`++`{ type: 'one of', value }` passes when the encoded row value is equal to one encoded member of `value`. Encoding is `_unstable_encodeRuleValue`: objects and arrays are compared by their encoded representation, not by reference identity. Nullish values pass only when the set contains the same nullish encoded value.-### View Query (required)+### `not in`-The view query is used to shape the data into a view data. It contains a list of view queries, each of which contains a view-level operation. A workflow must contain at least one view-level operation, which describes the structure of the view data.+`{ type: 'not in', value }` passes when the encoded row value is not equal to any encoded member of `value`. Nullish values pass unless the set contains the same nullish encoded value.-At the moment, there are 3 view-level operations: aggregate, fold, and raw.+### `regexp`-#### Aggregate Query+`{ type: 'regexp', value, caseSensitive? }` constructs a JavaScript-compatible regular expression from `value`. It tests the field value with search semantics (`RegExp.prototype.test`), not full-string matching. `caseSensitive: true` uses no flags; otherwise matching is case-insensitive. Invalid patterns compile to a predicate that rejects all rows.-Use the aggregate operation in the view query when you want the data to be aggregated. The aggregate operation contains a list of measures to be aggregated by a specified aggregation function with the group-by fields.+SQL backends that cannot implement JavaScript-compatible regular expressions must reject the payload or mark the case as an unsupported backend capability. They must not silently reinterpret anchors or flags.++## 4. Offset Date Model++Temporal transforms and temporal filters use two offsets:++- `offset`: the data parse timezone, in minutes, matching `Date#getTimezoneOffset` sign convention.+- `displayOffset`: the timezone used when extracting or truncating calendar fields.++The effective date constructor is:```ts-type IAggregator = 'sum' | 'count' | 'max' | 'min' | 'mean' | 'median' | 'variance' | 'stdev';--interface IAggQuery {- op: 'aggregate';- groupBy: string[];- measures: {- field: string;- agg: IAggregator;- asFieldKey: string;- }[];-}+const prepareDate = newOffsetDate(offset);+const toDisplayDate = newOffsetDate(displayOffset);+const date = toDisplayDate(prepareDate(value));```-#### Raw Query+For truncation results, the calendar components are computed in display time and then converted back to epoch milliseconds with `toDisplayDate(...)`. `displayOffset` is injected by `toWorkflow()` for `dateTimeDrill` and `dateTimeFeature`. `temporal range` uses `offset` only.-Use the raw operation in the view query when you want the data not to be aggregated. The raw operation contains a list of fields to be included in the view data.+## 5. Transform Step```ts-interface IRawQuery {- op: 'raw';- fields: string[];+export interface ITransformWorkflowStep {+ type: 'transform';+ transform: IFieldTransform[];}```-An aggregate query will be+Transforms are evaluated in array order. Each expression appends or replaces the field named by `expression.as` / `key` while preserving all existing columns and row order.-```ts-type IViewQuery = IAggQuery | IRawQuery;+Expression parameters can be fields, constants, literal values, nested expressions, SQL strings, paint maps, `offset`, `displayOffset`, or `format` metadata. Nested expressions are evaluated before their parent expression.-interface IViewQuery {- type: 'view';- query: Array<IViewQuery>;-}-```+### `bin`-The schema of the view query is--```json-{- "$schema": "http://json-schema.org/draft-07/schema#",- "type": "object",- "properties": {- "type": {- "type": "string",- "enum": [- "view"- ]- },- "query": {- "type": "array",- "items": {- "oneOf": [- {- "type": "object",- "properties": {- "op": {- "type": "string",- "enum": [- "aggregate"- ]- },- "groupBy": {- "type": "array",- "items": {- "type": "string"- }- },- "measures": {- "type": "array",- "items": {- "type": "object",- "properties": {- "field": {- "type": "string"- },- "agg": {- "type": "string",- "enum": [- "sum",- "count",- "max",- "min",- "mean",- "median",- "variance",- "stdev"- ]- },- "asFieldKey": {- "type": "string"- }- },- "required": [- "field",- "agg",- "asFieldKey"- ]- }- }- },- "required": [- "op",- "groupBy",- "measures"- ]- },- {- "type": "object",- "properties": {- "op": {- "type": "string",- "enum": [- "raw"- ]- },- "fields": {- "type": "array",- "items": {- "type": "string"- }- }- },- "required": [- "op",- "fields"- ]- }- ]- }- }- },- "required": [- "type",- "query"- ]-}-```+`bin(field, num = 10)` computes `_min` and `_max` over all values of `field`, then `step = (_max - _min) / num`. Each row receives `[lower, upper]`, where `bIndex = floor((value - _min) / step)`, clamped so the maximum value falls into the last bin. Bins are left-closed and right-open except the final bin, which includes `_max`.-### Sort Query (optional)+If all values are equal or the bin index is `NaN`, the bin index is `0`. Nullish or non-numeric values are not valid inputs.-The filter query is used to sort the result data. It contains a list of fields to be used for sort, and excepted sorting order.+### `binCount`-```ts-export interface ISortWorkflowStep {- type: 'sort';- sort: 'ascending' | 'descending';- by: string[];-}-```+`binCount(field, num = 10)` is quantile/rank bucketing. Values are sorted ascending and assigned 1-based bucket numbers by `floor(orderIndex / (rowCount / num)) + 1`, clamped to `num`. Ties keep the JavaScript stable sort order. For an all-equal column the output is still rank buckets, not one equal-width bucket.-The schema of the sort query is--```json-{- "$schema": "http://json-schema.org/draft-07/schema#",- "type": "object",- "properties": {- "type": {- "type": "string",- "enum": [- "sort"- ]- },- "sort": {- "type": "string",- "enum": [- "ascending",- "descending"- ]- },- "by": {- "type": "array",- "items": {- "type": "string",- }- }- },- "required": [- "type",- "sort",- "by"- ]-}-```+### `log`, `log2`, `log10`++`log(field, base = expression.num ?? 10)` computes `Math.log(value) / Math.log(base)`. The normative result for `value <= 0`, nullish, or non-numeric input is `null`. `log2` uses base 2 and `log10` uses base 10.++### `one`++`one()` returns `1` for each input row.++### `dateTimeDrill`++`dateTimeDrill(field, level)` truncates the timestamp to the start of the requested display-time unit and returns epoch milliseconds.++Supported levels:++- `year`: January 1, 00:00:00.000 of the display year.+- `quarter`: first day of the calendar quarter.+- `month`: first day of the month.+- `week`: Sunday start of week.+- `day`: day start.+- `hour`: hour start.+- `minute`: minute start.+- `second`: second start.+- `iso_year`: January 1 of the ISO week-numbering year containing the date.+- `iso_week`: Monday start of the ISO week.++Nullish input returns `null`.-## Computation Request+### `dateTimeFeature`-GraphicWalker regards a computation as a request. A computation function, including HTTP service, must follow the protocol of the request.+`dateTimeFeature(field, level)` extracts a display-time calendar component.-### Payload+Supported levels:++- `year`: full year.+- `quarter`: 1 through 4.+- `month`: 1 through 12.+- `week`: Sunday-based week number, starting at 1 for the first Sunday-starting week.+- `weekday`: Sunday = 0 through Saturday = 6.+- `iso_year`: ISO week-numbering year.+- `iso_week`: ISO week number.+- `iso_weekday`: Monday = 1 through Sunday = 7.+- `day`: day of month.+- `hour`, `minute`, `second`: clock component.++Nullish input returns `null`.++### `paint`++`paint` maps each row to a paint bucket using either the legacy 2D paint map (`type: 'map'`) or the current facet paint map (`type: 'newmap'`). The result is backend-specific but must be deterministic for the same map and row order. SQL backends may reject `paint` as an unsupported capability.++### `expr`++Transform-level `expr` evaluates the SQL-like expression supplied in the `sql` parameter against each row. If the expression returns an array, it must have exactly one value per input row. If it returns a scalar, the scalar is broadcast to every row. The expression language is the shared expression subset accepted by `pgsql-ast-parser` in the client and the SQL backend. Backends must reject expressions outside their supported subset.++## 6. View Step```ts-export interface IDataQueryPayload {- workflow: IDataQueryWorkflowStep[];- limit?: number;- offset?: number;+export interface IViewWorkflowStep {+ type: 'view';+ query: IViewQuery[];}```-### Return Value+Queries inside a `view` step are evaluated in array order.++### `aggregate`++Rows are grouped by the tuple of `groupBy` field values. Null group key values form ordinary groups; all nullish values for the same group field compare equal for grouping.++For each measure, the output key is `asFieldKey` when present, otherwise `getMeaAggKey(field, agg)`.++Aggregators:++- `sum`: arithmetic sum of all values.+- `count`: count of rows in the group, including rows where the measured field is nullish.+- `max`: maximum by numeric comparison.+- `min`: minimum by numeric comparison.+- `mean`: `sum(values) / rowCount`.+- `median`: middle value after ascending numeric sort, or the average of the two middle values.+- `variance`: population variance, `mean((x - mean(values)) ** 2)`.+- `stdev`: square root of population variance.+- `distinctCount`: count of distinct values using SameValueZero semantics; `null` counts as one distinct value and `undefined` counts as one distinct value.+- `expr`: evaluate the SQL-like aggregate expression over the group. It must return a scalar; returning an array is an error.++Aggregators other than `count`, `distinctCount`, and `expr` require numeric inputs. Their nullish behavior is defined by the operator formula above; implementations should converge on SQL-style null exclusion in a later spec revision, but current conformance records existing differences where they occur.++### `fold`++For each input row and each field in `foldBy`, emit one output row. The output row copies the input row, deletes the folded source field, sets `newFoldKeyCol` to the folded field id, and sets `newFoldValueCol` to the original field value. Output order is input row order, and within each input row the order of `foldBy`.++### view-level `bin`++View-level `bin` has the same bin boundary semantics as transform `bin`, but it appends `newBinCol` directly inside the view query sequence.++### `raw`++`raw` projects fields listed in `fields` and preserves row order. Conforming implementations should not expose unlisted fields in raw output.++## 7. Sort Step```ts-export interface IRow {- [key: string]: any;+export interface ISortWorkflowStep {+ type: 'sort';+ sort: 'ascending' | 'descending';+ by: string[];}-declare const result: IRow[];```-### Computation Function+Sort is lexicographic over `by`. For each key, numbers compare numerically; other values compare by `String(value).localeCompare(String(other))`. Direction applies to every key. The sort is stable: rows with equal sort keys preserve their input relative order.-```ts-export type IComputationFunction = (payload: IDataQueryPayload) => Promise<IRow[]>;-```+Nullish values sort by their string representation under the same comparator. Implementations should avoid database-default null ordering and must make null ordering explicit when compiling to SQL.++## 8. Coverage Notes++The phase-1 conformance suite covers filter range, temporal range, one-of/not-in, regexp, transform bin/binCount/log/one/date drills/date features/expr, all aggregate operators, group-by nulls, raw, sort with limit/offset, special-character fields, numeric strings, empty data, single-row data, null-heavy data, a `toWorkflow()` generated pipeline, and multi-view cascading.++Known gaps are recorded in `docs/computation-divergences.md`. The main not-yet-covered executable areas are `paint` and full expression-language conformance; both require a backend capability contract beyond the current parser behavior.diff --git a/docs/computation-divergences.md b/docs/computation-divergences.mdnew file mode 100644index 00000000..ac428fd8--- /dev/null+++ b/docs/computation-divergences.md@@ -0,0 +1,353 @@+# Workflow Computation Divergences++This file records known differences between the client-side JavaScript workflow executor and SQL generated by `@kanaries/gw-dsl-parser`. Each entry includes the normative decision from `computation.md` and the corresponding conformance-test handling.++## DVG-001: Log Transforms For Non-Positive Values++Minimal payload:++```json+{+ "workflow": [+ {+ "type": "transform",+ "transform": [{ "key": "log_value", "expression": { "op": "log10", "as": "log_value", "params": [{ "type": "field", "value": "value" }] } }]+ },+ { "type": "view", "query": [{ "op": "raw", "fields": ["value", "log_value"] }] }+ ]+}+```++Data:++```json+[{ "value": 10 }, { "value": 0 }, { "value": -5 }]+```++Client result: `1`, `-Infinity`, and `NaN`.++SQL result: `1`, `null`, and `null`.++Normative decision: SQL semantics. `log`, `log2`, and `log10` return `null` for non-positive, nullish, or non-numeric input. This is safer for analytical backends and avoids serializing non-JSON numeric sentinels.++Test handling: `test.failing` in conformance, because the client behavior is still divergent.++## DVG-002: `binCount` Is Quantile Bucketing In The Client And Equal-Width Bucketing In SQL++Minimal payload:++```json+{+ "workflow": [+ {+ "type": "transform",+ "transform": [{ "key": "bucket", "expression": { "op": "binCount", "as": "bucket", "num": 3, "params": [{ "type": "field", "value": "value" }] } }]+ },+ { "type": "view", "query": [{ "op": "raw", "fields": ["value", "bucket"] }] }+ ]+}+```++Data:++```json+[{ "value": 1 }, { "value": 2 }, { "value": 3 }, { "value": 100 }, { "value": 101 }, { "value": 102 }]+```++Client result: rank buckets `1, 1, 2, 2, 3, 3`.++SQL result: equal-width buckets based on `(value - min) / step`.++Normative decision: client semantics. The operator name means count-balanced buckets; equal-width bucketing is already covered by `bin`.++Test handling: `test.failing`.++## DVG-003: View-Level `fold` Is Unsupported By `gw-dsl-parser`++Minimal payload:++```json+{+ "workflow": [{ "type": "view", "query": [{ "op": "fold", "foldBy": ["a", "b"], "newFoldKeyCol": "key", "newFoldValueCol": "value" }] }]+}+```++Data:++```json+[{ "id": 1, "a": 10, "b": 20 }]+```++Client result: two rows, one for `a` and one for `b`.++SQL result: parser error: `unknown variant 'fold', expected 'raw' or 'aggregate'`.++Normative decision: client semantics. `fold` is part of the public `IViewQuery` type and has deterministic row expansion semantics.++Test handling: skipped conformance test with this entry id.++## DVG-004: View-Level `bin` Is Unsupported By `gw-dsl-parser`++Minimal payload:++```json+{+ "workflow": [{ "type": "view", "query": [{ "op": "bin", "binBy": "value", "newBinCol": "value_bin", "binSize": 3 }] }]+}+```++Data:++```json+[{ "value": 1 }, { "value": 2 }, { "value": 3 }]+```++Client result: rows with a `[min, max]` bin tuple in `value_bin`.++SQL result: parser error: `unknown variant 'bin', expected 'raw' or 'aggregate'`.++Normative decision: same semantics as transform-level `bin`, applied in the view query sequence.++Test handling: skipped conformance test with this entry id.++## DVG-005: `one` Transform Loses Its Alias In SQL++Minimal payload:++```json+{+ "workflow": [+ { "type": "transform", "transform": [{ "key": "one", "expression": { "op": "one", "as": "one", "params": [] } }] },+ { "type": "view", "query": [{ "op": "raw", "fields": ["one"] }] }+ ]+}+```++Data:++```json+[{ "value": 1 }]+```++Client result: `{ "one": 1 }`.++SQL result: `{ "1": 1 }`; generated SQL is `SELECT 1 ...` without `AS "one"`.++Normative decision: transform output must use `expression.as` / `key`.++Test handling: `test.failing`.++## DVG-006: Calendar Week Truncation Uses Different Week Starts++Minimal payload:++```json+{+ "workflow": [+ {+ "type": "transform",+ "transform": [+ {+ "key": "week",+ "expression": {+ "op": "dateTimeDrill",+ "as": "week",+ "params": [+ { "type": "field", "value": "ts" },+ { "type": "value", "value": "week" },+ { "type": "offset", "value": 0 },+ { "type": "displayOffset", "value": 0 }+ ]+ }+ }+ ]+ },+ { "type": "view", "query": [{ "op": "raw", "fields": ["week"] }] }+ ]+}+```++Data:++```json+[{ "ts": 1704067200000 }]+```++Client result: Sunday-start week.++SQL result: DuckDB `DATE_TRUNC('week', ...)`, which is Monday-start.++Normative decision: `dateTimeDrill('week')` is Sunday-start; `iso_week` is Monday-start.++Test handling: `test.failing`.++## DVG-007: ISO Date Features Are Incorrectly Lowered In SQL++Minimal payload:++```json+{+ "workflow": [+ {+ "type": "transform",+ "transform": [+ {+ "key": "iso_week",+ "expression": {+ "op": "dateTimeFeature",+ "as": "iso_week",+ "params": [+ { "type": "field", "value": "ts" },+ { "type": "value", "value": "iso_week" },+ { "type": "offset", "value": 0 },+ { "type": "displayOffset", "value": 0 }+ ]+ }+ }+ ]+ },+ { "type": "view", "query": [{ "op": "raw", "fields": ["iso_week"] }] }+ ]+}+```++Data:++```json+[{ "ts": 1704067200000 }]+```++Client result: ISO week number.++SQL result: generated SQL uses `EXTRACT(YEAR ...)` for `iso_year`, `iso_week`, and `iso_weekday`.++Normative decision: client ISO calendar semantics.++Test handling: `test.failing`.++## DVG-008: Client Raw View Does Not Project Fields++Minimal payload:++```json+{+ "workflow": [{ "type": "view", "query": [{ "op": "raw", "fields": ["a"] }] }]+}+```++Data:++```json+[{ "a": 1, "b": 2 }]+```++Client result: `{ "a": 1, "b": 2 }`.++SQL result: `{ "a": 1 }`.++Normative decision: SQL/documented semantics. `raw.fields` is a projection list and output should not expose unlisted fields.++Test handling: `test.failing`.++## DVG-009: Variance And Stdev Use Different Population/Sample Formulas++Minimal payload:++```json+{+ "workflow": [+ {+ "type": "view",+ "query": [+ {+ "op": "aggregate",+ "groupBy": ["segment"],+ "measures": [+ { "field": "value", "agg": "variance", "asFieldKey": "variance_value" },+ { "field": "value", "agg": "stdev", "asFieldKey": "stdev_value" }+ ]+ }+ ]+ }+ ]+}+```++Data:++```json+[+ { "segment": "A", "value": 1 },+ { "segment": "A", "value": 3 }+]+```++Client result: population variance `1` and stdev `1`.++SQL result: generated SQL currently uses DuckDB aggregate behavior that does not match the client for these cases.++Normative decision: client semantics, because `computation.md` defines population variance and stdev.++Test handling: `test.failing`.++## DVG-010: Null Sort Ordering Differs++Minimal payload:++```json+{+ "workflow": [+ { "type": "view", "query": [{ "op": "raw", "fields": ["segment", "value"] }] },+ { "type": "sort", "by": ["segment", "value"], "sort": "ascending" }+ ]+}+```++Data:++```json+[+ { "segment": "A", "value": 1 },+ { "segment": null, "value": 2 }+]+```++Client result: nullish values are compared by `String(value)`.++SQL result: DuckDB uses database null ordering unless the generated SQL makes null ordering explicit.++Normative decision: client comparator semantics; SQL generation should make null position explicit.++Test handling: `test.failing`.++## DVG-011: Numeric Strings In SQL Expressions Are Not Coerced By DuckDB++Minimal payload:++```json+{+ "workflow": [+ {+ "type": "transform",+ "transform": [+ { "key": "plus_one", "expression": { "op": "expr", "as": "plus_one", "params": [{ "type": "sql", "value": "\"number text\" + 1" }] } }+ ]+ },+ { "type": "view", "query": [{ "op": "raw", "fields": ["number text", "plus_one"] }] }+ ]+}+```++Data:++```json+[{ "number text": "1" }]+```++Client result: numeric string is coerced and returns `2`.++SQL result: DuckDB rejects `VARCHAR + INTEGER` without an explicit cast.++Normative decision: numeric strings coerce in numeric expression contexts for DSL portability.++Test handling: `test.failing`.diff --git a/packages/computation-conformance/jest.config.js b/packages/computation-conformance/jest.config.jsnew file mode 100644index 00000000..9b7dd312--- /dev/null+++ b/packages/computation-conformance/jest.config.js@@ -0,0 +1,11 @@+/** @type {import('ts-jest').JestConfigWithTsJest} */+module.exports = {+ preset: 'ts-jest',+ testEnvironment: 'node',+ moduleNameMapper: {+ '^@/(.*)$': '<rootDir>/../graphic-walker/src/$1',+ '^nanoid$': '<rootDir>/src/testDoubles/nanoid.js',+ },+ testMatch: ['<rootDir>/src/**/*.test.ts'],+ testTimeout: 30000,+};diff --git a/packages/computation-conformance/package.json b/packages/computation-conformance/package.jsonnew file mode 100644index 00000000..cd6a2e4b--- /dev/null+++ b/packages/computation-conformance/package.json@@ -0,0 +1,28 @@+{+ "name": "@kanaries/computation-conformance",+ "version": "0.0.0",+ "private": true,+ "license": "Apache-2.0",+ "scripts": {+ "test": "node --experimental-vm-modules ../../node_modules/jest/bin/jest.js --runInBand",+ "typecheck": "tsc --noEmit"+ },+ "prettier": {+ "tabWidth": 4,+ "printWidth": 160,+ "singleQuote": true+ },+ "dependencies": {+ "@kanaries/graphic-walker": "0.5.0"+ },+ "devDependencies": {+ "@duckdb/duckdb-wasm": "^1.28.0",+ "@kanaries/gw-dsl-parser": "^0.1.48-rc3",+ "@types/jest": "^29.5.3",+ "@types/node": "^24.0.0",+ "apache-arrow": "^17.0.0",+ "jest": "^29.6.2",+ "ts-jest": "^29.1.1",+ "typescript": "^5.2.2"+ }+}diff --git a/packages/computation-conformance/src/assertRows.ts b/packages/computation-conformance/src/assertRows.tsnew file mode 100644index 00000000..81b6006c--- /dev/null+++ b/packages/computation-conformance/src/assertRows.ts@@ -0,0 +1,64 @@+import type { IRow } from '../../graphic-walker/src/interfaces';++export const FLOAT_TOLERANCE = 1e-9;++interface CompareOptions {+ ordered?: boolean;+}++function normalizeValue(value: any): any {+ if (typeof value === 'number') {+ if (Number.isNaN(value)) {+ return 'NaN';+ }+ if (!Number.isFinite(value)) {+ return String(value);+ }+ return Math.abs(value) < FLOAT_TOLERANCE ? 0 : value;+ }+ if (Array.isArray(value)) {+ return value.map(normalizeValue);+ }+ if (value && typeof value === 'object') {+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, normalizeValue(item)]));+ }+ return value;+}++function compareValue(actual: any, expected: any, path: string) {+ if (typeof actual === 'number' && typeof expected === 'number' && Number.isFinite(actual) && Number.isFinite(expected)) {+ expect(Math.abs(actual - expected)).toBeLessThanOrEqual(FLOAT_TOLERANCE);+ return;+ }+ if (Array.isArray(actual) && Array.isArray(expected)) {+ expect(actual.length).toBe(expected.length);+ actual.forEach((item, index) => compareValue(item, expected[index], `${path}[${index}]`));+ return;+ }+ expect(normalizeValue(actual)).toEqual(normalizeValue(expected));+}++function stableStringify(row: IRow): string {+ return JSON.stringify(+ Object.fromEntries(+ Object.entries(normalizeValue(row)).sort(([left], [right]) => {+ return left.localeCompare(right);+ }),+ ),+ );+}++export function expectRowsToConform(actual: IRow[], expected: IRow[], options: CompareOptions = {}) {+ const ordered = options.ordered ?? true;+ const actualRows = ordered ? actual : [...actual].sort((left, right) => stableStringify(left).localeCompare(stableStringify(right)));+ const expectedRows = ordered ? expected : [...expected].sort((left, right) => stableStringify(left).localeCompare(stableStringify(right)));++ expect(actualRows.length).toBe(expectedRows.length);+ actualRows.forEach((actualRow, rowIndex) => {+ const expectedRow = expectedRows[rowIndex];+ expect(Object.keys(actualRow).sort()).toEqual(Object.keys(expectedRow).sort());+ for (const key of Object.keys(expectedRow)) {+ compareValue(actualRow[key], expectedRow[key], `${rowIndex}.${key}`);+ }+ });+}diff --git a/packages/computation-conformance/src/clientExecutor.ts b/packages/computation-conformance/src/clientExecutor.tsnew file mode 100644index 00000000..e4dccfe6--- /dev/null+++ b/packages/computation-conformance/src/clientExecutor.ts@@ -0,0 +1,33 @@+import type { IDataQueryPayload, IFilterFiledSimple, IRow } from '../../graphic-walker/src/interfaces';+import { filter } from '../../graphic-walker/src/lib/filter';+import { transformData } from '../../graphic-walker/src/lib/transform';+import { queryView } from '../../graphic-walker/src/lib/viewQuery';+import { sortBy } from '../../graphic-walker/src/lib/sort';++export async function executeClient(data: IRow[], payload: IDataQueryPayload): Promise<IRow[]> {+ let result = data;+ for (const step of payload.workflow) {+ switch (step.type) {+ case 'filter':+ result = filter(+ result,+ step.filters.map((item) => ({ fid: item.fid, rule: item.rule }) satisfies IFilterFiledSimple),+ );+ break;+ case 'transform':+ result = await transformData(result, step.transform);+ break;+ case 'view':+ for (const query of step.query) {+ result = queryView(result, query);+ }+ break;+ case 'sort':+ result = sortBy(result, step.by, step.sort);+ break;+ default:+ throw new Error(`Unknown workflow step: ${JSON.stringify(step)}`);+ }+ }+ return result.slice(payload.offset ?? 0, payload.limit && payload.limit > 0 ? (payload.offset ?? 0) + payload.limit : undefined);+}diff --git a/packages/computation-conformance/src/duckdbExecutor.ts b/packages/computation-conformance/src/duckdbExecutor.tsnew file mode 100644index 00000000..7250e117--- /dev/null+++ b/packages/computation-conformance/src/duckdbExecutor.ts@@ -0,0 +1,17 @@+import path from 'node:path';+import { execFileSync } from 'node:child_process';+import type { IDataQueryPayload, IRow } from '../../graphic-walker/src/interfaces';++export interface DuckDBExecuteOptions {+ emptySchema?: Record<string, 'DOUBLE' | 'VARCHAR' | 'BOOLEAN' | 'BIGINT'>;+}++export async function executeDuckDB(data: IRow[], payload: IDataQueryPayload, options: DuckDBExecuteOptions = {}): Promise<{ rows: IRow[]; sql: string }> {+ const runner = path.resolve(__dirname, 'duckdbRunner.mjs');+ const stdout = execFileSync(process.execPath, [runner], {+ input: JSON.stringify({ data, payload, options }),+ encoding: 'utf8',+ maxBuffer: 10 * 1024 * 1024,+ });+ return JSON.parse(stdout);+}diff --git a/packages/computation-conformance/src/duckdbRunner.mjs b/packages/computation-conformance/src/duckdbRunner.mjsnew file mode 100644index 00000000..443b5795--- /dev/null+++ b/packages/computation-conformance/src/duckdbRunner.mjs@@ -0,0 +1,88 @@+import fs from 'node:fs';+import path from 'node:path';+import { createRequire } from 'node:module';+import { pathToFileURL } from 'node:url';+import { Vector } from 'apache-arrow';+import { bigNumToString } from 'apache-arrow/util/bn';++const require = createRequire(import.meta.url);++function readStdin() {+ return fs.readFileSync(0, 'utf8');+}++function quoteIdentifier(identifier) {+ return `"${identifier.replace(/"/g, '""')}"`;+}++function arrowToJSON(value) {+ if (value === null || value === undefined) {+ return value;+ }+ if (value instanceof Vector) {+ return Array.from(value).map(arrowToJSON);+ }+ if (Array.isArray(value)) {+ return value.map(arrowToJSON);+ }+ if (typeof value === 'bigint') {+ return Number(value);+ }+ if (typeof value === 'object') {+ if (value instanceof Date) {+ return value.getTime();+ }+ if (value.constructor?.name?.includes('BigNum')) {+ return Number(bigNumToString(value));+ }+ }+ return value;+}++function transformResult(table) {+ return table.toArray().map((row) => Object.fromEntries(Object.entries(row.toJSON()).map(([key, value]) => [key, arrowToJSON(value)])));+}++async function main() {+ const { data, payload, options } = JSON.parse(readStdin());+ const duckdb = require('@duckdb/duckdb-wasm/blocking');+ const dist = path.dirname(require.resolve('@duckdb/duckdb-wasm'));+ const bundles = {+ mvp: { mainModule: path.resolve(dist, 'duckdb-mvp.wasm') },+ eh: { mainModule: path.resolve(dist, 'duckdb-eh.wasm') },+ };+ const db = await duckdb.createDuckDB(bundles, new duckdb.VoidLogger(), duckdb.NODE_RUNTIME);+ await db.instantiate(() => {});++ const parserDir = path.dirname(require.resolve('@kanaries/gw-dsl-parser/package.json'));+ const parser = await import(pathToFileURL(path.join(parserDir, 'gw_dsl_parser.js')).href);+ await parser.default(fs.readFileSync(path.join(parserDir, 'gw_dsl_parser_bg.wasm')));++ const tableName = 'gw_conf_table';+ const conn = db.connect();+ try {+ if (data.length === 0 && options.emptySchema) {+ const columns = Object.entries(options.emptySchema)+ .map(([field, type]) => `${quoteIdentifier(field)} ${type}`)+ .join(', ');+ conn.query(`CREATE TABLE ${quoteIdentifier(tableName)} (${columns})`);+ } else {+ const fileName = `${tableName}.json`;+ db.registerFileText(fileName, JSON.stringify(data));+ conn.insertJSONFromPath(fileName, { name: tableName });+ }++ const sql = parser.parser_dsl_with_table(tableName, JSON.stringify(payload));+ const rows = transformResult(conn.query(sql));+ process.stdout.write(JSON.stringify({ rows, sql }));+ } finally {+ conn.close();+ }+}++main().catch((error) => {+ if (process.env.GW_CONFORMANCE_VERBOSE_ERRORS) {+ process.stderr.write(error?.stack || String(error));+ }+ process.exit(1);+});diff --git a/packages/computation-conformance/src/testDoubles/nanoid.js b/packages/computation-conformance/src/testDoubles/nanoid.jsnew file mode 100644index 00000000..7bdbe2d8--- /dev/null+++ b/packages/computation-conformance/src/testDoubles/nanoid.js@@ -0,0 +1,8 @@+let counter = 0;++function nanoid() {+ counter += 1;+ return `testid${counter}`;+}++module.exports = { nanoid };diff --git a/packages/computation-conformance/src/workflow.conformance.test.ts b/packages/computation-conformance/src/workflow.conformance.test.tsnew file mode 100644index 00000000..b34ed997--- /dev/null+++ b/packages/computation-conformance/src/workflow.conformance.test.ts@@ -0,0 +1,474 @@+import type { IDataQueryPayload, IRow, IViewField } from '../../graphic-walker/src/interfaces';+import { executeClient } from './clientExecutor';+import { executeDuckDB, type DuckDBExecuteOptions } from './duckdbExecutor';+import { expectRowsToConform } from './assertRows';+import { toWorkflow } from '../../graphic-walker/src/utils/workflow';++async function expectConformance(data: IRow[], payload: IDataQueryPayload, options: { ordered?: boolean; duckdb?: DuckDBExecuteOptions } = {}) {+ const clientRows = await executeClient(data, payload);+ const { rows: duckdbRows } = await executeDuckDB(data, payload, options.duckdb);+ expectRowsToConform(duckdbRows, clientRows, { ordered: options.ordered });+}++const baseRows: IRow[] = [+ { id: 1, category: 'alpha', segment: 'A', value: 1, value2: 10, ts: Date.UTC(2024, 0, 1, 1, 2, 3), nullable: null, 'field (quoted)': 5, 中文: '甲' },+ { id: 2, category: 'Beta', segment: 'A', value: 2, value2: 20, ts: Date.UTC(2024, 0, 2, 4, 5, 6), nullable: 2, 'field (quoted)': 6, 中文: '乙' },+ { id: 3, category: 'gamma', segment: 'B', value: 3, value2: null, ts: Date.UTC(2024, 0, 7, 7, 8, 9), nullable: null, 'field (quoted)': 7, 中文: '甲' },+ { id: 4, category: 'delta', segment: null, value: 4, value2: 40, ts: Date.UTC(2024, 0, 8, 10, 11, 12), nullable: 4, 'field (quoted)': 8, 中文: '丙' },+ { id: 5, category: 'ALPHA', segment: 'B', value: 5, value2: 50, ts: Date.UTC(2024, 1, 1, 13, 14, 15), nullable: null, 'field (quoted)': 9, 中文: '甲' },+];++describe('workflow computation conformance', () => {+ test('filter range handles inclusive boundaries and null failures', async () => {+ await expectConformance(baseRows, {+ workflow: [+ { type: 'filter', filters: [{ fid: 'nullable', rule: { type: 'range', value: [2, 4] } }] },+ { type: 'view', query: [{ op: 'raw', fields: ['id', 'category', 'segment', 'value', 'value2', 'ts', 'nullable', 'field (quoted)', '中文'] }] },+ ],+ });+ });++ test('filter temporal range applies offset parsing', async () => {+ await expectConformance(baseRows, {+ workflow: [+ { type: 'filter', filters: [{ fid: 'ts', rule: { type: 'temporal range', value: [Date.UTC(2024, 0, 2), Date.UTC(2024, 0, 31)], offset: 0 } }] },+ { type: 'view', query: [{ op: 'raw', fields: ['id', 'category', 'segment', 'value', 'value2', 'ts', 'nullable', 'field (quoted)', '中文'] }] },+ ],+ });+ });++ test('filter one-of and not-in compare mixed encoded values', async () => {+ await expectConformance(baseRows, {+ workflow: [+ {+ type: 'filter',+ filters: [+ { fid: 'category', rule: { type: 'one of', value: ['alpha', 'gamma', 5] } },+ { fid: 'segment', rule: { type: 'not in', value: ['Z'] } },+ ],+ },+ { type: 'view', query: [{ op: 'raw', fields: ['id', 'category', 'segment', 'value', 'value2', 'ts', 'nullable', 'field (quoted)', '中文'] }] },+ ],+ });+ });++ test('filter regexp supports case-insensitive search without anchors', async () => {+ await expectConformance(baseRows, {+ workflow: [+ { type: 'filter', filters: [{ fid: 'category', rule: { type: 'regexp', value: 'alp', caseSensitive: false } }] },+ { type: 'view', query: [{ op: 'raw', fields: ['id', 'category', 'segment', 'value', 'value2', 'ts', 'nullable', 'field (quoted)', '中文'] }] },+ ],+ });+ });++ test('filter regexp anchors use JavaScript search semantics', async () => {+ await expectConformance(baseRows, {+ workflow: [+ { type: 'filter', filters: [{ fid: 'category', rule: { type: 'regexp', value: '^a', caseSensitive: false } }] },+ { type: 'view', query: [{ op: 'raw', fields: ['id', 'category', 'segment', 'value', 'value2', 'ts', 'nullable', 'field (quoted)', '中文'] }] },+ ],+ });+ });++ test('transform bin produces interval tuples', async () => {+ await expectConformance(baseRows, {+ workflow: [+ {+ type: 'transform',+ transform: [{ key: 'value_bin', expression: { op: 'bin', as: 'value_bin', num: 2, params: [{ type: 'field', value: 'value' }] } }],+ },+ {+ type: 'view',+ query: [{ op: 'raw', fields: ['id', 'category', 'segment', 'value', 'value2', 'ts', 'nullable', 'field (quoted)', '中文', 'value_bin'] }],+ },+ ],+ });+ });++ test.failing('DVG-002: transform binCount is quantile/rank bucketing', async () => {+ await expectConformance([{ value: 1 }, { value: 2 }, { value: 3 }, { value: 100 }, { value: 101 }, { value: 102 }], {+ workflow: [+ {+ type: 'transform',+ transform: [{ key: 'bucket', expression: { op: 'binCount', as: 'bucket', num: 3, params: [{ type: 'field', value: 'value' }] } }],+ },+ { type: 'view', query: [{ op: 'raw', fields: ['value', 'bucket'] }] },+ ],+ });+ });++ test('transform log family works for positive values', async () => {+ await expectConformance([{ value: 1 }, { value: 10 }, { value: 100 }], {+ workflow: [+ {+ type: 'transform',+ transform: [+ { key: 'ln', expression: { op: 'log', as: 'ln', params: [{ type: 'field', value: 'value' }] } },+ { key: 'log2', expression: { op: 'log2', as: 'log2', params: [{ type: 'field', value: 'value' }] } },+ { key: 'log10', expression: { op: 'log10', as: 'log10', params: [{ type: 'field', value: 'value' }] } },+ ],+ },+ { type: 'view', query: [{ op: 'raw', fields: ['value', 'ln', 'log2', 'log10'] }] },+ ],+ });+ });++ test.failing('DVG-001: transform log returns null for non-positive values', async () => {+ await expectConformance([{ value: 10 }, { value: 0 }, { value: -5 }], {+ workflow: [+ { type: 'transform', transform: [{ key: 'log10', expression: { op: 'log10', as: 'log10', params: [{ type: 'field', value: 'value' }] } }] },+ { type: 'view', query: [{ op: 'raw', fields: ['value', 'log10'] }] },+ ],+ });+ });++ test('transform expr evaluates row-wise', async () => {+ await expectConformance(baseRows, {+ workflow: [+ {+ type: 'transform',+ transform: [{ key: 'calc', expression: { op: 'expr', as: 'calc', params: [{ type: 'sql', value: 'value + "field (quoted)"' }] } }],+ },+ {+ type: 'view',+ query: [{ op: 'raw', fields: ['id', 'category', 'segment', 'value', 'value2', 'ts', 'nullable', 'field (quoted)', '中文', 'calc'] }],+ },+ ],+ });+ });++ test.failing('DVG-005: transform one aliases its output field', async () => {+ await expectConformance([{ value: 1 }, { value: 2 }], {+ workflow: [+ { type: 'transform', transform: [{ key: 'one', expression: { op: 'one', as: 'one', params: [] } }] },+ { type: 'view', query: [{ op: 'raw', fields: ['value', 'one'] }] },+ ],+ });+ });++ test.each(['year', 'quarter', 'month', 'day', 'hour', 'minute', 'second'] as const)(+ 'dateTimeDrill %s conforms with offset/displayOffset',+ async (level) => {+ await expectConformance(baseRows, {+ workflow: [+ {+ type: 'transform',+ transform: [+ {+ key: level,+ expression: {+ op: 'dateTimeDrill',+ as: level,+ params: [+ { type: 'field', value: 'ts' },+ { type: 'value', value: level },+ { type: 'offset', value: 0 },+ { type: 'displayOffset', value: 0 },+ ],+ },+ },+ ],+ },+ {+ type: 'view',+ query: [{ op: 'raw', fields: ['id', 'category', 'segment', 'value', 'value2', 'ts', 'nullable', 'field (quoted)', '中文', level] }],+ },+ ],+ });+ },+ );++ test.failing('DVG-006: dateTimeDrill week is Sunday-start', async () => {+ await expectConformance(baseRows, {+ workflow: [+ {+ type: 'transform',+ transform: [+ {+ key: 'week',+ expression: {+ op: 'dateTimeDrill',+ as: 'week',+ params: [+ { type: 'field', value: 'ts' },+ { type: 'value', value: 'week' },+ { type: 'offset', value: 0 },+ { type: 'displayOffset', value: 0 },+ ],+ },+ },+ ],+ },+ {+ type: 'view',+ query: [{ op: 'raw', fields: ['id', 'category', 'segment', 'value', 'value2', 'ts', 'nullable', 'field (quoted)', '中文', 'week'] }],+ },+ ],+ });+ });++ test.each(['year', 'quarter', 'month', 'weekday', 'day', 'hour', 'minute', 'second'] as const)('dateTimeFeature %s conforms', async (level) => {+ await expectConformance(baseRows, {+ workflow: [+ {+ type: 'transform',+ transform: [+ {+ key: level,+ expression: {+ op: 'dateTimeFeature',+ as: level,+ params: [+ { type: 'field', value: 'ts' },+ { type: 'value', value: level },+ { type: 'offset', value: 0 },+ { type: 'displayOffset', value: 0 },+ ],+ },+ },+ ],+ },+ {+ type: 'view',+ query: [{ op: 'raw', fields: ['id', 'category', 'segment', 'value', 'value2', 'ts', 'nullable', 'field (quoted)', '中文', level] }],+ },+ ],+ });+ });++ test.failing('DVG-006: dateTimeFeature week uses Sunday-based week numbering', async () => {+ await expectConformance(baseRows, {+ workflow: [+ {+ type: 'transform',+ transform: [+ {+ key: 'week',+ expression: {+ op: 'dateTimeFeature',+ as: 'week',+ params: [+ { type: 'field', value: 'ts' },+ { type: 'value', value: 'week' },+ { type: 'offset', value: 0 },+ { type: 'displayOffset', value: 0 },+ ],+ },+ },+ ],+ },+ {+ type: 'view',+ query: [{ op: 'raw', fields: ['id', 'category', 'segment', 'value', 'value2', 'ts', 'nullable', 'field (quoted)', '中文', 'week'] }],+ },+ ],+ });+ });++ test.failing.each(['iso_year', 'iso_week', 'iso_weekday'] as const)('DVG-007: dateTimeFeature %s uses ISO calendar semantics', async (level) => {+ await expectConformance([{ ts: Date.UTC(2021, 0, 1) }, { ts: Date.UTC(2021, 0, 4) }], {+ workflow: [+ {+ type: 'transform',+ transform: [+ {+ key: level,+ expression: {+ op: 'dateTimeFeature',+ as: level,+ params: [+ { type: 'field', value: 'ts' },+ { type: 'value', value: level },+ { type: 'offset', value: 0 },+ { type: 'displayOffset', value: 0 },+ ],+ },+ },+ ],+ },+ { type: 'view', query: [{ op: 'raw', fields: ['ts', level] }] },+ ],+ });+ });++ test('view aggregate covers all aggregators and null group keys', async () => {+ await expectConformance(+ baseRows,+ {+ workflow: [+ {+ type: 'view',+ query: [+ {+ op: 'aggregate',+ groupBy: ['segment'],+ measures: [+ { field: 'value', agg: 'sum', asFieldKey: 'sum_value' },+ { field: 'value', agg: 'count', asFieldKey: 'count_value' },+ { field: 'value', agg: 'max', asFieldKey: 'max_value' },+ { field: 'value', agg: 'min', asFieldKey: 'min_value' },+ { field: 'value', agg: 'mean', asFieldKey: 'mean_value' },+ { field: 'value', agg: 'median', asFieldKey: 'median_value' },+ { field: 'nullable', agg: 'distinctCount', asFieldKey: 'distinct_nullable' },+ { field: 'sum(value) + count(value)', agg: 'expr', asFieldKey: 'expr_metric' },+ ],+ },+ ],+ },+ ],+ },+ { ordered: false },+ );+ });++ test.failing('DVG-009: variance and stdev use population formulas', async () => {+ await expectConformance(+ [+ { segment: 'A', value: 1 },+ { segment: 'A', value: 3 },+ ],+ {+ workflow: [+ {+ type: 'view',+ query: [+ {+ op: 'aggregate',+ groupBy: ['segment'],+ measures: [+ { field: 'value', agg: 'variance', asFieldKey: 'variance_value' },+ { field: 'value', agg: 'stdev', asFieldKey: 'stdev_value' },+ ],+ },+ ],+ },+ ],+ },+ );+ });++ test('sort supports multiple keys with limit and offset at pipeline end', async () => {+ await expectConformance(+ [+ { id: 1, value: 2, tie: 2 },+ { id: 2, value: 1, tie: 3 },+ { id: 3, value: 1, tie: 1 },+ { id: 4, value: 3, tie: 1 },+ ],+ {+ workflow: [+ { type: 'view', query: [{ op: 'raw', fields: ['id', 'value', 'tie'] }] },+ { type: 'sort', by: ['value', 'tie'], sort: 'ascending' },+ ],+ limit: 2,+ offset: 1,+ },+ );+ });++ test.failing('DVG-010: sort uses explicit client null ordering', async () => {+ await expectConformance(baseRows, {+ workflow: [+ { type: 'view', query: [{ op: 'raw', fields: ['id', 'category', 'segment', 'value', 'value2', 'ts', 'nullable', 'field (quoted)', '中文'] }] },+ { type: 'sort', by: ['segment', 'value'], sort: 'ascending' },+ ],+ });+ });++ test('special-character fields survive SQL quoting', async () => {+ await expectConformance(+ [+ { 'quoted "field"': 'kept', 'number text': '1', 中文: '甲' },+ { 'quoted "field"': 'kept2', 'number text': '2', 中文: '乙' },+ ],+ {+ workflow: [{ type: 'view', query: [{ op: 'raw', fields: ['quoted "field"', 'number text', '中文'] }] }],+ },+ );+ });++ test.failing('DVG-011: numeric strings coerce in expression arithmetic', async () => {+ await expectConformance([{ 'number text': '1' }, { 'number text': '2' }], {+ workflow: [+ {+ type: 'transform',+ transform: [{ key: 'plus_one', expression: { op: 'expr', as: 'plus_one', params: [{ type: 'sql', value: '"number text" + 1' }] } }],+ },+ { type: 'view', query: [{ op: 'raw', fields: ['number text', 'plus_one'] }] },+ ],+ });+ });++ test('empty dataset returns an empty raw result with explicit SQL schema', async () => {+ await expectConformance(+ [],+ { workflow: [{ type: 'view', query: [{ op: 'raw', fields: ['value', 'category'] }] }] },+ { duckdb: { emptySchema: { value: 'DOUBLE', category: 'VARCHAR' } } },+ );+ });++ test('single-row aggregate works', async () => {+ await expectConformance([{ value: 7, category: 'solo' }], {+ workflow: [+ { type: 'view', query: [{ op: 'aggregate', groupBy: ['category'], measures: [{ field: 'value', agg: 'sum', asFieldKey: 'sum_value' }] }] },+ ],+ });+ });++ test('toWorkflow generated six-step style pipeline conforms for supported operators', async () => {+ const valueField: IViewField = { fid: 'value', name: 'value', semanticType: 'quantitative', analyticType: 'measure', aggName: 'sum' };+ const segmentField: IViewField = { fid: 'segment', name: 'segment', semanticType: 'nominal', analyticType: 'dimension' };+ const doubledField: IViewField = {+ fid: 'double_value',+ name: 'double value',+ semanticType: 'quantitative',+ analyticType: 'measure',+ computed: true,+ expression: { op: 'expr', as: 'double_value', params: [{ type: 'sql', value: 'value * 2' }] },+ aggName: 'sum',+ };+ const workflow = toWorkflow(+ [{ ...segmentField, rule: { type: 'not in', value: ['Z'] } }],+ [valueField, segmentField, doubledField],+ [segmentField],+ [doubledField],+ true,+ 'descending',+ [],+ 2,+ 0,+ );+ await expectConformance(baseRows, { workflow, limit: 2 }, { ordered: false });+ });++ test('multiple view steps cascade sequentially', async () => {+ await expectConformance(+ baseRows,+ {+ workflow: [+ { type: 'view', query: [{ op: 'aggregate', groupBy: ['segment'], measures: [{ field: 'value', agg: 'sum', asFieldKey: 'sum_value' }] }] },+ { type: 'view', query: [{ op: 'aggregate', groupBy: [], measures: [{ field: 'sum_value', agg: 'sum', asFieldKey: 'grand_total' }] }] },+ ],+ },+ { ordered: false },+ );+ });++ test.skip('DVG-003: view fold is specified but unsupported by gw-dsl-parser', async () => {+ await expectConformance([{ id: 1, a: 10, b: 20 }], {+ workflow: [{ type: 'view', query: [{ op: 'fold', foldBy: ['a', 'b'], newFoldKeyCol: 'key', newFoldValueCol: 'value' }] }],+ });+ });++ test.skip('DVG-004: view bin is specified but unsupported by gw-dsl-parser', async () => {+ await expectConformance([{ value: 1 }, { value: 2 }, { value: 3 }], {+ workflow: [{ type: 'view', query: [{ op: 'bin', binBy: 'value', newBinCol: 'value_bin', binSize: 3 }] }],+ });+ });++ test.failing('DVG-008: raw view projects fields', async () => {+ await expectConformance([{ a: 1, b: 2 }], {+ workflow: [{ type: 'view', query: [{ op: 'raw', fields: ['a'] }] }],+ });+ });+});diff --git a/packages/computation-conformance/tsconfig.json b/packages/computation-conformance/tsconfig.jsonnew file mode 100644index 00000000..41014c8c--- /dev/null+++ b/packages/computation-conformance/tsconfig.json@@ -0,0 +1,22 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "lib": ["ES2022", "DOM"],+ "module": "ESNext",+ "moduleResolution": "Node",+ "jsx": "react",+ "allowJs": true,+ "isolatedModules": true,+ "esModuleInterop": true,+ "allowSyntheticDefaultImports": true,+ "resolveJsonModule": true,+ "strict": true,+ "noImplicitAny": false,+ "skipLibCheck": true,+ "baseUrl": ".",+ "paths": {+ "@/*": ["../graphic-walker/src/*"]+ }+ },+ "include": ["src/**/*.ts"]+}diff --git a/yarn.lock b/yarn.lockindex 9c87aa58..50321c4b 100644--- a/yarn.lock+++ b/yarn.lock@@ -1803,6 +1803,13 @@dependencies:undici-types "~6.21.0"+"@types/node@^24.0.0":+ version "24.13.2"+ resolved "https://registry.yarnpkg.com/@types/node/-/node-24.13.2.tgz#3b9b280a7055128359f125eb1067d9a190f39854"+ integrity sha512-fRa09kZTgu8o71KFcDjUFuc7F+dEbZYZmkI0mg5YBTRs0yMKjYHsq/c0urDKeDb+D5qVgXOdFcuu+DZPKOITwA==+ dependencies:+ undici-types "~7.18.0"+"@types/[email protected]":version "2.1.1"resolved "https://registry.npmmirror.com/@types/pad-left/-/pad-left-2.1.1.tgz#17d906fc75804e1cc722da73623f1d978f16a137"@@ -5671,6 +5678,11 @@ undici-types@~6.21.0:resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-6.21.0.tgz#691d00af3909be93a7faa13be61b3a5b50ef12cb"integrity sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==+undici-types@~7.18.0:+ version "7.18.2"+ resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-7.18.2.tgz#29357a89e7b7ca4aef3bf0fd3fd0cd73884229e9"+ integrity sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==+update-browserslist-db@^1.0.13:version "1.0.13"resolved "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz#3c5e4f5c083661bd38ef64b6328c26ed6c8248c4"