Skip to content

About

Self-hosted data clean room for buy-side M&A diligence — tokenizes target financials so analysts get income statements, working capital, concentration, and EBITDA analysis without legal risk.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

ma-clean-room

For analysts

Point any SQL client, Excel, or Power BI at clean_db as the read-only analyst role and query the curated views below directly — no infra setup required on your end. Real, unedited example output (CSVs, an audit record, and the rendered tear sheet) is committed at docs/sample_output/; a full column-by-column reference is at docs/data_dictionary.md.

-- Revenue, COGS, gross margin, and reported/adjusted EBITDA by month
SELECT * FROM clean.income_statement_summary ORDER BY fiscal_year, fiscal_month;

-- AR/AP/inventory balances, DSO/DPO/DIO, and cash conversion cycle by month
SELECT * FROM clean.working_capital ORDER BY fiscal_year, fiscal_month;

-- Top 10 customers by revenue, with Pareto cumulative % and portfolio HHI
SELECT * FROM clean.customer_concentration WHERE is_top10 ORDER BY revenue_rank;

Every identifying value you'll see (customer_token, vendor_token) is an HMAC pseudonym, never a name — see "Redaction: before / after" below. The rest of this README is the operational runbook for standing up and running the pipeline; skip to "What analysts get" for more sample output, or straight to the query reference above if that's all you need.

A self-hosted data clean room for buy-side M&A diligence: it turns a target's raw GL export into the standard diligence deliverables — income statement, working-capital and DSO/DPO trends, customer/vendor concentration with HHI, EBITDA bridge — while analysts only ever touch tokenized data that's already cleared a leak scan and a trial-balance check.

What analysts get

Everything below is a real, unedited export from this repo's own pipeline, run against cleanroom.gen_data's seeded synthetic target (--seed 7) — not a mockup. Full CSVs and one complete audit record are committed at docs/sample_output/; see that directory's README for exact reproduction steps and a few caveats about what's a real pipeline result versus an artifact of random synthetic data (short version: the mechanics are real, the specific ratios are not representative of an actual business — read the caveats before quoting a number from this section).

The single deliverable this whole pipeline builds toward is cleanroom.report's one-page Preliminary Diligence Findings tear sheet — financial summary, adjusted EBITDA bridge, NWC/DSO/DPO/DIO trend, customer/vendor concentration with HHI, AR/AP aging, and a flags panel (out-of-balance periods, unmapped accounts, reconciliation items for manual review), rendered as both HTML and PDF from the analyst role's own curated-view access, nothing more privileged. A real, generated example is committed at docs/sample_output/preliminary_diligence_findings.pdf (HTML) — run make report to produce your own after make pipeline PASSes.

Income statement (full 24-period detail) — clean.income_statement, FY2024 rolled up by account:

Account FY2024 amount (USD)
Product Revenue 3,904,537.23
Service Revenue 3,129,925.81
Cost of Goods Sold 509,344.55
Salaries Expense 491,983.11
Rent Expense 533,769.04
Utilities Expense 701,108.63
Marketing Expense 270,345.16
Office Supplies Expense 915,072.83
Travel Expense 505,226.09
Professional Fees 855,449.84
Depreciation Expense 609,987.02
Insurance Expense 683,432.05
Bank Fees 424,709.62

EBITDA bridge (full 24-period detail) — clean.ebitda_bridge, FY2024, built from clean.ebitda_addback_config (edit that config's account list per deal — see cleanroom.analytics's module docstring):

Bridge line FY2024 amount (USD)
Reported EBITDA 1,144,022.12
+ Marketing Expense — one-time rebrand campaign 270,345.16
+ Professional Fees — non-recurring transaction/legal costs 855,449.84
Adjusted EBITDA 2,269,817.12

Reported EBITDA margin 16.26%, adjusted EBITDA margin 32.27% (both off revenue of $7,034,463.04) — from clean.income_statement_summary.

Working capital / DSO-DPO (full 24-month detail) — clean.working_capital, first two quarters of 2023 (a period this synthetic run's AR/AP balances are still realistic — see the sample-output README on why the trend gets implausible by late 2024 in this particular synthetic run):

Period AR (USD) AP (USD) DSO (days) DPO (days) DIO (days) Cash conversion cycle (days)
2023-01 1,312,026.95 901,684.68 33.9 309.9 16.4 -259.6
2023-02 2,420,048.23 1,928,834.46 62.3 690.6 19.5 -608.8
2023-03 3,849,273.38 2,800,943.20 82.3 1,642.3 0.0 -1,560.0
2023-04 5,007,487.75 3,791,238.84 129.5 1,072.1 17.2 -925.4

Customer concentration (full 119-customer detail) — clean.customer_concentration, top 10 by revenue:

Rank Customer token Revenue (USD) % of total Cumulative %
1 CUSTOMER_4437e800378681418692 415,867.16 2.03% 2.03%
2 CUSTOMER_a882fd9f7dff75eb3a7c 338,370.02 1.65% 3.68%
3 CUSTOMER_c53d6f65abba65694349 320,778.36 1.57% 5.25%
4 CUSTOMER_4317fef5bb013c304149 299,630.95 1.46% 6.71%
5 CUSTOMER_4eb4f28a241bd2f0caf0 285,322.94 1.39% 8.10%
6 CUSTOMER_4597966f09f03ac21923 282,486.99 1.38% 9.48%
7 CUSTOMER_167d50fe7630c20c43e5 281,297.94 1.37% 10.85%
8 CUSTOMER_07c9946305bafb1ca0f4 278,171.11 1.36% 12.21%
9 CUSTOMER_b1ef38b176be286a2c7b 276,878.96 1.35% 13.56%
10 CUSTOMER_9fde8ade13cc437fad4c 272,863.82 1.33% 14.89%

Portfolio HHI: 99.29 → Low (unconcentrated), DOJ/FTC-style bucket computed on every row of clean.customer_concentration, not just the top 10 (see this run's customer_concentration_full.csv).

Every customer_token/vendor_token is an HMAC pseudonym, never a name — see "Redaction: before / after" below. Analysts query exactly these curated views; see src/cleanroom/analytics.py for the complete list (financial statements, quality of earnings, working capital, customer/vendor concentration, AR/AP aging, trends).

The problem

In the run-up to closing an M&A deal, buy-side analysts need to validate the target's financials — revenue recognition, customer concentration, contract terms, liabilities — well before the deal closes. But antitrust and confidentiality rules mean those analysts often cannot legally see the target's raw data pre-close: doing so risks "gun-jumping" violations and breaches of the confidentiality agreements that govern the deal. The standard workaround is to hire an outside consulting firm to stand up a data clean room for the deal. These engagements are widely described in the industry as expensive and slow to stand up — there's no public benchmark for what one costs, and it varies a lot by deal size, scope, and vendor, but a meaningful share of that cost is spent re-solving the same tokenization, access-control, and audit-trail problem from scratch, for every deal.

ma-clean-room replaces that engagement with a self-hosted, repeatable pipeline: raw target financials are loaded into an isolated raw_db, deterministically tokenized (via HMAC-salted, LUKS-protected mapping) into an analyst-facing clean_db, and every export is checked by a leak scanner before analysts ever query it — see "What analysts get" above for what that actually produces.

How we let analysts get that without legal risk

Everything above is real output, but an analyst never queries raw target data to get it. The pipeline sits between the target's export and the analyst, and does four things before anything is queryable:

  1. Tokenize. cleanroom.anonymize replaces vendor/customer names, tax IDs, IBANs, and emails with a deterministic HMAC-SHA256(salt, normalized_value) token before anything crosses from raw_db into clean_db. Two source rows for the same real-world entity (a typo'd name, a re-cased duplicate) reconcile to the same token when they share a tax ID/IBAN or an exact core name after suffix-stripping — see "Redaction: before / after" below for what that actually looks like.
  2. Vault the mapping. The original↔token crosswalk is written only to a LUKS-encrypted mapping vault (.vault/mapping-vault), never to clean_db, never returned in any anonymized output. It's the single highest-value target in the system — see THREAT_MODEL.md.
  3. Gate on a leak scan and a trial-balance check. cleanroom.verify scans every text cell of every clean-side table against every value the vault has ever recorded, and independently checks that total debits equal total credits. Either failing is a hard block: clean_db gets no analyst grant at all until both pass — see verify.py's module docstring and this run's real audit_record_example.json.
  4. Grant least privilege, and only after a PASS. The analyst role gets SELECT on the curated views in "What analysts get" above — never on the per-row vendors/customers/gl_entries tables underneath them, and never before verify passes. docker-compose.yml's container hardening (read_only, cap_drop: [ALL], no network egress) and role-based SQL privileges (sql/init/00-roles.sql) back this up at the infrastructure layer. Full detail in THREAT_MODEL.md and the diagram in docs/architecture.md.

What this replaces

Outside clean-room engagement ma-clean-room
Cost Widely reported as expensive, deal-by-deal One-time setup cost; marginal cost per deal is just infra (a host + containers)
Timeline Weeks — staffing, tooling, review cycles with a vendor Minutes to bring up the stack and run the pipeline once secrets exist
Reuse across deals Re-scoped and re-negotiated with the vendor each time Same pipeline and controls every deal; a fresh .vault per engagement
What's actually being paid for Mostly re-solving the same tokenization / access-control / audit-trail problem That problem solved once, in code, and reviewed like any other change
Auditability Depends on the vendor's own tooling and reporting Built-in: append-only audit record + table-hash manifest per run (cleanroom.verify)

The tokenization, role-based access control, and audit trail are the expensive, hard-to-differentiate parts of a bespoke clean-room engagement — this repository is that work, done once and reused per deal instead of re-bought.

Repository layout

scripts/          operational and ETL scripts
sql/init/          database schema / bootstrap SQL for raw_db and clean_db
src/cleanroom/     Python package: tokenization, ETL, leak scanning, analytics
docs/sample_output/ committed example diligence output (see "What analysts get")
ansible/           provisioning/config-management for the isolated hosts
.github/workflows/ CI
docs/              additional documentation

Status

The pipeline (ingest → anonymize → map-coa → load-clean → verify) and the container/role hardening described in THREAT_MODEL.md are implemented and exercised end to end in CI on every push, against synthetic data, with CLEANROOM_STORAGE_MODE=plain standing in for the LUKS vault (see .github/workflows/ci.yml).

The gate ordering is: load_clean builds the full curated analytics layer (clean.trial_balance plus everything in cleanroom.analytics) but grants analyst nothing at all. verify.py runs next, independently, and is the only thing that ever grants or revokes that access — grant_analyst() runs if and only if both the leak scan and the trial-balance check PASS; revoke_analyst() runs on any FAIL, so a stale grant from an earlier passing run can't outlive a later failed one. See verify.py's module docstring for the full sequence and load_clean.verify_analyst_isolation() for the check that confirms it held. cleanroom.report is the analyst-facing entrypoint that actually uses that grant — see "What analysts get" above.

Before pointing this at a real deal's data, read THREAT_MODEL.md's non-goals in full — this has not had an independent security review, and a couple of specific pipeline caveats worth knowing about are in "Known limitations" below.

Known limitations

Two things about the pipeline's two hard gates (cleanroom.verify) worth understanding before trusting a PASS or investigating a FAIL - see that module's docstring for the gates themselves, and docs/sample_output/README.md for limitations specific to this repo's committed synthetic sample output (unrealistic margins, an implausible late-period revenue swing, etc.) — distinct from, and not duplicated by, the two below, which apply to any dataset this pipeline runs against, real or synthetic.

  • The trial-balance gate's whole-ledger check uses a tolerance that scales with ledger size, not a fixed cent amount. check_trial_balance() converts each GL line to USD independently (load_clean.attach_fx()'s per-line .round(2)), and on a split multi-currency journal (one side of a debit/credit pair represented as two or more GL rows), independently rounding each of those rows can leave the ledger-wide debit and credit totals a cent or two apart even though the pre-conversion, pre-rounding amounts balance exactly. A fixed BALANCE_TOLERANCE_USD (one cent) was too tight for this - a handful of seeds, --seed 42 (the CLI default) included, crossed it on nothing but this rounding noise. The whole-ledger check now allows BALANCE_TOLERANCE_USD plus a small per-entry allowance (PER_LINE_ROUNDING_SLACK_USD, scaled by sqrt(entry count) to reflect that these errors partially cancel rather than accumulate linearly) - see cleanroom.verify's check_trial_balance() for the exact formula and reasoning. This tolerance stays many orders of magnitude below any real transaction in this pipeline's data (the smallest synthetic journal is $10), so it absorbs reproducible FX-rounding noise without meaningfully widening what the gate would still catch: a dropped/duplicated row, a bad FX conversion, or a genuine mapping bug. Per-period balances (reported alongside the whole-ledger total, for visibility) still use the fixed, unscaled tolerance and never gate status either way - see cleanroom.verify's module docstring.

  • The leak scanner does exact/substring matching against known vault values, case-insensitively - it is defense-in-depth behind the clean-side column allowlist (load_clean.CLEAN_TABLES), not a semantic scrubber. It will not catch a leaked value that's been transformed (re-cased in a way normalization doesn't already handle, truncated, paraphrased, split across cells) - the column allowlist and the tokenization step upstream are what actually prevent that class of leak; the scanner exists to catch a raw value that shouldn't be there at all, not to detect every way one could be obscured. It also treats very short vault values (below verify.SHORT_VALUE_BOUNDARY_THRESHOLD, e.g. a two-letter company name) as a word-boundary match rather than a bare substring match, so a short value doesn't flag every larger word that happens to contain it as a substring - see build_leak_pattern()'s docstring for exactly what that trades away (a short value concatenated into a longer token with no delimiter at all would slip past it) and why that's judged far rarer in practice than the false-positive rate a bare substring match produces at short lengths.

Storage vault

scripts/storage-up.sh / scripts/storage-down.sh bring up and tear down the LUKS-encrypted .vault/ volume described in THREAT_MODEL.md (pgdata-raw, pgdata-clean, secrets, mapping-vault, audit). Set CLEANROOM_STORAGE_MODE=plain to skip encryption for CI/test runs only — never on a host that will hold real target data.

Swap must not be able to hold plaintext. Before running storage-up.sh in luks mode on a real host, disable swap (swapoff -a) or make sure any swap in use is itself encrypted. If the host swaps out live memory to a plaintext swap device, the LUKS passphrase/key and the HMAC pseudonymization salt can end up written to disk in the clear, defeating the encryption-at-rest control regardless of how the vault itself is configured.

Running this for real

This is the real, non-CI flow — CLEANROOM_STORAGE_MODE defaults to luks, so ./.vault is a genuine LUKS2-encrypted volume, not a plain directory. You'll be prompted for a LUKS passphrase the first time (storage-up formats and opens the container); pick one and keep it somewhere safe, since losing it means losing the mapping vault.

# 1. Install the package (provides the `cleanroom` CLI modules used below)
pip install -e .

# 2. Bring up the encrypted vault and generate one-time secrets into it
#    (HMAC salt + per-role Postgres passwords). Safe to re-run - both
#    scripts are idempotent and never overwrite existing secrets.
make storage-up
make secrets

# 3. Build and start raw_db/clean_db/processor, and wait for both
#    Postgres instances to come up.
make up

# 4. One-time per fresh vault: load the standardized chart of accounts
#    that `load-clean` maps every target's own CoA onto. Nothing in the
#    Makefile does this automatically (see sql/standard_coa.sql) - it isn't
#    per-deal data, so it only needs loading once per fresh ./.vault, not
#    once per pipeline run.
docker compose exec -T clean_db psql -U postgres -d clean_db < sql/standard_coa.sql

# 5. Generate or drop in this deal's raw CSV exports, then run the
#    pipeline: ingest -> anonymize -> map-coa -> load-clean -> verify.
#    verify is a hard gate - it exits 1 and blocks promotion to clean_db
#    if any raw vault value (name, tax ID, IBAN, email) resurfaces.
python -m cleanroom.gen_data --out-dir sample_data   # or supply real exports
make pipeline

# Later runs against the same vault (e.g. re-running after fixing
# mapping.yaml) can use the shorter `make all`, which bundles steps 2-3 and
# 5 together (it re-runs storage-up/secrets/up idempotently, then pipeline) -
# standard_coa only needs loading once, per step 4.
make all

# 6. Render the analyst-facing tear sheet (HTML + PDF), reading clean_db as
#    the read-only `analyst` role - only live after a PASSing verify run.
#    Writes into docs/sample_output/ by default (REPORT_OUT_DIR overrides
#    it); see src/cleanroom/analytics.py for the full curated view list
#    (financial statements, quality of earnings, working capital,
#    customer/vendor concentration, AR/AP aging, trends) this draws from,
#    on top of clean.trial_balance.
make report

# When the engagement is done:
make down          # stop containers, leave the vault mounted
make storage-down  # unmount and close the vault

CLEANROOM_STORAGE_MODE=plain is CI-only (see .github/workflows/ci.yml, which runs this same flow against synthetic data on every push) — make all refuses to run in that mode (see guard-vault-mounted in the Makefile).

Redaction: before / after

cleanroom.anonymize replaces sensitive fields with a deterministic HMAC-SHA256(salt, normalized_value) token before anything crosses into clean_db; cleanroom.load_clean's column allowlist drops quasi-identifier and free-text fields entirely rather than forwarding them. Token values below are illustrative — actual tokens depend on your vault's HMAC salt and will differ per deployment.

Field Raw value (raw_db) What analysts see (clean_db) Mechanism
vendor_name "ACME CORPORATION" and "Acme Corp." (two source rows) VENDOR_3f9a2c1b8e4d7a10c2b5 (same token for both) HMAC token of the suffix-stripped core name — duplicate spellings of one entity reconcile to one pseudonym
tax_id "12-3456789" TAXID_9e1d4a7c0b3f6e82d5a1 HMAC token of the normalized tax ID
iban "DE89 3704 0044 0532 0130 00" IBAN_7b2e5f8a1c4d9b60e3f7 HMAC token of the whitespace-stripped IBAN
email "ap@acmecorp.com" EMAIL_1a6c9e2b5d8f3a70c4b1 HMAC token of the lower-cased email
account_code (target's own CoA) "AC-6010" standard_account_id = "6010" (Rent Expense) Deterministic crosswalk (mapping.yaml) or rapidfuzz fallback — not tokenized, since it's non-sensitive reference data
phone, city, country, GL description present in raw_db absent from clean_db entirely Dropped by load_clean's column allowlist, not tokenized — free text and quasi-identifiers are exactly what the leak scanner (verify.py) can't fully guarantee are safe to forward

Two source rows for the same real-world vendor/customer only reconcile to one token when they share a tax ID/IBAN or an exact core name after suffix-stripping ("Acme Corp" → "Acme Corporation"); a merely similar-looking name with no shared identifier is flagged in the vault crosswalk for manual review, never auto-merged (see anonymize.py's reconcile_names).

License

Apache-2.0 — see LICENSE.

About

Self-hosted data clean room for buy-side M&A diligence — tokenizes target financials so analysts get income statements, working capital, concentration, and EBITDA analysis without legal risk.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages