From 3f5af6d0a2994f56b25d529a21b4419416385e1e Mon Sep 17 00:00:00 2001 From: Andrew Stein Date: Sat, 28 Nov 2026 10:52:39 -0500 Subject: [PATCH 1/3] Fix redhat10 build issues Signed-off-by: Andrew Stein --- rust/perspective-python/perspective/tests/conftest.py | 2 ++ rust/perspective-server/cpp/perspective/CMakeLists.txt | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/rust/perspective-python/perspective/tests/conftest.py b/rust/perspective-python/perspective/tests/conftest.py index 69cd247298..6194b7477a 100644 --- a/rust/perspective-python/perspective/tests/conftest.py +++ b/rust/perspective-python/perspective/tests/conftest.py @@ -15,6 +15,7 @@ import numpy as np import pandas as pd import pyarrow as pa +import time from pytest import fixture from random import random, randint, choice from faker import Faker @@ -32,6 +33,7 @@ os.environ["TZ"] = "UTC" +time.tzset() def new_encoder(self, obj): diff --git a/rust/perspective-server/cpp/perspective/CMakeLists.txt b/rust/perspective-server/cpp/perspective/CMakeLists.txt index 3ea679149d..0af7285207 100644 --- a/rust/perspective-server/cpp/perspective/CMakeLists.txt +++ b/rust/perspective-server/cpp/perspective/CMakeLists.txt @@ -439,7 +439,9 @@ list(APPEND all_deps_INCLUDE_DIRS ${exprtk_INCLUDE_DIRS}) # Protobuf setup -set(protobuf_BUILD_TESTS OFF FORCE) +set(protobuf_BUILD_TESTS OFF CACHE BOOL "" FORCE) +# Always use protobuf's bundled abseil, never a host install (conda/Homebrew/system) +set(protobuf_FORCE_FETCH_DEPENDENCIES ON CACHE BOOL "" FORCE) add_subdirectory(${PSP_CMAKE_MODULE_PATH}/../cpp/protos "${CMAKE_BINARY_DIR}/protos-build") # #################### From 4c1fc7443789ee8ac2dfb25a41a0f97f18776338 Mon Sep 17 00:00:00 2001 From: Andrew Stein Date: Fri, 27 Nov 2026 23:54:49 -0500 Subject: [PATCH 2/3] Accept RecordBatch from Python Signed-off-by: Andrew Stein --- docs/md/FAQ.md | 3 ++- docs/md/explanation/table/loading_data.md | 10 +++++----- docs/md/how_to/python/table.md | 1 + docs/md/how_to/python/table_data.md | 7 +++++++ .../tests/table/test_table_arrow.py | 16 ++++++++++++++++ .../src/client/client_async.rs | 7 +++---- .../src/client/client_sync.rs | 2 +- rust/perspective-python/src/client/pyarrow.rs | 18 +++++++++++------- 8 files changed, 46 insertions(+), 18 deletions(-) diff --git a/docs/md/FAQ.md b/docs/md/FAQ.md index 2815e4673b..ec60a2a083 100644 --- a/docs/md/FAQ.md +++ b/docs/md/FAQ.md @@ -509,7 +509,8 @@ Perspective accepts (see [Loading data](./explanation/table/loading_data.md)): - **JavaScript**: JSON (row-oriented or column-oriented objects), NDJSON, CSV strings, Apache Arrow `ArrayBuffer` - **Python**: `dict`, `list`, `pandas.DataFrame`, `polars.DataFrame`, - `pyarrow.Table`, NDJSON, CSV strings, Apache Arrow bytes + `pyarrow.Table`, `pyarrow.RecordBatch`, NDJSON, CSV strings, Apache Arrow + bytes diff --git a/docs/md/explanation/table/loading_data.md b/docs/md/explanation/table/loading_data.md index 4ea3464832..74d9319e02 100644 --- a/docs/md/explanation/table/loading_data.md +++ b/docs/md/explanation/table/loading_data.md @@ -3,11 +3,11 @@ A `Table` may also be created-or-updated by data in CSV, [Apache Arrow](https://arrow.apache.org/), JSON row-oriented or JSON column-oriented formats. In addition to these, `perspective-python` additionally -supports `pyarrow.Table`, `polars.DataFrame` and `pandas.DataFrame` objects -directly. These formats are otherwise identical to the built-in formats and -don't exhibit any additional support or type-awareness; e.g., `pandas.DataFrame` -support is _just_ `pyarrow.Table.from_pandas` piped into Perspective's Arrow -reader. +supports `pyarrow.Table`, `pyarrow.RecordBatch`, `polars.DataFrame` and +`pandas.DataFrame` objects directly. These formats are otherwise identical to +the built-in formats and don't exhibit any additional support or type-awareness; +e.g., `pandas.DataFrame` support is _just_ `pyarrow.Table.from_pandas` piped +into Perspective's Arrow reader. `Client::table` and `Table::update` perform _coercion_ on their input for all input formats _except_ Arrow (which comes with its own schema and has no need diff --git a/docs/md/how_to/python/table.md b/docs/md/how_to/python/table.md index c2b6e666c5..72580d3b1e 100644 --- a/docs/md/how_to/python/table.md +++ b/docs/md/how_to/python/table.md @@ -7,6 +7,7 @@ commonly used when processing data: - `pandas.DataFrame` - `polars.DataFrame` +- `pyarrow.Table` and `pyarrow.RecordBatch` - `bytes` (encoding an Apache Arrow) - `objects` (either extracting a repr or via reference) - `str` (encoding as a CSV) diff --git a/docs/md/how_to/python/table_data.md b/docs/md/how_to/python/table_data.md index ab6dc76dac..4510c22123 100644 --- a/docs/md/how_to/python/table_data.md +++ b/docs/md/how_to/python/table_data.md @@ -27,6 +27,13 @@ The same applies to `Table.update()`: table.update(arrow_table) ``` +A `pyarrow.RecordBatch` is accepted anywhere a `pyarrow.Table` is: + +```python +batch = pa.RecordBatch.from_pydict({"int": [4, 5], "float": [4.5, 5.5], "string": ["d", "e"]}) +table.update(batch) +``` + If you have Arrow data already in IPC format (e.g. read from disk, received over the wire, or produced by another tool), pass the raw `bytes` directly — both stream and file formats are auto-detected: diff --git a/rust/perspective-python/perspective/tests/table/test_table_arrow.py b/rust/perspective-python/perspective/tests/table/test_table_arrow.py index 27f641cb1c..c8e35115cc 100644 --- a/rust/perspective-python/perspective/tests/table/test_table_arrow.py +++ b/rust/perspective-python/perspective/tests/table/test_table_arrow.py @@ -175,6 +175,22 @@ def test_empty_arrow(self, util): "col2": "string", } + def test_table_arrow_record_batch(self): + batch = pa.RecordBatch.from_pydict( + { + "col1": [1, 2, 3], + "col2": ["abc", "foo", "bar"], + } + ) + + tbl = client.table(batch) + assert tbl.schema() == {"col1": "integer", "col2": "string"} + tbl.update(batch) + assert tbl.view().to_columns() == { + "col1": [1, 2, 3, 1, 2, 3], + "col2": ["abc", "foo", "bar", "abc", "foo", "bar"], + } + def test_table_arrow_loads_float_stream(self, util): data = [[i for i in range(10)], [i * 1.5 for i in range(10)]] arrow_data = util.make_arrow(["a", "b"], data) diff --git a/rust/perspective-python/src/client/client_async.rs b/rust/perspective-python/src/client/client_async.rs index f8bc7d2b64..e3f491ce42 100644 --- a/rust/perspective-python/src/client/client_async.rs +++ b/rust/perspective-python/src/client/client_async.rs @@ -73,9 +73,8 @@ fn negotiate_extra_arg( return Ok(ExtraArg::Positional); } else if kind.eq(&positional_only)? || kind.eq(&positional_or_keyword)? { positional += 1; - } else if kind.eq(&var_keyword)? { - keyword = true; - } else if kind.eq(&keyword_only)? && param.getattr("name")?.extract::()? == name + } else if kind.eq(&var_keyword)? + || (kind.eq(&keyword_only)? && param.getattr("name")?.extract::()? == name) { keyword = true; } @@ -261,7 +260,7 @@ impl AsyncClient { /// The [`Client::table`] factory function can be initialized with either a /// _schema_ (see [`Table::schema`]), or data in one of these formats: /// - /// - Apache Arrow + /// - Apache Arrow (IPC `bytes`, `pyarrow.Table` or `pyarrow.RecordBatch`) /// - CSV /// - JSON row-oriented /// - JSON column-oriented diff --git a/rust/perspective-python/src/client/client_sync.rs b/rust/perspective-python/src/client/client_sync.rs index 4c1d2ae95e..882b7f8c50 100644 --- a/rust/perspective-python/src/client/client_sync.rs +++ b/rust/perspective-python/src/client/client_sync.rs @@ -120,7 +120,7 @@ impl Client { /// The [`Client::table`] factory function can be initialized with either a /// _schema_ (see [`Table::schema`]), or data in one of these formats: /// - /// - Apache Arrow + /// - Apache Arrow (IPC `bytes`, `pyarrow.Table` or `pyarrow.RecordBatch`) /// - CSV /// - JSON row-oriented /// - JSON column-oriented diff --git a/rust/perspective-python/src/client/pyarrow.rs b/rust/perspective-python/src/client/pyarrow.rs index 5f152ff965..57bcbacb4c 100644 --- a/rust/perspective-python/src/client/pyarrow.rs +++ b/rust/perspective-python/src/client/pyarrow.rs @@ -12,13 +12,15 @@ use pyo3::exceptions::PyValueError; use pyo3::prelude::*; -use pyo3::types::{PyAny, PyBytes}; +use pyo3::types::{PyAny, PyBytes, PyTuple}; -fn get_pyarrow_table_cls(py: Python<'_>) -> PyResult>> { +/// The `(pyarrow.Table, pyarrow.RecordBatch)` classes, if `pyarrow` is loaded. +fn get_pyarrow_table_cls(py: Python<'_>) -> PyResult>> { let sys = PyModule::import(py, "sys")?; if sys.getattr("modules")?.contains("pyarrow")? { - let pandas = PyModule::import(py, "pyarrow")?; - Ok(Some(pandas.getattr("Table")?.unbind())) + let pyarrow = PyModule::import(py, "pyarrow")?; + let classes = (pyarrow.getattr("Table")?, pyarrow.getattr("RecordBatch")?); + Ok(Some(classes.into_pyobject(py)?.unbind())) } else { Ok(None) } @@ -38,10 +40,12 @@ pub fn to_arrow_bytes<'py>( ) -> PyResult> { let pyarrow = PyModule::import(py, "pyarrow")?; let table_class = get_pyarrow_table_cls(py)? - .ok_or_else(|| PyValueError::new_err("Failed to import pyarrow.Table"))?; + .ok_or_else(|| PyValueError::new_err("Failed to import pyarrow"))?; if !table.is_instance(table_class.bind(py))? { - return Err(PyValueError::new_err("Input is not a pyarrow.Table")); + return Err(PyValueError::new_err( + "Input is not a pyarrow.Table or pyarrow.RecordBatch", + )); } let sink = pyarrow.call_method0("BufferOutputStream")?; @@ -52,7 +56,7 @@ pub fn to_arrow_bytes<'py>( (sink.clone(), table.getattr("schema")?), )?; - writer.call_method1("write_table", (table,))?; + writer.call_method1("write", (table,))?; writer.call_method0("close")?; } From 455593ff627f12452f3a65e02faaa5840126180a Mon Sep 17 00:00:00 2001 From: Andrew Stein Date: Thu, 19 Nov 2026 23:09:04 -0500 Subject: [PATCH 3/3] Schemars Signed-off-by: Andrew Stein --- .github/workflows/build.yaml | 1 + Cargo.lock | 65 ++++++++++++ pnpm-lock.yaml | 68 ++----------- pnpm-workspace.yaml | 1 + rust/metadata/Cargo.toml | 7 ++ rust/metadata/main.rs | 43 ++++++++ rust/perspective-client/Cargo.toml | 5 + .../src/rust/config/aggregates.rs | 3 +- .../src/rust/config/expressions.rs | 3 +- .../src/rust/config/filters.rs | 9 +- .../src/rust/config/sort.rs | 5 +- .../src/rust/config/view_config.rs | 9 +- .../src/rust/config/viewer/layout.rs | 10 +- .../src/rust/config/viewer/optional_update.rs | 25 +++++ .../src/rust/config/viewer/viewer_config.rs | 9 +- .../rust/config/viewer/workspace_config.rs | 12 ++- .../src/rust/config/windows.rs | 16 ++- rust/perspective-viewer/build.mjs | 3 +- rust/perspective-viewer/package.json | 2 +- .../src/rust/agent/tools.rs | 92 +++++++++++------ .../test/js/agent/agent_docs.spec.ts | 36 ++++--- rust/perspective-viewer/tools.mjs | 98 +++++++------------ 22 files changed, 327 insertions(+), 195 deletions(-) diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 7c22e9f1f0..2d6ff0783b 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -121,6 +121,7 @@ jobs: rust/perspective-js/dist/ts-rs/ rust/perspective-viewer/src/ts/ rust/perspective-viewer/dist/ts-rs/ + rust/target/json_schema/ rust/perspective-python/LICENSE_THIRDPARTY_cargo.yml # ,-,---. . . ,-_/ .---. . diff --git a/Cargo.lock b/Cargo.lock index cc2a34dd8d..6ff8eec191 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -777,6 +777,12 @@ dependencies = [ "dtoa", ] +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + [[package]] name = "either" version = "1.15.0" @@ -2118,6 +2124,8 @@ dependencies = [ "perspective-js", "perspective-server", "perspective-viewer", + "schemars", + "serde_json", "ts-rs", ] @@ -2402,6 +2410,7 @@ dependencies = [ "prost-types", "protobuf-src", "rand 0.9.1", + "schemars", "serde", "serde_bytes", "serde_json", @@ -3031,6 +3040,26 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "regex" version = "1.12.2" @@ -3157,6 +3186,31 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 3.0.10", +] + [[package]] name = "scopeguard" version = "1.2.0" @@ -3239,6 +3293,17 @@ dependencies = [ "syn 2.0.111", ] +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "serde_json" version = "1.0.151" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 65a3d91ecb..a3703cd6eb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -45,6 +45,9 @@ catalogs: '@zip.js/zip.js': specifier: ^2.7.54 version: 2.8.8 + ajv: + specifier: ^8.2 + version: 8.17.1 apache-arrow: specifier: 17.0.0 version: 17.0.0 @@ -1097,15 +1100,15 @@ importers: '@types/ws': specifier: 'catalog:' version: 8.18.1 + ajv: + specifier: 'catalog:' + version: 8.17.1 lightningcss: specifier: 'catalog:' version: 1.33.0 prettier: specifier: 'catalog:' version: 3.6.2 - ts-json-schema-generator: - specifier: ^2.4.0 - version: 2.9.0 typedoc: specifier: 'catalog:' version: 0.28.14(typescript@5.9.3) @@ -3432,10 +3435,6 @@ packages: glob-to-regexp@0.4.1: resolution: {integrity: sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==} - glob@13.0.6: - resolution: {integrity: sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==} - engines: {node: 18 || 20 || >=22} - glob@7.1.7: resolution: {integrity: sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ==} deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me @@ -4029,10 +4028,6 @@ packages: lower-case@2.0.2: resolution: {integrity: sha512-7fm3l3NAF9WfN6W3JOmf5drwpVqX78JtoGJ3A6W0a6ZnldM41w2fV5D490psKFTpMds8TJse/eHLFFsNHHjHgg==} - lru-cache@11.5.2: - resolution: {integrity: sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==} - engines: {node: 20 || >=22} - lru-cache@6.0.0: resolution: {integrity: sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==} engines: {node: '>=10'} @@ -4127,10 +4122,6 @@ packages: resolution: {integrity: sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==} engines: {node: '>=16 || 14 >=14.17'} - minipass@7.1.3: - resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==} - engines: {node: '>=16 || 14 >=14.17'} - minizlib@3.1.0: resolution: {integrity: sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==} engines: {node: '>= 18'} @@ -4201,10 +4192,6 @@ packages: normalize-package-data@2.5.0: resolution: {integrity: sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==} - normalize-path@3.0.0: - resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==} - engines: {node: '>=0.10.0'} - npm-run-all@4.1.5: resolution: {integrity: sha512-Oo82gJDAVcaMdi3nuoKFavkIHBRVqQ1qvMb+9LHk/cF4P6B2m8aP04hGf7oL6wZ9BuGwX1onlLhpuoofSyoQDQ==} engines: {node: '>= 4'} @@ -4327,10 +4314,6 @@ packages: path-parse@1.0.7: resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} - path-scurry@2.0.2: - resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==} - engines: {node: 18 || 20 || >=22} - path-type@3.0.0: resolution: {integrity: sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==} engines: {node: '>=4'} @@ -4613,10 +4596,6 @@ packages: resolution: {integrity: sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==} engines: {node: '>= 0.4'} - safe-stable-stringify@2.5.0: - resolution: {integrity: sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==} - engines: {node: '>=10'} - safer-buffer@2.1.2: resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} @@ -4906,11 +4885,6 @@ packages: peerDependencies: typescript: '>=4.8.4' - ts-json-schema-generator@2.9.0: - resolution: {integrity: sha512-NR5ZE108uiPtBHBJNGnhwoUaUx5vWTDJzDFG9YlRoqxPU76n+5FClRh92dcGgysbe1smRmYalM9Saj97GW1J4Q==} - engines: {node: '>=22.0.0'} - hasBin: true - tslib@1.14.1: resolution: {integrity: sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==} @@ -8071,12 +8045,6 @@ snapshots: glob-to-regexp@0.4.1: {} - glob@13.0.6: - dependencies: - minimatch: 10.2.5 - minipass: 7.1.3 - path-scurry: 2.0.2 - glob@7.1.7: dependencies: fs.realpath: 1.0.0 @@ -8680,8 +8648,6 @@ snapshots: dependencies: tslib: 2.8.1 - lru-cache@11.5.2: {} - lru-cache@6.0.0: dependencies: yallist: 4.0.0 @@ -8760,8 +8726,6 @@ snapshots: minipass@7.1.2: {} - minipass@7.1.3: {} - minizlib@3.1.0: dependencies: minipass: 7.1.2 @@ -8814,8 +8778,6 @@ snapshots: semver: 5.7.2 validate-npm-package-license: 3.0.4 - normalize-path@3.0.0: {} - npm-run-all@4.1.5: dependencies: ansi-styles: 3.2.1 @@ -8962,11 +8924,6 @@ snapshots: path-parse@1.0.7: {} - path-scurry@2.0.2: - dependencies: - lru-cache: 11.5.2 - minipass: 7.1.3 - path-type@3.0.0: dependencies: pify: 3.0.0 @@ -9314,8 +9271,6 @@ snapshots: es-errors: 1.3.0 is-regex: 1.2.1 - safe-stable-stringify@2.5.0: {} - safer-buffer@2.1.2: {} sanitize-html@2.12.1: @@ -9657,17 +9612,6 @@ snapshots: dependencies: typescript: 5.9.3 - ts-json-schema-generator@2.9.0: - dependencies: - '@types/json-schema': 7.0.15 - commander: 14.0.3 - glob: 13.0.6 - json5: 2.2.3 - normalize-path: 3.0.0 - safe-stable-stringify: 2.5.0 - tslib: 2.8.1 - typescript: 5.9.3 - tslib@1.14.1: {} tslib@2.8.1: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 59a9156df6..7903eca3d3 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -83,6 +83,7 @@ catalog: "@types/ws": ">=8" "@types/chroma-js": "^3.1.2" "@zip.js/zip.js": "^2.7.54" + "ajv": "^8.2" "apache-arrow": "17.0.0" "arraybuffer-loader": ">=1.0.8 <2" "auto-changelog": "^2.5.0" diff --git a/rust/metadata/Cargo.toml b/rust/metadata/Cargo.toml index d61f56ad66..cc29a264b7 100644 --- a/rust/metadata/Cargo.toml +++ b/rust/metadata/Cargo.toml @@ -29,6 +29,13 @@ artifact = ["bin"] version = "11.0.1" features = ["serde-json-impl", "no-serde-warnings"] +[dependencies.schemars] +version = "1.2.3" +features = ["preserve_order"] + +[dependencies.serde_json] +version = "1.0.107" + [dependencies.perspective-server] path = "../perspective-server" features = ["external-cpp", "disable-cpp"] diff --git a/rust/metadata/main.rs b/rust/metadata/main.rs index ef1d37f165..4112d42d51 100644 --- a/rust/metadata/main.rs +++ b/rust/metadata/main.rs @@ -22,6 +22,9 @@ //! - Recurisvely set external proto on `perspective-client` //! - `perspective-server` //! - Copy `cpp` and `cmake` to local root +//! - `perspective-viewer` +//! - TypeScript types +//! - JSON Schema (draft 2020-12) for the agent's tool parameters //! //! The `metadata` binary must be run for these assets to be updated in //! your local dev tree! @@ -129,6 +132,45 @@ pub fn generate_type_bindings_viewer() -> Result<(), Box> { into_declarations(&path) } +/// One JSON Schema per config type the `` agent accepts +/// as a tool argument, as `rust/target/json_schema/.json` — a build +/// intermediate (cleaned and git-ignored with the rest of `rust/target`). +/// The viewer build's `tools.mjs` bundles them into +/// `dist/docs/perspective-docs.json`, from which the agent splices them into +/// its tool parameters. Draft 2020-12 is pinned explicitly (it is also +/// schemars' current default) because the Anthropic API rejects anything +/// else. +pub fn generate_json_schemas() -> Result<(), Box> { + let path = std::env::current_dir()?.join("../target/json_schema"); + + // 100% generated: wipe so a type dropped from this list cannot linger as + // a stale file. + if path.exists() { + fs::remove_dir_all(&path)?; + } + + fs::create_dir_all(&path)?; + fn root_schema() -> schemars::Schema { + schemars::generate::SchemaSettings::draft2020_12() + .into_generator() + .into_root_schema_for::() + } + + for (name, schema) in [ + ("ViewerConfigUpdate", root_schema::()), + ("ViewerConfigInitial", root_schema::()), + ( + "WorkspaceConfigUpdate", + root_schema::(), + ), + ] { + let json = serde_json::to_string_pretty(&schema)?; + fs::write(path.join(format!("{name}.json")), json)?; + } + + Ok(()) +} + fn generate_exprtk_docs() -> Result<(), Box> { let mut txt = "
\n\n# Perspective ExprTK Extensions\n\n".to_string(); for rec in perspective_client::config::COMPLETIONS { @@ -191,6 +233,7 @@ pub fn generate_python_cargo_licenses() -> Result<(), Box> { fn main() -> Result<(), Box> { generate_type_bindings_js()?; generate_type_bindings_viewer()?; + generate_json_schemas()?; generate_exprtk_docs()?; generate_python_cargo_licenses()?; Ok(()) diff --git a/rust/perspective-client/Cargo.toml b/rust/perspective-client/Cargo.toml index b62b79b2d4..cf27b1aa3d 100644 --- a/rust/perspective-client/Cargo.toml +++ b/rust/perspective-client/Cargo.toml @@ -79,6 +79,11 @@ prost-types = { version = "0.12.3" } getrandom = { version = "0", features = ["wasm_js"] } num-traits = "0.2.19" rand = { version = ">=0.9,<1" } + +# JSON Schema (draft 2020-12) for the config types, emitted by `rust/metadata` +# for the viewer agent's tool parameters. `preserve_order` keeps properties in +# declaration order. +schemars = { version = "1.2.3", features = ["preserve_order"] } serde = { version = "1.0", features = ["derive"] } serde_bytes = { version = "0.11" } serde_json = { version = "1.0.107", features = ["raw_value", "preserve_order"] } diff --git a/rust/perspective-client/src/rust/config/aggregates.rs b/rust/perspective-client/src/rust/config/aggregates.rs index d04188acb7..ae85efd965 100644 --- a/rust/perspective-client/src/rust/config/aggregates.rs +++ b/rust/perspective-client/src/rust/config/aggregates.rs @@ -12,12 +12,13 @@ use std::fmt::Display; +use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use ts_rs::TS; use crate::proto::{ColumnType, view_config}; -#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize, TS)] +#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, Ord, PartialEq, PartialOrd, Serialize, TS)] #[serde(untagged)] pub enum Aggregate { SingleAggregate(String), diff --git a/rust/perspective-client/src/rust/config/expressions.rs b/rust/perspective-client/src/rust/config/expressions.rs index 60d33ebe91..392704826e 100644 --- a/rust/perspective-client/src/rust/config/expressions.rs +++ b/rust/perspective-client/src/rust/config/expressions.rs @@ -161,12 +161,13 @@ use std::borrow::Cow; use std::collections::HashMap; use std::fmt; +use schemars::JsonSchema; use serde::de::value::MapAccessDeserializer; use serde::de::{MapAccess, Visitor}; use serde::{Deserialize, Deserializer, Serialize}; use ts_rs::TS; -#[derive(Serialize, Clone, PartialEq, Debug, Default, TS)] +#[derive(Serialize, Clone, PartialEq, Debug, Default, JsonSchema, TS)] pub struct Expressions(pub HashMap); impl<'de> Deserialize<'de> for Expressions { diff --git a/rust/perspective-client/src/rust/config/filters.rs b/rust/perspective-client/src/rust/config/filters.rs index c95b5ce139..2b52c33615 100644 --- a/rust/perspective-client/src/rust/config/filters.rs +++ b/rust/perspective-client/src/rust/config/filters.rs @@ -13,6 +13,7 @@ use std::fmt::Display; use itertools::Itertools; +use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use ts_rs::TS; @@ -21,7 +22,7 @@ use crate::proto::scalar; /// This type represents the ViewConfig serializable type, which must be JSON /// safe. -#[derive(Clone, Default, Deserialize, Debug, PartialEq, Serialize, TS)] +#[derive(Clone, Default, Deserialize, Debug, JsonSchema, PartialEq, Serialize, TS)] #[serde(untagged)] pub enum Scalar { Float(f64), @@ -51,7 +52,7 @@ impl Display for Scalar { } } -#[derive(Clone, Deserialize, Debug, PartialEq, Serialize, TS)] +#[derive(Clone, Deserialize, Debug, JsonSchema, PartialEq, Serialize, TS)] #[serde(untagged)] pub enum FilterTerm { Array(Vec), @@ -97,7 +98,7 @@ impl FilterTerm { } } -#[derive(Clone, Deserialize, Debug, PartialEq, Serialize, TS)] +#[derive(Clone, Deserialize, Debug, JsonSchema, PartialEq, Serialize, TS)] #[serde()] pub struct Filter(String, String, #[serde(default)] FilterTerm); @@ -143,7 +144,7 @@ impl Filter { } } -#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq, TS)] +#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)] pub enum FilterReducer { #[default] #[serde(rename = "and")] diff --git a/rust/perspective-client/src/rust/config/sort.rs b/rust/perspective-client/src/rust/config/sort.rs index 0d75e97715..440f92d94b 100644 --- a/rust/perspective-client/src/rust/config/sort.rs +++ b/rust/perspective-client/src/rust/config/sort.rs @@ -12,16 +12,17 @@ use std::fmt::Display; +use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use ts_rs::TS; use crate::proto; -#[derive(Clone, Deserialize, Debug, Eq, PartialEq, Serialize, TS)] +#[derive(Clone, Deserialize, Debug, Eq, JsonSchema, PartialEq, Serialize, TS)] #[serde()] pub struct Sort(pub String, pub SortDir); -#[derive(Clone, Copy, Deserialize, Debug, Eq, PartialEq, Serialize, TS)] +#[derive(Clone, Copy, Deserialize, Debug, Eq, JsonSchema, PartialEq, Serialize, TS)] #[serde()] pub enum SortDir { #[serde(rename = "none")] diff --git a/rust/perspective-client/src/rust/config/view_config.rs b/rust/perspective-client/src/rust/config/view_config.rs index c7d0875a2b..1b611415ca 100644 --- a/rust/perspective-client/src/rust/config/view_config.rs +++ b/rust/perspective-client/src/rust/config/view_config.rs @@ -13,6 +13,7 @@ use std::collections::HashMap; use std::fmt::Display; +use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use ts_rs::TS; @@ -24,7 +25,7 @@ use super::windows::*; use crate::proto; use crate::proto::{ColumnType, columns_update}; -#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq, TS)] +#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)] pub enum GroupRollupMode { #[default] #[serde(rename = "rollup")] @@ -73,7 +74,7 @@ impl From for proto::GroupRollupMode { /// subtotal column groups in "totals before" order. There is no `Total` /// variant - an empty `split_by` already expresses a single grand-total /// column group. -#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq, TS)] +#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)] pub enum SplitRollupMode { #[default] #[serde(rename = "flat")] @@ -110,7 +111,7 @@ impl From for proto::SplitRollupMode { } } -#[derive(Clone, Debug, Deserialize, Default, PartialEq, Serialize, TS)] +#[derive(Clone, Debug, Deserialize, Default, JsonSchema, PartialEq, Serialize, TS)] #[serde(deny_unknown_fields)] pub struct ViewConfig { #[serde(default)] @@ -158,7 +159,7 @@ fn is_default_value(value: &A) -> bool { value == &A::default() } -#[derive(Clone, Debug, Deserialize, Default, PartialEq, Serialize, TS)] +#[derive(Clone, Debug, Deserialize, Default, JsonSchema, PartialEq, Serialize, TS)] #[serde(deny_unknown_fields)] pub struct ViewConfigUpdate { /// A group by _groups_ the dataset by the unique values of each column used diff --git a/rust/perspective-client/src/rust/config/viewer/layout.rs b/rust/perspective-client/src/rust/config/viewer/layout.rs index 82dff494db..fa7ac61f7d 100644 --- a/rust/perspective-client/src/rust/config/viewer/layout.rs +++ b/rust/perspective-client/src/rust/config/viewer/layout.rs @@ -14,7 +14,9 @@ use serde::{Deserialize, Serialize}; /// The direction a [`SplitLayout`] divides its space in: `horizontal` places /// children side by side as columns, `vertical` stacks them as rows. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)] +#[derive( + Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema, ts_rs::TS, +)] #[serde(rename_all = "lowercase")] pub enum Orientation { /// Children side by side, as columns. @@ -26,7 +28,7 @@ pub enum Orientation { /// A dashboard's panel arrangement: nested splits whose leaves are tab stacks /// of panel ids, naming each panel at most once. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ts_rs::TS)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, schemars::JsonSchema, ts_rs::TS)] #[serde(tag = "type")] pub enum Layout { /// Space divided among children, side-by-side or stacked. @@ -39,7 +41,7 @@ pub enum Layout { } /// A row or column of child layouts, nested to form a grid. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ts_rs::TS)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, schemars::JsonSchema, ts_rs::TS)] pub struct SplitLayout { /// Child layouts, in left-to-right or top-to-bottom order. pub children: Vec, @@ -54,7 +56,7 @@ pub struct SplitLayout { } /// A stack of panels shown as tabs, one visible at a time. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ts_rs::TS)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, schemars::JsonSchema, ts_rs::TS)] pub struct TabLayout { /// Panel ids (slot names) in this stack. pub tabs: Vec, diff --git a/rust/perspective-client/src/rust/config/viewer/optional_update.rs b/rust/perspective-client/src/rust/config/viewer/optional_update.rs index aa9d60fc9d..f49245499c 100644 --- a/rust/perspective-client/src/rust/config/viewer/optional_update.rs +++ b/rust/perspective-client/src/rust/config/viewer/optional_update.rs @@ -10,6 +10,9 @@ // ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ +use std::borrow::Cow; + +use schemars::{JsonSchema, Schema, SchemaGenerator}; use serde::{Deserialize, Deserializer, Serialize}; use serde_json::Value; use ts_rs::TS; @@ -66,6 +69,28 @@ impl From> for OptionalUpdate { } } +/// Hand-written because the derived (untagged) schema would list both unit +/// variants. On the wire this is exactly `Option` — `null` resets, a value +/// replaces — and "absent" is the containing field's `#[serde(default)]`, +/// which already makes the property optional. +impl JsonSchema for OptionalUpdate { + fn inline_schema() -> bool { + true + } + + fn schema_name() -> Cow<'static, str> { + format!("OptionalUpdate_{}", T::schema_name()).into() + } + + fn schema_id() -> Cow<'static, str> { + format!("OptionalUpdate<{}>", T::schema_id()).into() + } + + fn json_schema(generator: &mut SchemaGenerator) -> Schema { + as JsonSchema>::json_schema(generator) + } +} + impl<'a, T> Deserialize<'a> for OptionalUpdate where T: Deserialize<'a> + Clone, diff --git a/rust/perspective-client/src/rust/config/viewer/viewer_config.rs b/rust/perspective-client/src/rust/config/viewer/viewer_config.rs index 6045718855..b87dae1e1a 100644 --- a/rust/perspective-client/src/rust/config/viewer/viewer_config.rs +++ b/rust/perspective-client/src/rust/config/viewer/viewer_config.rs @@ -13,6 +13,7 @@ use std::collections::HashMap; use std::ops::Deref; +use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use serde_json::Value; use ts_rs::TS; @@ -166,7 +167,8 @@ impl Deref for PluginConfig { /// The `restore()` argument: a field-wise update of a panel's state, where an /// absent key is unchanged, `null` resets and a value replaces. -#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize, TS)] +#[derive(Clone, Debug, Default, Deserialize, JsonSchema, PartialEq, Serialize, TS)] +#[schemars(deny_unknown_fields)] pub struct ViewerConfigUpdate { /// The `@perspective-dev/viewer` version a saved config was written /// by, named in the error when such a config is rejected. Omit it — the @@ -248,6 +250,7 @@ pub struct ViewerConfigUpdate { /// Rejects keys no field above consumed. #[serde(flatten, skip_serializing)] #[ts(skip)] + #[schemars(skip)] pub unknown: UnknownKeys, } @@ -258,7 +261,8 @@ pub struct ViewerConfigUpdate { /// binding would be permanently blank), absent fields mean "default" /// rather than "leave unchanged" (so no [`OptionalUpdate`] tri-state), and /// there is no `settings` field (element-level, not per-panel). -#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, TS)] +#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize, TS)] +#[schemars(deny_unknown_fields)] pub struct ViewerConfigInitial { /// Name of the `Table` the new panel renders, as hosted on the /// `Client`. REQUIRED: a placed panel with no table binding would be @@ -309,6 +313,7 @@ pub struct ViewerConfigInitial { /// Rejects keys no field above consumed. #[serde(flatten, skip_serializing)] #[ts(skip)] + #[schemars(skip)] pub unknown: UnknownKeys, } diff --git a/rust/perspective-client/src/rust/config/viewer/workspace_config.rs b/rust/perspective-client/src/rust/config/viewer/workspace_config.rs index 8a11a803e9..cd67b9e143 100644 --- a/rust/perspective-client/src/rust/config/viewer/workspace_config.rs +++ b/rust/perspective-client/src/rust/config/viewer/workspace_config.rs @@ -22,7 +22,10 @@ use crate::config::{Filter, ViewConfig}; /// the config of that `View`; generic over the `table` slot, which is a name /// in the workspace `derived_tables` map and a recursive [`TableRef`] when /// inlined in a single-panel config. -#[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize, ts_rs::TS)] +#[derive( + Clone, Debug, PartialEq, schemars::JsonSchema, serde::Deserialize, serde::Serialize, ts_rs::TS, +)] +#[schemars(inline)] pub struct DerivedTableConfig { /// The `Table` this derivation reads, which may itself be another /// derived `Table`. @@ -35,13 +38,14 @@ pub struct DerivedTableConfig { /// Rejects keys no field above consumed. #[serde(flatten, skip_serializing)] #[ts(skip)] + #[schemars(skip)] pub unknown: UnknownKeys, } /// What may occupy a `table` position in a single-panel config: a hosted /// `Table`'s name, or an inline derived-table definition recursing through /// its own `table` field until a concrete name. -#[derive(Clone, Debug, PartialEq, serde::Serialize)] +#[derive(Clone, Debug, PartialEq, schemars::JsonSchema, serde::Serialize)] #[serde(untagged)] pub enum TableRef { /// A hosted `Table`'s name. @@ -239,7 +243,8 @@ pub struct WorkspaceConfig { /// key is unchanged, `null` resets and a value replaces. /// /// [`ViewerConfigUpdate`]: super::ViewerConfigUpdate -#[derive(serde::Deserialize, ts_rs::TS)] +#[derive(schemars::JsonSchema, serde::Deserialize, ts_rs::TS)] +#[schemars(deny_unknown_fields)] pub struct WorkspaceConfigUpdate { /// The `@perspective-dev/viewer` version a saved workspace was written /// by, named in the error when such a workspace is rejected. @@ -299,6 +304,7 @@ pub struct WorkspaceConfigUpdate { /// Rejects keys no field above consumed. #[serde(flatten)] #[ts(skip)] + #[schemars(skip)] pub unknown: UnknownKeys, } diff --git a/rust/perspective-client/src/rust/config/windows.rs b/rust/perspective-client/src/rust/config/windows.rs index f5c754219c..6ca195a1a6 100644 --- a/rust/perspective-client/src/rust/config/windows.rs +++ b/rust/perspective-client/src/rust/config/windows.rs @@ -22,6 +22,7 @@ use std::collections::HashMap; +use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use ts_rs::TS; @@ -41,7 +42,7 @@ pub enum WindowFrame { /// A window's order direction. A dedicated two-variant enum rather than /// [`crate::config::SortDir`] - the column-sort extras (`col asc`, `abs`, /// `none`) are meaningless inside a window frame and unrepresentable here. -#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize, TS)] +#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize, TS)] #[serde(rename_all = "snake_case")] pub enum WindowSortDir { #[default] @@ -61,15 +62,19 @@ impl std::fmt::Display for WindowSortDir { /// The `Table` column which orders each partition, with its direction - /// serialized as a two-element array (`["ts", "desc"]`), symmetric with the /// `ViewConfig`'s `sort` field. -#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, TS)] +#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize, TS)] pub struct WindowSort(pub String, pub WindowSortDir); /// The window columns of a `ViewConfig`, keyed by output column alias - /// symmetric with `expressions` (`{"name": {...spec}}`). An alias must not /// collide with a `Table` column, expression alias, or another window's /// key. -#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize, TS)] -pub struct Windows(#[ts(as = "HashMap")] pub HashMap); +#[derive(Clone, Debug, Default, Deserialize, JsonSchema, PartialEq, Serialize, TS)] +pub struct Windows( + #[ts(as = "HashMap")] + #[schemars(with = "HashMap")] + pub HashMap, +); impl std::ops::Deref for Windows { type Target = HashMap; @@ -100,9 +105,10 @@ pub struct WindowSpec { } /// The serialized form of [`WindowSpec`]. -#[derive(Clone, Debug, Deserialize, Serialize, TS)] +#[derive(Clone, Debug, Deserialize, JsonSchema, Serialize, TS)] #[serde(deny_unknown_fields)] #[ts(rename = "WindowSpec")] +#[schemars(rename = "WindowSpec")] struct RawWindowSpec { /// The input column - either a real `Table` column or an expression /// alias from the same `ViewConfig`. diff --git a/rust/perspective-viewer/build.mjs b/rust/perspective-viewer/build.mjs index 19c90b2d59..3309772ec2 100644 --- a/rust/perspective-viewer/build.mjs +++ b/rust/perspective-viewer/build.mjs @@ -60,7 +60,8 @@ export async function build_all() { } // The agent metadata bundle: `search_docs` corpus + tool parameter - // schemas (needs the freshly-emitted `.d.ts` / ts-rs output). + // schemas (needs the freshly-emitted `.d.ts`, plus the `dist/ts-rs` and + // `rust/target/json_schema` output of the metadata build). const docs_stats = await buildDocsCorpus(); console.log( `docs corpus: ${docs_stats.chunks} chunks / ${docs_stats.bytes} bytes from ${docs_stats.files} files`, diff --git a/rust/perspective-viewer/package.json b/rust/perspective-viewer/package.json index 7935cbc854..ae20a811d2 100644 --- a/rust/perspective-viewer/package.json +++ b/rust/perspective-viewer/package.json @@ -71,6 +71,7 @@ "@perspective-dev/esbuild-plugin": "workspace:^", "@perspective-dev/test": "workspace:^", "@perspective-dev/metadata": "workspace:^", + "ajv": "catalog:", "lightningcss": "catalog:", "@playwright/test": "catalog:", "@playwright/experimental-ct-react": "catalog:", @@ -79,7 +80,6 @@ "@types/react-dom": "catalog:", "@types/ws": "catalog:", "prettier": "catalog:", - "ts-json-schema-generator": "^2.4.0", "typedoc": "catalog:", "typescript": "catalog:", "ws": "catalog:", diff --git a/rust/perspective-viewer/src/rust/agent/tools.rs b/rust/perspective-viewer/src/rust/agent/tools.rs index 898a3c5f25..4895f87c31 100644 --- a/rust/perspective-viewer/src/rust/agent/tools.rs +++ b/rust/perspective-viewer/src/rust/agent/tools.rs @@ -173,12 +173,15 @@ fn panel_property() -> Value { }) } -/// The `config` property node + root `definitions` for tools taking a -/// config argument (`key` = the generated schema's type name, e.g. -/// `"ViewerConfigUpdate"`): the generated schema (from the docs metadata -/// bundle) when available, else a permissive object. `require` lists -/// config properties the AGENT contract requires beyond the public type -/// (unioned into the definition's `required`, stated outright in the +/// The JSON pointer prefix of a schema's shared definitions (draft 2020-12). +const DEFS_PREFIX: &str = "#/$defs/"; + +/// The `config` property node + root `$defs` for tools taking a config +/// argument (`key` = the schema's type name, e.g. `"ViewerConfigUpdate"`): +/// the type's draft 2020-12 JSON Schema (from the docs metadata bundle, as +/// emitted by `rust/metadata`) when available, else a permissive object. +/// `require` lists config properties the AGENT contract requires beyond the +/// public type (unioned into the schema's `required`, stated outright in the /// fallback) — the tool body must enforce the same fields at dispatch. /// `omit` lists public properties the agent contract withholds. fn spliced_config( @@ -188,20 +191,22 @@ fn spliced_config( require: &[&str], omit: &[&str], ) -> (Value, Option) { - match schemas.and_then(|x| x.get(key)) { + match schemas.and_then(|x| x.get(key)).and_then(|x| x.as_object()) { Some(schema) => { - let mut definitions = schema - .get("definitions") - .and_then(|x| x.as_object()) - .cloned() - .unwrap_or_default(); - - let original = definitions.remove(key); - let mut config = original - .clone() - .unwrap_or_else(|| json!({ "type": "object" })); + // The bundle schema is a root document: the type's own schema, + // `$schema`/`title` metadata, and its `$defs`. Spliced in as a + // property it keeps only the type schema; the `$defs` move to + // the tool parameters' root, where `#/$defs/...` still resolves. + let mut original = schema.clone(); + let mut definitions = match original.remove("$defs") { + Some(Value::Object(x)) => x, + _ => serde_json::Map::new(), + }; - if let Some(properties) = config["properties"].as_object_mut() { + original.remove("$schema"); + original.remove("title"); + let mut config = Value::Object(original.clone()); + if let Some(properties) = config.get_mut("properties").and_then(|x| x.as_object_mut()) { for field in omit { properties.remove(*field); } @@ -221,12 +226,18 @@ fn spliced_config( config["description"] = json!(description); - // A self-recursive config type still needs its own entry. - if let Some(original) = original - && serde_json::to_string(&definitions) - .unwrap_or_default() - .contains(&format!("#/definitions/{key}")) - { + // A self-reference to the root (`"#"`) would point at the tool + // parameters once spliced, so a self-recursive config type is + // re-homed under its own `$defs` entry. + let target = format!("{DEFS_PREFIX}{key}"); + let mut recursive = retarget_root_refs(&mut config, &target); + for definition in definitions.values_mut() { + recursive |= retarget_root_refs(definition, &target); + } + + if recursive { + let mut original = Value::Object(original); + retarget_root_refs(&mut original, &target); definitions.insert(key.to_owned(), original); } @@ -246,14 +257,37 @@ fn spliced_config( } } +/// Point every root self-reference (`"$ref": "#"`) under `node` at +/// `target`, returning whether there were any. +fn retarget_root_refs(node: &mut Value, target: &str) -> bool { + let mut found = false; + match node { + Value::Object(map) => { + for (key, value) in map.iter_mut() { + if key == "$ref" && value.as_str() == Some("#") { + *value = Value::from(target); + found = true; + } else { + found |= retarget_root_refs(value, target); + } + } + }, + Value::Array(values) => { + for value in values { + found |= retarget_root_refs(value, target); + } + }, + _ => {}, + } + + found +} + fn definition_refs(node: &Value, out: &mut Vec) { match node { Value::Object(map) => { for (key, value) in map { - match value - .as_str() - .and_then(|x| x.strip_prefix("#/definitions/")) - { + match value.as_str().and_then(|x| x.strip_prefix(DEFS_PREFIX)) { Some(name) if key == "$ref" => out.push(name.to_owned()), _ => definition_refs(value, out), } @@ -311,7 +345,7 @@ fn config_parameters( }); if let Some(definitions) = definitions { - parameters["definitions"] = definitions; + parameters["$defs"] = definitions; } parameters diff --git a/rust/perspective-viewer/test/js/agent/agent_docs.spec.ts b/rust/perspective-viewer/test/js/agent/agent_docs.spec.ts index 46650a2d47..0f3f91ec14 100644 --- a/rust/perspective-viewer/test/js/agent/agent_docs.spec.ts +++ b/rust/perspective-viewer/test/js/agent/agent_docs.spec.ts @@ -257,13 +257,25 @@ test.describe("llm-agent search_docs", () => { expect(Object.keys(config_props)).toContain("windows"); expect(Object.keys(config_props)).toContain("columns_config"); expect(Object.keys(config_props)).toContain("group_by"); - expect(config_props.columns.type).toEqual("array"); - for (const ref of JSON.stringify(params).match( - /#\/definitions\/[^"]+/g, - ) ?? []) { - const name = ref.slice("#/definitions/".length); + // `Option>` is nullable in the generated schema. + expect([config_props.columns.type].flat()).toContain("array"); + + // Draft 2020-12, which Anthropic's API enforces on `input_schema`: + // tuples (`Sort`, `Filter`, ...) are `prefixItems`, never the + // draft-07 `items` array, and the root document's metadata stays + // out of the spliced `config` property. + const json = JSON.stringify(params); + expect(json).toContain('"prefixItems"'); + expect(json).not.toMatch(/"items":\[/); + expect(params.properties.config["$schema"]).toBeUndefined(); + expect(params.properties.config["$defs"]).toBeUndefined(); + + const refs = json.match(/#\/\$defs\/[^"]+/g) ?? []; + expect(refs.length).toBeGreaterThan(0); + for (const ref of refs) { + const name = ref.slice("#/$defs/".length); expect(name).not.toContain("%"); - expect(params.definitions[name]).toBeDefined(); + expect(params.$defs[name]).toBeDefined(); } expect(result.system).toContain("search_docs"); @@ -375,12 +387,12 @@ test.describe("llm-agent search_docs", () => { expect(config_props).toContain("masters"); expect(config_props).toContain("global_filters"); expect(config_props).not.toContain("panels"); - expect(params.definitions?.ViewerConfigInitial).toBeUndefined(); - for (const ref of JSON.stringify(params).match( - /#\/definitions\/[^"]+/g, - ) ?? []) { - const name = ref.slice("#/definitions/".length); - expect(params.definitions[name]).toBeDefined(); + expect(params.$defs?.ViewerConfigInitial).toBeUndefined(); + const refs = JSON.stringify(params).match(/#\/\$defs\/[^"]+/g) ?? []; + expect(refs.length).toBeGreaterThan(0); + for (const ref of refs) { + const name = ref.slice("#/$defs/".length); + expect(params.$defs[name]).toBeDefined(); } }); diff --git a/rust/perspective-viewer/tools.mjs b/rust/perspective-viewer/tools.mjs index c8d1f64cad..ae43a86e0c 100644 --- a/rust/perspective-viewer/tools.mjs +++ b/rust/perspective-viewer/tools.mjs @@ -357,80 +357,50 @@ function normalizeChunks(chunks) { return out; } -// JSON Schemas for tool parameters, generated from the ts-rs `.d.ts` output +// JSON Schemas (draft 2020-12) for tool parameters, emitted from the Rust +// config types by `rust/metadata` (`generate_json_schemas`) into the cargo +// target dir — an intermediate, read only here and bundled into +// `dist/docs/perspective-docs.json`. const TOOL_SCHEMA_TYPES = [ - ["ViewerConfigUpdate", "dist/ts-rs/ViewerConfigUpdate.d.ts"], - ["ViewerConfigInitial", "dist/ts-rs/ViewerConfigInitial.d.ts"], - ["WorkspaceConfigUpdate", "dist/ts-rs/WorkspaceConfigUpdate.d.ts"], + ["ViewerConfigUpdate", "../target/json_schema/ViewerConfigUpdate.json"], + ["ViewerConfigInitial", "../target/json_schema/ViewerConfigInitial.json"], + [ + "WorkspaceConfigUpdate", + "../target/json_schema/WorkspaceConfigUpdate.json", + ], ]; -// Inline every definition whose GENERATED NAME is not a legible -// identifier, replacing each `$ref` to it with the type itself. -function inlineMangledDefinitions(schema) { - const defs = schema.definitions ?? {}; - const mangled = new Map( - Object.entries(defs).filter( - ([name]) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name), - ), - ); - - if (mangled.size === 0) { - return schema; - } - - const walk = (node) => { - if (Array.isArray(node)) { - return node.map(walk); - } - - if (!node || typeof node !== "object") { - return node; - } - - const ref = node["$ref"]; - if (typeof ref === "string" && ref.startsWith("#/definitions/")) { - const name = decodeURIComponent(ref.slice("#/definitions/".length)); - - if (mangled.has(name)) { - // Sibling keys (`description`) win over the inlined body. - const { $ref, ...rest } = node; - return { - ...walk(JSON.parse(JSON.stringify(mangled.get(name)))), - ...rest, - }; - } - } - - return Object.fromEntries( - Object.entries(node).map(([k, v]) => [k, walk(v)]), - ); - }; - - const out = walk(schema); - for (const name of mangled.keys()) { - delete out.definitions[name]; - } - - return out; -} - +// Read each tool schema and check it is valid draft 2020-12 — the draft the +// Anthropic API enforces on tool `input_schema`, rejecting the WHOLE request +// otherwise. `validateSchema` checks the schema against the 2020-12 +// meta-schema; `compile` additionally resolves every `$ref`. Formats are +// annotations here (schemars emits e.g. `uint32`), so they are not validated. async function buildToolSchemas(missing) { - const { createGenerator } = await import("ts-json-schema-generator"); + const { default: Ajv2020 } = await import("ajv/dist/2020.js"); const schemas = {}; for (const [type, path] of TOOL_SCHEMA_TYPES) { if (!fs.existsSync(path)) { - missing.push(`${path} (${type} tool schema)`); + missing.push( + `${path} (${type} tool schema; run the metadata build)`, + ); continue; } - schemas[type] = inlineMangledDefinitions( - createGenerator({ - path, - type, - skipTypeCheck: true, - topRef: true, - }).createSchema(type), - ); + const schema = JSON.parse(fs.readFileSync(path, "utf8")); + const ajv = new Ajv2020({ strict: false, validateFormats: false }); + if (!ajv.validateSchema(schema)) { + throw new Error( + `${path}: not a valid JSON Schema 2020-12: ${ajv.errorsText(ajv.errors)}`, + ); + } + + try { + ajv.compile(schema); + } catch (e) { + throw new Error(`${path}: ${e.message}`); + } + + schemas[type] = schema; } return schemas;