Skip to main content

relsynth

Bayesian synthetic data for whole relational databases. relsynth reads a database (Oracle, SQL Server, PostgreSQL, MySQL, MariaDB, SQLite), a cloud warehouse (Databricks SQL, Microsoft Fabric, Snowflake, BigQuery), a lakehouse table (Apache Iceberg, Delta Lake) or a folder of CSV or Parquet files. It identifies the tables, keys, links and business rules, fits one Bayesian model of the whole schema, and writes a synthetic database with the same table structure. Every primary and foreign key resolves, every rule holds, and the statistics match the source. Each statement the engine relies on is a numbered proposition with a proof (docs/proofs/relsynth-proofs.pdf) and a test that checks it.

Release 2.2 closes privacy gaps found by a roadmap audit: several privacy units in one DP run with composite keys followed and generated, a quick privacy check at the end of relsynth run by default (not in DP mode), an opt-in privacy margin for small dimension tables (segment shrinkage and a near-copy guard), privacy benchmarks for every built-in generator, and cart smoothing continuous values by default. See the changelog for the other skip conditions.

Release 2.1 adds document databases (MongoDB, Cosmos DB, DynamoDB, Couchbase, JSON), row-conditioned synthetic text with differentially private methods, a PII layer and a leakage audit, agents that draft and explain while people decide, two-way marginals (MST, AIM) in DP mode, a claim register and assurance case for privacy, legal and audit teams, and wider security scanning with fixes for every finding. See the changelog.

Release 2.0 adds an optional differential privacy mode with a per-person guarantee, privacy attacks and a report per release context, governance (signed manifests, a privacy budget ledger, policy and approvals), time series and event sequences, partitioned generation on many processes or Spark, generator plug-ins, a canonical IR 2.0 document for the data estate, adjustable engine settings with autotune, and a service with an API, a web UI and single sign-on for running relsynth for many teams. See the changelog.

pip install "relsynth[postgres]"
relsynth introspect --source "postgresql://analyst@db/sales" --source-password-env PGPASSWORD --out spec.yaml
relsynth run spec.yaml --target "sqlite:synthetic.db" --fail-under 0.98
You are Start with
A business user who wants test data or a shareable copy of a database Quick start (command line), then the user guide
A data scientist or engineer who wants it in Python Quick start (Python), then the API reference
Setting up a CI/CD job CI/CD and docs/cicd.md
Running relsynth as a service for many teams (SSO, approvals, Kubernetes, air-gapped) docs/service/
A privacy officer or data protection officer Privacy and differential privacy, docs/privacy.md, docs/dp.md, governance
Synthesising MongoDB, Cosmos DB, DynamoDB or Couchbase collections Document databases and docs/documents.md
On a privacy, legal or audit team docs/assurance/: the assurance case, regulation mapping, DPIA template and claim register
A database administrator Connectors, security, large tables
Reviewing the method Theory, docs/theory.md and the proofs

Contents


What it does

  • Whole databases. relsynth handles star and snowflake schemas, operational schemas, self-referencing hierarchies (an employee's manager, a category tree), nested facts, order headers with lines, bridges, type 2 slowly changing dimensions, unknown members, views and reference tables, time-stamped facts and free text.
  • Structure first. Synthetic tables have the source's columns and types. Primary keys are unique, foreign keys resolve, hierarchies have no cycles, and composite and unique keys hold.
  • Business rules. Rules such as amount = unit_price * quantity, ship_date >= order_date, lookups, running balances and aggregates (an order total equal to its lines) hold on every row. You can declare rules, or relsynth can find them in the data.
  • Statistics. Each table's marginals and dependence come from a Bayesian Gaussian copula over mixed types. Links between tables come from latent segments, so customers who buy more of one product kind keep doing so. Counts, participation and multiplicities follow fitted laws.
  • Bayesian. Each synthetic dataset is one draw from the posterior predictive distribution. Several datasets show the model's own uncertainty, and posterior.mode: mean gives stable test data.
  • Scale. You set the size per table: --scale 0.1 for a small test database, or --scale 10 for load tests. Facts follow the tables they hang from by the fitted rates.
  • Privacy. Rows are drawn from a fitted model; only tables you declare mode: copy are copied. Distance-to-closest-record checks compare synthetic rows with real ones, against the real data's own spacing. Text cannot reproduce rare source content, and memorisation guards are on by default. relsynth privacy attacks a release per person (membership, attribute inference, singling out, linkability) and writes a report per release context. By default relsynth run ends with a quick membership check on a proxy release and prints one privacy line (except in DP mode, or when it is skipped: see docs/privacy.md); it never changes the synthetic files.
  • Differential privacy (optional). relsynth run --epsilon 1 gives a user-level (ε, δ) guarantee for each person of the privacy unit and all their rows. The organisation sets ε; there is no default. Releases outside the organisation are refused without it.
  • Governance. Signed, hash-chained manifests of every run, a privacy budget ledger per domain, an organisation policy and human approvals before release (relsynth gov).
  • Documents. MongoDB, Cosmos DB, DynamoDB (single-table designs included), Couchbase and JSON collections keep their shape: optional fields, unions, nested arrays with their length laws, polymorphic sub-documents, maps and references between collections (relsynth docs).
  • Text. A text column is generated from its row (a billing ticket talks about billing) by a word-level model, a local language model or Private Evolution, optionally with user-level differential privacy; personal data is replaced by typed placeholders and the output is audited for leaks (relsynth text).
  • Agents. relsynth agent answers the review questions of a draft spec with evidence, explains reports in plain language and drafts contracts and policies. Agents only propose; a person decides.
  • Time. Event sequences (a customer's orders) keep their gaps, life times and calendar; meter-style series keep their seasonal profiles and autocorrelation; relsynth extend adds new days to a synthetic dataset.
  • Large tables. Facts larger than memory are fitted from statistics computed inside the database (GROUP BY, window functions) plus a uniform sample. Rows never leave the database as a whole. Generation can run in partitions on many processes or Spark, with the same output for any number of workers.
  • Pluggable and adjustable. Each table's columns come from a generator plug-in (copula by default, independent, cart, or third-party packages). 101 engine settings can be changed in a file, a preset or per table, and relsynth autotune tunes them toward your objectives.
  • Quality gate. A scorecard compares synthetic with real data, check by check, with calibrated limits. --fail-under 0.98 makes a CI job fail when quality drops.
  • Explainable. relsynth model draws the identified data model, and relsynth export-model writes the fitted Bayesian model as PDF, Markdown, JSON and a standalone Python sampler. relsynth doctor turns failed checks into spec fixes.

Install

Python 3.10 or newer. The core needs numpy, pandas, scipy, SQLAlchemy and PyYAML. Add the extra for each database you use:

pip install relsynth                       # CSV and SQLite
pip install "relsynth[postgres]"           # + PostgreSQL (psycopg 3)
pip install "relsynth[mssql]"              # + SQL Server (pyodbc; needs Microsoft ODBC Driver 17 or 18)
pip install "relsynth[mssql-pymssql]"      # + SQL Server without ODBC (pymssql)
pip install "relsynth[oracle]"             # + Oracle (python-oracledb, thin mode: no Oracle client needed)
pip install "relsynth[mysql]"              # + MySQL 8 and MariaDB (PyMySQL)
pip install "relsynth[databricks]"         # + Databricks SQL
pip install "relsynth[fabric]"             # + Microsoft Fabric Warehouse and Lakehouse SQL endpoints
pip install "relsynth[snowflake]"          # + Snowflake
pip install "relsynth[bigquery]"           # + Google BigQuery
pip install "relsynth[parquet]"            # + Parquet files (pyarrow)
pip install "relsynth[iceberg]"            # + Apache Iceberg tables (PyIceberg)
pip install "relsynth[delta]"              # + Delta Lake tables (delta-rs)
pip install "relsynth[all]"                # all of the above
pip install "relsynth[dp]"                 # differential privacy mode (OpenDP)
pip install "relsynth[gov]"                # signed manifests, registry, policy (relsynth gov)
pip install "relsynth[ir]"                 # JSON Schema check of IR documents
pip install "relsynth[service]"            # the REST API, workers and web UI (relsynth-service)
pip install "relsynth[service-otel]"       # + OpenTelemetry traces and metrics for the service
pip install "relsynth[documents]"          # document databases: MongoDB, Cosmos DB, DynamoDB (relsynth docs)
pip install "relsynth[couchbase]"          # + Couchbase
pip install "relsynth[speed]"              # optional numba kernels (same output, faster on large schemas)
pip install "relsynth[spark]"              # optional: the spark executor of the partitioned runtime (PySpark; needs Java)
pip install "relsynth[text-lm]"            # optional: local language models for text (PyTorch, transformers, peft)
pip install "relsynth[text-pii]"           # optional: Presidio, spaCy and GLiNER recognizers for personal data in text

From a checkout or a wheel file:

pip install .                   # or: pip install relsynth-2.2.0-py3-none-any.whl
relsynth version                # versions of relsynth and its main dependencies

A container image is described in the Dockerfile (all drivers and ODBC Driver 18 included):

docker build -t relsynth:2.2.0 .
docker run --rm -v "$PWD:/work" -e PGPASSWORD relsynth:2.2.0 run /work/spec.yaml --json

Quick start (command line)

1. Draft a specification from your database. relsynth reads the catalog and a sample of rows. It identifies keys and links (from declared constraints and from the data), then writes spec.yaml. The file lists every table and column with its role, every link and every rule found, and a review: list of questions only you can answer.

relsynth introspect --source "postgresql://analyst@db.internal/sales" \
                    --source-password-env PGPASSWORD --out spec.yaml
relsynth check spec.yaml --connect           # validate the spec and that every table is there
relsynth model spec.yaml --out model         # model.md: the data model with a join diagram

Sources are written as csv:folder, parquet:folder, sqlite:file.db, iceberg:..., delta:..., or a database URL (postgresql://, mssql://, oracle://, mysql://, mariadb://, databricks://, fabric://, snowflake://, bigquery://). From release 2.0, introspect writes an IR 2.0 document by default (--format v1 keeps the 1.0 spec); every command reads both. Passwords come from an environment variable (--source-password-env), or the whole URL does (--source-url-env). Never put a password on the command line.

2. Generate, write and score.

relsynth run spec.yaml --target "sqlite:synthetic.db" --scale 1 --report report.md

The run fits the model, draws a synthetic database, writes it, and compares it with the source. It prints the scorecard and writes diagnostics_bundle.json (aggregates only, no rows).

3. If checks fail, ask the doctor.

relsynth doctor diagnostics_bundle.json --spec spec.yaml --apply --out spec.fixed.yaml --report doctor.md
relsynth tune spec.yaml --rounds 3 --out spec.tuned.yaml      # run, doctor and apply, until no fix remains

4. Share the model, not the data (optional).

relsynth export-model spec.yaml --out model/        # model.pdf, model.md, model.json, replicate.py

Every command takes --json for machine-readable output and returns an exit code for scripts.

Quick start (Python)

import relsynth as rs

spec = rs.introspect("sqlite:shop.db")            # a Spec; review spec.review
spec = spec.set("synthesis.scale.default", 0.5)   # any setting, by dotted key
model = rs.fit(spec)                               # the fitted Bayesian model
data = model.sample()                              # dataset 0: a dict-like of DataFrames
report = model.evaluate(data)                      # the scorecard
print(report.passed, "/", report.total)
report.require(0.98)                               # raises QualityGateError below 98%
data.write("postgresql://loader@test-db/sales_synth")   # or data.to_csv("out/"), data.to_parquet("out/")

more = [model.sample(dataset=i) for i in range(1, 4)]   # three more posterior draws
big = model.sample(scale={"customer": 10})               # 10x customers, their facts follow

One call runs the whole pipeline, as the CLI does:

result = rs.run("spec.yaml", out="csv:synthetic/", fail_under=0.98, bundle="bundle.json")
diagnosis = rs.doctor(result)                 # causes and spec patches for any failed check
fixed = diagnosis.fixed_spec("spec.yaml")

How it works

 source DB / files ──introspect──▶ spec.yaml ──fit──▶ Bayesian model ──sample──▶ synthetic DB
        │                            ▲  (you review)        │                        │
        │                            └────── doctor ◀── scorecard ◀──── evaluate ◀───┘
        └── large facts: GROUP BY statistics + uniform sample, computed in the database
  1. Specification. A YAML file says what each table is (entity, fact, view, reference), how tables link, which rules hold, and how to synthesise each column. introspect drafts it, you review it, and it is validated strictly: every option is documented in docs/spec-reference.md, and misspelt keys are refused with a suggestion.
  2. Model.
    • Every entity row (a customer, a product) gets a latent segment, fitted by Gibbs sampling over the whole schema. The segments explain who links to whom and how often.
    • Each table's columns follow a Bayesian Gaussian copula with exact marginals, per segment or pooled.
    • Facts are counts of links between segments, with fitted rates, multiplicities, participation and seasonality.
    • Hierarchies follow a Galton–Watson process, and text follows a proper predictive law with memorisation guards.
  3. Synthesis. A dataset draws every parameter once from its posterior, then the rows, entities first and facts after. Rules are imposed by exact conditioning: rejection, a redraw instead of a deletion, or calibrated link draws.
  4. Evaluation. The scorecard checks marginals, dependence, joins, cardinalities, trees, time, text, rules and privacy, each against a limit calibrated to the sampling noise of a posterior predictive draw.

The user guide walks through each step with a worked example.

Sources and targets

Read (source) Write (target) Fit in the database Tested live
PostgreSQL yes yes (COPY) yes PostgreSQL 16.15
SQL Server yes yes (fast executemany) yes SQL Server 2022 (16.0), ODBC Driver 18
Oracle yes yes (array insert) yes Oracle Database 26ai Free (23.26)
MySQL, MariaDB yes yes (multi-row insert) yes MySQL 8.4.13, MariaDB 11.4.13
Databricks SQL yes yes (multi-row insert, or Parquet and COPY INTO) yes Spark 3.5.8 + Delta 3.2.1 stand-in (warehouses)
Microsoft Fabric yes yes (ODBC parameter arrays, or Parquet and COPY INTO) yes SQL Server 2022 stand-in (warehouses)
Snowflake yes yes (multi-row insert, or Parquet staged and COPY INTO) yes fakesnow 0.12 stand-in (warehouses)
Google BigQuery yes yes (load jobs from Parquet, or DML INSERT) yes not yet: unit tests only (warehouses)
SQLite yes yes yes SQLite 3.45
CSV folder yes (also .csv.gz) yes yes, with DuckDB over the files yes
Parquet folder yes yes yes, with DuckDB over the files yes (pyarrow 26, DuckDB 2.0)
Apache Iceberg (local, S3, ADLS; any PyIceberg catalog) yes, one snapshot per table (snapshot, as_of) yes, one commit per table, partitioned by Iceberg transforms yes, with DuckDB over the snapshot local disk; S3 (moto) and Azurite stand-ins (lakehouse)
Delta Lake (local, S3, ADLS) yes, one version per table yes, one commit per table yes, with DuckDB over the version local disk; S3 (moto) and Azurite stand-ins (lakehouse)

Writes come in four modes:

  • replace: drop and create.
  • append.
  • truncate: delete rows, children first.
  • fail: stop when a target table exists.

The target's structure comes in three forms:

  • clone: the source's DDL, with types, keys, unique constraints, indexes and identity columns.
  • infer: from the spec and the data.
  • existing: tables created beforehand.

relsynth clone-schema creates an empty copy of a schema. URL forms, drivers, schemas, authentication and type mappings per database are in docs/connectors.md.

Command line

Command What it does
relsynth introspect --source LOC --out spec.yaml Draft a spec from a database or folder
relsynth check spec.yaml [--connect] Validate a spec (alias validate); --connect also checks the source
relsynth plan spec.yaml Which tables would be fitted inside the database, and why the others are not
relsynth run spec.yaml [--target LOC] [--scale X] [--fail-under S] Fit, sample, write and score; writes the diagnostics bundle
relsynth evaluate spec.yaml --synthetic LOC Score synthetic data that is already written
relsynth verify spec.yaml [--draws 5] Model checks without ground truth (R1–R7): posterior predictive, scale rule, stability, reproducibility
relsynth doctor bundle.json [--spec spec.yaml --apply] Causes of failed checks and the spec fixes
relsynth tune spec.yaml [--rounds 3] Run, doctor and apply, repeated
relsynth autotune spec.yaml Tune engine settings toward your objectives over several seeds; constraints report for what cannot be met
relsynth settings show|explain|validate|template|reference The engine settings, their ranges and the checks each affects
relsynth run spec.yaml --epsilon E [--dp-unit TABLE[,TABLE]] [--dp-measure copula|mst|aim] Differentially private run (needs relsynth[dp]); writes a DP statement; --dp-unit takes several units separated by commas; mst/aim release two-way marginals
relsynth privacy spec.yaml Attack a release per person; privacy report per release context
relsynth extend spec.yaml --until DATE [--step day] Continue the event histories of a synthetic dataset step by step
relsynth generators list|show, relsynth compute Installed generator plug-ins; GPUs found and the device each generator would get
relsynth ir migrate|validate|convert|privacy|odcs|from-odcs|openlineage|check-contract IR 2.0 documents, data contracts (ODCS) and lineage (OpenLineage)
relsynth gov init|keys|policy|budget|approve|release|verify ... Governance: registry, keys, policy, privacy budget, approvals and releases
relsynth-service serve|worker|migrate|tenant|audit|openapi The service: REST API, web UI and job workers (needs relsynth[service])
relsynth model spec.yaml The identified data model (Markdown with a Mermaid ER diagram, and JSON)
relsynth export-model spec.yaml --out DIR The fitted Bayesian model as JSON, Markdown, PDF and runnable Python
relsynth clone-schema --source LOC --target LOC Create the source's tables empty in a target database
relsynth profile --source LOC Row, null and distinct counts computed in the source (no rows read)
relsynth ping --source LOC Test a connection
relsynth text models|pii-eval|audit|metrics Synthetic text: model licences, PII recall, leakage audit, text metrics
relsynth docs discover|synth|check Document databases: infer the schema with counts, synthesise collections, score their shape (needs relsynth[documents])
relsynth agent review|apply|explain|doctor|draft|eval Agents: review answers with evidence, a person's decisions, plain-language reports, doctor proposals, contract and policy drafts, accuracy
relsynth version Versions of relsynth and its dependencies

Shared options:

  • --json: one JSON document on stdout.
  • --log-level debug|info|warning|error.
  • --set KEY=VALUE: override any spec value, for example --set synthesis.seed=7.

The full reference with every option is in docs/cli.md.

Exit codes

Code Meaning
0 Success
1 Quality gate failed (--fail-under)
2 Invalid spec or invalid arguments
3 Connection, permission or file error
4 Engine failure (fitting or sampling)
130 Interrupted

Python API

Call Returns
rs.introspect(source, ...) Spec drafted from a source
rs.Spec.load(path), Spec.from_dict(d), .set(key, value), .with_source(loc), .with_target(loc), .errors(), .check(), .save(path), .model_report(stem) Load, edit, validate and save specs (saved specs never contain passwords)
rs.fit(spec, pushdown=None, seed=None) FittedModel
FittedModel.sample(scale=None, dataset=None) SyntheticData (a mapping of table name to DataFrame)
FittedModel.evaluate(data) / rs.evaluate(spec, data, real=None) EvaluationReport (.passed, .total, .score, .failed, .require(min), .to_markdown(), .to_json())
FittedModel.export(out_dir) / rs.export_model(spec, out_dir) Paths of the exported model files
SyntheticData.write(target), .to_csv(dir), .to_parquet(dir) Written locations
rs.run(spec, ...) RunResult (.data, .model, .report, .bundle, .errors)
rs.verify(spec, draws=5) VerifyReport (R1–R7)
rs.doctor(bundle) Diagnosis (.issues, .patches, .markdown, .fixed_spec(spec))
rs.tune(spec, rounds=3) (best spec, bundle, history)
rs.clone_schema(source, target), rs.profile(source), rs.ping(source), rs.connect(source) Database utilities
rs.Settings, Spec.with_settings(...), fit(spec, settings=...) Engine settings with editable, validated attributes
rs.privacy(spec, ...), rs.assess_quality(...) Privacy attacks per person; the 2.0 quality report
rs.extend(...) Continue a synthetic dataset's event histories
rs.Synthesizer The engine class, for full control
relsynth.documents.DocumentSynthesizer Document collections: discover, synthesise, check (docs/documents.md)
relsynth.agents Review, explain, doctor and draft agents with their backends (docs/agents.md)

Errors are typed:

  • SpecError (exit code 2).
  • SourceError (3).
  • EngineError (4).
  • QualityGateError (1).

All derive from RelsynthError, except SpecError, which is a ValueError. The full reference, with every parameter, is in docs/api.md.

CI/CD

A job that refreshes a test database every night and fails when quality drops:

# .github/workflows/synthetic-data.yml (excerpt)
- run: pip install "relsynth[postgres]==2.2.0"
- run: relsynth check spec.yaml --connect --json
- run: relsynth run spec.yaml --target-url-env TEST_DB_URL --fail-under 0.98 --json > run.json
  env:
    PGPASSWORD: ${{ secrets.PROD_READONLY_PASSWORD }}
    TEST_DB_URL: ${{ secrets.TEST_DB_URL }}
- uses: actions/upload-artifact@v4
  with: { name: diagnostics, path: diagnostics_bundle.json }

Ready-made pipelines for GitHub Actions, GitLab CI, Azure DevOps and Jenkins are in examples/ci/, explained in docs/cicd.md. The package's own CI is in .github/workflows/ci.yml: lint, security and licence scans, types, unit tests on Python 3.10–3.13 and three operating systems, integration tests against live PostgreSQL, SQL Server, Oracle, MySQL, MariaDB, TimescaleDB, S3 and Azure stand-ins, warehouse stand-ins, the statistical check suite in four shards, the benchmark regression gate, the proofs build, and a signed wheel with an SBOM (docs/development/ci.md).

Tables larger than memory

A fact table is fitted inside the database (pushed down) when synthesis.pushdown.mode is on, or auto with at least min_rows rows (default 1,000,000). The engine then reads:

  • exact GROUP BY counts over the key tuples the model uses;
  • sums of rank normal scores, computed with window functions;
  • first rows per document key, for order headers and running balances;
  • a uniform, seeded sample of sample_rows rows (default 500,000) for the column models.

Entities (dimensions) are always loaded, because each of their rows carries its own latent segment.

synthesis:
  pushdown: {mode: auto, min_rows: 1000000, sample_rows: 500000}
relsynth plan spec.yaml          # what will be pushed down, and why other tables are not

The relational part of the model is unchanged: Proposition 100 proves it, and a run with a sample of every row gives exactly the in-memory result on all four databases. The column models are an exact posterior given the sample (Proposition 104). Memory grows with the number of distinct key tuples, not with rows times columns. Details: docs/pushdown.md.

Quality: the scorecard, the doctor and model checks

  • Scorecard (run, evaluate). It holds hundreds of pass/fail checks: marginals, dependence, join distributions, cardinalities, duplicate rates, trees, time, text, rules, privacy and a discriminator AUC. Each limit is the larger of a fixed tolerance and the sampling limit of its statistic under the null that the synthetic data is a posterior predictive draw. Families of checks are Šidák-corrected, and each check reports its significance level, so the number of false failures to expect is known.
  • Doctor. It maps each failed check and each error in the diagnostics bundle to a cause and a spec patch. tune applies the patches in a loop.
  • Model checks (verify). These are checks that need no ground truth: posterior predictive checks of key statistics (R3), the scale rule (R4), structural validity (R5), segment stability across seeds (R6), and reproducibility (R7).

Privacy, differential privacy and governance

  • Measured risk (relsynth privacy, docs/privacy.md). Attacks count per person of the privacy unit, not per row: membership inference (shadow models, DOMIAS, LiRA), attribute inference against the population baseline, singling out and linkability. The report gives a verdict per release context (internal, partner, public) for a privacy officer to sign.
  • Differential privacy (relsynth run --epsilon E, relsynth[dp], docs/dp.md). Stage 1 bounds each person's contribution and releases noisy integer statistics with OpenDP's discrete Gaussian mechanism; stage 2 fits the ordinary engine to them. The guarantee is user-level (ε, δ) for one person and all their rows; δ is at most 10⁻⁵ and ε has no default. Every run writes a DP statement in the NIST SP 800-226 style. On Contoso at ε = 1 the measured membership-inference rate stayed below the DP bound.
  • Governance (relsynth gov, relsynth[gov], docs/governance/guide.md). A registry of signed (Ed25519, DSSE / in-toto) manifests in a hash-chained log; an organisation policy with ε caps; a privacy budget ledger per domain that reserves before any data is read; approvals with quorum and separation of duties; signed release packages. A run with --context partner or public is refused before reading data unless it is differentially private.
  • Service (docs/service/). The same engine behind a REST API and web UI with OIDC single sign-on, roles per tenant, encrypted artefacts, approval before download, a durable job queue, Helm and docker compose deployments and an air-gapped bundle.

Time series, generators, settings and scale

  • Time series (docs/timeseries.md). tables.<t>.sequence redraws the times of an entity's events from a point-process model (calendar in operational time, life-time copula, gamma renewal gaps), keeping keys, counts and rules. tables.<t>.series synthesises regular readings with daily, weekly and yearly profiles. relsynth extend adds the events after a dataset day by day; a stepwise run equals one long run. TimescaleDB hypertables are read and created.
  • Generator plug-ins (docs/generators.md, docs/compute.md). tables.<t>.generator picks the model of a table's columns; the engine keeps keys, links, segments, counts and rules whatever the generator. Third-party generators install through the relsynth.generators entry point; compute.yaml presets control GPUs.
  • Engine settings and autotune (docs/settings.md, docs/autotune.md). 101 settings with type, range and the checks they affect, from defaults, a settings file, presets (fast, thorough), the spec or --set. Adding the settings changed no output: their defaults reproduce the earlier engine byte for byte. The small-dimension settings of release 2.2 (marginals.segment_prior_rows, privacy.near_copy) are off by default and keep that output. relsynth autotune separates systematic failures from noise over several seeds and changes settings until your objectives hold, or says why they cannot.
  • Partitioned generation (docs/runtime.md). synthesis.runtime runs fact rows in partitions on the local, process or spark executor. Each partition draws from a Philox stream keyed by seed, dataset, fact and partition, so the output is the same for 1, 8 or 64 workers and for Spark (Prop. 950).
  • IR 2.0 (docs/ir-guide.md). One versioned document describes a data estate: entities with shapes (record, document, node, edge, event), nested arrays, keys, references, hierarchies, time and versioning, partitions, rules and the privacy unit. 1.0 specs convert without loss (same synthetic data); ODCS v3 data contracts and OpenLineage are exported and checked.

Document databases

relsynth docs (docs/documents.md, relsynth[documents]) synthesises document collections from MongoDB, Cosmos DB for MongoDB, Cosmos DB for NoSQL, DynamoDB, Couchbase and JSON files.

relsynth docs discover jsonl:data/shop --out shop.ir.json          # the schema with counts, as IR 2.0
relsynth docs synth source.yaml --to jsonl:synthetic/ --report report.json
relsynth docs check jsonl:data/shop jsonl:synthetic/
  • Inference with counts. Types, presence, array lengths and field sets per path; maps keyed by identifiers, variants with a discriminator, length fields, set arrays, references (by _id or a natural key) and sequences are found in the data.
  • Through the engine. Collections are shredded into tables (one per array, map and optional sub-document, with tag and length columns), synthesised by the relational engine and nested again; nest(shred(D)) = D exactly (Prop. 1401).
  • Valid documents. Every synthetic document validates against the inferred schema and references resolve; what had to be repaired is counted per kind and path.
  • Shape metrics (presence, type mix, array lengths, field sets, depth, size) with limits calibrated on real-versus-real splits.
  • DynamoDB single-table designs: item types are split by a discriminator and keys such as CUSTOMER#{customer_id} are rebuilt from learned templates, unique and with the same access patterns.
  • In MongoDB, exact counts come from one $group pipeline and the rest from a $sample.

Synthetic text

A text column (type: text) is generated from its row: condition_on: [category, priority] makes a billing ticket talk about billing. Four methods, chosen per column in text.method:

Method Runs on Privacy
ngram (default, the 1.0 model) CPU, no weights memorisation guards per row (not DP)
ngram + dp CPU, no weights, air-gapped user-level differential privacy (DP n-gram release)
lm (+ dp) a local model folder (relsynth[text-lm]), GPU optional not DP; with dp, user-level DP-GD fine-tuning
pe a public generator (local model or public corpus) user-level DP by Private Evolution
body:
  type: text
  text:
    condition_on: [category, priority]
    method: ngram
    pii: {recognizers: [regex]}           # typed placeholders before training, surrogates after
    dp: {epsilon: 2.0, delta: 1.0e-6, unit_column: customer_id}

relsynth ships no model weights; relsynth text models lists models with their licences. relsynth text pii-eval measures the recall of the PII recognizers, and relsynth text audit inserts canaries, measures their exposure against the DP bound and searches the output for copies of training texts. See docs/text.md.

Agents: drafting and explaining, never deciding

relsynth agent (docs/agents.md) saves people time on the checking that comes before a decision, and makes no decision itself.

  • review answers the review: items of an introspected draft (keys, links, lookups, rules, ASK questions) with evidence measured on every row, and proposes the change each answer implies. relsynth agent apply --by <person> applies the answers that person accepts.
  • explain words a quality, privacy or scorecard report in plain language; doctor turns doctor findings into proposals (privacy settings become advice for the privacy officer); draft contract and draft policy write an ODCS contract and an organisation policy with every budget left empty.
  • Backends. Deterministic rules by default; any OpenAI-compatible model server on the same machine (Ollama, vLLM, llama.cpp) for questions that need the meaning of a name. A remote server must be allowed explicitly, use https, and gets aggregates only.
  • Safeguards. Agents never see rows: they get names and whole-column aggregates, and single values only in the values scope when they occur at least 10 times. Untrusted text is marked as data; verdicts, parents and changes come from closed sets; a confirmation the evidence contradicts becomes a rejection; numbers in model text must occur in the evidence. In the service an agent account can read and propose only, and in the governance registry an agent key cannot approve. A prompt-injection suite runs 20 payloads against a model that obeys every instruction.
  • Accuracy. With the catalog hidden, the rules backend's answers about keys and links matched the ground truth on 122 of 124 answered items on Chinook, AdventureWorks DW, Contoso and bi/COREP; the CI job agents gates it and measures a small local model.

Security

  • Credentials. Passwords are never accepted on the command line; they come from password_env or url_env. Passwords are masked in every message, log, saved spec, diagnostics bundle and exported model. The masking covers URL passwords, password=/token= query parameters and ODBC PWD=.
  • SQL. Every SQL statement is built with SQLAlchemy Core, with quoted identifiers and bound values. Table and column names cannot inject SQL; tests use hostile names on every database.
  • Specs. A spec is YAML read with a safe loader that also refuses aliases, so an alias bomb fails. Rule expressions run in a sandboxed evaluator: no attribute access, calls only to a fixed list of functions, and size and depth limits. Regular expressions with catastrophic backtracking are refused.
  • Files. Table names cannot leave the target folder (.., separators, absolute paths and symlinks are refused).
  • Data. Rows never leave the source database for pushed-down facts. Bundles and profiles hold aggregates only, and profile --top must be asked for explicitly. Copy guards run by default; they are not a privacy check (docs/privacy.md measures privacy). The quick privacy check of relsynth run is a smoke test, not an assessment.
  • Supply chain. The code is scanned with bandit and ruff's security rules, and dependencies with pip-audit, in CI.
  • Code scanning. Every pull request also runs CodeQL (security-extended and security-and-quality suites), Semgrep with project rules, gitleaks, zizmor for the workflows and GitHub dependency review; Dependabot watches dependencies and the digest-pinned base images (docs/development/ci.md).

Details and the threat model: docs/security.md.

Performance

  • Fits use exact vectorised kernels, with numba kernels as an option (relsynth[speed]). Sampling is linear in the output size.
  • Writes use each database's bulk path: COPY on PostgreSQL, fast executemany on SQL Server, array binds on Oracle.
  • Large facts are pushed down (see above). On AdventureWorks DW (27 tables, 1.05 million rows), pushing the ten eligible facts down cut peak memory from 2.1 GiB to 1.6 GiB and run time from 803 s to 668 s on a 4-core machine.

Tuning knobs and measurements: docs/pushdown.md.

Validation

Release 2.2. The check suite adds C1700–C1706 (privacy units), C1720–C1723 (small dimensions) and C1740–C1741 (quick privacy check): 162 science tests in four CI shards, next to about 990 unit, end-to-end, security and live-server tests. The benchmark's privacy suite now attacks the copula, cart and independent generators on ACS and Berka. Without DP, the default (copula) output is byte-identical to 2.1.0; cart output and DP-mode output change for the same seed, as listed in the changelog.

Release 2.1. The check suite adds C1300–C1306 (DP two-way marginals), C1400–C1405 (document databases), C1500–C1507 (synthetic text) and C1600–C1604 (agents): 141 science tests in four CI shards, next to about 930 unit, end-to-end, security and live-server integration tests. New CI jobs measure the agents (122 of 124 review answers correct on four real databases), the document pipeline against a MongoDB 7 server and real dumps, and DP two-way marginals against smartnoise-synth on ACS (dp-eval). Draws for the same seed are unchanged with default settings.

Release 2.0. The statistical check suite now has C00–C82 plus the 2.0 checks C600–C606 (privacy attacks), C800–C803 (governance), C900–C906 (differential privacy) and C1200–C1206 (time series), with the generator propositions 700–706 tested in tests/unit/test_generators.py: 113 science tests, all run in CI on every pull request in four shards, next to about 800 unit, end-to-end, security and live-server integration tests. A benchmark harness (bench/) reruns the real databases (bi/COREP, Chinook, AdventureWorks DW, Contoso, plus Berka, ACS PUMS and a doubled Chinook) on every change and flags drift against a five-seed baseline. Draws for the same seed change on databases with link tables, because degree laws are now the default (synthesis.facts.link_degree: segment restores the 1.0 draws); the changelog lists every change.

relsynth 1.0.0 was checked at three levels. Every number below comes from the final code.

Fake data with known ground truth. The statistical check suite (pytest -m science) generates eleven databases from known models, from one mixed-type table to an enterprise schema with nested facts, views, trees and order headers. It then checks that each numbered proposition holds: posterior recovery and calibration, identification of keys and rules, rules on every row, privacy guards, reproducibility. All 79 checks (C00–C78, more than 500 assertions) pass.

Four real databases, each from an unedited introspect draft, fitted in memory and with every eligible fact pushed down:

Database Rows Scorecard in memory Scorecard pushdown Domain checks (rules and invariants)
EBA COREP reporting 68 k 177/178 178/178 B1–B8 equal in both modes; B6 per-cell KS 0.10 and 0.13
Chinook 15.6 k 144/146 144/146
Contoso V2 100k (Parquet) 753 k 253/253 253/253 T1–T17 within 0.015 between modes
AdventureWorks DW 1.05 M 1229/1286 1237/1285 G1–G13 equal in both modes, except two counts within 2%

In both modes, every key resolves, every unique key but one holds (an AdventureWorks alternate key with a start date), and every declared or found rule holds on every row. The remaining failures, database by database, are described in docs/pushdown.md.

Software tests (pytest): 136 unit, end-to-end CLI and security tests, and 24 integration tests run live against PostgreSQL 16.15, SQL Server 2022 (16.0) and Oracle Database 26ai Free (23.26). On every server, the same seed gives the same synthetic database as SQLite, value for value. The wheel was installed and tested in clean environments on Python 3.11, 3.12 and 3.13. Python 3.10 is supported by the code and the CI matrix, but it was not available on the build machine.

Theory: propositions and proofs

The method is described in two papers shipped with the package:

  • docs/proofs/algorithms.pdf: the layer 1 algorithms, with complexity and proofs. It covers the Bayesian Gaussian copula, latent segments from in-database sufficient statistics, the merge step and differential privacy on summaries.
  • docs/proofs/relsynth-proofs.pdf: 189 propositions with proofs, each tied to a numbered check. They are grouped as follows:
Area Propositions (examples)
One table, mixed types Marginal preservation; the copula sampler targets the posterior; rank likelihood with parameter expansion; rare columns kept independent
Links between tables Identifiability of segments; block-rate posterior; splitting and degree correction; the scale rule; chained segments compose; nested refinement
Counts and structure Spike-and-slab multiplicities; structural zeros; sparse Dirichlet inclusion; mandatory participation; learned structural weights; Pólya-urn marginal
Hierarchies, time and text Galton–Watson generation sizes; hierarchies of a given size; seasonality by multinomial thinning; proper predictive text with memorisation guards
Rules and keys Rules by rejection; three-valued rules agree with the database; computed columns are exact; unique keys by exact conditioning; order headers (lossless split); running balances
Bayesian synthesis One parameter draw per dataset; posterior predictive draws; soft rules; group effects; SCD type 2; exported draw m is dataset m
Identification Significance of discovered dependencies; inclusion by chance; permutation test of a forest
Evaluation Calibrated limits under the posterior predictive null; Šidák over families; distances with an atom at zero
In-database fitting (v1.0) 100 sufficiency of the in-database statistics; 101 agreement with in-memory fitting; 102 Acklam's quantile bound; 103 hash sampling is Bernoulli; 104 the sample posterior is exact; 105 eligibility
IR, generators and quality (v2.0) 106 loss-free 1.0 conversion; 107–108 privacy-unit tracing; 109–113 calibrated quality report; 700–706 the skeleton is kept whatever the generator
Privacy and governance (v2.0) Per-person attack metrics; 800–803 the budget ledger bounds the domain's privacy loss, reserve before reading, tamper evidence; 900–906 discrete Gaussian, stable contribution bounding, exact partition selection, two-stage DP
DP two-way marginals (v2.1) 1300–1306 report noisy max; sensitivity of scores and pairs; the selections spend within the plan; the forest estimate and its sampler; compression; error falls with the budget
Documents (v2.1) 1400–1405 the inferred schema admits its source; shredding is invertible; conformance; calibrated shape limits; key templates; references and lengths
Time and scale (v2.0) 1200–1206 time change, gamma renewal bridge, sequence posterior, calibrated limits, incremental runs; degree laws of link tables; 950–954 worker independence, partitions keep the law, keys across partitions, drift tests
Synthetic text (v2.1) 1500–1507 canary exposure under DP; DP n-gram release; user-level DP-GD; Private Evolution votes; expected exposure; near-duplicate search; PII placeholders; consistency with the row
Agents (v2.1) 1600–1604 data minimisation, containment of any model output, evidence first, grounded wording, no authority without a person
Privacy units (v2.2) 1700–1704 ownership is the union over all paths, composite links included; real composite keys in the DP seed; several units with one account each; governed multi-unit runs
Small dimensions (v2.2) 1720–1723 segment shrinkage toward the table's marginal; the near-copy guard only redraws rows and keeps keys and rules
Quick privacy check (v2.2) 1740–1741 false alarms of the quick check are bounded under no membership signal; the check leaves the release unchanged

docs/theory.md gives a readable summary of the model and of the six v1.0 propositions, with the proofs in full.

Testing the package

pip install -e ".[dev]"
pytest                                    # unit, end-to-end and security tests (SQLite, CSV, Parquet)
docker compose -f docker-compose.test.yml up -d       # PostgreSQL, SQL Server, Oracle, MySQL, MariaDB
export RELSYNTH_TEST_PG_URL=postgresql://relsynth:RelSynthTest1@localhost/relsynth
export RELSYNTH_TEST_MSSQL_URL="mssql://sa:RelSynth_Test1!@localhost:1433/master?TrustServerCertificate=yes&driver=ODBC+Driver+18+for+SQL+Server"
export RELSYNTH_TEST_ORACLE_URL="oracle://relsynth:RelSynthTest1@localhost:1521/?service_name=FREEPDB1"
export RELSYNTH_TEST_MYSQL_URL=mysql://root:RelSynthTest1@localhost:3306/relsynth
export RELSYNTH_TEST_MARIADB_URL=mariadb://root:RelSynthTest1@localhost:3307/relsynth
export RELSYNTH_TEST_MONGO_URL=mongodb://localhost:27017   # a MongoDB 7 server: pytest -m mongodb
pytest tests/integration                  # the same checks against live servers
pytest -m science                         # the statistical check suite: C00–C82 and the 2.x checks (about an hour and a half; CI runs it in four shards)
pytest --cov=relsynth --cov-report=term   # coverage
ruff check src tests && bandit -c pyproject.toml -r src && pip-audit

What each test module covers is in docs/testing.md.

Limitations

  • The scorecard on real data compares with the source, which is itself only one draw. A check can fail by chance, and each check's level is reported (alpha).
  • Rules that hold on every source row but are not declared or found are reproduced statistically, not exactly. Declare them in the spec.
  • Differential privacy mode releases one-way statistics, degrees and one correlation matrix per table, so its utility is nearly flat in ε (0.80–0.91 of the checks pass from ε = 0.5 to 8 on Chinook, Contoso and AdventureWorks). It has one privacy unit, no in-database pushdown, and placeholders for pii, text and binary columns (docs/dp.md). measure: mst or aim release privately chosen two-way marginals instead: on one table the two-way error drops by about a quarter and falls with ε up to about ε = 4, while on the multi-table databases the share of checks passing stays within the copula's intervals (docs/dp.md sec. 7).
  • Graph stores are planned; the IR already describes graphs. Data lakes on S3 and ADLS work through Iceberg and Delta.
  • In document collections, a value deep in a document depends on its parent element only through the engine's latent segments: an item's tags keep about half of their dependence on the item's name in the sample data (spike). The Cassandra and Gremlin APIs of Cosmos DB are not supported.
  • Free text from the default word-level model keeps vocabulary, phrases and the link to the row, not meaning; a local language model (text.method: lm) gives fluent text. Text columns are still empty in DP mode (--dp); use text.dp on the column (its guarantee covers that column only).
  • BigQuery is tested with unit tests only; the other warehouses against stand-ins, not the live services.

Documentation map

Document Contents
docs/user-guide.md The workflow step by step, with a worked example
docs/spec-reference.md Every specification option, with recipes (template)
docs/settings.md Engine settings: settings files, presets, per-table overrides, editable attributes (reference)
docs/text.md Synthetic text: methods, DP, the PII layer, the leakage audit, model licences
docs/autotune.md relsynth autotune: objectives, the search, the history and the constraints report
docs/ir-guide.md The IR 2.0 document: migration from 1.0 specs, documents, graphs, streams, the privacy unit, ODCS and OpenLineage, deprecation policy
docs/ir-reference.md Every IR field (generated from the model; JSON Schema in src/relsynth/ir/schema/)
docs/adr/ Architecture decision records
docs/cli.md Every command and option
docs/api.md Every public class and function
docs/connectors.md Databases and files: URLs, drivers, schemas, write modes, types
docs/pushdown.md Fitting inside the database; performance
docs/connector-sdk.md Writing a connector for a new database or warehouse
docs/warehouses.md Databricks SQL, Microsoft Fabric, Snowflake and BigQuery: sign-in, cost guards, loading
docs/lakehouse.md Apache Iceberg and Delta Lake on disk, S3 and ADLS; time travel; data contracts
docs/documents.md Document databases: MongoDB, Cosmos DB, DynamoDB single-table designs, Couchbase; inference, shredding, shape metrics
docs/runtime.md Partitioned generation: executors, streams, partition modes, drift statistics
docs/timeseries.md Event sequences, regular series, incremental runs, TimescaleDB
docs/generators.md Generator plug-ins and how to write one (compute presets)
docs/privacy.md Privacy attacks per person and the report per release context
docs/governance/guide.md Registry, signed manifests, policy, budget ledger, approvals (design)
docs/service/ The service: API, UI, SSO, tenancy, deployment, operations, security
docs/agents.md Agents: review answers, report explanations, doctor proposals, contract and policy drafts; safeguards and accuracy
docs/metrics.md The quality report 2.0 and its metrics
docs/profiling.md Where 1.0 spends time and memory, and which changes that justifies
docs/cicd.md Pipelines, quality gates, secrets, containers
docs/security.md Threat model and protections
docs/dp.md Differential privacy mode: the guarantee, the two stages, MST/AIM two-way marginals, utility against ε
docs/theory.md The model in brief and the v1.0 propositions with proofs
docs/proofs/ The full proofs (PDF and LaTeX source)
docs/testing.md The test suite
CHANGELOG.md Versions
docs/development/ For maintainers: CI and security scanning, the release checklist, supply chain and release verification
docs/datasets.md Which datasets may be used, committed and where
CONTRIBUTING.md How to contribute: workflow, commits, sign-off, tests
SECURITY.md Reporting a vulnerability
docs/assurance/ For privacy, legal and audit teams: the assurance case, the regulation mapping (GDPR and EDPB 02/2026, AI Act, HIPAA, NIST, ISO), a DPIA template, release guidance and the claim register

Licence

relsynth is licensed under the Apache License 2.0. Third-party material and its licences are listed in NOTICE. Contributions are accepted under the same licence with a Developer Certificate of Origin sign-off.

Metadata

Release files for relsynth 2.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for relsynth 2.2.0
File Size Uploaded Provenance Actions
relsynth-2.2.0.tar.gz 946.9 kB With provenance Details for relsynth-2.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for relsynth 2.2.0
File Interpreter ABI Platform Actions
relsynth-2.2.0-py3-none-any.whl Python 3 none any Details for relsynth-2.2.0-py3-none-any.whl

Total release size: 2.0 MB

Release files / relsynth-2.2.0.tar.gz

Download URL relsynth-2.2.0.tar.gz
Size 946.9 kB
Tags Source
SHA-256 checksum
How to use checksums
e240b154ef0ff88a0ccc19bbf065481990bc37361810bd1b0b243a6bef1a4dab
BLAKE2b-256 checksum
How to use checksums
866c498ea9532835f0f829592c1d051591594b300b7ae5b322a19bf083077450
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Release files / relsynth-2.2.0-py3-none-any.whl

Download URL relsynth-2.2.0-py3-none-any.whl
Size 1.0 MB
Tags Python 3
SHA-256 checksum
How to use checksums
27fc8e711d0abdf78a85d9ab425c101d067e2727463a31886076db6802d820e9
BLAKE2b-256 checksum
How to use checksums
0f574e68b6a39ac10ee0dd5eb464f05f027635a33981c828478e1b5cd6ca1b74
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Security for relsynth 2.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for relsynth-2.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page