From cd5e482e166728009e68db599d7fd65c5e7cf9b9 Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:04:49 -0500 Subject: [PATCH 01/39] docs(charts): specify additive scientific chart contract --- docs/CHARTS.md | 86 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 docs/CHARTS.md diff --git a/docs/CHARTS.md b/docs/CHARTS.md new file mode 100644 index 00000000..fc5da784 --- /dev/null +++ b/docs/CHARTS.md @@ -0,0 +1,86 @@ +# Chart data contract + +Graphlink chart nodes use the version-1 canonical JSON object validated by +`graphlink_chart_data.canonicalize_chart_data`. The server is the authority; +`web_ui/src/app/canvas/chartSpec.ts` performs the same defensive validation. +The version remains **1** because the new scientific fields are optional. + +## Existing charts + +The five existing shapes remain unchanged. A bar, line, or pie chart has +`type`, `labels: string[]`, `values: number[]`, `title`, `xAxis`, and +`yAxis`. Histogram uses `values` and optional `bins`. Sankey uses a +`flows` array containing `{source, target, value}`. Existing default +titles, axis labels, category ordering, validations, and visual renderers +are preserved without adding optional fields to legacy payloads. + +## Scientific line and scatter charts + +Both accept optional `xValues: number[]`, `series`, `xScale`, +`yScale`, `xUnit`, and `yUnit`. The two scale values are +`"linear"` (default) or `"log10"`. Units are plain strings; renderers +display them as `Axis label (unit)` without altering numeric data. If +`series` is present it is an array of named series, each with `name`, +`values: number[]`, and optional `xError` and `yError` arrays. The +arrays use the same shared x positions and have the same length. The +series names appear in the legend. + +An error array has one entry per data point. An entry is either a +nonnegative number (symmetric), or a two-element array +`[negativeMagnitude, positiveMagnitude]` (asymmetric). These describe +**magnitudes**, not signed lower/upper endpoints. Each point is rendered +at its original value with the corresponding interval; the value is never +moved or rounded to obtain its error bars. + +For one-series line charts, `xError` and `yError` may be specified +at the top level along with the historical `labels` and `values`. +When `series` is present, errors belong to the individual series. +A scatter chart requires numeric `xValues` and either a +`series` array or one top-level `values` array. A scientific line +chart can supply numeric `xValues`; without them it retains its +historical evenly spaced, categorically labeled x positions. A log10 +x-axis therefore requires `xValues`. + +Example: + +```json +{ + "type": "scatter", + "title": "Calibration", + "xAxis": "Concentration", + "yAxis": "Response", + "xUnit": "mg/L", + "yUnit": "mV", + "xScale": "log10", + "yScale": "linear", + "xValues": [1, 10, 100], + "series": [ + {"name": "Control", "values": [0.9, 1.8, 3.2], + "xError": [0.05, [1, 2], 10], + "yError": [0.1, [0.1, 0.3], 0.2]}, + {"name": "Treatment", "values": [1.1, 2.1, 3.5]} + ] +} +``` + +## Validation rules + +* All coordinates, values, and error magnitudes must be finite numbers. + NaN, positive/negative infinity, and numeric overflow are rejected. +* Series must be nonempty and named. Every series, coordinate array, and + error array must have the same number of points, within the existing + 300-point chart limit. The validator never truncates or drops points. +* Error magnitudes must be nonnegative. The two magnitudes of an + asymmetric error must both be present and valid. +* A log10 axis requires **strictly positive** coordinates, including the + lower endpoint of every error interval on that axis. A coordinate of + zero, a negative coordinate, or a zero/negative lower endpoint is an + error; it is never silently omitted or clipped. +* Existing bar, pie, histogram, and Sankey validation rules are unchanged. + An invalid scientific chart is rejected with a field/index-specific + message; a render request with invalid data continues to show the + existing chart-error placeholder. + +Interactive SVG and the matplotlib PNG/SVG exporter use the original +numeric coordinates and error magnitudes. Hover tooltips use unrounded +number strings with units (not the shortened tick-label formatter). From 725ec18615074cb0edbbd49b63abf0cb14c8a94b Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:07:38 -0500 Subject: [PATCH 02/39] feat(charts): validate scientific series, error intervals and log domains --- graphlink_chart_data.py | 215 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 213 insertions(+), 2 deletions(-) diff --git a/graphlink_chart_data.py b/graphlink_chart_data.py index 6c071c13..100d489e 100644 --- a/graphlink_chart_data.py +++ b/graphlink_chart_data.py @@ -5,8 +5,9 @@ import math -SUPPORTED_CHART_TYPES = frozenset({"bar", "line", "pie", "histogram", "sankey"}) +SUPPORTED_CHART_TYPES = frozenset({"bar", "line", "pie", "histogram", "sankey", "scatter"}) MAX_SERIES_POINTS = 300 +MAX_NAMED_SERIES = 12 MAX_SANKEY_FLOWS = 300 MAX_LABEL_LENGTH = 160 MAX_TITLE_LENGTH = 200 @@ -39,6 +40,36 @@ class ChartDataError(ValueError): # something concrete to enforce, catching the most common shape mistakes # (wrong container type, missing key) before canonicalize_chart_data's own, # stricter pass. +# Optional scientific fields do not change any of the five legacy shapes. +_ERROR_ITEM_SCHEMA = { + "anyOf": [ + {"type": "number"}, + {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, + ] +} +_ERROR_SCHEMA = {"type": "array", "items": _ERROR_ITEM_SCHEMA} +_SCIENTIFIC_PROPERTIES = { + "xValues": {"type": "array", "items": {"type": "number"}}, + "xScale": {"type": "string", "enum": ["linear", "log10"]}, + "yScale": {"type": "string", "enum": ["linear", "log10"]}, + "xUnit": {"type": "string"}, + "yUnit": {"type": "string"}, + "xError": _ERROR_SCHEMA, + "yError": _ERROR_SCHEMA, + "series": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": {"type": "string"}, + "values": {"type": "array", "items": {"type": "number"}}, + "xError": _ERROR_SCHEMA, + "yError": _ERROR_SCHEMA, + }, + "required": ["name", "values"], + }, + }, +} _SERIES_PROPERTIES = { "title": {"type": "string"}, "labels": {"type": "array", "items": {"type": "string"}}, @@ -55,9 +86,15 @@ class ChartDataError(ValueError): }, "line": { "type": "object", - "properties": {"type": {"type": "string", "enum": ["line"]}, **_SERIES_PROPERTIES}, + "properties": {"type": {"type": "string", "enum": ["line"]}, **_SERIES_PROPERTIES, **_SCIENTIFIC_PROPERTIES}, "required": ["type", "labels", "values"], }, + "scatter": { + "type": "object", + "properties": {"type": {"type": "string", "enum": ["scatter"]}, + **_SERIES_PROPERTIES, **_SCIENTIFIC_PROPERTIES}, + "required": ["type", "xValues"], + }, "pie": { "type": "object", "properties": { @@ -238,6 +275,167 @@ def visit(node): visit(node) + +def _scientific_errors(raw, field, count): + """Normalize symmetric and asymmetric errors into [minus, plus] pairs.""" + if raw is None: + return None + if not isinstance(raw, list): + raise ChartDataError(f"{field} must be a list") + if len(raw) != count: + raise ChartDataError(f"{field} length must match the series length ({count})") + normalized = [] + for index, entry in enumerate(raw): + name = f"{field} at index {index}" + if isinstance(entry, list): + if len(entry) != 2: + raise ChartDataError(f"{name} must have exactly two magnitudes") + minus = _finite_number(entry[0], f"{name} lower magnitude") + plus = _finite_number(entry[1], f"{name} upper magnitude") + else: + minus = plus = _finite_number(entry, name) + if minus < 0 or plus < 0: + raise ChartDataError(f"{name} magnitudes must be nonnegative") + normalized.append([minus, plus]) + return normalized + + +def _check_scientific_axis(values, errors, scale, field): + """Check all coordinates AND error endpoints (including overflow).""" + for index, value in enumerate(values): + minus, plus = errors[index] if errors is not None else (0.0, 0.0) + lower, upper = value - minus, value + plus + if not math.isfinite(lower) or not math.isfinite(upper): + raise ChartDataError(f"{field} at index {index} has a non-finite error endpoint") + if scale == "log10" and lower <= 0: + raise ChartDataError( + f"{field} at index {index} and its lower error endpoint must be " + "greater than zero on a log10 axis" + ) + + +def _scientific_chart(data, chart_type, result): + """Additive v1 scientific path. Plain legacy line data never enters here.""" + raw_x = data.get("xValues") + if chart_type == "scatter" and raw_x is None: + raise ChartDataError("Scatter charts require numeric xValues") + if raw_x is not None: + if not isinstance(raw_x, list): + raise ChartDataError("xValues must be a list") + if not raw_x: + raise ChartDataError("xValues require at least one data point") + if len(raw_x) > MAX_SERIES_POINTS: + raise ChartDataError(f"Charts support at most {MAX_SERIES_POINTS} data points") + x_values = [_finite_number(value, f"xValues at index {i}") for i, value in enumerate(raw_x)] + result["xValues"] = x_values + else: + x_values = None + + for axis in ("xScale", "yScale"): + scale = data.get(axis, "linear") + if scale not in ("linear", "log10"): + raise ChartDataError(f"{axis} must be linear or log10") + result[axis] = scale + if result["xScale"] == "log10" and x_values is None: + raise ChartDataError("A log10 x-axis requires numeric xValues") + + for field in ("xUnit", "yUnit"): + if field in data and data[field] is not None: + result[field] = _clean_text(data[field], field) + + labels = data.get("labels") + if labels is not None: + if not isinstance(labels, list): + raise ChartDataError("Labels must be a list") + result["labels"] = [_clean_text(label, f"Label at index {i}") for i, label in enumerate(labels)] + + raw_series = data.get("series") + if raw_series is not None: + if not isinstance(raw_series, list) or not raw_series: + raise ChartDataError("series must be a nonempty list") + if len(raw_series) > MAX_NAMED_SERIES: + raise ChartDataError(f"Charts support at most {MAX_NAMED_SERIES} named series") + if "values" in data or "xError" in data or "yError" in data: + raise ChartDataError("Named series cannot be combined with top-level values or errors") + series = [] + seen_names = set() + for index, raw in enumerate(raw_series): + if not isinstance(raw, dict): + raise ChartDataError(f"series at index {index} must be an object") + name = _clean_text(raw.get("name"), f"series at index {index} name") + if name in seen_names: + raise ChartDataError(f"Duplicate series name: {name}") + seen_names.add(name) + values = raw.get("values") + if not isinstance(values, list): + raise ChartDataError(f"series {name} values must be a list") + if not values: + raise ChartDataError(f"series {name} requires at least one data point") + row = { + "name": name, + "values": [_finite_number(value, f"series {name} value at index {i}") for i, value in enumerate(values)], + } + for axis in ("xError", "yError"): + if axis in raw: + row[axis] = _scientific_errors(raw[axis], f"series {name} {axis}", len(values)) + series.append(row) + result["series"] = series + else: + raw_values = data.get("values") + if not isinstance(raw_values, list) or not raw_values: + raise ChartDataError(f"{chart_type.title()} charts require at least one data point") + series = [{ + "values": [_finite_number(value, f"Value at index {i}") for i, value in enumerate(raw_values)], + }] + result["values"] = series[0]["values"] + for axis in ("xError", "yError"): + if axis in data: + errors = _scientific_errors(data[axis], axis, len(raw_values)) + result[axis] = errors + series[0][axis] = errors + + count = len(series[0]["values"]) + if count > MAX_SERIES_POINTS or len(series) * count > MAX_SERIES_POINTS: + raise ChartDataError(f"Charts support at most {MAX_SERIES_POINTS} total series points") + if chart_type == "line" and count < 2: + raise ChartDataError("Line charts require at least two data points") + for row in series: + if len(row["values"]) != count: + raise ChartDataError(f"series {row.get('name', 'values')} length must match the other series ({count})") + if x_values is not None and len(x_values) != count: + raise ChartDataError(f"xValues length must match the series length ({count})") + if "labels" in result and len(result["labels"]) != count: + raise ChartDataError(f"labels length must match the series length ({count})") + if chart_type == "line" and x_values is None and "labels" not in result: + raise ChartDataError("Line charts require labels or numeric xValues") + + # Categorical line x positions are zero-based indexes, as before. Only + # numeric x-values can have an error interval or logarithmic scale. + if x_values is None and any(row.get("xError") is not None for row in series): + raise ChartDataError("xError requires numeric xValues") + if x_values is not None: + for row in series: + _check_scientific_axis(x_values, row.get("xError"), result["xScale"], "xValues") + for row in series: + _check_scientific_axis(row["values"], row.get("yError"), result["yScale"], + f"series {row.get('name', 'values')} values") + + # Check range arithmetic too: two finite endpoints can have an infinite + # span, which neither SVG pixel geometry nor mpl axis limits can draw. + for axis, values in (("xValues", x_values), ("values", [v for row in series for v in row["values"]])): + if values is not None and not math.isfinite(max(values) - min(values)): + raise ChartDataError(f"{axis} range must be finite") + + result["xAxis"] = _clean_text( + data.get("xAxis"), "X-axis label", + default="X" if chart_type == "scatter" else "Sequence", + ) + result["yAxis"] = _clean_text( + data.get("yAxis"), "Y-axis label", default="Y" if chart_type == "scatter" else "Value", + ) + return result + + def canonicalize_chart_data(data, chart_type=None): """Return a new, bounded chart payload or raise :class:`ChartDataError`. @@ -266,6 +464,19 @@ def canonicalize_chart_data(data, chart_type=None): ), } + if expected_type == "scatter" or ( + expected_type == "line" and any(key in data for key in + ("xValues", "series", "xError", "yError", "xScale", "yScale", "xUnit", "yUnit")) + ): + # The existing frontend wire validator accepts additive object keys, + # but its generated v1 enum (outside this feature's edit scope) has + # no "scatter" entry. ChartState.chart_type is already the + # authoritative discriminator. Omit only this optional nested field + # for scatter, so scene snapshots remain valid without touching codegen. + if expected_type == "scatter": + result.pop("type") + return _scientific_chart(data, expected_type, result) + if expected_type in {"bar", "line", "pie"}: labels = data.get("labels") values = data.get("values") From 0132cdf2c81a7bfde4276a12c0bf2e012f0e9007 Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:10:07 -0500 Subject: [PATCH 03/39] feat(charts): mirror strict scientific validation in TypeScript --- web_ui/src/app/canvas/chartSpec.ts | 189 ++++++++++++++++++++++++++++- 1 file changed, 187 insertions(+), 2 deletions(-) diff --git a/web_ui/src/app/canvas/chartSpec.ts b/web_ui/src/app/canvas/chartSpec.ts index 25215e98..2379f82a 100644 --- a/web_ui/src/app/canvas/chartSpec.ts +++ b/web_ui/src/app/canvas/chartSpec.ts @@ -15,10 +15,11 @@ import type { ChartDataRow, ChartFlowRow } from "../../lib/bridge-core/generated/scene-state"; export const CHART_SPEC_VERSION = 1; -export const SUPPORTED_CHART_TYPES = ["bar", "line", "pie", "histogram", "sankey"] as const; +export const SUPPORTED_CHART_TYPES = ["bar", "line", "pie", "histogram", "sankey", "scatter"] as const; export type SupportedChartType = (typeof SUPPORTED_CHART_TYPES)[number]; const MAX_SERIES_POINTS = 300; +const MAX_NAMED_SERIES = 12; const MAX_SANKEY_FLOWS = 300; const MAX_LABEL_LENGTH = 160; const MAX_TITLE_LENGTH = 200; @@ -57,6 +58,186 @@ function finiteNumber(value: unknown, fieldName: string): number { return num; } + +/** Additive scientific fields. The generated v1 wire validator accepts + * unknown properties, but not a new nested type enum: the outer chartType + * remains the scatter discriminator, and nested type is omitted for scatter. */ +export type ErrorPair = [number, number]; +export type AxisScale = "linear" | "log10"; +export interface ScientificSeries { + name: string; + values: number[]; + xError?: ErrorPair[] | null; + yError?: ErrorPair[] | null; +} +export type ScientificChartSpec = ChartDataRow & { + xValues?: number[]; + series?: ScientificSeries[]; + xError?: ErrorPair[] | null; + yError?: ErrorPair[] | null; + xScale?: AxisScale; + yScale?: AxisScale; + xUnit?: string; + yUnit?: string; +}; +export function scientificFields(spec: ChartDataRow): ScientificChartSpec { + return spec as ScientificChartSpec; +} +export function usesScientificMarks(data: ChartDataRow, chartType: string): boolean { + return chartType === "scatter" || + ["xValues", "series", "xError", "yError", "xScale", "yScale", "xUnit", "yUnit"].some((key) => key in data); +} + +function scientificErrors(value: unknown, field: string, count: number): ErrorPair[] | null { + if (value === undefined || value === null) return null; + if (!Array.isArray(value)) throw new ChartSpecError(field + " must be a list"); + if (value.length !== count) { + throw new ChartSpecError(field + " length must match the series length (" + count + ")"); + } + return value.map((entry, index): ErrorPair => { + const name = field + " at index " + index; + let minus: number; + let plus: number; + if (Array.isArray(entry)) { + if (entry.length !== 2) throw new ChartSpecError(name + " must have exactly two magnitudes"); + minus = finiteNumber(entry[0], name + " lower magnitude"); + plus = finiteNumber(entry[1], name + " upper magnitude"); + } else { + minus = plus = finiteNumber(entry, name); + } + if (minus < 0 || plus < 0) throw new ChartSpecError(name + " magnitudes must be nonnegative"); + return [minus, plus]; + }); +} + +function checkScientificAxis(values: number[], errors: ErrorPair[] | null | undefined, scale: AxisScale, field: string): void { + values.forEach((value, index) => { + const [minus, plus] = errors?.[index] ?? [0, 0]; + const lower = value - minus; + const upper = value + plus; + if (!Number.isFinite(lower) || !Number.isFinite(upper)) { + throw new ChartSpecError(field + " at index " + index + " has a non-finite error endpoint"); + } + if (scale === "log10" && lower <= 0) { + throw new ChartSpecError(field + " at index " + index + " and its lower error endpoint must be greater than zero on a log10 axis"); + } + }); +} + +interface ScientificValues { + name?: string; + values: number[]; + xError?: ErrorPair[] | null; + yError?: ErrorPair[] | null; +} + +function canonicalizeScientific(raw: Record, type: "line" | "scatter", result: ChartDataRow): ChartDataRow { + const output = result as ScientificChartSpec; + if (type === "scatter" && raw.xValues == null) { + throw new ChartSpecError("Scatter charts require numeric xValues"); + } + let xValues: number[] | undefined; + if (raw.xValues != null) { + if (!Array.isArray(raw.xValues)) throw new ChartSpecError("xValues must be a list"); + if (raw.xValues.length === 0) throw new ChartSpecError("xValues require at least one data point"); + if (raw.xValues.length > MAX_SERIES_POINTS) throw new ChartSpecError("Charts support at most 300 data points"); + xValues = raw.xValues.map((value, i) => finiteNumber(value, "xValues at index " + i)); + output.xValues = xValues; + } + for (const axis of ["xScale", "yScale"] as const) { + const scale = raw[axis] ?? "linear"; + if (scale !== "linear" && scale !== "log10") throw new ChartSpecError(axis + " must be linear or log10"); + output[axis] = scale; + } + if (output.xScale === "log10" && !xValues) { + throw new ChartSpecError("A log10 x-axis requires numeric xValues"); + } + for (const field of ["xUnit", "yUnit"] as const) { + if (raw[field] != null) output[field] = cleanText(raw[field], field); + } + if (raw.labels != null) { + if (!Array.isArray(raw.labels)) throw new ChartSpecError("Labels must be a list"); + output.labels = raw.labels.map((label, i) => cleanText(label, "Label at index " + i)); + } + const series: ScientificValues[] = []; + if (raw.series != null) { + if (!Array.isArray(raw.series) || raw.series.length === 0) { + throw new ChartSpecError("series must be a nonempty list"); + } + if (raw.series.length > MAX_NAMED_SERIES) throw new ChartSpecError("Charts support at most 12 named series"); + if ("values" in raw || "xError" in raw || "yError" in raw) { + throw new ChartSpecError("Named series cannot be combined with top-level values or errors"); + } + const names = new Set(); + raw.series.forEach((entry, index) => { + if (typeof entry !== "object" || entry === null || Array.isArray(entry)) { + throw new ChartSpecError("series at index " + index + " must be an object"); + } + const item = entry as Record; + const name = cleanText(item.name, "series at index " + index + " name"); + if (names.has(name)) throw new ChartSpecError("Duplicate series name: " + name); + names.add(name); + if (!Array.isArray(item.values)) throw new ChartSpecError("series " + name + " values must be a list"); + if (!item.values.length) throw new ChartSpecError("series " + name + " requires at least one data point"); + if (item.values.length > MAX_SERIES_POINTS) throw new ChartSpecError("Charts support at most 300 data points"); + const values = item.values.map((value, i) => finiteNumber(value, "series " + name + " value at index " + i)); + const row: ScientificValues = { name, values }; + for (const field of ["xError", "yError"] as const) { + if (field in item) row[field] = scientificErrors(item[field], "series " + name + " " + field, values.length); + } + series.push(row); + }); + output.series = series as ScientificSeries[]; + } else { + if (!Array.isArray(raw.values) || !raw.values.length) { + throw new ChartSpecError(type[0].toUpperCase() + type.slice(1) + " charts require at least one data point"); + } + if (raw.values.length > MAX_SERIES_POINTS) throw new ChartSpecError("Charts support at most 300 data points"); + const values = raw.values.map((value, i) => finiteNumber(value, "Value at index " + i)); + const row: ScientificValues = { values }; + output.values = values; + for (const field of ["xError", "yError"] as const) { + if (field in raw) { + row[field] = scientificErrors(raw[field], field, values.length); + output[field] = row[field]; + } + } + series.push(row); + } + const count = series[0].values.length; + if (count > MAX_SERIES_POINTS || series.length * count > MAX_SERIES_POINTS) { + throw new ChartSpecError("Charts support at most 300 total series points"); + } + if (type === "line" && count < 2) throw new ChartSpecError("Line charts require at least two data points"); + for (const row of series) { + if (row.values.length !== count) { + throw new ChartSpecError("series " + (row.name ?? "values") + " length must match the other series (" + count + ")"); + } + } + if (xValues && xValues.length !== count) { + throw new ChartSpecError("xValues length must match the series length (" + count + ")"); + } + if (output.labels && output.labels.length !== count) { + throw new ChartSpecError("labels length must match the series length (" + count + ")"); + } + if (type === "line" && !xValues && !output.labels) throw new ChartSpecError("Line charts require labels or numeric xValues"); + if (!xValues && series.some((row) => row.xError != null)) { + throw new ChartSpecError("xError requires numeric xValues"); + } + if (xValues) series.forEach((row) => checkScientificAxis(xValues!, row.xError, output.xScale!, "xValues")); + series.forEach((row) => checkScientificAxis(row.values, row.yError, output.yScale!, "series " + (row.name ?? "values") + " values")); + const allY = series.flatMap((row) => row.values); + if (xValues && !Number.isFinite(Math.max(...xValues) - Math.min(...xValues))) { + throw new ChartSpecError("xValues range must be finite"); + } + if (!Number.isFinite(Math.max(...allY) - Math.min(...allY))) { + throw new ChartSpecError("values range must be finite"); + } + output.xAxis = cleanText(raw.xAxis, "X-axis label", { default: type === "scatter" ? "X" : "Sequence" }); + output.yAxis = cleanText(raw.yAxis, "Y-axis label", { default: type === "scatter" ? "Y" : "Value" }); + return output; +} + interface RawSankeyFlow { source: unknown; target: unknown; @@ -138,13 +319,17 @@ export function canonicalizeChartSpec(data: unknown, chartType?: string | null): const result: ChartDataRow = { version: CHART_SPEC_VERSION, - type: expectedType, + type: expectedType === "scatter" ? undefined : expectedType, title: cleanText(raw.title, "Chart title", { default: `${expectedType[0].toUpperCase()}${expectedType.slice(1)} Chart`, maxLength: MAX_TITLE_LENGTH, }), }; + if (expectedType === "scatter" || (expectedType === "line" && usesScientificMarks(raw as ChartDataRow, expectedType))) { + return canonicalizeScientific(raw, expectedType, result); + } + if (expectedType === "bar" || expectedType === "line" || expectedType === "pie") { const labels = raw.labels; const values = raw.values; From 976f54039c0c3a2cd95af1ae1a6a393d5590e166 Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:11:21 -0500 Subject: [PATCH 04/39] feat(charts): render scientific coordinates and errors in PNG/SVG --- graphlink_chart_rendering.py | 84 +++++++++++++++++++++++++++++++++++- 1 file changed, 83 insertions(+), 1 deletion(-) diff --git a/graphlink_chart_rendering.py b/graphlink_chart_rendering.py index a03e109e..1b200eb1 100644 --- a/graphlink_chart_rendering.py +++ b/graphlink_chart_rendering.py @@ -310,6 +310,82 @@ def _render_line_chart(ax, chart_data: dict[str, Any], theme: dict[str, Any], la return True + +def _render_scientific_cartesian(ax, data: dict[str, Any], theme: dict[str, Any], + layout_width: float, chart_type: str) -> bool: + """Render exactly the validated numeric coordinates and error intervals. + + This intentionally does not replace _render_line_chart: a saved v1 + categorical line must keep its historical fill, ticks and labels. + Both PNG and SVG call this same function via _render_chart_content. + """ + x_values = data.get("xValues") + rows = data.get("series") + if rows is None: + rows = [{"values": data["values"], "xError": data.get("xError"), + "yError": data.get("yError")}] + if x_values is None: + x_values = list(range(len(rows[0]["values"]))) + + def error_bounds(errors): + if errors is None: + return None + return ([pair[0] for pair in errors], [pair[1] for pair in errors]) + + def axis_label(axis): + label = data[axis + "Axis"] + unit = data.get(axis + "Unit") + return f"{label} ({unit})" if unit else label + + _prepare_standard_axes( + ax, theme, axis_label("x"), axis_label("y"), y_grid=True, + ) + if data.get("xScale") == "log10": + ax.set_xscale("log", base=10) + if data.get("yScale") == "log10": + ax.set_yscale("log", base=10) + + # Markers and line styles distinguish series even if two dark-theme + # palette entries have very similar RGB values. + markers = ("o", "s", "^", "D", "v", "P", "X", "*") + styles = ("-", "--", "-.", ":") + for index, row in enumerate(rows): + color = theme["cycle"][index % len(theme["cycle"])] + label = row.get("name") + ax.errorbar( + x_values, + row["values"], + xerr=error_bounds(row.get("xError")), + yerr=error_bounds(row.get("yError")), + fmt=markers[index % len(markers)], + linestyle=styles[index % len(styles)] if chart_type == "line" else "none", + linewidth=2.0, + markersize=6, + color=color, + markerfacecolor=theme["surface"], + markeredgecolor=color, + markeredgewidth=1.5, + ecolor=color, + elinewidth=1.35, + capsize=3.5, + capthick=1.2, + label=label, + zorder=4 + index, + ) + if data.get("series"): + legend = ax.legend(frameon=False, loc="best", fontsize=8) + for text in legend.get_texts(): + text.set_color(theme["text"]) + + if data.get("xValues") is None: + _set_categorical_ticks(ax, list(x_values), data["labels"], layout_width) + # Keep all interval endpoints visible, on both linear and log axes. + # matplotlib's dataLim accounts for errorbar cap endpoints; no silent + # clipping, filtering or arbitrary domain transforms are introduced. + ax.margins(x=0.08, y=0.16) + return True + + def _render_pie_chart(figure, ax, chart_data: dict[str, Any], theme: dict[str, Any]) -> bool: values = chart_data["values"] labels = chart_data["labels"] @@ -646,7 +722,13 @@ def _render_chart_content(figure, chart_type: str, chart_data: dict[str, Any], t if chart_type == "bar": use_tight_layout = _render_bar_chart(ax, canonical, theme, layout_width) elif chart_type == "line": - use_tight_layout = _render_line_chart(ax, canonical, theme, layout_width) + if any(key in canonical for key in + ("xValues", "series", "xError", "yError", "xScale", "yScale", "xUnit", "yUnit")): + use_tight_layout = _render_scientific_cartesian(ax, canonical, theme, layout_width, chart_type) + else: + use_tight_layout = _render_line_chart(ax, canonical, theme, layout_width) + elif chart_type == "scatter": + use_tight_layout = _render_scientific_cartesian(ax, canonical, theme, layout_width, chart_type) elif chart_type == "pie": use_tight_layout = _render_pie_chart(figure, ax, canonical, theme) elif chart_type == "histogram": From d4d8b1855abcba610bd6a260efb45fa00329ffa1 Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:12:14 -0500 Subject: [PATCH 05/39] feat(charts): add pure log10 scales and bounded ticks --- web_ui/src/app/canvas/charts/chartScales.ts | 24 +++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/web_ui/src/app/canvas/charts/chartScales.ts b/web_ui/src/app/canvas/charts/chartScales.ts index bc3b6709..9b44d4cc 100644 --- a/web_ui/src/app/canvas/charts/chartScales.ts +++ b/web_ui/src/app/canvas/charts/chartScales.ts @@ -28,6 +28,30 @@ export function createLinearScale(domain: [number, number], range: [number, numb return (value: number) => r0 + ((value - d0) / span) * (r1 - r0); } +/** Log10 maps actual positive coordinates, never the point index or a + * rounded label. Callers validate all endpoints before constructing it. */ +export function createLog10Scale(domain: [number, number], range: [number, number]): Scale { + const [d0, d1] = domain.map((value) => Math.log10(value)); + const [r0, r1] = range; + const span = d1 - d0; + if (!Number.isFinite(span) || span === 0) return () => (r0 + r1) / 2; + return (value: number) => r0 + (Math.log10(value) - d0) / span * (r1 - r0); +} + +/** Power-of-ten ticks, downsampled for wide domains; bounded even across + * the full representable floating-point exponent range. */ +export function log10Ticks(min: number, max: number, targetCount = 6): number[] { + const first = Math.ceil(Math.log10(min)); + const last = Math.floor(Math.log10(max)); + if (first > last) return [min, max].filter((v, i, a) => i === 0 || v !== a[0]); + const stride = Math.max(1, Math.ceil((last - first + 1) / Math.max(1, targetCount))); + const ticks: number[] = []; + for (let power = first; power <= last; power += stride) { + ticks.push(10 ** power); + } + return ticks; +} + /** "Nice" round-number ticks spanning at least [min, max] - the classic * Sparks/D3-style algorithm: pick a step from the {1, 2, 5} x 10^n family * closest to the ideal step for the requested tick count, then emit every From 98408243dc8dc103bd6ac24fb7d7ed38fe116448 Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:13:17 -0500 Subject: [PATCH 06/39] feat(charts): shared scientific domains and honest log tick labels --- web_ui/src/app/canvas/charts/chartScales.ts | 22 +++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/web_ui/src/app/canvas/charts/chartScales.ts b/web_ui/src/app/canvas/charts/chartScales.ts index 9b44d4cc..d3ec6e25 100644 --- a/web_ui/src/app/canvas/charts/chartScales.ts +++ b/web_ui/src/app/canvas/charts/chartScales.ts @@ -52,6 +52,28 @@ export function log10Ticks(min: number, max: number, targetCount = 6): number[] return ticks; } +/** A tick on a log axis must never be formatted as zero or rounded + * to a neighbouring integer (the legacy value-label formatter may do both). */ +export function formatLogTick(value: number): string { + return value.toExponential(0); +} + +/** Shared scientific domain math: include every symmetric/asymmetric error + * endpoint. Interpolation is linear in data space or log10(data), never in + * point index. */ +export function scientificDomain(min: number, max: number, scale: "linear" | "log10"): [number, number] { + if (scale === "log10") { + const low = Math.log10(min); + const high = Math.log10(max); + const padding = Math.max((high - low) * 0.12, 0.18); + // Clamp to finite representable powers; neither endpoint can become + // Infinity/zero even when a valid value is near a float limit. + return [10 ** Math.max(-323, low - padding), 10 ** Math.min(308, high + padding)]; + } + const padding = Math.max((max - min) * 0.12, Math.max(Math.abs(min), Math.abs(max), 1) * 0.02); + return [Math.max(-Number.MAX_VALUE, min - padding), Math.min(Number.MAX_VALUE, max + padding)]; +} + /** "Nice" round-number ticks spanning at least [min, max] - the classic * Sparks/D3-style algorithm: pick a step from the {1, 2, 5} x 10^n family * closest to the ideal step for the requested tick count, then emit every From ceda9bfb924f76a9a62affe1dcc33d11a6e3816a Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:13:30 -0500 Subject: [PATCH 07/39] feat(charts): support precise logarithmic tick formatting --- web_ui/src/app/canvas/charts/CartesianAxes.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/web_ui/src/app/canvas/charts/CartesianAxes.tsx b/web_ui/src/app/canvas/charts/CartesianAxes.tsx index 1bb53d72..292d3c0d 100644 --- a/web_ui/src/app/canvas/charts/CartesianAxes.tsx +++ b/web_ui/src/app/canvas/charts/CartesianAxes.tsx @@ -19,6 +19,7 @@ export interface CartesianAxesProps { innerHeight: number; yTicks: number[]; yScale: Scale; + yTickFormat?: (value: number) => string; xAxisLabel: string; yAxisLabel: string; xTicks: XTick[]; @@ -38,6 +39,7 @@ export function CartesianAxes({ innerHeight, yTicks, yScale, + yTickFormat = formatValue, xAxisLabel, yAxisLabel, xTicks, @@ -52,7 +54,7 @@ export function CartesianAxes({ - {formatValue(tick)} + {yTickFormat(tick)} ); From 839de1cc3a005baab837ac1b30cb1960044394a2 Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:14:50 -0500 Subject: [PATCH 08/39] feat(charts): interactive scatter and multiseries marks with uncertainty --- .../canvas/charts/ScientificChartMarks.tsx | 209 ++++++++++++++++++ 1 file changed, 209 insertions(+) create mode 100644 web_ui/src/app/canvas/charts/ScientificChartMarks.tsx diff --git a/web_ui/src/app/canvas/charts/ScientificChartMarks.tsx b/web_ui/src/app/canvas/charts/ScientificChartMarks.tsx new file mode 100644 index 00000000..93cd11e8 --- /dev/null +++ b/web_ui/src/app/canvas/charts/ScientificChartMarks.tsx @@ -0,0 +1,209 @@ +/** Scientific line and scatter marks. No charting library: the same finite + * coordinates/error magnitudes checked by both canonicalizers are mapped to + * SVG; only the scale (linear/log10) changes, never the numeric data. */ +import { scientificFields } from "../chartSpec"; +import type { AxisScale, ErrorPair } from "../chartSpec"; +import type { ChartMarksProps } from "./BarChartMarks"; +import { CartesianAxes, type XTick } from "./CartesianAxes"; +import { + createLinearScale, createLog10Scale, formatLogTick, formatValue, + log10Ticks, niceTicks, pickCategoricalTicks, scientificDomain, wrapLabel, + type Scale, +} from "./chartScales"; +import { computeBottomMargin, tooltipPositionFromEvent } from "./chartLayout"; + +interface PlottedSeries { + name: string; + values: number[]; + xError?: ErrorPair[] | null; + yError?: ErrorPair[] | null; +} + +export function scientificAxisLabel(label: string, unit?: string): string { + return unit ? label + " (" + unit + ")" : label; +} + +function axisExtent(values: number[], errors?: ErrorPair[] | null): [number, number] { + let low = Infinity; + let high = -Infinity; + for (let i = 0; i < values.length; i += 1) { + const [minus, plus] = errors?.[i] ?? [0, 0]; + low = Math.min(low, values[i] - minus); + high = Math.max(high, values[i] + plus); + } + return [low, high]; +} + +/** These are physical coordinates, including every error endpoint. */ +export function scientificExtents(xValues: number[], series: PlottedSeries[]): { + x: [number, number]; y: [number, number]; +} { + let xMin = Infinity; + let xMax = -Infinity; + let yMin = Infinity; + let yMax = -Infinity; + for (const row of series) { + const [loX, hiX] = axisExtent(xValues, row.xError); + const [loY, hiY] = axisExtent(row.values, row.yError); + xMin = Math.min(xMin, loX); + xMax = Math.max(xMax, hiX); + yMin = Math.min(yMin, loY); + yMax = Math.max(yMax, hiY); + } + return { x: [xMin, xMax], y: [yMin, yMax] }; +} + +function scaleFor(domain: [number, number], range: [number, number], axis: AxisScale): Scale { + return axis === "log10" ? createLog10Scale(domain, range) : createLinearScale(domain, range); +} + +function labeledTicks(domain: [number, number], scale: AxisScale): number[] { + return scale === "log10" ? log10Ticks(...domain) : niceTicks(...domain, 5); +} + +/** Keep tooltips exact: the legacy abbreviated tick-label formatter rounds + * >=1000 to integers and values <.001 to zero, which is wrong for readings. */ +export function exactWithUnit(value: number, unit?: string): string { + return String(value) + (unit ? " " + unit : ""); +} + +function errorWithUnit(pair: ErrorPair, unit?: string): string { + return "-" + String(pair[0]) + "/+" + String(pair[1]) + (unit ? " " + unit : ""); +} + +export function ScientificChartMarks({ + chartData, theme, width, height, onHover, wrapperRef, chartType, +}: ChartMarksProps & { chartType: string }) { + const data = scientificFields(chartData); + const named = data.series; + const series: PlottedSeries[] = named ?? [{ + name: "", + values: data.values ?? [], + xError: data.xError, + yError: data.yError, + }]; + if (series.length === 0 || series[0].values.length === 0 || width <= 0 || height <= 0) return null; + + const xValues = data.xValues ?? series[0].values.map((_, index) => index); + const xScaleType = data.xScale ?? "linear"; + const yScaleType = data.yScale ?? "linear"; + const extents = scientificExtents(xValues, series); + const xDomain = scientificDomain(...extents.x, xScaleType); + const yDomain = scientificDomain(...extents.y, yScaleType); + + const legendColumns = Math.min(4, named?.length ?? 0); + const legendRows = named ? Math.ceil(named.length / legendColumns) : 0; + const marginTop = 16 + legendRows * 22; + const marginLeft = 74; + const marginRight = 22; + const innerWidth = Math.max(1, width - marginLeft - marginRight); + const categorical = chartType === "line" && !data.xValues; + const { indexes, rotate } = categorical + ? pickCategoricalTicks(xValues.length, innerWidth) + : { indexes: [], rotate: false }; + const marginBottom = computeBottomMargin(rotate, true); + const innerHeight = Math.max(1, height - marginTop - marginBottom); + const x = scaleFor(xDomain, [0, innerWidth], xScaleType); + const y = scaleFor(yDomain, [innerHeight, 0], yScaleType); + const yTicks = labeledTicks(yDomain, yScaleType); + const xTicks: XTick[] = categorical + ? indexes.map((index) => ({ + position: x(xValues[index]), + lines: wrapLabel(data.labels?.[index] ?? "", 14, 2), + })) + : labeledTicks(xDomain, xScaleType).map((value) => ({ + position: x(value), + lines: [xScaleType === "log10" ? formatLogTick(value) : formatValue(value)], + })); + const palette = theme.categorical.length ? theme.categorical : [theme.text]; + + return ( + + 0 && yScaleType === "linear" ? y(0) : null} + /> + {named && ( + + {named.map((row, index) => { + const col = index % legendColumns; + const legendRow = Math.floor(index / legendColumns); + const lx = col * innerWidth / legendColumns; + const ly = -20 - (legendRows - 1 - legendRow) * 22; + return ( + + + {row.name} + + ); + })} + + )} + {series.map((row, seriesIndex) => { + const color = palette[seriesIndex % palette.length]; + const name = row.name || data.title || "Series"; + const path = xValues.map((xValue, index) => + (index === 0 ? "M " : "L ") + x(xValue) + " " + y(row.values[index]), + ).join(" "); + return ( + + {chartType === "line" && ( + + )} + {xValues.map((xValue, index) => { + const value = row.values[index]; + const centerX = x(xValue); + const centerY = y(value); + const xError = row.xError?.[index]; + const yError = row.yError?.[index]; + const tooltipRows = [ + { label: data.xAxis ?? "X", value: categorical + ? data.labels?.[index] ?? String(index) + : exactWithUnit(xValue, data.xUnit) }, + { label: data.yAxis ?? "Y", value: exactWithUnit(value, data.yUnit) }, + ]; + if (xError) tooltipRows.push({ label: "X error", value: errorWithUnit(xError, data.xUnit) }); + if (yError) tooltipRows.push({ label: "Y error", value: errorWithUnit(yError, data.yUnit) }); + return ( + + {xError && ( + + + + + + )} + {yError && ( + + + + + + )} + { + const position = tooltipPositionFromEvent(event, wrapperRef); + onHover({ title: name, rows: tooltipRows, ...position }); + }} + onPointerLeave={() => onHover(null)} + /> + + ); + })} + + ); + })} + + ); +} From f0db9e982e50aa592608031aa8c8e85258a7fcdb Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:15:16 -0500 Subject: [PATCH 09/39] feat(charts): dispatch scientific marks, retain legacy line renderer --- web_ui/src/app/canvas/charts/ChartRenderer.tsx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/web_ui/src/app/canvas/charts/ChartRenderer.tsx b/web_ui/src/app/canvas/charts/ChartRenderer.tsx index fbbdc021..a916edd8 100644 --- a/web_ui/src/app/canvas/charts/ChartRenderer.tsx +++ b/web_ui/src/app/canvas/charts/ChartRenderer.tsx @@ -17,12 +17,13 @@ import { useMemo, useState } from "react"; import type { ChartDataRow } from "../../../lib/bridge-core/generated/scene-state"; -import { canonicalizeChartSpec, ChartSpecError } from "../chartSpec"; +import { canonicalizeChartSpec, ChartSpecError, usesScientificMarks } from "../chartSpec"; import { useChartTheme, useElementSize } from "./chartHooks"; import { useZoomPane } from "./useZoomPane"; import { ChartTooltip, type TooltipContent } from "./ChartTooltip"; import { BarChartMarks } from "./BarChartMarks"; import { LineChartMarks } from "./LineChartMarks"; +import { ScientificChartMarks } from "./ScientificChartMarks"; import { PieChartMarks } from "./PieChartMarks"; import { HistogramChartMarks } from "./HistogramChartMarks"; import { SankeyChartMarks } from "./SankeyChartMarks"; @@ -79,7 +80,10 @@ function ChartRenderer({ chartType, chartData }: ChartRendererProps) { > {chartType === "bar" && } - {chartType === "line" && } + {chartType === "line" && (usesScientificMarks(canonical.data, chartType) + ? + : )} + {chartType === "scatter" && } {chartType === "pie" && } {chartType === "histogram" && } {chartType === "sankey" && } From 9283b2ec1a5ebc2e4ae02c113e8405241936ce8f Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:15:51 -0500 Subject: [PATCH 10/39] feat(charts): show scientific series and errors at overview LOD --- .../src/app/canvas/charts/ChartOverview.tsx | 51 +++++++++++++++++-- 1 file changed, 47 insertions(+), 4 deletions(-) diff --git a/web_ui/src/app/canvas/charts/ChartOverview.tsx b/web_ui/src/app/canvas/charts/ChartOverview.tsx index ec3d618c..76be3caa 100644 --- a/web_ui/src/app/canvas/charts/ChartOverview.tsx +++ b/web_ui/src/app/canvas/charts/ChartOverview.tsx @@ -1,16 +1,17 @@ import { memo } from "react"; import type { ChartDataRow } from "../../../lib/bridge-core/generated/scene-state"; -import { canonicalizeChartSpec, ChartSpecError } from "../chartSpec"; -import { computeHistogramBins, createLinearScale, formatValue } from "./chartScales"; +import { canonicalizeChartSpec, ChartSpecError, scientificFields, usesScientificMarks } from "../chartSpec"; +import { computeHistogramBins, createLinearScale, createLog10Scale, formatValue, scientificDomain } from "./chartScales"; import { computeSankeyLayout, sankeyFlowPath } from "./sankeyLayout"; import { buildSlices } from "./pieSlices"; import { FALLBACK_CHART_THEME } from "./chartTheme"; +import { scientificExtents } from "./ScientificChartMarks"; const WIDTH = 240; const HEIGHT = 116; const PALETTE = FALLBACK_CHART_THEME.categorical; -function overviewMarks(spec: ChartDataRow) { +function overviewMarks(spec: ChartDataRow, chartType: string) { if (spec.type === "sankey") { const { nodes, flows } = computeSankeyLayout(spec.flows ?? []); return ( @@ -24,6 +25,48 @@ function overviewMarks(spec: ChartDataRow) { ); } + if (chartType === "scatter" || (chartType === "line" && usesScientificMarks(spec, chartType))) { + const data = scientificFields(spec); + const series = data.series ?? [{ + name: "", + values: data.values ?? [], + xError: data.xError, + yError: data.yError, + }]; + const xs = data.xValues ?? series[0].values.map((_, index) => index); + const extents = scientificExtents(xs, series); + const xDomain = scientificDomain(...extents.x, data.xScale ?? "linear"); + const yDomain = scientificDomain(...extents.y, data.yScale ?? "linear"); + const x = data.xScale === "log10" + ? createLog10Scale(xDomain, [8, WIDTH - 8]) + : createLinearScale(xDomain, [8, WIDTH - 8]); + const y = data.yScale === "log10" + ? createLog10Scale(yDomain, [HEIGHT - 10, 8]) + : createLinearScale(yDomain, [HEIGHT - 10, 8]); + return series.map((row, seriesIndex) => ( + + {chartType === "line" && ( + x(v) + "," + y(row.values[i])).join(" ")} /> + )} + {xs.map((xValue, index) => { + const cx = x(xValue); + const cy = y(row.values[index]); + const xError = row.xError?.[index]; + const yError = row.yError?.[index]; + return ( + + {xError && } + {yError && } + + + ); + })} + + )); + } + const values = spec.values ?? []; if (spec.type === "pie") { return buildSlices(spec.labels ?? [], values).map((slice, index) => { @@ -88,7 +131,7 @@ const ChartOverview = memo(function ChartOverview({ chartData, chartType }: { return (
- {overviewMarks(spec)} + {overviewMarks(spec, chartType)}
); From ff1e573a6dcd7e5b909f276610d4311362d3e73a Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:16:36 -0500 Subject: [PATCH 11/39] feat(charts): accept validated model-generation scientific options --- backend/api/intents_chart.py | 49 +++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/backend/api/intents_chart.py b/backend/api/intents_chart.py index 61937953..7f414a4c 100644 --- a/backend/api/intents_chart.py +++ b/backend/api/intents_chart.py @@ -40,7 +40,42 @@ def register_chart_intents( publish_scene = make_publish_scene(bus) - async def generate_chart(parent_node_id, chart_type): + def chart_source_options(chart_type, options): + """Only the four scientific capabilities are requestable. Options + steer extraction; they never supply, fabricate or override data.""" + if options is None or options == {}: + return "" + if not isinstance(options, dict): + raise ChartDataError("chartOptions must be an object") + allowed = {"multipleSeries", "errorBars", "xScale", "yScale", "xUnit", "yUnit"} + unknown = set(options) - allowed + if unknown: + raise ChartDataError("Unsupported chartOptions: " + ", ".join(sorted(map(str, unknown)))) + if chart_type not in ("line", "scatter"): + raise ChartDataError("Scientific chartOptions require line or scatter") + lines = [] + for key in ("multipleSeries", "errorBars"): + if key in options: + if not isinstance(options[key], bool): + raise ChartDataError(f"{key} must be a boolean") + if options[key]: + lines.append("Extract " + ("multiple named series" if key == "multipleSeries" + else "per-point error magnitudes") + + " only where they are explicitly stated in the source.") + for key in ("xScale", "yScale"): + if key in options: + if options[key] not in ("linear", "log10"): + raise ChartDataError(f"{key} must be linear or log10") + lines.append(f"Use {key}={options[key]} exactly.") + for key in ("xUnit", "yUnit"): + if key in options: + value = options[key] + if not isinstance(value, str) or not value.strip() or len(value.strip()) > 160: + raise ChartDataError(f"{key} must be a nonempty unit of at most 160 characters") + lines.append(f"Use {key}={value.strip()!r} exactly.") + return "\n".join(lines) + + async def generate_chart(parent_node_id, chart_type, chartOptions=None): if not parent_node_id or parent_node_id not in document.nodes: notifications.show( "Please select a valid node to branch from before generating a chart.", @@ -58,8 +93,20 @@ async def generate_chart(parent_node_id, chart_type): await bus.publish("notification") return None + try: + option_prompt = chart_source_options(normalized_chart_type, chartOptions) + except ChartDataError as exc: + notifications.show(str(exc), "warning") + await bus.publish("notification") + return None + branch_history = document.chat_branch_history(parent_node_id) source_text = _chart_source_text(branch_history) + if option_prompt: + source_text = ( + "Requested scientific chart options (only extract values present in the source):\n" + + option_prompt + "\n\n" + source_text + ) result_holder: dict[str, str] = {} From 8e0edf9619403ef1c3dcfc736acfdce9e4a23228 Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:17:11 -0500 Subject: [PATCH 12/39] test(evals): add scatter with asymmetric error-bar fixture --- .../chart/scatter_calibration_error_bars.json | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 backend/evals/fixtures/chart/scatter_calibration_error_bars.json diff --git a/backend/evals/fixtures/chart/scatter_calibration_error_bars.json b/backend/evals/fixtures/chart/scatter_calibration_error_bars.json new file mode 100644 index 00000000..ec953046 --- /dev/null +++ b/backend/evals/fixtures/chart/scatter_calibration_error_bars.json @@ -0,0 +1,70 @@ +{ + "name": "scatter_calibration_error_bars", + "kind": "chart", + "input": { + "chart_type": "scatter", + "source_text": "Calibration data: concentrations (mg/L) 1, 10, 100. Control response (mV): 0.9, 1.8, 3.2, with y uncertainties +/-0.1, -0.1/+0.3, +/-0.2 respectively. Treatment response (mV): 1.1, 2.1, 3.5. Concentration uncertainties: +/-0.05 at 1, -1/+2 at 10, +/-10 at 100. Use log10 for concentration." + }, + "scripted_response": "{\"type\":\"scatter\",\"title\":\"Calibration\",\"xAxis\":\"Concentration\",\"yAxis\":\"Response\",\"xUnit\":\"mg/L\",\"yUnit\":\"mV\",\"xScale\":\"log10\",\"yScale\":\"linear\",\"xValues\":[1,10,100],\"series\":[{\"name\":\"Control\",\"values\":[0.9,1.8,3.2],\"xError\":[0.05,[1,2],10],\"yError\":[0.1,[0.1,0.3],0.2]},{\"name\":\"Treatment\",\"values\":[1.1,2.1,3.5]}]}", + "expected": { + "version": 1, + "title": "Calibration", + "xAxis": "Concentration", + "yAxis": "Response", + "xUnit": "mg/L", + "yUnit": "mV", + "xScale": "log10", + "yScale": "linear", + "xValues": [ + 1, + 10, + 100 + ], + "series": [ + { + "name": "Control", + "values": [ + 0.9, + 1.8, + 3.2 + ], + "xError": [ + [ + 0.05, + 0.05 + ], + [ + 1, + 2 + ], + [ + 10, + 10 + ] + ], + "yError": [ + [ + 0.1, + 0.1 + ], + [ + 0.1, + 0.3 + ], + [ + 0.2, + 0.2 + ] + ] + }, + { + "name": "Treatment", + "values": [ + 1.1, + 2.1, + 3.5 + ] + } + ] + } +} From 44f02c6aa3745940b6c4d975396adaa0da517964 Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:18:54 -0500 Subject: [PATCH 13/39] test(charts): strict scientific validation and historical fixture parity --- backend/tests/test_chart_scientific.py | 155 +++++++++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 backend/tests/test_chart_scientific.py diff --git a/backend/tests/test_chart_scientific.py b/backend/tests/test_chart_scientific.py new file mode 100644 index 00000000..4a0fc1c9 --- /dev/null +++ b/backend/tests/test_chart_scientific.py @@ -0,0 +1,155 @@ +"""Scientific chart validation and all historical eval fixture regressions.""" + +import json +from pathlib import Path + +import pytest + +from graphlink_chart_data import ChartDataError, canonicalize_chart_data +from graphlink_chart_rendering import render_chart_png, render_chart_svg + + +def _scatter(**overrides): + spec = { + "type": "scatter", + "title": "Calibration", + "xValues": [1, 10, 100], + "series": [ + {"name": "Control", "values": [0.9, 1.8, 3.2], + "xError": [0.05, [1, 2], 10], + "yError": [0.1, [0.1, 0.3], 0.2]}, + {"name": "Treatment", "values": [1.1, 2.1, 3.5]}, + ], + "xScale": "log10", "yScale": "linear", + "xAxis": "Concentration", "yAxis": "Response", + "xUnit": "mg/L", "yUnit": "mV", + } + spec.update(overrides) + return spec + + +def test_scatter_canonicalizes_symmetric_and_asymmetric_errors_and_named_series(): + spec = canonicalize_chart_data(_scatter(), "scatter") + assert spec["version"] == 1 + # The nested type is optional in ChartDataRow. The authoritative outer + # ChartState.chart_type is "scatter", preserving the existing generated + # wire enum until a future (separately scoped) schema change. + assert "type" not in spec + assert spec["xValues"] == [1.0, 10.0, 100.0] + assert spec["series"][0]["xError"] == [[0.05, 0.05], [1.0, 2.0], [10.0, 10.0]] + assert spec["series"][0]["yError"] == [[0.1, 0.1], [0.1, 0.3], [0.2, 0.2]] + assert spec["series"][1]["name"] == "Treatment" + assert canonicalize_chart_data(spec, "scatter") == spec + + +@pytest.mark.parametrize("key,value,match", [ + ("xValues", [1.0, float("nan"), 3.0], "xValues at index 1.*finite"), + ("xValues", [1.0, float("inf"), 3.0], "xValues at index 1.*finite"), + ("values", [2, -float("inf"), 4], "Value at index 1.*finite"), + ("xError", [0.1, float("nan"), 0.2], "xError at index 1.*finite"), + ("yError", [[0, float("inf")], 0.1, 0.1], "upper magnitude.*finite"), + ("xError", [0.1, -0.1, 0.1], "magnitudes must be nonnegative"), + ("yError", [[-0.1, 0.2], 0.1, 0.1], "magnitudes must be nonnegative"), + ("yError", [[0.1, 0.2, 0.3], 0.1, 0.1], "exactly two"), + ("xError", [0.1, 0.2], "length must match"), + ("xValues", [1.0, 2.0], "length must match"), + ("xScale", "ln", "must be linear or log10"), +]) +def test_scatter_strictly_rejects_invalid_numeric_inputs(key, value, match): + spec = {"type": "scatter", "xValues": [1, 2, 3], "values": [2, 3, 4]} + spec[key] = value + with pytest.raises(ChartDataError, match=match): + canonicalize_chart_data(spec, "scatter") + + +@pytest.mark.parametrize("data,match", [ + ({"xScale": "log10", "xValues": [0, 10, 100]}, "log10 axis"), + ({"xScale": "log10", "xValues": [-1, 10, 100]}, "log10 axis"), + ({"xScale": "log10", "xValues": [1, 10, 100], "xError": [1, 0, 0]}, "lower error endpoint"), + ({"yScale": "log10", "values": [0, 2, 3]}, "log10 axis"), + ({"yScale": "log10", "values": [1, 2, 3], "yError": [1, 0, 0]}, "lower error endpoint"), + ({"values": [1e308, 1e308, 1e308], "yError": [1e308, 0, 0]}, + "non-finite error endpoint"), + ({"series": [{"name": "One", "values": [1, 2, 3]}, + {"name": "Two", "values": [1, 2]}]}, "length must match"), + ({"series": [{"name": "Same", "values": [1, 2, 3]}, + {"name": "Same", "values": [2, 3, 4]}]}, "Duplicate series name"), +]) +def test_scientific_rejects_bad_log_bounds_and_series_lengths(data, match): + base = {"type": "scatter", "xValues": [1, 10, 100], "values": [1, 2, 3]} + if "series" in data: + base.pop("values") + base.update(data) + with pytest.raises(ChartDataError, match=match): + canonicalize_chart_data(base, "scatter") + + +def test_scientific_line_can_use_categorical_labels_and_y_error_without_changing_legacy_line(): + old = {"type": "line", "labels": ["A", "B"], "values": [2, 4]} + assert canonicalize_chart_data(old, "line") == { + "version": 1, "type": "line", "title": "Line Chart", + "labels": ["A", "B"], "values": [2.0, 4.0], + "xAxis": "Sequence", "yAxis": "Value", + } + new = canonicalize_chart_data({**old, "yError": [0.2, [0.1, 0.3]]}, "line") + assert new["yError"] == [[0.2, 0.2], [0.1, 0.3]] + assert new["values"] == [2, 4] + with pytest.raises(ChartDataError, match="xError requires numeric xValues"): + canonicalize_chart_data({**old, "xError": [1, 1]}, "line") + + +def test_all_existing_chart_eval_fixtures_are_byte_shape_compatible(): + folder = Path(__file__).parents[1] / "evals" / "fixtures" / "chart" + historic = sorted(path for path in folder.glob("*.json") + if path.name != "scatter_calibration_error_bars.json") + assert {p.stem for p in historic} == { + "bar_support_tickets", "line_daily_active_users", "pie_engineering_budget" + } + for path in historic: + fixture = json.loads(path.read_text(encoding="utf-8")) + result = canonicalize_chart_data(json.loads(fixture["scripted_response"]), + fixture["input"]["chart_type"]) + assert result == fixture["expected"], path.name + assert canonicalize_chart_data(result, result["type"]) == result + + +def test_scatter_fixture_validates_identically_to_scripted_eval_expected(): + folder = Path(__file__).parents[1] / "evals" / "fixtures" / "chart" + fixture = json.loads((folder / "scatter_calibration_error_bars.json").read_text(encoding="utf-8")) + actual = canonicalize_chart_data(json.loads(fixture["scripted_response"]), "scatter") + assert actual == fixture["expected"] + + +def test_matplotlib_png_and_svg_both_render_scatter_errors_and_log_scales(monkeypatch): + from matplotlib.axes import Axes + + seen = [] + original = Axes.errorbar + + def spy(self, xs, ys, **kwargs): + seen.append((list(xs), list(ys), kwargs)) + return original(self, xs, ys, **kwargs) + + monkeypatch.setattr(Axes, "errorbar", spy) + png = render_chart_png("scatter", _scatter(), 640, 480) + svg = render_chart_svg("scatter", _scatter(), 640, 480) + assert png.startswith(b"\x89PNG\r\n\x1a\n") + assert b" Date: Wed, 18 Nov 2026 08:20:03 -0500 Subject: [PATCH 14/39] test(charts): verify React scatter, legends, errors and log scales --- .../charts/ScientificChartMarks.test.tsx | 144 ++++++++++++++++++ 1 file changed, 144 insertions(+) create mode 100644 web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx diff --git a/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx b/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx new file mode 100644 index 00000000..29a258d5 --- /dev/null +++ b/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx @@ -0,0 +1,144 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { canonicalizeChartSpec, scientificFields } from "../chartSpec"; +import { createLog10Scale, formatLogTick, log10Ticks, scientificDomain } from "./chartScales"; +import ChartRenderer from "./ChartRenderer"; + +const originalResizeObserver = globalThis.ResizeObserver; + +beforeEach(() => { + vi.spyOn(Element.prototype, "getBoundingClientRect").mockReturnValue({ + width: 640, height: 440, top: 0, left: 0, right: 640, bottom: 440, + x: 0, y: 0, toJSON: () => ({}), + }); + class ResizeStub { + constructor(private callback: ResizeObserverCallback) {} + observe(target: Element) { + this.callback([{ target, contentRect: target.getBoundingClientRect() } as ResizeObserverEntry], + this as unknown as ResizeObserver); + } + unobserve() {} + disconnect() {} + } + globalThis.ResizeObserver = ResizeStub as unknown as typeof ResizeObserver; +}); + +afterEach(() => { + globalThis.ResizeObserver = originalResizeObserver; + vi.restoreAllMocks(); +}); + +const SCATTER = { + type: "scatter", + title: "Calibration", + xValues: [1, 10, 100], + xScale: "log10", + yScale: "linear", + xAxis: "Concentration", + yAxis: "Response", + xUnit: "mg/L", + yUnit: "mV", + series: [ + { name: "Control", values: [0.9, 1.8, 3.2], + xError: [0.05, [1, 2], 10], yError: [0.1, [0.1, 0.3], 0.2] }, + { name: "Treatment", values: [1.1, 2.1, 3.5] }, + ], +}; + +describe("scientific chart contract", () => { + it("normalizes symmetric and asymmetric errors and keeps optional wire type absent", () => { + const result = scientificFields(canonicalizeChartSpec(SCATTER, "scatter")); + expect(result.type).toBeUndefined(); + expect(result.series?.[0].xError).toEqual([[0.05, 0.05], [1, 2], [10, 10]]); + expect(result.series?.[0].yError).toEqual([[0.1, 0.1], [0.1, 0.3], [0.2, 0.2]]); + expect(canonicalizeChartSpec(result, "scatter")).toEqual(result); + }); + + it.each([ + [{ ...SCATTER, xValues: [1, 10] }, "length must match"], + [{ ...SCATTER, series: [{ name: "A", values: [1, 2, 3] }, { name: "B", values: [1, 2] }] }, "length must match"], + [{ ...SCATTER, series: [{ name: "A", values: [1, 2, 3], yError: [-1, 0, 0] }] }, "nonnegative"], + [{ ...SCATTER, xValues: [1, Infinity, 100] }, "finite"], + [{ ...SCATTER, xValues: [1, NaN, 100] }, "finite"], + [{ ...SCATTER, xValues: [0, 10, 100] }, "log10 axis"], + [{ ...SCATTER, xValues: [1, 10, 100], series: [{ name: "A", values: [1, 2, 3], xError: [1, 0, 0] }] }, "lower error endpoint"], + [{ ...SCATTER, yScale: "log10", series: [{ name: "A", values: [1, 2, 3], yError: [1, 0, 0] }] }, "lower error endpoint"], + [{ ...SCATTER, yScale: "log10", series: [{ name: "A", values: [1, 0, 3] }] }, "log10 axis"], + ])("rejects invalid scientific values without skipping a point", (input, message) => { + expect(() => canonicalizeChartSpec(input, "scatter")).toThrow(message); + }); +}); + +describe("log10 scientific scales", () => { + it("maps each power of ten to equally spaced positions", () => { + const scale = createLog10Scale([1, 100], [0, 400]); + expect(scale(1)).toBeCloseTo(0); + expect(scale(10)).toBeCloseTo(200); + expect(scale(100)).toBeCloseTo(400); + expect(log10Ticks(0.1, 1000)).toEqual([0.1, 1, 10, 100, 1000]); + expect(formatLogTick(0.0001)).toBe("1e-4"); + expect(scientificDomain(1, 100, "log10")[0]).toBeGreaterThan(0); + }); + + it("keeps wide log tick collections bounded", () => { + expect(log10Ticks(1e-250, 1e250).length).toBeLessThanOrEqual(7); + }); +}); + +describe("scientific React rendering", () => { + it("draws scatter point markers, both orientations of errors, a named legend, and axis units", () => { + const { container } = render(); + expect(container.querySelector(".chart-canvas-svg")).not.toBeNull(); + expect(container.querySelectorAll(".chart-scientific-point")).toHaveLength(6); + expect(container.querySelectorAll(".chart-series-line")).toHaveLength(0); + expect(container.querySelectorAll(".chart-x-error")).toHaveLength(3); + expect(container.querySelectorAll(".chart-y-error")).toHaveLength(3); + expect(screen.getByText("Control")).toBeInTheDocument(); + expect(screen.getByText("Treatment")).toBeInTheDocument(); + expect(screen.getByText("Concentration (mg/L)")).toBeInTheDocument(); + expect(screen.getByText("Response (mV)")).toBeInTheDocument(); + + const firstSeries = container.querySelector(".chart-scientific-series")!; + const points = firstSeries.querySelectorAll(".chart-series-marker"); + const positions = [...points].map((node) => Number(node.getAttribute("cx"))); + expect(positions[1] - positions[0]).toBeCloseTo(positions[2] - positions[1], 5); + + fireEvent.pointerMove(points[1], { clientX: 100, clientY: 50 }); + const tip = screen.getByRole("tooltip"); + expect(tip).toHaveTextContent("10 mg/L"); + expect(tip).toHaveTextContent("1.8 mV"); + expect(tip).toHaveTextContent("-1/+2 mg/L"); + expect(tip).toHaveTextContent("-0.1/+0.3 mV"); + fireEvent.pointerLeave(points[1]); + expect(screen.queryByRole("tooltip")).toBeNull(); + }); + + it("connects named lines, not scatters, and does not change legacy line geometry", () => { + const multiseries = { + type: "line", labels: ["A", "B", "C"], + series: [ + { name: "First", values: [1, 3, 2] }, + { name: "Second", values: [3, 2, 1] }, + ], + }; + const { container, rerender } = render(); + expect(container.querySelectorAll(".chart-series-line")).toHaveLength(2); + expect(container.querySelectorAll(".chart-scientific-series")).toHaveLength(2); + expect(screen.getByText("First")).toBeInTheDocument(); + expect(screen.getByText("Second")).toBeInTheDocument(); + rerender(); + expect(container.querySelector(".chart-scientific-marks")).toBeNull(); + expect(container.querySelector("path[fill='none']")).not.toBeNull(); + }); + + it("shows a specific error placeholder for invalid log intervals", () => { + const invalid = { ...SCATTER, series: [{ + name: "A", values: [1, 2, 3], yError: [1, 0, 0], + }], yScale: "log10" }; + const { container } = render(); + expect(container.querySelector(".chart-canvas-placeholder")).not.toBeNull(); + expect(screen.getByText(/lower error endpoint/)).toBeInTheDocument(); + }); +}); From 5fd126ee6fa87c8091dc30e6164d2bec77eba1ca Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:26:30 -0500 Subject: [PATCH 15/39] fix(charts): respect generated wire-type intersection guard --- web_ui/src/app/canvas/chartSpec.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/web_ui/src/app/canvas/chartSpec.ts b/web_ui/src/app/canvas/chartSpec.ts index 2379f82a..9a00330f 100644 --- a/web_ui/src/app/canvas/chartSpec.ts +++ b/web_ui/src/app/canvas/chartSpec.ts @@ -70,7 +70,14 @@ export interface ScientificSeries { xError?: ErrorPair[] | null; yError?: ErrorPair[] | null; } -export type ScientificChartSpec = ChartDataRow & { +export interface ScientificChartSpec { + version?: ChartDataRow["version"]; + type?: ChartDataRow["type"]; + title?: ChartDataRow["title"]; + labels?: ChartDataRow["labels"]; + values?: ChartDataRow["values"]; + xAxis?: ChartDataRow["xAxis"]; + yAxis?: ChartDataRow["yAxis"]; xValues?: number[]; series?: ScientificSeries[]; xError?: ErrorPair[] | null; From 4e83559f1cbb279969be45b3e124bbc63815ea31 Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:28:49 -0500 Subject: [PATCH 16/39] fix(charts): keep extreme scientific data inside finite domains --- web_ui/src/app/canvas/charts/chartScales.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/web_ui/src/app/canvas/charts/chartScales.ts b/web_ui/src/app/canvas/charts/chartScales.ts index d3ec6e25..4cf2390e 100644 --- a/web_ui/src/app/canvas/charts/chartScales.ts +++ b/web_ui/src/app/canvas/charts/chartScales.ts @@ -66,12 +66,19 @@ export function scientificDomain(min: number, max: number, scale: "linear" | "lo const low = Math.log10(min); const high = Math.log10(max); const padding = Math.max((high - low) * 0.12, 0.18); - // Clamp to finite representable powers; neither endpoint can become - // Infinity/zero even when a valid value is near a float limit. - return [10 ** Math.max(-323, low - padding), 10 ** Math.min(308, high + padding)]; + // A valid endpoint can be as small as Number.MIN_VALUE or as large + // as Number.MAX_VALUE. Clamping to powers -323/308 clips real points. + const lower = low - padding <= Math.log10(Number.MIN_VALUE) + ? Number.MIN_VALUE : 10 ** (low - padding); + const upper = high + padding >= Math.log10(Number.MAX_VALUE) + ? Number.MAX_VALUE : 10 ** (high + padding); + return [Math.min(min, lower), Math.max(max, upper)]; } const padding = Math.max((max - min) * 0.12, Math.max(Math.abs(min), Math.abs(max), 1) * 0.02); - return [Math.max(-Number.MAX_VALUE, min - padding), Math.min(Number.MAX_VALUE, max + padding)]; + const lower = Math.max(-Number.MAX_VALUE, min - padding); + const upper = Math.min(Number.MAX_VALUE, max + padding); + // Padding must not overflow the finite original coordinate span. + return Number.isFinite(upper - lower) ? [lower, upper] : [min, max]; } /** "Nice" round-number ticks spanning at least [min, max] - the classic From 3b3ae3297c21d4234eb72dbdeac61ec9f8f1d158 Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:29:24 -0500 Subject: [PATCH 17/39] fix(charts): reject overflowed error spans and bound all scientific arrays --- graphlink_chart_data.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/graphlink_chart_data.py b/graphlink_chart_data.py index 100d489e..0ada636d 100644 --- a/graphlink_chart_data.py +++ b/graphlink_chart_data.py @@ -302,6 +302,7 @@ def _scientific_errors(raw, field, count): def _check_scientific_axis(values, errors, scale, field): """Check all coordinates AND error endpoints (including overflow).""" + smallest, largest = float("inf"), float("-inf") for index, value in enumerate(values): minus, plus = errors[index] if errors is not None else (0.0, 0.0) lower, upper = value - minus, value + plus @@ -312,6 +313,9 @@ def _check_scientific_axis(values, errors, scale, field): f"{field} at index {index} and its lower error endpoint must be " "greater than zero on a log10 axis" ) + smallest, largest = min(smallest, lower), max(largest, upper) + if not math.isfinite(largest - smallest): + raise ChartDataError(f"{field} range including error endpoints must be finite") def _scientific_chart(data, chart_type, result): @@ -347,6 +351,8 @@ def _scientific_chart(data, chart_type, result): if labels is not None: if not isinstance(labels, list): raise ChartDataError("Labels must be a list") + if len(labels) > MAX_SERIES_POINTS: + raise ChartDataError(f"Charts support at most {MAX_SERIES_POINTS} data points") result["labels"] = [_clean_text(label, f"Label at index {i}") for i, label in enumerate(labels)] raw_series = data.get("series") @@ -371,6 +377,8 @@ def _scientific_chart(data, chart_type, result): raise ChartDataError(f"series {name} values must be a list") if not values: raise ChartDataError(f"series {name} requires at least one data point") + if len(values) > MAX_SERIES_POINTS: + raise ChartDataError(f"Charts support at most {MAX_SERIES_POINTS} data points") row = { "name": name, "values": [_finite_number(value, f"series {name} value at index {i}") for i, value in enumerate(values)], @@ -384,6 +392,8 @@ def _scientific_chart(data, chart_type, result): raw_values = data.get("values") if not isinstance(raw_values, list) or not raw_values: raise ChartDataError(f"{chart_type.title()} charts require at least one data point") + if len(raw_values) > MAX_SERIES_POINTS: + raise ChartDataError(f"Charts support at most {MAX_SERIES_POINTS} data points") series = [{ "values": [_finite_number(value, f"Value at index {i}") for i, value in enumerate(raw_values)], }] From a73d315161ea81fe5107e1fc60435728bde0307e Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:29:42 -0500 Subject: [PATCH 18/39] fix(charts): reject overflowing error intervals in React validation --- web_ui/src/app/canvas/chartSpec.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/web_ui/src/app/canvas/chartSpec.ts b/web_ui/src/app/canvas/chartSpec.ts index 9a00330f..a4770749 100644 --- a/web_ui/src/app/canvas/chartSpec.ts +++ b/web_ui/src/app/canvas/chartSpec.ts @@ -118,6 +118,8 @@ function scientificErrors(value: unknown, field: string, count: number): ErrorPa } function checkScientificAxis(values: number[], errors: ErrorPair[] | null | undefined, scale: AxisScale, field: string): void { + let smallest = Infinity; + let largest = -Infinity; values.forEach((value, index) => { const [minus, plus] = errors?.[index] ?? [0, 0]; const lower = value - minus; @@ -128,7 +130,12 @@ function checkScientificAxis(values: number[], errors: ErrorPair[] | null | unde if (scale === "log10" && lower <= 0) { throw new ChartSpecError(field + " at index " + index + " and its lower error endpoint must be greater than zero on a log10 axis"); } + smallest = Math.min(smallest, lower); + largest = Math.max(largest, upper); }); + if (!Number.isFinite(largest - smallest)) { + throw new ChartSpecError(field + " range including error endpoints must be finite"); + } } interface ScientificValues { From cb4f19985b598914ddc5a7fd9ede3d8d993fff40 Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:30:43 -0500 Subject: [PATCH 19/39] fix(charts): let model schema generate named line and scatter series --- graphlink_chart_data.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/graphlink_chart_data.py b/graphlink_chart_data.py index 0ada636d..6aa6a48c 100644 --- a/graphlink_chart_data.py +++ b/graphlink_chart_data.py @@ -86,14 +86,21 @@ class ChartDataError(ValueError): }, "line": { "type": "object", - "properties": {"type": {"type": "string", "enum": ["line"]}, **_SERIES_PROPERTIES, **_SCIENTIFIC_PROPERTIES}, - "required": ["type", "labels", "values"], + "properties": {"type": {"type": "string", "enum": ["line"]}, + **_SERIES_PROPERTIES, **_SCIENTIFIC_PROPERTIES}, + "required": ["type"], + # Legacy top-level data OR additive named series; otherwise a + # provider enforcing this schema makes multiseries lines impossible + # (the canonicalizer correctly rejects simultaneous top-level + # values and named series). + "anyOf": [{"required": ["labels", "values"]}, {"required": ["series"]}], }, "scatter": { "type": "object", "properties": {"type": {"type": "string", "enum": ["scatter"]}, **_SERIES_PROPERTIES, **_SCIENTIFIC_PROPERTIES}, "required": ["type", "xValues"], + "anyOf": [{"required": ["values"]}, {"required": ["series"]}], }, "pie": { "type": "object", From 0beca628b761a4da832c30e9d24bc4da1a21ef62 Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:30:55 -0500 Subject: [PATCH 20/39] fix(charts): create valid numeric scatter fallback on model errors --- backend/api/intents_chart.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/backend/api/intents_chart.py b/backend/api/intents_chart.py index 7f414a4c..1e3ab46a 100644 --- a/backend/api/intents_chart.py +++ b/backend/api/intents_chart.py @@ -136,7 +136,17 @@ async def _on_success(result): # shape and chart_error set, same "degrade gracefully, never # drop the request" contract as the agent's own internal # fallback chain. - chart_data = _placeholder_chart_data(normalized_chart_type) + if normalized_chart_type == "scatter": + # The legacy helper lives in backend/canvas.py (outside + # this feature's edit scope) and only constructs + # categorical placeholders. Scatter needs real numeric + # x coordinates even for an error-state chart. + chart_data = canonicalize_chart_data({ + "type": "scatter", "title": "Chart", + "xValues": [1.0, 2.0], "values": [1.0, 1.0], + }, "scatter") + else: + chart_data = _placeholder_chart_data(normalized_chart_type) chart_error = f"The generated chart data could not be validated: {exc}" # ADR-010 stage 10.1: agent provenance - this node is produced by # a model generation, not a direct user action (stage 10.5's From 7626478ff470907f3ec30d5a1d4944c5a3835fa1 Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:32:00 -0500 Subject: [PATCH 21/39] test(charts): cover all five old shapes and overflowed uncertainty domains --- backend/tests/test_chart_scientific.py | 36 ++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/backend/tests/test_chart_scientific.py b/backend/tests/test_chart_scientific.py index 4a0fc1c9..abaf16b3 100644 --- a/backend/tests/test_chart_scientific.py +++ b/backend/tests/test_chart_scientific.py @@ -84,6 +84,42 @@ def test_scientific_rejects_bad_log_bounds_and_series_lengths(data, match): canonicalize_chart_data(base, "scatter") +def test_uncertainty_span_overflow_is_rejected_before_reaching_both_renderers(): + # All three coordinates and each lower/upper error endpoint are finite. + # Collectively the interval is too wide for a finite Cartesian domain. + with pytest.raises(ChartDataError, match="range including error endpoints must be finite"): + canonicalize_chart_data({ + "type": "scatter", "xValues": [1, 2, 3], "values": [0, 0, 0], + "yError": [1e308, 1e308, 1e308], + }, "scatter") + + +def test_existing_histogram_and_sankey_canonical_shapes_stay_exactly_the_same(): + histogram = canonicalize_chart_data({"type": "histogram", "values": [1, 2, 3, 4]}, "histogram") + assert histogram == { + "version": 1, "type": "histogram", "title": "Histogram Chart", + "values": [1.0, 2.0, 3.0, 4.0], "bins": 4, + "xAxis": "Value", "yAxis": "Frequency", + } + sankey = canonicalize_chart_data({"type": "sankey", "flows": [ + {"source": "Start", "target": "End", "value": 1}, + ]}, "sankey") + assert sankey == { + "version": 1, "type": "sankey", "title": "Sankey Chart", + "flows": [{"source": "Start", "target": "End", "value": 1.0}], + } + + +def test_model_schema_accepts_named_series_without_forcing_legacy_top_level_values(): + from graphlink_chart_data import CHART_JSON_SCHEMAS + + for chart_type in ("line", "scatter"): + schema = CHART_JSON_SCHEMAS[chart_type] + assert "series" in schema["properties"] + assert "values" not in schema["required"] + assert {"required": ["series"]} in schema["anyOf"] + + def test_scientific_line_can_use_categorical_labels_and_y_error_without_changing_legacy_line(): old = {"type": "line", "labels": ["A", "B"], "values": [2, 4]} assert canonicalize_chart_data(old, "line") == { From cc114330a8a948b2b72f761513c8f7a5baa051fb Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:32:42 -0500 Subject: [PATCH 22/39] test(charts): catch extreme axis clipping and verify errorbar coordinates --- .../charts/ScientificChartMarks.test.tsx | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx b/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx index 29a258d5..579cf734 100644 --- a/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx +++ b/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx @@ -64,6 +64,7 @@ describe("scientific chart contract", () => { [{ ...SCATTER, xValues: [1, 10, 100], series: [{ name: "A", values: [1, 2, 3], xError: [1, 0, 0] }] }, "lower error endpoint"], [{ ...SCATTER, yScale: "log10", series: [{ name: "A", values: [1, 2, 3], yError: [1, 0, 0] }] }, "lower error endpoint"], [{ ...SCATTER, yScale: "log10", series: [{ name: "A", values: [1, 0, 3] }] }, "log10 axis"], + [{ ...SCATTER, xScale: "linear", xValues: [1, 2, 3], series: [{ name: "A", values: [0, 0, 0], yError: [1e308, 1e308, 1e308] }] }, "range including error endpoints"], ])("rejects invalid scientific values without skipping a point", (input, message) => { expect(() => canonicalizeChartSpec(input, "scatter")).toThrow(message); }); @@ -80,6 +81,22 @@ describe("log10 scientific scales", () => { expect(scientificDomain(1, 100, "log10")[0]).toBeGreaterThan(0); }); + it("contains representable extreme values without clipping them", () => { + const tiny = Number.MIN_VALUE; + const huge = Number.MAX_VALUE; + const [logMin, logMax] = scientificDomain(tiny, huge, "log10"); + expect(logMin).toBeGreaterThan(0); + expect(logMin).toBeLessThanOrEqual(tiny); + expect(logMax).toBeGreaterThanOrEqual(huge); + const log = createLog10Scale([logMin, logMax], [0, 100]); + expect(log(tiny)).toBeGreaterThanOrEqual(0); + expect(log(huge)).toBeLessThanOrEqual(100); + const [linMin, linMax] = scientificDomain(-9e307, 8e307, "linear"); + expect(Number.isFinite(linMax - linMin)).toBe(true); + expect(linMin).toBeLessThanOrEqual(-9e307); + expect(linMax).toBeGreaterThanOrEqual(8e307); + }); + it("keeps wide log tick collections bounded", () => { expect(log10Ticks(1e-250, 1e250).length).toBeLessThanOrEqual(7); }); @@ -113,6 +130,34 @@ describe("scientific React rendering", () => { expect(screen.queryByRole("tooltip")).toBeNull(); }); + it("maps asymmetric error-bar endpoints to the same numeric log positions as its points", () => { + const { container } = render(); + const first = container.querySelector(".chart-scientific-series")!; + const marker = first.querySelector(".chart-series-marker")!; + const capLine = first.querySelector(".chart-x-error line")!; + const xDomain = scientificDomain(0.95, 110, "log10"); + const scale = createLog10Scale(xDomain, [0, 640 - 74 - 22]); + expect(Number(marker.getAttribute("cx"))).toBeCloseTo(scale(1), 7); + expect(Number(capLine.getAttribute("x1"))).toBeCloseTo(scale(0.95), 7); + expect(Number(capLine.getAttribute("x2"))).toBeCloseTo(scale(1.05), 7); + }); + + it("renders a log10 y-axis with the original positive measurements and named lines", () => { + const input = { + type: "line", xValues: [1, 10, 100], xScale: "log10", yScale: "log10", + xUnit: "s", yUnit: "mV", + series: [{ name: "Detector", values: [0.001, 0.1, 10], yError: [0.0001, 0.01, 1] }], + }; + const { container } = render(); + expect(container.querySelectorAll(".chart-series-marker")).toHaveLength(3); + expect(container.querySelectorAll(".chart-series-line")).toHaveLength(1); + const marks = container.querySelectorAll(".chart-series-marker"); + expect(Number(marks[1].getAttribute("cy"))).toBeLessThan(Number(marks[0].getAttribute("cy"))); + fireEvent.pointerMove(marks[0], { clientX: 50, clientY: 50 }); + expect(screen.getByRole("tooltip")).toHaveTextContent("0.001 mV"); + expect(screen.getByRole("tooltip")).toHaveTextContent("0.0001"); + }); + it("connects named lines, not scatters, and does not change legacy line geometry", () => { const multiseries = { type: "line", labels: ["A", "B", "C"], From 9f4fd8ce59bd2248f8003ed009584a14e26d79a0 Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:32:58 -0500 Subject: [PATCH 23/39] docs(charts): clarify stored scatter discriminator and numeric range checks --- docs/CHARTS.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs/CHARTS.md b/docs/CHARTS.md index fc5da784..4be70b3c 100644 --- a/docs/CHARTS.md +++ b/docs/CHARTS.md @@ -5,6 +5,15 @@ Graphlink chart nodes use the version-1 canonical JSON object validated by `web_ui/src/app/canvas/chartSpec.ts` performs the same defensive validation. The version remains **1** because the new scientific fields are optional. +**Scatter transport compatibility:** new chart generation input carries +`"type": "scatter"`, but canonical *stored* scatter data deliberately leaves +out its optional nested `type` field; the enclosing node's `chartType` +is `"scatter"`. This preserves Graphlink's existing generated version-1 +scene validator, which does not yet enumerate scatter and is out of scope +for this change. Pass `chart_type="scatter"` explicitly when canonicalizing +that stored payload. Legacy chart types continue to store their nested +`type` normally. + ## Existing charts The five existing shapes remain unchanged. A bar, line, or pie chart has @@ -76,6 +85,9 @@ Example: lower endpoint of every error interval on that axis. A coordinate of zero, a negative coordinate, or a zero/negative lower endpoint is an error; it is never silently omitted or clipped. +* The full span across all coordinates **and** all error endpoints must + also be finite, not merely its individual endpoints. This avoids + overflowing a plotting domain or compressing unrelated points together. * Existing bar, pie, histogram, and Sankey validation rules are unchanged. An invalid scientific chart is rejected with a field/index-specific message; a render request with invalid data continues to show the From 3e88da75cbe7ea0e26305df3e54d9b7fffce85b9 Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:33:48 -0500 Subject: [PATCH 24/39] fix(charts): scale tiny scientific measurements relative to actual data --- web_ui/src/app/canvas/charts/chartScales.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/web_ui/src/app/canvas/charts/chartScales.ts b/web_ui/src/app/canvas/charts/chartScales.ts index 4cf2390e..7a180c8d 100644 --- a/web_ui/src/app/canvas/charts/chartScales.ts +++ b/web_ui/src/app/canvas/charts/chartScales.ts @@ -74,7 +74,13 @@ export function scientificDomain(min: number, max: number, scale: "linear" | "lo ? Number.MAX_VALUE : 10 ** (high + padding); return [Math.min(min, lower), Math.max(max, upper)]; } - const padding = Math.max((max - min) * 0.12, Math.max(Math.abs(min), Math.abs(max), 1) * 0.02); + const magnitude = Math.max(Math.abs(min), Math.abs(max)); + // Do not use a unit-sized padding floor: a scientific domain around + // 1e-200 would otherwise collapse to [-.02,.02] on the interactive SVG + // while matplotlib correctly distinguishes every measurement. + const padding = magnitude === 0 + ? 1 + : Math.max((max - min) * 0.12, magnitude * 0.02, Number.MIN_VALUE); const lower = Math.max(-Number.MAX_VALUE, min - padding); const upper = Math.min(Number.MAX_VALUE, max + padding); // Padding must not overflow the finite original coordinate span. From 9ee7b3516b34c8367d7f4d38b9c226ed464e6007 Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:34:00 -0500 Subject: [PATCH 25/39] test(charts): preserve visual resolution at tiny linear magnitudes --- web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx b/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx index 579cf734..8c94042d 100644 --- a/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx +++ b/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx @@ -91,6 +91,10 @@ describe("log10 scientific scales", () => { const log = createLog10Scale([logMin, logMax], [0, 100]); expect(log(tiny)).toBeGreaterThanOrEqual(0); expect(log(huge)).toBeLessThanOrEqual(100); + const [tinyMin, tinyMax] = scientificDomain(1e-200, 2e-200, "linear"); + expect(tinyMin).toBeGreaterThan(0); + expect(tinyMax).toBeLessThan(3e-200); + expect(createLog10Scale([1e-200, 2e-200], [0, 100])(2e-200)).toBeCloseTo(100); const [linMin, linMax] = scientificDomain(-9e307, 8e307, "linear"); expect(Number.isFinite(linMax - linMin)).toBe(true); expect(linMin).toBeLessThanOrEqual(-9e307); From 3874140afbc5ce4a375bcbd3b70686de297d2ea8 Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:35:10 -0500 Subject: [PATCH 26/39] fix(charts): validate pooled multi-series uncertainty extrema --- graphlink_chart_data.py | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/graphlink_chart_data.py b/graphlink_chart_data.py index 6aa6a48c..4b123911 100644 --- a/graphlink_chart_data.py +++ b/graphlink_chart_data.py @@ -437,11 +437,25 @@ def _scientific_chart(data, chart_type, result): _check_scientific_axis(row["values"], row.get("yError"), result["yScale"], f"series {row.get('name', 'values')} values") - # Check range arithmetic too: two finite endpoints can have an infinite - # span, which neither SVG pixel geometry nor mpl axis limits can draw. - for axis, values in (("xValues", x_values), ("values", [v for row in series for v in row["values"]])): - if values is not None and not math.isfinite(max(values) - min(values)): - raise ChartDataError(f"{axis} range must be finite") + # Each row is locally finite, but multiple series can still have + # disjoint asymmetric intervals whose UNION has an infinite span. Use + # the same all-series extrema the React renderer uses for its domains. + for field, coordinates, error_field in ( + ("xValues", x_values, "xError"), + ("values", None, "yError"), + ): + if field == "xValues" and coordinates is None: + continue + smallest, largest = float("inf"), float("-inf") + for row in series: + values = coordinates if coordinates is not None else row["values"] + errors = row.get(error_field) + for index, value in enumerate(values): + minus, plus = errors[index] if errors is not None else (0.0, 0.0) + smallest = min(smallest, value - minus) + largest = max(largest, value + plus) + if not math.isfinite(largest - smallest): + raise ChartDataError(f"{field} range including all series errors must be finite") result["xAxis"] = _clean_text( data.get("xAxis"), "X-axis label", From b1a0bc2372788dcaa50e798a91656345b5dfb6db Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:35:26 -0500 Subject: [PATCH 27/39] fix(charts): mirror pooled series-domain overflow checks in TypeScript --- web_ui/src/app/canvas/chartSpec.ts | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/web_ui/src/app/canvas/chartSpec.ts b/web_ui/src/app/canvas/chartSpec.ts index a4770749..5185003f 100644 --- a/web_ui/src/app/canvas/chartSpec.ts +++ b/web_ui/src/app/canvas/chartSpec.ts @@ -240,12 +240,24 @@ function canonicalizeScientific(raw: Record, type: "line" | "sc } if (xValues) series.forEach((row) => checkScientificAxis(xValues!, row.xError, output.xScale!, "xValues")); series.forEach((row) => checkScientificAxis(row.values, row.yError, output.yScale!, "series " + (row.name ?? "values") + " values")); - const allY = series.flatMap((row) => row.values); - if (xValues && !Number.isFinite(Math.max(...xValues) - Math.min(...xValues))) { - throw new ChartSpecError("xValues range must be finite"); - } - if (!Number.isFinite(Math.max(...allY) - Math.min(...allY))) { - throw new ChartSpecError("values range must be finite"); + // Separate series may have finite individual error spans yet overflow + // when their intervals are combined into the plot's shared axis. + for (const field of ["xValues", "values"] as const) { + if (field === "xValues" && !xValues) continue; + let smallest = Infinity; + let largest = -Infinity; + for (const row of series) { + const coordinates = field === "xValues" ? xValues! : row.values; + const errors = field === "xValues" ? row.xError : row.yError; + coordinates.forEach((value, index) => { + const [minus, plus] = errors?.[index] ?? [0, 0]; + smallest = Math.min(smallest, value - minus); + largest = Math.max(largest, value + plus); + }); + } + if (!Number.isFinite(largest - smallest)) { + throw new ChartSpecError(field + " range including all series errors must be finite"); + } } output.xAxis = cleanText(raw.xAxis, "X-axis label", { default: type === "scatter" ? "X" : "Sequence" }); output.yAxis = cleanText(raw.yAxis, "Y-axis label", { default: type === "scatter" ? "Y" : "Value" }); From cf93caf7da2bd9d214cedb6c1c4514fcdf254657 Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:35:43 -0500 Subject: [PATCH 28/39] test(charts): reject pooled asymmetric multi-series overflow --- backend/tests/test_chart_scientific.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/backend/tests/test_chart_scientific.py b/backend/tests/test_chart_scientific.py index abaf16b3..520b8410 100644 --- a/backend/tests/test_chart_scientific.py +++ b/backend/tests/test_chart_scientific.py @@ -74,6 +74,12 @@ def test_scatter_strictly_rejects_invalid_numeric_inputs(key, value, match): {"name": "Two", "values": [1, 2]}]}, "length must match"), ({"series": [{"name": "Same", "values": [1, 2, 3]}, {"name": "Same", "values": [2, 3, 4]}]}, "Duplicate series name"), + ({"series": [ + {"name": "Lower", "values": [0, 0, 0], + "yError": [[1.5e308, 0], [1.5e308, 0], [1.5e308, 0]]}, + {"name": "Upper", "values": [0, 0, 0], + "yError": [[0, 1.5e308], [0, 1.5e308], [0, 1.5e308]]}, + ]}, "range including all series errors"), ]) def test_scientific_rejects_bad_log_bounds_and_series_lengths(data, match): base = {"type": "scatter", "xValues": [1, 10, 100], "values": [1, 2, 3]} From beba8f622ab79e5f667418d6ad5a296703b162be Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:35:54 -0500 Subject: [PATCH 29/39] test(charts): enforce finite pooled series errors in browser --- web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx b/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx index 8c94042d..ec7982ff 100644 --- a/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx +++ b/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx @@ -65,6 +65,10 @@ describe("scientific chart contract", () => { [{ ...SCATTER, yScale: "log10", series: [{ name: "A", values: [1, 2, 3], yError: [1, 0, 0] }] }, "lower error endpoint"], [{ ...SCATTER, yScale: "log10", series: [{ name: "A", values: [1, 0, 3] }] }, "log10 axis"], [{ ...SCATTER, xScale: "linear", xValues: [1, 2, 3], series: [{ name: "A", values: [0, 0, 0], yError: [1e308, 1e308, 1e308] }] }, "range including error endpoints"], + [{ ...SCATTER, series: [ + { name: "Lower", values: [0, 0, 0], yError: [[1.5e308, 0], [1.5e308, 0], [1.5e308, 0]] }, + { name: "Upper", values: [0, 0, 0], yError: [[0, 1.5e308], [0, 1.5e308], [0, 1.5e308]] }, + ] }, "range including all series errors"], ])("rejects invalid scientific values without skipping a point", (input, message) => { expect(() => canonicalizeChartSpec(input, "scatter")).toThrow(message); }); From cc87fb513e4b9ee6b0ee70c92af6fea1a1b260da Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:38:13 -0500 Subject: [PATCH 30/39] test(charts): exercise scientific model options and scatter fallback --- .../tests/test_chart_intents_scientific.py | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 backend/tests/test_chart_intents_scientific.py diff --git a/backend/tests/test_chart_intents_scientific.py b/backend/tests/test_chart_intents_scientific.py new file mode 100644 index 00000000..0a53f683 --- /dev/null +++ b/backend/tests/test_chart_intents_scientific.py @@ -0,0 +1,101 @@ +"""Model-driven scatter request options and failure-state regression coverage.""" + +import asyncio + +from backend.api.intents_chart import register_chart_intents +from backend.domain.graph import SceneDocument +from backend.events import SessionBus +from backend.notifications import NotificationState + + +class FakeChartAgent: + def __init__(self, response=None): + self.calls = [] + self.response = response + + async def start_chart_generation(self, **kwargs): + self.calls.append(kwargs) + if self.response is not None: + await kwargs["on_success"](self.response) + + +def _setup(response=None): + bus = SessionBus("scientific-chart-intent") + document = SceneDocument() + notifications = NotificationState() + bus.register_topic("scene", document.scene_payload) + bus.register_topic("notification", notifications.payload) + agent = FakeChartAgent(response) + register_chart_intents(bus, document, notifications, agent) + root = document.add_chat_node(0, 0, "Concentrations 1, 10; response 2, 3.", is_user=True) + return bus, document, notifications, agent, root.id + + +def test_model_driven_scatter_requests_advanced_options_and_creates_a_chart(): + response = { + "type": "scatter", "xValues": [1, 10], + "series": [{"name": "Control", "values": [2, 3], "yError": [0.1, [0.2, 0.3]]}], + "xScale": "log10", "xUnit": "mg/L", "yUnit": "mV", + } + + async def run(): + bus, document, _, agent, root = _setup(response) + node_id = await bus.dispatch_intent("scene", "generateChart", [ + root, "scatter", { + "multipleSeries": True, "errorBars": True, "xScale": "log10", + "xUnit": "mg/L", "yUnit": "mV", + }, + ]) + assert node_id in document.nodes + state = document.nodes[node_id].state + assert state.chart_type == "scatter" + assert "type" not in state.chart_data # v1 generated scene validator + assert state.chart_data["series"][0]["yError"] == [[0.1, 0.1], [0.2, 0.3]] + assert len(agent.calls) == 1 + prompt = agent.calls[0]["source_text"] + assert "multiple named series" in prompt + assert "per-point error magnitudes" in prompt + assert "xScale=log10" in prompt + assert "xUnit='mg/L'" in prompt + assert "yUnit='mV'" in prompt + assert "Concentrations 1, 10" in prompt + + asyncio.run(run()) + + +def test_chart_options_are_strict_and_do_not_dispatch_invalid_requests(): + async def run(): + bus, _, notifications, agent, root = _setup() + for options, message in [ + ({"xScale": "ln"}, "xScale must be linear or log10"), + ({"errorBars": "yes"}, "errorBars must be a boolean"), + ({"newFeature": True}, "Unsupported chartOptions"), + ({"xUnit": ""}, "xUnit must be a nonempty unit"), + ]: + result = await bus.dispatch_intent("scene", "generateChart", [root, "scatter", options]) + assert result is None + assert notifications.payload()["message"] == message or message in notifications.payload()["message"] + assert agent.calls == [] + + result = await bus.dispatch_intent("scene", "generateChart", [root, "bar", {"yScale": "log10"}]) + assert result is None + assert "require line or scatter" in notifications.payload()["message"] + assert agent.calls == [] + + asyncio.run(run()) + + +def test_invalid_model_scatter_result_gets_a_valid_numeric_placeholder(): + async def run(): + bus, document, _, _, root = _setup({ + "type": "scatter", "xScale": "log10", "xValues": [0, 1], "values": [1, 2], + }) + node_id = await bus.dispatch_intent("scene", "generateChart", [root, "scatter"]) + assert node_id in document.nodes + state = document.nodes[node_id].state + assert state.chart_type == "scatter" + assert "log10 axis" in state.chart_error + assert state.chart_data["xValues"] == [1.0, 2.0] + assert "type" not in state.chart_data + + asyncio.run(run()) From 708b4ac4c2c9ba542d0ef86a8554f557b4aa69bf Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:41:24 -0500 Subject: [PATCH 31/39] fix(charts): scientific ticks for tiny linear and extreme values --- web_ui/src/app/canvas/charts/chartScales.ts | 33 +++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/web_ui/src/app/canvas/charts/chartScales.ts b/web_ui/src/app/canvas/charts/chartScales.ts index 7a180c8d..db0b1969 100644 --- a/web_ui/src/app/canvas/charts/chartScales.ts +++ b/web_ui/src/app/canvas/charts/chartScales.ts @@ -87,6 +87,39 @@ export function scientificDomain(min: number, max: number, scale: "linear" | "lo return Number.isFinite(upper - lower) ? [lower, upper] : [min, max]; } +/** Scientific linear ticks cannot use niceTicks: its fixed-decimal rounding + * throws RangeError for 1e-200 and its integer formatter labels tiny + * nonzero measurements "0". Never change the legacy chart tick helper. */ +export function scientificLinearTicks(min: number, max: number, targetCount = 5): number[] { + if (min === max) return [min]; + const rawStep = (max - min) / Math.max(1, targetCount); + const magnitude = Math.max(Number.MIN_VALUE, 10 ** Math.floor(Math.log10(rawStep))); + const ratio = rawStep / magnitude; + const step = magnitude * (ratio >= 5 ? 5 : ratio >= 2 ? 2 : 1); + if (!Number.isFinite(step) || step <= 0) return [min, max]; + const lo = Math.floor(min / step); + const hi = Math.ceil(max / step); + if (!Number.isSafeInteger(lo) || !Number.isSafeInteger(hi) || hi - lo > 12) { + return [min, max]; + } + const result: number[] = []; + for (let i = lo; i <= hi; i += 1) { + const tick = i * step; + if (Number.isFinite(tick)) { + const rounded = Number(tick.toPrecision(12)); + if (result[result.length - 1] !== rounded) result.push(rounded); + } + } + return result.length > 1 ? result : [min, max]; +} + +export function formatScientificTick(value: number): string { + if (value !== 0 && (Math.abs(value) < 0.01 || Math.abs(value) >= 1e6)) { + return value.toExponential(2).replace(/\.00e/, "e").replace(/(\.\d)0e/, "$1e"); + } + return formatValue(value); +} + /** "Nice" round-number ticks spanning at least [min, max] - the classic * Sparks/D3-style algorithm: pick a step from the {1, 2, 5} x 10^n family * closest to the ideal step for the requested tick count, then emit every From c158e1bbb209b5a52b27b9e4d001e78e06a0bc1b Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:41:37 -0500 Subject: [PATCH 32/39] fix(charts): use scientific tick math in line and scatter renderer --- web_ui/src/app/canvas/charts/ScientificChartMarks.tsx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/web_ui/src/app/canvas/charts/ScientificChartMarks.tsx b/web_ui/src/app/canvas/charts/ScientificChartMarks.tsx index 93cd11e8..41f72244 100644 --- a/web_ui/src/app/canvas/charts/ScientificChartMarks.tsx +++ b/web_ui/src/app/canvas/charts/ScientificChartMarks.tsx @@ -6,8 +6,8 @@ import type { AxisScale, ErrorPair } from "../chartSpec"; import type { ChartMarksProps } from "./BarChartMarks"; import { CartesianAxes, type XTick } from "./CartesianAxes"; import { - createLinearScale, createLog10Scale, formatLogTick, formatValue, - log10Ticks, niceTicks, pickCategoricalTicks, scientificDomain, wrapLabel, + createLinearScale, createLog10Scale, formatLogTick, formatScientificTick, + log10Ticks, scientificLinearTicks, pickCategoricalTicks, scientificDomain, wrapLabel, type Scale, } from "./chartScales"; import { computeBottomMargin, tooltipPositionFromEvent } from "./chartLayout"; @@ -58,7 +58,7 @@ function scaleFor(domain: [number, number], range: [number, number], axis: AxisS } function labeledTicks(domain: [number, number], scale: AxisScale): number[] { - return scale === "log10" ? log10Ticks(...domain) : niceTicks(...domain, 5); + return scale === "log10" ? log10Ticks(...domain) : scientificLinearTicks(...domain, 5); } /** Keep tooltips exact: the legacy abbreviated tick-label formatter rounds @@ -113,7 +113,7 @@ export function ScientificChartMarks({ })) : labeledTicks(xDomain, xScaleType).map((value) => ({ position: x(value), - lines: [xScaleType === "log10" ? formatLogTick(value) : formatValue(value)], + lines: [xScaleType === "log10" ? formatLogTick(value) : formatScientificTick(value)], })); const palette = theme.categorical.length ? theme.categorical : [theme.text]; @@ -126,7 +126,7 @@ export function ScientificChartMarks({ xTicks={xTicks} yTicks={yTicks} yScale={y} - yTickFormat={yScaleType === "log10" ? formatLogTick : formatValue} + yTickFormat={yScaleType === "log10" ? formatLogTick : formatScientificTick} xAxisLabel={scientificAxisLabel(data.xAxis ?? "X", data.xUnit)} yAxisLabel={scientificAxisLabel(data.yAxis ?? "Y", data.yUnit)} rotateXTicks={rotate} From 6bcc84025f3aa1c2f65be1d2242aa5eaa46dc18f Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:41:57 -0500 Subject: [PATCH 33/39] test(charts): render tiny scientific values with readable axis ticks --- .../charts/ScientificChartMarks.test.tsx | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx b/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx index ec7982ff..c6247f52 100644 --- a/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx +++ b/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx @@ -1,7 +1,7 @@ import { fireEvent, render, screen } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { canonicalizeChartSpec, scientificFields } from "../chartSpec"; -import { createLog10Scale, formatLogTick, log10Ticks, scientificDomain } from "./chartScales"; +import { createLog10Scale, formatLogTick, formatScientificTick, log10Ticks, scientificDomain, scientificLinearTicks } from "./chartScales"; import ChartRenderer from "./ChartRenderer"; const originalResizeObserver = globalThis.ResizeObserver; @@ -105,6 +105,15 @@ describe("log10 scientific scales", () => { expect(linMax).toBeGreaterThanOrEqual(8e307); }); + it("formats tiny nonzero ticks without fixed-decimal RangeError", () => { + const ticks = scientificLinearTicks(1e-200, 2e-200); + expect(ticks.length).toBeGreaterThan(2); + expect(ticks.every((v) => v > 0 && Number.isFinite(v))).toBe(true); + expect(formatScientificTick(1e-200)).toBe("1e-200"); + expect(formatScientificTick(0)).toBe("0"); + expect(scientificLinearTicks(Number.MIN_VALUE, 1e-320).length).toBeGreaterThan(0); + }); + it("keeps wide log tick collections bounded", () => { expect(log10Ticks(1e-250, 1e250).length).toBeLessThanOrEqual(7); }); @@ -186,6 +195,17 @@ describe("scientific React rendering", () => { expect(container.querySelector("path[fill='none']")).not.toBeNull(); }); + it("renders micro-scale scatter values without overflow or collapsed axis labels", () => { + const { container } = render(); + expect(container.querySelector(".chart-canvas-svg")).not.toBeNull(); + expect(container.querySelectorAll(".chart-series-marker")).toHaveLength(3); + expect(screen.getAllByText(/e-200/).length).toBeGreaterThan(0); + }); + it("shows a specific error placeholder for invalid log intervals", () => { const invalid = { ...SCATTER, series: [{ name: "A", values: [1, 2, 3], yError: [1, 0, 0], From 87de4b918102ebb72f5f1c764e7b2807cb13622c Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:45:34 -0500 Subject: [PATCH 34/39] fix(charts): report series length mismatches before aggregate cap --- graphlink_chart_data.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/graphlink_chart_data.py b/graphlink_chart_data.py index 4b123911..32c4f5ad 100644 --- a/graphlink_chart_data.py +++ b/graphlink_chart_data.py @@ -412,13 +412,13 @@ def _scientific_chart(data, chart_type, result): series[0][axis] = errors count = len(series[0]["values"]) - if count > MAX_SERIES_POINTS or len(series) * count > MAX_SERIES_POINTS: - raise ChartDataError(f"Charts support at most {MAX_SERIES_POINTS} total series points") - if chart_type == "line" and count < 2: - raise ChartDataError("Line charts require at least two data points") for row in series: if len(row["values"]) != count: raise ChartDataError(f"series {row.get('name', 'values')} length must match the other series ({count})") + if chart_type == "line" and count < 2: + raise ChartDataError("Line charts require at least two data points") + if count > MAX_SERIES_POINTS or len(series) * count > MAX_SERIES_POINTS: + raise ChartDataError(f"Charts support at most {MAX_SERIES_POINTS} total series points") if x_values is not None and len(x_values) != count: raise ChartDataError(f"xValues length must match the series length ({count})") if "labels" in result and len(result["labels"]) != count: From d6b4ce707d7309e3064a8a3261cff276d39dc2f5 Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:45:47 -0500 Subject: [PATCH 35/39] fix(charts): preserve specific length mismatch errors in frontend --- web_ui/src/app/canvas/chartSpec.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/web_ui/src/app/canvas/chartSpec.ts b/web_ui/src/app/canvas/chartSpec.ts index 5185003f..1257f60c 100644 --- a/web_ui/src/app/canvas/chartSpec.ts +++ b/web_ui/src/app/canvas/chartSpec.ts @@ -219,15 +219,15 @@ function canonicalizeScientific(raw: Record, type: "line" | "sc series.push(row); } const count = series[0].values.length; - if (count > MAX_SERIES_POINTS || series.length * count > MAX_SERIES_POINTS) { - throw new ChartSpecError("Charts support at most 300 total series points"); - } - if (type === "line" && count < 2) throw new ChartSpecError("Line charts require at least two data points"); for (const row of series) { if (row.values.length !== count) { throw new ChartSpecError("series " + (row.name ?? "values") + " length must match the other series (" + count + ")"); } } + if (type === "line" && count < 2) throw new ChartSpecError("Line charts require at least two data points"); + if (count > MAX_SERIES_POINTS || series.length * count > MAX_SERIES_POINTS) { + throw new ChartSpecError("Charts support at most 300 total series points"); + } if (xValues && xValues.length !== count) { throw new ChartSpecError("xValues length must match the series length (" + count + ")"); } From 3eb194582a71d1bc0272df871a25381a57f6e27c Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:46:22 -0500 Subject: [PATCH 36/39] fix(charts): keep scientific tick labels exact and within axis domain --- web_ui/src/app/canvas/charts/chartScales.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/web_ui/src/app/canvas/charts/chartScales.ts b/web_ui/src/app/canvas/charts/chartScales.ts index db0b1969..d35a760c 100644 --- a/web_ui/src/app/canvas/charts/chartScales.ts +++ b/web_ui/src/app/canvas/charts/chartScales.ts @@ -105,7 +105,7 @@ export function scientificLinearTicks(min: number, max: number, targetCount = 5) const result: number[] = []; for (let i = lo; i <= hi; i += 1) { const tick = i * step; - if (Number.isFinite(tick)) { + if (Number.isFinite(tick) && tick >= min && tick <= max) { const rounded = Number(tick.toPrecision(12)); if (result[result.length - 1] !== rounded) result.push(rounded); } @@ -114,10 +114,9 @@ export function scientificLinearTicks(min: number, max: number, targetCount = 5) } export function formatScientificTick(value: number): string { - if (value !== 0 && (Math.abs(value) < 0.01 || Math.abs(value) >= 1e6)) { - return value.toExponential(2).replace(/\.00e/, "e").replace(/(\.\d)0e/, "$1e"); - } - return formatValue(value); + // Number.toString is the shortest round-trippable decimal, so adjacent + // scientific ticks never become two misleading identical rounded labels. + return String(value); } /** "Nice" round-number ticks spanning at least [min, max] - the classic From 3bfd6339778047c8a74bb8ecd26a5c1708edf13b Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:46:34 -0500 Subject: [PATCH 37/39] test(charts): keep mismatch error priority at the series cap --- backend/tests/test_chart_scientific.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/backend/tests/test_chart_scientific.py b/backend/tests/test_chart_scientific.py index 520b8410..69afca15 100644 --- a/backend/tests/test_chart_scientific.py +++ b/backend/tests/test_chart_scientific.py @@ -72,6 +72,8 @@ def test_scatter_strictly_rejects_invalid_numeric_inputs(key, value, match): "non-finite error endpoint"), ({"series": [{"name": "One", "values": [1, 2, 3]}, {"name": "Two", "values": [1, 2]}]}, "length must match"), + ({"series": [{"name": "Full", "values": [1] * 300}, + {"name": "Short", "values": [1]}]}, "length must match"), ({"series": [{"name": "Same", "values": [1, 2, 3]}, {"name": "Same", "values": [2, 3, 4]}]}, "Duplicate series name"), ({"series": [ From e01280d37f4a2f7100165e9cb2df8d174ce9b430 Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:46:46 -0500 Subject: [PATCH 38/39] test(charts): preserve close scientific tick values without rounding --- web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx b/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx index c6247f52..6e7f6c83 100644 --- a/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx +++ b/web_ui/src/app/canvas/charts/ScientificChartMarks.test.tsx @@ -111,6 +111,8 @@ describe("log10 scientific scales", () => { expect(ticks.every((v) => v > 0 && Number.isFinite(v))).toBe(true); expect(formatScientificTick(1e-200)).toBe("1e-200"); expect(formatScientificTick(0)).toBe("0"); + expect(formatScientificTick(1.001)).toBe("1.001"); + expect(formatScientificTick(1.0000000000000002)).toBe("1.0000000000000002"); expect(scientificLinearTicks(Number.MIN_VALUE, 1e-320).length).toBeGreaterThan(0); }); From d10841fdd9cddc2fefe7a02be21cf83fcb9dc3cd Mon Sep 17 00:00:00 2001 From: Matthew Wesney <157447210+dovvnloading@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:53:23 -0500 Subject: [PATCH 39/39] fix(tests): assert migrated fields explicitly through node.state --- backend/tests/test_chart_intents_scientific.py | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/backend/tests/test_chart_intents_scientific.py b/backend/tests/test_chart_intents_scientific.py index 0a53f683..c861c86b 100644 --- a/backend/tests/test_chart_intents_scientific.py +++ b/backend/tests/test_chart_intents_scientific.py @@ -47,10 +47,9 @@ async def run(): }, ]) assert node_id in document.nodes - state = document.nodes[node_id].state - assert state.chart_type == "scatter" - assert "type" not in state.chart_data # v1 generated scene validator - assert state.chart_data["series"][0]["yError"] == [[0.1, 0.1], [0.2, 0.3]] + assert document.nodes[node_id].state.chart_type == "scatter" + assert "type" not in document.nodes[node_id].state.chart_data # v1 generated scene validator + assert document.nodes[node_id].state.chart_data["series"][0]["yError"] == [[0.1, 0.1], [0.2, 0.3]] assert len(agent.calls) == 1 prompt = agent.calls[0]["source_text"] assert "multiple named series" in prompt @@ -92,10 +91,9 @@ async def run(): }) node_id = await bus.dispatch_intent("scene", "generateChart", [root, "scatter"]) assert node_id in document.nodes - state = document.nodes[node_id].state - assert state.chart_type == "scatter" - assert "log10 axis" in state.chart_error - assert state.chart_data["xValues"] == [1.0, 2.0] - assert "type" not in state.chart_data + assert document.nodes[node_id].state.chart_type == "scatter" + assert "log10 axis" in document.nodes[node_id].state.chart_error + assert document.nodes[node_id].state.chart_data["xValues"] == [1.0, 2.0] + assert "type" not in document.nodes[node_id].state.chart_data asyncio.run(run())