datamimic README

README проекта с github.com/rapiddweller/datamimic. Одним файлом markdown: README.md.

DATAMIMIC

Community Edition

Test data must agree with itself.

Docs | Agent plugin | Case studies | Discussions | Enterprise Platform

CI Coverage Maintainability Python 3.11 to 3.14 License: MIT MCP Ready

Independent random values do not agree with each other: an order points to a customer that does not exist, a postal code does not belong to its city, and the next run gives different rows.

DATAMIMIC Community Edition (CE) is an open-source Python library and command line tool, made by rapiddweller and released under the MIT license, that generates connected test data from one XML model. Records reference each other, domain values come from data files, and the same seed gives the same rows again. CE can also replace personal data in an existing export.

Pre-release. CE 5.0 is not on PyPI yet. PyPI has 4.3.0, which does not have the commands on this page. Until 5.0.0 is released, install from the GitHub branch development as shown below.

Quick start: command line

You need Python 3.11 to 3.14.

python3.11 -m venv .venv && source .venv/bin/activate
python -m pip install "datamimic-ce @ git+https://github.com/rapiddweller/datamimic@development"

Make a project directory shop with these two files.

shop/datamimic.xml:

<setup rngSeed="7">
    <generate name="customers" count="25" target="CSV">
        <variable name="person" entity="Person" dataset="DE"/>
        <variable name="address" entity="Address" dataset="DE"/>
        <key name="id" generator="IncrementGenerator"/>
        <key name="name" script="person.name"/>
        <key name="postal_code" script="address.postal_code"/>
        <key name="city" script="address.city"/>
        <generate name="orders" count="2" target="CSV">
            <key name="customer_id" script="parent.id"/>
            <key name="line_no" generator="IncrementGenerator"/>
            <key name="amount" type="int" min="5" max="500"/>
        </generate>
    </generate>
</setup>
shop/acceptance/build.json (the rules that Build checks)
{
  "version": "5.0",
  "expectations": [
    {"kind": "exact_count", "subject": {"kind": "product", "product": "customers"}, "count": 25},
    {"kind": "exact_count", "subject": {"kind": "product", "product": "orders"}, "count": 50},
    {"kind": "unique", "subject": {"kind": "product", "product": "customers"}, "field": "id"},
    {"kind": "foreign_key",
     "child": {"subject": {"kind": "product", "product": "orders"}, "field": "customer_id"},
     "parent": {"subject": {"kind": "product", "product": "customers"}, "field": "id"}}
  ]
}

Check the project, then run it:

datamimic authoring build shop     # prints JSON; "outcome": "ready" and exit code 0
datamimic run shop/datamimic.xml   # writes shop/output/<task id>/customers.csv and orders.csv

A run generates the data. Build is the step that checks it. Thus use Build as the gate, and use a run for the full output.

Build answers ready (exit code 0), ready_with_gaps (exit code 3: it passed, but coverage names what it did not check, such as a product without expectation or a project without rngSeed; fix each gap before you report success) or rejected (exit code 1). To start from a project that Build proves as ready, run datamimic authoring init shop; it writes datamimic.xml and acceptance/build.json and never overwrites a file.

What you get

customers.csv:

id|name|postal_code|city
1|Marion Abraham|36419|Schleid
2|Peter Bayer|24161|Levensau
3|Ludmila Jehle|56368|Katzenelnbogen

orders.csv:

customer_id|line_no|amount
1|1|237
1|2|207
2|1|373
Build outcome Exit code Meaning
ready 0 All declared expectations passed on a complete, bounded capture.
ready_with_gaps 3 Passed, but coverage names what Build did not check. Fix each gap before you report success.
rejected 1 Read the first entry in diagnostics, correct the project, build again.

Why not only Faker?

Faker gives single values, and CE uses Faker as a dependency. CE adds the model around the values.

You need With Faker With CE
Records that reference each other You write the code that keeps the keys correct. A nested <generate> copies the key of its parent. Build checks the reference with a foreign_key expectation.
The same data again You call Faker.seed() or seed_instance() in your code. The seed is in the model: <setup rngSeed="7">. Build replays the seeded run, and CI compares seeded output on Linux and Windows.
A check that the data follows your rules Faker has no check. You write tests. acceptance/build.json holds the rules. Build gives ready or rejected.

Use Faker for a few values in a unit test. Use CE when the data has a structure that must be correct each time.

Quick start: coding agents

The plugin gives the agent two skills and a local MCP server. You need uv for the MCP server.

Claude Code:

claude plugin marketplace add https://github.com/rapiddweller/datamimic.git
claude plugin install datamimic@datamimic

Codex:

codex plugin marketplace add https://github.com/rapiddweller/datamimic.git
codex plugin add datamimic@datamimic

Start a new session in your project and ask:

Use DATAMIMIC. In ./shop make a project that generates 25 customers
(id, name, email) as CSV with seed 7. Build until the outcome is ready,
then run it. Show me the model and the Build evidence.

What the agent does (from a recorded session with Claude Code, 2026-11-15; shortened, file reads left out):

datamimic_reference      topic=assembly name=starter   -> project layout
datamimic_capabilities                                 -> entities, generators, exporters
datamimic_capability     domain=entity name=Person     -> fields of Person
Write                    datamimic.xml, acceptance/build.json
datamimic_build          project=./shop                -> outcome: ready
datamimic_run_project    project=./shop                -> completed, exit 0, 1.4 s
                                                          output/<id>/customers_csv.csv, 25 rows

In an empty project the agent can start with datamimic_init, which writes the starter datamimic.xml and acceptance/build.json and never overwrites a file. Like every project tool, it takes an absolute path, for example datamimic_init project=/home/me/shop.

The first start of the MCP server downloads CE from GitHub and takes about 7 s when uv has the other packages cached; with an empty cache expect minutes. Later starts take about 1 s. We measured these on one machine. If the server does not connect, the skills still work with the command line. To use the MCP server without the plugin, install python -m pip install "datamimic-ce[mcp] @ git+https://github.com/rapiddweller/datamimic@development".

What the agent can and cannot do:

More: agent plugin guide, MCP guide, the consumer skill and the model review format.

Engineering you can check

What can CE do?

<generate name="readings" start="2026-01-01T00:00:00+00:00"
          end="2026-01-02T00:00:00+00:00" interval="PT1H" target="CSV">
    <key name="timestamp" script="ts.now.isoformat()"/>
    <key name="value" script="20 - 10 * math.cos(ts.now.hour * math.pi / 12)"/>
</generate>
Domain Services
Healthcare Patient, Doctor, Hospital, MedicalDevice, MedicalProcedure
Finance Bank, BankAccount, CreditCard, Transaction
Insurance InsuranceCompany, InsuranceProduct, InsurancePolicy, InsuranceCoverage
E-commerce Order, Product
Public sector AdministrationOffice, EducationalInstitution, PoliceOfficer
Demographics Person (locale packs; see the domain docs), Address, City, Country
Common Company

Is the output reproducible?

Yes, under these conditions: the same CE version, the same project files and the same seed, on the tested platforms. Without a seed the output is not repeatable.

How do I pseudonymize an export?

Name the fields and give each one a generated replacement. This model is the tested scenario s28_pseudonymize_source. It replaces the personal data in a pipe-separated export (customer_id|first_name|last_name|email|iban|birth_date):

<setup rngSeed="42">
  <generate name="customers" source="data/entity/customers.ent.csv" target="CSV" distribution="ordered">
    <!-- rngSeed makes seeded runs produce the same pseudonyms; remove it for a new
         mapping per run. distribution="ordered" keeps source row N mapped to the
         same pseudonym. -->
    <variable name="p"   entity="Person"      dataset="DE" />
    <variable name="acc" entity="BankAccount" dataset="DE" />

    <key name="customer_id" script="customer_id" />
    <key name="first_name" script="p.given_name" />
    <key name="last_name"  script="p.family_name" />
    <key name="email"      script="p.email" />
    <key name="iban"       script="acc.iban" />
    <key name="birth_date" script="p.birthdate" />
  </generate>
</setup>

Use a controlled export or staging input, not a live production source. Key management and the converter list are in the pseudonymization guide.

Command reference

Authoring commands print JSON and accept a file or - for standard input.

Command MCP tool Use
datamimic authoring init <project> datamimic_init Write a starter project that Build proves as ready
datamimic authoring build <project> datamimic_build Check a project against acceptance/build.json
datamimic authoring run-project <project> datamimic_run_project Build, then run for real data
datamimic run <datamimic.xml> datamimic_run_project_unverified (stdio only, needs confirmation) Run a model without Build
datamimic authoring lint <file> datamimic_lint Check one XML file
datamimic authoring dry-run <file> datamimic_dry_run Run one XML file with a bounded capture
datamimic authoring run <file> datamimic_run Run one XML file with limits
datamimic authoring version datamimic_version Show the CE version and contracts
datamimic authoring schema [--name <name>] datamimic_schema Show a contract schema
datamimic authoring capabilities datamimic_capabilities List the DSL vocabulary
datamimic authoring capability --domain element --name generate datamimic_capability Show one element
datamimic authoring reference --topic assembly --name starter datamimic_reference Read focused guidance
datamimic authoring compile - / decompile <file> datamimic_compile / datamimic_decompile Convert between DM JSON and XML
datamimic init, demo list, demo create, info, version none Project and demo helpers

Exit codes: 0 for success, 1 for a rejected result, 2 for a usage error, 3 for a Build with gaps.

Python API

import random
from datamimic_ce.domains.healthcare.services import PatientService

patient = PatientService(rng=random.Random(42)).generate()
print(patient.full_name, patient.age, patient.conditions)  # the same values for seed 42
from datamimic_ce.domains.facade import generate_domain

response = generate_domain({
    "domain": "person", "version": "v1", "count": 1,
    "seed": "ci-42", "locale": "en_US", "clock": "2026-01-01T00:00:00Z",
})
print(response["determinism_proof"]["content_hash"])

The content hash is on the results of generate_domain (person, address, patient, doctor). Files from datamimic run have no such hash.

Where can CE support a compliance program?

DATAMIMIC provides test data and run evidence that can support compliance work. It does not replace your data protection officer, your security officer or your auditor. The compliance pointers show where CE output fits for DORA, ISO/IEC 27701, HIPAA, GDPR and PCI DSS 4.0.1. They are not attestations.

Where DATAMIMIC is used

These projects used DATAMIMIC with the Enterprise Platform and services from rapiddweller, and the case studies describe the Enterprise Platform. The model language of these projects is the XML DSL that you use in CE.

Sector What was done, in the words of the case study
Payments "Records anonymised inline at millions per hour" in Kafka streams, for records with "140-180 columns". ACI Worldwide
Banking Test data across Oracle, MongoDB and Kafka. Lead time: "Before 20-28 days After 6-12 hours". Tier-1 European bank
Public sector, statutory insurance After a public tender, "DATAMIMIC replaced these legacy tools with model-driven test-data generation integrated into the client's CI/CD pipeline". Public-sector body in German statutory accident insurance
Education "Replaced the ~10,000-line custom generator with about 1,200 lines of DATAMIMIC models" for about 30 PostgreSQL schemas with more than 200 tables. School management system

What is the difference between DATAMIMIC CE and the Enterprise Platform?

DATAMIMIC has two editions. Both use the same XML model language.

Community Edition (this repository) is a Python library and a command line tool. Your team installs it, keeps the project files, and runs it on a workstation or in CI. It has no web UI, no source scanner, no scheduler, no access control, no Kafka or RabbitMQ target and no message template engine.

The DATAMIMIC Enterprise Platform is a commercial, self-managed product for teams. It runs on a separate engine, the Enterprise Core. It adds a web UI, shared projects with access control, a Workbench that scans data sources, tasks with a scheduler, and IDE extensions for VS Code and JetBrains IDEs. (Release notes)

What a team gets from the Platform, and where the proof is:

The two editions use different engines. Do not expect the same output bytes from CE and from the Platform for the same model and seed. The determinism evidence in this repository is for CE only.

The agent plugin works with both: with a local CE project, or with a project on a connected Platform.

Comparison: https://datamimic.io

Get help and contribute

License

MIT. See LICENSE. The DATAMIMIC Enterprise Platform is a separate commercial product of rapiddweller. Contact rapiddweller.

The DATAMIMIC name and logo are trademarks of rapiddweller and are not covered by the MIT license.

datamimic (rapiddweller/datamimic)

Ищем в базе…

Что это такое?DATAMIMIC CE — это Python-движок с открытым исходным кодом под лицензией MIT, который создаёт детерминированные синтетические тестовые данные по декларативным моделям — исходные данные для этого не нужны, — а также умеет псевдонимизировать реальные выгрузки из staging- или QA-сред. Это бесплатное ядро коммерческой платформы DATAMIMIC Enterprise Platform, рассчитанное на регулируемые отрасли.
Это библиотека, CLI или целая платформа?Это Python-пакет, работающий и как CLI, и как библиотека: Python-API, XML-пайплайны и командная строка datamimic, плюс опциональный MCP-адаптер, чтобы им могли управлять ИИ-агенты. Enterprise Platform поверх добавляет governance, дашборды и выполнение на нескольких системах, но CE полностью самодостаточен и сам по себе.
Как пройти путь от установки до первого сгенерированного набора данных?Установите пакет через pip install datamimic-ce, создайте файл модели (команда datamimic scaffold model.dm.json --format json сгенерирует заготовку), затем запустите его командой datamimic run для выбранного целевого хранилища. Внутри checkout-копии используйте обёртку .venv/bin/datamimic, чтобы устаревшая глобальная установка не затмила вашу схему или команды.
Нужна ли база данных или какие-то исходные данные, чтобы хоть что-то сгенерировать?Нет — генерация полностью управляется моделью и не требует исходных данных вообще; достаточно среды Python. Подключение к PostgreSQL, MySQL, Oracle, MS SQL, SQLite или MongoDB, либо запись в файлы CSV, JSON, XML или XLSX — это просто ваш выбор целевого вывода.
Есть ли что-то, чего бесплатная версия не умеет?Создание моделей через scaffolded JSON покрывает файловые и in-memory цели с одним уровнем вложенных дочерних продуктов; цели-базы данных или MongoDB и более глубокая вложенность без верифицированного сертификата уходят на устаревший путь с сырым XML. Сканер PII, пайплайны Kafka, отраслевые шаблоны сообщений и масштаб в миллиарды записей — только в Enterprise.
Это делали для регулируемых отраслей вроде банков и здравоохранения?Да — в комплекте есть доменные модели для Finance, Healthcare и Demographics, и продукт развёрнут в регулируемых банковских средах ЕС для тестовых данных в пайплайнах Oracle, MongoDB и Kafka. Аудиторские доказательства для GDPR и PCI DSS — это то, где подставляется Enterprise-версия.
Можно ли скормить ему реальные данные из staging, содержащие персональные данные (PII)?Да — для этого есть режим псевдонимизации: PII-поля заменяются преобразованиями с фиксированным seed (повторяемыми) или уникальными для запуска (без seed), которые вручную описываются в XML-пайплайне. А автоматический сканер PII с оценкой по вероятности, который сам предлагает маппинг полей, — это функция Enterprise Platform, не входящая в CE.
Всё это бесплатно? И где начинается платная часть?Community Edition из этого репозитория распространяется под лицензией MIT и бесплатна для самостоятельного использования. Enterprise Platform — отдельный коммерческий продукт: тот же DSL, но независимо оптимизированный движок с governance, аудитом и пропускной способностью корпоративного масштаба.
Какие данные он умеет генерировать?Поставляются доменные модели для Finance, Healthcare и Demographics, а своё поведение вы описываете с помощью взвешенных конечных автоматов, составных ссылок на несколько полей, управляющих конструкций, сценарного memstore для поэтапной агрегации и генерации временных рядов по ISO 8601.
Можно ли получить ровно один и тот же набор данных при каждом запуске?Да — генерация детерминирована благодаря seeding, а каждый запуск пишет логи выполнения и SHA-256-хеш содержимого выходных данных, так что два запуска можно проверить на идентичность результата.
Куда попадают сгенерированные данные?Пайплайны для одной системы пишут в PostgreSQL, MySQL, Oracle, MS SQL, SQLite или MongoDB, либо в файлы: CSV, JSON, XML, XLSX, DbUnit и fixed-width (.fcw).
Могут ли ИИ-агенты для кодинга работать с ним напрямую?Да — CLI спроектирован как контракт для агентов: машиночитаемый JSON из команд datamimic capabilities, reference, scaffold, lint и dry-run, плюс опциональный MCP-адаптер, который ставится через pip install 'datamimic-ce[mcp]'.
Какие есть похожие проекты?presidio, faker, shrt, app-store-compliance, ZizkaDB, SurrogateShield, lynis, yuvomi
Автор
rapiddweller
Размер
54.1 MB
Звёзды
117
Возраст
1 г
Коммиты · 90 дней