Reference

Library & HTTP API

The engine is a set of crates before it is a binary. This page lists the public Rust API of each crate for embedders, then the HTTP endpoints of the serve console.

The 0.5 additions are not on this page yet: see the changelog. Generated from the 0.4.0 source: the pub use lists in each crate's src/lib.rs, the item signatures behind them, and the router in shapeshift-serve/src/lib.rs with the request and response types in handlers.rs and http.rs. When a release changes them, diff this page against those files rather than trusting it. Rustdoc (cargo doc --open) is the complete reference.

The crates

cratewhat it is
shapeshift-coreThe engine, with no I/O dependency: the spec model, inference, transforms, the Shaper (JSON record → Arrow RecordBatch), the Sink trait, drift detection, the cost arithmetic.
shapeshift-jsonStreaming JSONL and JSON-array sources on simd-json, as serde_json::Value iterators and as zero-allocation tape readers.
shapeshift-parquetParquetSink and a footer-only inspect.
shapeshift-icebergIcebergSink (append, merge, partitioning, evolution), compact_table, expire_table, inspect, and the backend-neutral building blocks an object-store sink reuses.
shapeshift-objstoreBoth sinks, compaction, expiry and inspect against S3, GCS, Azure and file://.
shapeshift-serveThe local console: ServeConfig and serve.
shapeshift-cliThe shapeshift binary.

The crates are not on crates.io; depend on the repository at a release tag:

Cargo.toml
[dependencies]
shapeshift-core    = { git = "https://github.com/lucheeseng827/shapeshift", tag = "v0.4.0" }
shapeshift-parquet = { git = "https://github.com/lucheeseng827/shapeshift", tag = "v0.4.0" }
serde_json = "1"

Embed it

The Sink trait lives in core and is driven, never depended on, so the engine never sees Parquet or Iceberg. This is shapeshift-cli/examples/embed.rs:

examples/embed.rs
use serde_json::json;
use shapeshift_core::{infer_columns, run_pipeline, Compression, Shaper};
use shapeshift_parquet::ParquetSink;

fn main() -> shapeshift_core::Result<()> {
    let records = vec![
        json!({"id": 1, "user": {"name": "Ada"},   "amount": 12.5}),
        json!({"id": 2, "user": {"name": "Grace"}, "amount": 3.0}),
    ];
    let cols = infer_columns(records.iter(), true);
    let shaper = Shaper::new(cols, /* strict = */ false)?;
    let mut sink = ParquetSink::create("out.parquet", shaper.schema(), Compression::Snappy)?;
    let (report, summary) = run_pipeline(shaper, records, &mut sink, 50_000)?;
    println!("rows_out={} bytes={}", report.rows_out, summary.bytes);
    Ok(())
}
run
$ cargo run --release -p shapeshift-cli --example embed
rows_out=2 bytes=1141

To drive a spec instead: DatasetSpec::parse(text)?, infer columns if schema is infer, then Shaper::from_spec(&spec, &inferred)?, which also honours the spec's drift block. For a table, swap the sink for IcebergSink::create(dir, schema, compression, append, &partition_by)?.

shapeshift-core

Spec model

itemwhat it is
DatasetSpecThe whole spec: dataset, source, output, schema, columns, drift, options. parse(&str) -> Result<Self> (YAML or JSON, validated), to_yaml(), validate(). Unknown keys are refused.
SourceSpec, SourceFormatformat (Jsonl | JsonArray) and optional path.
OutputSpec, OutputFormat, Compressionformat (Parquet | Iceberg), path, compression (Snappy | Zstd | Uncompressed), partition_by, merge_on.
SchemaModeInfer | Strict.
ColumnSpecname, from, type (ColumnType), transform, required; source_path().
Optionsflatten, row_group_rows, infer_sample.
ColumnTypeBool, Int64, Float64, String, Date, Timestamp, Json; arrow_type(), iceberg_type(), as_str().
TransformThe eight named transforms; apply(Value) -> Value.
partition_source_column(&str) -> &strThe source column of a partition expression (day(event_at) → event_at).

Engine

itemwhat it is
Shaper::new(columns, strict) -> Result<Shaper>A shaper over fixed columns, with no drift detection.
Shaper::with_drift(columns, strict, &DriftSpec, flatten)The same, watching for drift.
Shaper::from_spec(&DatasetSpec, &inferred)Build from a spec and the inferred columns (empty in strict mode); honours drift.
shaper.push(record) -> Result<PushOutcome>Shape one record (&Value or any Record). Appended, or Rejected(reason) under the lenient policy; strict failures are errors.
shaper.flush() -> Result<Option<RecordBatch>>The pending rows as one batch (one row group).
schema(), pending(), drift_report(), into_drift_report()The Arrow schema; rows waiting; the drift seen so far.
run_pipeline(shaper, records, &mut sink, row_group_rows)Push, flush at row-group boundaries, finish the sink. Returns (RunReport, SinkSummary).
RunReportrows_in, rows_out, rows_rejected, batches, drift: Option<DriftReport>.
effective_columns(&spec, &inferred)Declared columns merged with inferred ones, as the shaper uses them.
infer_columns(samples, flatten) -> Vec<ColumnSpec>Inference over an iterator of &Value. Also looks_like_date, looks_like_timestamp.
Record, KindThe read-only record trait the shaper consumes; &serde_json::Value implements it, and so does shapeshift_json::TapeRecord.
select, segments, flatten_leavesPath selection and flattening over a Value.
RecordBatch, Schema, SchemaRefRe-exported from Arrow, so an embedder need not pin it.

Sink

shapeshift_core::Sink
pub trait Sink {
    /// One row group's worth of rows; the schema the sink was built with.
    fn write_batch(&mut self, batch: &RecordBatch) -> Result<()>;
    /// Footers, table metadata, the commit. Called exactly once.
    fn finish(&mut self) -> Result<SinkSummary>;
}
structfields
SinkSummaryfiles, rows, bytes, merge: Option<MergeSummary>, table_version: Option<u64>, snapshot_id: Option<i64> (the last two None for Parquet).
MergeSummarykey_columns, distinct_keys, keys_updated, keys_inserted, prior_rows_replaced, duplicates_in_input, null_key_rows, data_files_scanned, data_files_pruned, delete_files, position_deletes.

Drift

itemwhat it is
DriftPolicyIgnore, Warn (default), Rescue, Quarantine, Error.
DriftSpecpolicy, rescue_column, max_examples.
DriftReportpolicy, rows_scanned, rows_with_drift, rows_quarantined, rows_rescued, new_fields (path → NewField), type_mismatches (column → TypeMismatch), truncated; is_clean(), events(), suggested_columns().
NewField, TypeMismatchCount, first record, suggested type, examples; a mismatch also carries the declared type and the reason.
MAX_TRACKED_PATHS1,000: distinct paths tracked per run before the report is truncated.

Errors and cost

itemwhat it is
ShapeErrorSpec, Schema, Record (a strict failure), Drift (policy error), Arrow, Sink, Source, and since 0.4 Conflict: another writer committed while this one ran; nothing was published; safe to retry from the start. An exhaustive match needs an arm for it.
Result<T>std::result::Result<T, ShapeError>.
estimate_mar(MarInputs) -> MarReportThe cost arithmetic. MarInputs { rows, vendor_per_million, self_host_cost }; MarReport { rows, vendor_cost, self_host_cost, saved, saved_fraction }.

shapeshift-json

itemwhat it is
JsonlReader<R>new(BufRead), open(path), with_max_line(n). An Iterator<Item = Result<Value, JsonError>>; blank lines skipped, a bad line is an error item and iteration continues.
JsonArrayReader<R>new(BufRead), open(path), from_reader(r), with_max_record(n). Streams one element at a time.
open_reader(path, SourceFormat) -> Result<RecordSource, JsonError>A boxed iterator for either format; - is standard input.
TapeJsonlReader, TapeJsonArrayReader, TapeSource, TapeRecordThe zero-allocation path: each record parses onto a reused simd-json tape. TapeSource is lending, not an Iterator: next_tape() borrows the reader; next_owned() returns a Value to keep.
JsonErrorIo(io::Error) or Parse { line, message, raw }; the raw text is kept for the reject sidecar.
is_stdin(path), is_rereadable(path)Whether a path is -; whether it can be read twice.

shapeshift-parquet

itemwhat it is
ParquetSink::create(path, SchemaRef, Compression) -> Result<Self>A Sink writing one file, a row group per batch. The codec is checked before the file is created.
inspect(path) -> Result<ParquetInfo>Footer only: schema, rows, row_groups, columns.

shapeshift-iceberg

itemwhat it is
IcebergSink::create(dir, schema, compression, append, &partition_by)A Sink landing one snapshot on a local table. append chains onto an existing table, accepting new optional columns.
IcebergSink::create_merge(dir, schema, compression, &partition_by, &merge_on)The upsert sink; creates the table if absent.
set_footer(FileFooter)New in 0.4: key-value pairs every data file of the write carries in its Parquet footer, made from the file's row count as it closes. Also on PartitionedWriter and IcebergDataWriter.
inspect(dir) -> Result<IcebergInfo>format_version, table_uuid, current_snapshot_id, total_records, total_position_deletes, fields; live_records().
compact_table(dir, &CompactOptions) -> Result<CompactSummary>CompactOptions { target_file_size, compression, row_group_rows } (defaults 512 MiB, Snappy, 50,000). The summary's snapshot_id and version are None when nothing was compacted.
expire_table(dir, &ExpireOptions) -> Result<ExpireSummary>ExpireOptions { older_than_ms, retain_last, dry_run }. plan_expiry is the planning half for another backend.
current_scan_files(dir) -> Result<Vec<ScanFile>>Each live data file with the positions its deletes remove: what a reader needs to return the live rows.
current_data_files(dir)The current snapshot's data files; errors on a table with deletes, since reading those files whole would resurrect deleted rows.
TableFiles, LocalTableFilesThe read seam merges, compaction and expiry go through: read, size, read_ranges, readers(). Must be Sync since 0.4.

Lower-level pieces, for writing a table to another backend: IcebergDataWriter, PartitionedWriter, MergeWriter, build_metadata_artifacts with MetadataBuild and MetadataArtifacts, compact with CompactContext, partition helpers (parse_partition_expr, resolve_partition_fields, Transform), and the Avro manifest readers. A caller that persists MetadataArtifacts itself must create the metadata file only if absent, or it loses the commit guard.

shapeshift-objstore

itemwhat it is
ObjectStoreParquetSink::create(url, schema, compression)Writes the file locally a row group at a time, uploads on finish: one PUT, or 8 MiB multipart parts.
ObjectStoreIcebergSink::create(url, schema, compression, append, &partition_by), create_merge(url, schema, compression, &partition_by, &merge_on)The table sinks, same semantics as the local ones.
compact_iceberg(url, &CompactOptions), expire_iceberg(url, &ExpireOptions), inspect_iceberg(url)The table operations on a store.
StoreFiles::open(url, location)The store's TableFiles; builds an HTTP client its own runtime drives.
is_object_url(&str) -> boolWhether a string is a URL this crate handles.

Credentials come from the AWS_*, GOOGLE_* and AZURE_* environment variables; nothing is logged or stored.

shapeshift-serve

run the console from your own binary
let cfg = shapeshift_serve::ServeConfig::new("127.0.0.1:8087", "shapeshift-data");
shapeshift_serve::serve(cfg)?;   // blocks

ServeConfig has addr, data_dir, allowed_hosts and allow_any_host, matching the command's flags.

HTTP API of shapeshift serve

A small JSON API behind the console's single page. The server is hand-rolled on std::net: a fixed pool of 2 to 16 worker threads, a 30-second read timeout, a 64 MiB request-body limit. It is local and single-user, with no authentication.

routewhat it does
GET /, /index.htmlThe console (with a strict Content-Security-Policy: everything from this origin, nothing off-box).
GET /styles.css, /app.jsThe console's two other embedded files.
GET /api/healthLiveness and version.
POST /api/inferInfer a spec from pasted records.
POST /api/shapeShape pasted records, or a server-side file, into Parquet or Iceberg under the data directory.
POST /api/inspectInspect a Parquet file or Iceberg table.
POST /api/costThe MAR comparison.

Rules every request meets

GET /api/health

response
{"data_dir":"sd","service":"shapeshift-serve","status":"ok","version":"0.4.0"}

POST /api/infer

request fieldtypedefaultmeaning
inputstringrequiredRecords, in the chosen format.
format"jsonl" | "json-array""jsonl"Input format.
flattenbooltrueFlatten nested objects.
sampleint1000Records to sample.
datasetstring"dataset"Name, sanitised to letters, digits, _ and -.

Response: dataset, spec_yaml (ready to edit and send back to /api/shape), columns and sampled.

real exchange
$ curl -s -H 'Content-Type: application/json' \
    -d '{"input":"{\"id\":1,\"user\":{\"name\":\"Ada\"},\"amount\":12.5}\n{\"id\":2,\"user\":{\"name\":\"Grace\"},\"amount\":3}\n","dataset":"events"}' \
    http://127.0.0.1:8087/api/infer
{"dataset":"events","spec_yaml":"dataset: events\nsource:\n  format: jsonl\noutput:\n  format: parquet\n  path: events.parquet\n  compression: snappy\nschema: infer\ncolumns:\n- name: amount\n  type: float64\n  required: false\n- name: id\n  type: int64\n  required: false\n- name: user.name\n  type: string\n  required: false\noptions:\n  flatten: true\n  row_group_rows: 50000\n  infer_sample: 1000\n","columns":[{"name":"amount","required":false,"type":"float64"},{"name":"id","required":false,"type":"int64"},{"name":"user.name","required":false,"type":"string"}],"sampled":2}

POST /api/shape

request fieldtypedefaultmeaning
inputstring—Records inline. Ignored when input_path is given; one of the two is required.
input_pathstring—A file on the server to shape instead.
spec_yamlstringnoneAn edited spec, YAML or JSON. Without it the schema is inferred. With output.merge_on set, the shape is a merge.
format"jsonl" | "json-array""jsonl"Input format.
to"parquet" | "iceberg""parquet"Output format.
compression"snappy" | "zstd" | "uncompressed""snappy"Codec.
datasetstring"dataset"Name; also the output's name under outputs/.
partition_bylist of string[]Iceberg partition fields.
appendboolfalseIceberg: add a snapshot instead of starting the table afresh.
on_driftpolicythe spec's"ignore", "warn", "rescue", "quarantine", "error".

The form's fields win over the spec's for format, compression, dataset and output location. Response: dataset, format, output_path, metadata_path (Iceberg), rows_in, rows_out, rejected, parse_errors, row_groups, bytes, rejects_total, rejects_path, rejects_sample (up to 200 of {line?, error, raw}), and drift when something drifted: the policy and counts, up to 25 rows each of new_fields and type_mismatches ({path, count, first_record, suggested_type, declared_type?, example?}), their totals, truncated, and suggested_columns_yaml.

real exchange (captured on Windows, hence the backslashes)
$ curl -s -H 'Content-Type: application/json' \
    -d '{"input":"{\"id\":1,\"amount\":12.5}\nnot-json\n{\"id\":2,\"amount\":3,\"currency\":\"usd\"}\n","dataset":"events","to":"iceberg"}' \
    http://127.0.0.1:8087/api/shape
{"dataset":"events","format":"iceberg","output_path":"sd\\outputs\\events","metadata_path":"sd\\outputs\\events\\metadata/v1.metadata.json","rows_in":2,"rows_out":2,"rejected":0,"parse_errors":1,"row_groups":1,"bytes":1364,"rejects_total":1,"rejects_path":"sd\\outputs\\events.rejects.jsonl","rejects_sample":[{"line":2,"error":"ExpectedNull at character 0 ('n')","raw":"not-json"}]}

POST /api/inspect

Request: {"path": "<file or table>"}, relative to the data directory or absolute. A directory is read as an Iceberg table, anything else as Parquet.

kindresponse fields
"iceberg"path, format_version, table_uuid, current_snapshot_id, total_records, position_deletes, live_records, columns [{name, type}]
"parquet"path, rows, row_groups, columns [{name, type}]
real exchange
$ curl -s -H 'Content-Type: application/json' -d '{"path":"outputs/events"}' http://127.0.0.1:8087/api/inspect
{"columns":[{"name":"amount","type":"double"},{"name":"id","type":"long"},{"name":"currency","type":"string"}],"current_snapshot_id":8115425086776560787,"format_version":2,"kind":"iceberg","live_records":2,"path":"sd\\outputs/events","position_deletes":0,"table_uuid":"fcf5f526-8d4a-49f4-bc29-04ed3ba78048","total_records":2}

Unlike the CLI's --summary-json, this response carries the snapshot id as a JSON number, which JavaScript cannot hold exactly past 253.

POST /api/cost

request fieldtypedefaultmeaning
rowsintrequiredBillable rows.
vendor_per_millionnumberrequiredYour plan's effective price per million MAR.
self_host_costnumber0What running shapeshift cost.
real exchange
$ curl -s -H 'Content-Type: application/json' \
    -d '{"rows":50000000,"vendor_per_million":0.75,"self_host_cost":12}' http://127.0.0.1:8087/api/cost
{"rows":50000000,"saved":25.5,"saved_fraction":0.68,"self_host_cost":12.0,"vendor_cost":37.5,"vendor_per_million":0.75}

saved_fraction is null when the vendor cost is zero.

Errors, as the server returns them

real responses
# no Content-Type: application/json
{"error":"expected Content-Type: application/json"}                                     # 415
# GET on a POST route
{"error":"method not allowed"}                                                         # 405
# Host: evil.example
{"error":"request rejected: unrecognised Host header (pass --allow-host to permit it)"} # 403
# {"rows":"x"} to /api/cost
{"error":"invalid JSON body: invalid type: string \"x\", expected u64 at line 1 column 11"} # 400