Appearance
Clean Room Full Lab
Ten steps. Forty-five minutes. Two organizations, zero data sharing.
This lab simulates the complete lifecycle of a federated clean room using an M&A due diligence scenario. You'll use two SDK client instances (one per organization) to walk through every stage — from room creation through mutual attestation, sandboxed execution, escrowed results, dual-approved release, and independent provenance verification.
Scenario
Acme Corp (the acquirer) and WidgetCo (the target) need to analyze customer revenue overlap for a potential acquisition. Neither company will share raw customer or revenue data. A federated clean room lets them run an agreed-upon analysis on combined data without either party seeing the other's inputs.
Prerequisites
Before starting, ensure you have completed the first three steps of the GhostScience Full Lab:
- [ ] PhD Mode enabled:
PHD_MODE_ENABLED=true - [ ] Clean Room enabled:
CLEAN_ROOM_ENABLED=true - [ ] Sandbox enabled:
SANDBOX_ENABLED=true - [ ] PhD sandbox image built:
docker images ghostai-phd-sandboxshows the image - [ ] Docker running:
docker infosucceeds - [ ] Python SDK installed:
from ghostscience import GhostScienceClientworks - [ ] Two API keys: You need two organization-scoped API keys (one per org). If you only have one, your admin can create a second org in the admin panel, or you can use the same key and simulate the second org (the API accepts different org identifiers).
Verify prerequisites
bash
curl -s http://localhost:8000/api/phd/health | python3 -m json.toolConfirm "phd_mode_enabled": true, "sandbox_available": true.
Enable Clean Room (if not already)
Add to securechat/backend/.env:
bash
CLEAN_ROOM_ENABLED=trueRestart the backend.
Step 1: Set Up Two SDK Clients
Duration: 2 minutes Goal: Create two GhostScienceClient instances representing the two organizations.
1.1 Create a lab script
Create a file called clean_room_lab.py:
python
import os
import json
import time
from ghostscience import GhostScienceClient
BASE_URL = os.environ.get("GHOSTSCIENCE_BASE_URL", "http://localhost:8000")
ORG_A_KEY = os.environ.get("ORG_A_API_KEY", os.environ["GHOSTSCIENCE_API_KEY"])
ORG_B_KEY = os.environ.get("ORG_B_API_KEY", os.environ["GHOSTSCIENCE_API_KEY"])
client_a = GhostScienceClient(api_key=ORG_A_KEY, base_url=BASE_URL)
client_b = GhostScienceClient(api_key=ORG_B_KEY, base_url=BASE_URL)
print("Acme Corp client: OK")
print("WidgetCo client: OK")
health = client_a.health()
print(f"PhD Mode: {health['phd_mode_enabled']}")
print(f"Sandbox: {health['sandbox_available']}")1.2 Run it
bash
export GHOSTSCIENCE_API_KEY="gst_your_key"
# If you have two keys:
# export ORG_A_API_KEY="gst_acme_key"
# export ORG_B_API_KEY="gst_widgetco_key"
python3 clean_room_lab.pyExpected output:
Acme Corp client: OK
WidgetCo client: OK
PhD Mode: True
Sandbox: TrueStep 2: Create a Clean Room
Duration: 3 minutes Goal: Acme Corp creates a clean room for the M&A analysis.
2.1 Add to your script
python
room = client_a.create_clean_room(
name="M&A Revenue Overlap Analysis",
description="Customer overlap and concentration risk for Acme-WidgetCo acquisition due diligence"
)
room_id = room["id"]
print(f"\nClean Room Created")
print(f" ID: {room_id}")
print(f" Name: {room['name']}")
print(f" Status: {room['status']}")Expected output:
Clean Room Created
ID: cr-a1b2c3d4-...
Name: M&A Revenue Overlap Analysis
Status: draftThe room starts in draft status. No computation can run yet.
Step 3: Invite WidgetCo
Duration: 2 minutes Goal: Acme sends an invitation to WidgetCo's organization.
3.1 Send the invitation
python
invite = client_a.invite_to_clean_room(room_id, target_org_id="org-widgetco")
print(f"\nInvitation Sent")
print(f" Target Org: {invite.get('target_org_id', 'org-widgetco')}")
print(f" Status: {invite.get('status', 'invited')}")3.2 Verify the room shows both participants
python
room_status = client_a.get_clean_room(room_id)
print(f"\nParticipants:")
for p in room_status.get("participants", []):
print(f" {p['organization_id']:20s} role={p['role']:12s} status={p['status']}")Expected output:
Invitation Sent
Target Org: org-widgetco
Status: invited
Participants:
org-acme role=initiator status=accepted
org-widgetco role=participant status=invitedStep 4: WidgetCo Accepts
Duration: 2 minutes Goal: WidgetCo reviews and accepts the clean room invitation.
4.1 Accept the invitation
python
client_b.accept_clean_room(room_id)
print(f"\nWidgetCo accepted the clean room invitation")4.2 Verify both orgs are accepted
python
room_status = client_a.get_clean_room(room_id)
print(f"Room status: {room_status['status']}")
for p in room_status.get("participants", []):
print(f" {p['organization_id']:20s} status={p['status']}")Expected output:
WidgetCo accepted the clean room invitation
Room status: draft
org-acme status=accepted
org-widgetco status=acceptedBoth organizations are now accepted. The room is still in draft because the computation template hasn't been set yet.
Step 5: Set the Computation Template
Duration: 5 minutes Goal: Define the exact Python code that will run in the clean room sandbox.
5.1 Define the template
python
TEMPLATE_CODE = """
import pandas as pd
import numpy as np
from collections import Counter
# --- Data loaded automatically by the clean room runtime ---
# org_a_data: Acme's customer revenue DataFrame
# org_b_data: WidgetCo's customer revenue DataFrame
# Both have columns: customer_hash, revenue, segment
# 1. Customer overlap
overlap = pd.merge(
org_a_data[['customer_hash', 'revenue']],
org_b_data[['customer_hash', 'revenue']],
on='customer_hash',
how='inner',
suffixes=('_acme', '_widgetco')
)
overlap_count = len(overlap)
overlap_pct_acme = overlap_count / len(org_a_data) * 100
overlap_pct_widgetco = overlap_count / len(org_b_data) * 100
# 2. Combined overlap revenue
overlap['combined_revenue'] = overlap['revenue_acme'] + overlap['revenue_widgetco']
total_overlap_revenue = overlap['combined_revenue'].sum()
# 3. Customer concentration (top 10)
top_10 = overlap.nlargest(10, 'combined_revenue')[['customer_hash', 'combined_revenue']]
concentration_pct = top_10['combined_revenue'].sum() / total_overlap_revenue * 100
# 4. Revenue synergy estimate
synergy = total_overlap_revenue * 0.15 # conservative 15% cross-sell estimate
# 5. Results
print(f"=== M&A Revenue Overlap Analysis ===")
print(f"Acme customers: {len(org_a_data):,}")
print(f"WidgetCo customers: {len(org_b_data):,}")
print(f"Overlapping customers: {overlap_count:,}")
print(f"Overlap % (Acme): {overlap_pct_acme:.1f}%")
print(f"Overlap % (WidgetCo): {overlap_pct_widgetco:.1f}%")
print(f"Total overlap revenue: ${total_overlap_revenue:,.2f}")
print(f"Top-10 concentration: {concentration_pct:.1f}%")
print(f"Synergy estimate (15%): ${synergy:,.2f}")
"""5.2 Set the template on the clean room
python
client_a.set_clean_room_template(
clean_room_id=room_id,
computation_template=TEMPLATE_CODE,
sandbox_config={
"timeout": 120,
"max_memory": "2g",
"max_cpu": 1
}
)
print(f"\nComputation template set")
print(f" Code lines: {TEMPLATE_CODE.count(chr(10))}")
print(f" Timeout: 120s")
print(f" Memory: 2GB")5.3 Review the template (as WidgetCo would)
python
room_detail = client_b.get_clean_room(room_id)
print(f"\nWidgetCo reviews the template:")
print(f" Status: {room_detail['status']}")
template = room_detail.get("computation_template", "")
print(f" Template preview:\n{template[:200]}...")Both organizations can now review the exact code that will execute. No changes can be made after attestation.
Step 6: Mutual Attestation
Duration: 5 minutes Goal: Both organizations cryptographically attest to the computation environment.
6.1 Get the attestation bundle (what will be hashed)
python
attestation = client_a.get_attestation_status(room_id)
print(f"\nAttestation Bundle (pre-signing):")
print(json.dumps(attestation, indent=2, default=str))The attestation bundle contains four hashes:
- Image hash: SHA-256 of the Docker sandbox image
- Code hash: SHA-256 of the computation template
- Config hash: SHA-256 of the sandbox configuration
- Combined hash: HMAC of image + code + config
6.2 Acme attests
python
bundle_hash = attestation.get("combined_hash", "")
result_a = client_a.attest_clean_room(room_id, bundle_hash=bundle_hash)
print(f"\nAcme attestation: {result_a.get('status', 'submitted')}")6.3 WidgetCo attests
python
attestation_b = client_b.get_attestation_status(room_id)
bundle_hash_b = attestation_b.get("combined_hash", "")
# Verify the hashes match before signing
print(f"\nHash comparison:")
print(f" Acme combined hash: {bundle_hash[:32]}...")
print(f" WidgetCo combined hash: {bundle_hash_b[:32]}...")
print(f" Match: {bundle_hash == bundle_hash_b}")
assert bundle_hash == bundle_hash_b, "ALERT: Hash mismatch — do not attest!"
result_b = client_b.attest_clean_room(room_id, bundle_hash=bundle_hash_b)
print(f" WidgetCo attestation: {result_b.get('status', 'submitted')}")6.4 Verify the room moved to ready
python
room_status = client_a.get_clean_room(room_id)
print(f"\nRoom status after mutual attestation: {room_status['status']}")Expected output:
Hash comparison:
Acme combined hash: a1b2c3d4e5f6...
WidgetCo combined hash: a1b2c3d4e5f6...
Match: True
WidgetCo attestation: submitted
Room status after mutual attestation: readyThe room is now ready. Both organizations have cryptographically agreed on the exact environment.
Step 7: Execution
Duration: 5 minutes Goal: The clean room executes the attested computation in a hardened sandbox.
7.1 Wait for execution to complete
Once both parties attest, execution begins automatically. Poll for completion:
python
print(f"\nWaiting for execution...")
for i in range(30):
status = client_a.get_clean_room(room_id)
current = status["status"]
print(f" [{i*2:3d}s] Status: {current}")
if current in ("escrowed", "released", "rejected", "expired"):
break
time.sleep(2)
print(f"\nFinal status: {current}")Expected output:
Waiting for execution...
[ 0s] Status: ready
[ 2s] Status: executing
[ 4s] Status: executing
[ 6s] Status: escrowed
Final status: escrowedThe computation has run. Results are encrypted and held in escrow. Neither organization can see them yet.
7.2 Understand what happened
During execution:
- A gVisor-isolated Docker container launched using the attested image
- Both organizations' data was loaded (encrypted at rest, decrypted only inside the sandbox)
- The attested Python code executed
- Results were encrypted with an escrow key and stored
- The sandbox was destroyed (no persistent state)
Step 8: Review and Release
Duration: 5 minutes Goal: Both organizations review the escrowed summary and decide whether to release results.
8.1 Review the escrow summary (as Acme)
python
summary_a = client_a.get_clean_room_results(room_id)
print(f"\nAcme sees escrow summary:")
print(f" Status: {summary_a.get('status', 'escrowed')}")
print(f" Output count: {summary_a.get('output_count', 'N/A')}")
print(f" Summary: {summary_a.get('summary', 'N/A')}")8.2 Review the escrow summary (as WidgetCo)
python
summary_b = client_b.get_clean_room_results(room_id)
print(f"\nWidgetCo sees escrow summary:")
print(f" Status: {summary_b.get('status', 'escrowed')}")
print(f" Summary: {summary_b.get('summary', 'N/A')}")The summary provides metadata (output count, PII scan results) but NOT the actual results. Both organizations decide based on the summary.
8.3 Acme approves
python
release_a = client_a.release_clean_room_result(
clean_room_id=room_id,
approve=True,
reason="Revenue overlap analysis looks appropriate. Approved by CFO."
)
print(f"\nAcme decision: {release_a.get('action', 'approve')}")
print(f"Room status: {release_a.get('room_status', 'pending')}")8.4 WidgetCo approves
python
release_b = client_b.release_clean_room_result(
clean_room_id=room_id,
approve=True,
reason="Computation scope verified. Approved by General Counsel."
)
print(f"\nWidgetCo decision: {release_b.get('action', 'approve')}")
print(f"Room status: {release_b.get('room_status', 'released')}")8.5 Retrieve the released results
python
results = client_a.get_clean_room_results(room_id)
print(f"\n=== Released Results ===")
print(results.get("output", "(no output)"))Expected output:
=== Released Results ===
=== M&A Revenue Overlap Analysis ===
Acme customers: 12,450
WidgetCo customers: 8,200
Overlapping customers: 847
Overlap % (Acme): 6.8%
Overlap % (WidgetCo): 10.3%
Total overlap revenue: $42,350,000.00
Top-10 concentration: 34.2%
Synergy estimate (15%): $6,352,500.008.6 (Alternative) What happens if WidgetCo rejects
If WidgetCo's GC doesn't approve:
python
# DO NOT RUN THIS — it would destroy the results
# release_b = client_b.release_clean_room_result(
# clean_room_id=room_id,
# approve=False,
# reason="Output count exceeds expected scope. Rejected."
# )
# Room status → "rejected", escrow key deleted, results permanently destroyedStep 9: Inspect Dual Provenance
Duration: 5 minutes Goal: Each organization retrieves its independent provenance record and verifies consistency.
9.1 Acme's provenance
python
prov_a = client_a.get_clean_room_provenance(room_id)
print(f"\n=== Acme Provenance Record ===")
print(f" Room ID: {prov_a.get('room_id', room_id)}")
print(f" Org: {prov_a.get('org_id', 'org-acme')}")
print(f" Code hash: {prov_a.get('code_hash', 'N/A')[:32]}...")
print(f" Environment hash: {prov_a.get('environment_hash', 'N/A')[:32]}...")
print(f" Result hash: {prov_a.get('result_hash', 'N/A')[:32]}...")
print(f" Created at: {prov_a.get('created_at', 'N/A')}")9.2 WidgetCo's provenance
python
prov_b = client_b.get_clean_room_provenance(room_id)
print(f"\n=== WidgetCo Provenance Record ===")
print(f" Room ID: {prov_b.get('room_id', room_id)}")
print(f" Org: {prov_b.get('org_id', 'org-widgetco')}")
print(f" Code hash: {prov_b.get('code_hash', 'N/A')[:32]}...")
print(f" Environment hash: {prov_b.get('environment_hash', 'N/A')[:32]}...")
print(f" Result hash: {prov_b.get('result_hash', 'N/A')[:32]}...")
print(f" Created at: {prov_b.get('created_at', 'N/A')}")9.3 Cross-verify
python
print(f"\n=== Cross-Verification ===")
print(f" Code hashes match: {prov_a.get('code_hash') == prov_b.get('code_hash')}")
print(f" Environment hashes match: {prov_a.get('environment_hash') == prov_b.get('environment_hash')}")
print(f" Result hashes match: {prov_a.get('result_hash') == prov_b.get('result_hash')}")Expected output:
=== Cross-Verification ===
Code hashes match: True
Environment hashes match: True
Result hashes match: TrueBoth organizations independently verify that:
- The same code ran (code hash)
- In the same environment (environment hash)
- Producing the same output (result hash)
Neither provenance record reveals anything about the other organization's input data.
Step 10: Cleanup
Duration: 2 minutes Goal: Review the final state and understand the lifecycle.
10.1 Final room state
python
final = client_a.get_clean_room(room_id)
print(f"\n=== Final Clean Room State ===")
print(json.dumps(final, indent=2, default=str))10.2 Lifecycle summary
draft → attesting → ready → executing → escrowed → released
→ rejected (alternative)
→ expired (timeout)| Status | What happened |
|---|---|
draft | Room created, invitations sent |
attesting | Template set, orgs submitting attestation hashes |
ready | All orgs attested, hashes verified, ready to execute |
executing | Sandbox running the attested code on combined data |
escrowed | Results encrypted, awaiting dual approval |
released | Both orgs approved, results decrypted and available |
rejected | One or more orgs rejected, escrow key destroyed |
expired | Escrow timeout reached, key destroyed |
10.3 What each GC takes away
Acme's General Counsel receives:
- Provenance record proving the attested code ran in the attested environment
- Result hash that can be independently verified against WidgetCo's record
- Timestamp chain from creation through release
- No visibility into WidgetCo's raw data
WidgetCo's General Counsel receives:
- Identical provenance guarantees from their perspective
- Proof that Acme could not have modified the computation after attestation
- No visibility into Acme's raw data
Troubleshooting
Clean Room not enabled
Symptom: POST /api/clean-room returns 403 or "feature not available"
Fix: Add CLEAN_ROOM_ENABLED=true to .env and restart the backend.
Attestation hash mismatch
Symptom: assert bundle_hash == bundle_hash_b fails
Possible causes:
- Docker image was rebuilt between the two attestation calls
- Template was modified after one org already attested
- Sandbox config differs between orgs
Fix: Ensure both orgs are seeing the same room state. Have both re-attest from a clean state.
Room stuck in executing
Symptom: Status stays at executing for more than 5 minutes
Possible causes:
- Sandbox timeout too low for the computation
- Docker daemon overloaded
- Computation has an infinite loop
Fix:
- Check Docker containers:
docker ps | grep phd - Check backend logs for sandbox errors
- Increase timeout in sandbox config
- If stuck, the admin can force-expire the room
Escrow expired
Symptom: Room moved to expired before both orgs approved
Fix: The default escrow window may be too short for the lab. Set CLEAN_ROOM_ESCROW_TIMEOUT_HOURS=48 in .env. For labs, a shorter value like 2 hours is fine but requires timely approval.
"Both orgs" with one API key
If you only have one API key, the lab still works but both clients will be authenticated as the same org. The clean room API allows this for testing — the invitation and acceptance flow still executes, but the provenance records will show the same org ID for both sides.
For a realistic simulation, ask your admin to create a second organization with its own API key.
What's Next
- GhostScience tools: Explore all eight scientific tools with the GhostScience Full Lab
- Demo practice: Run the Clean Room Demo Script for a polished customer presentation
- API reference: See the full Clean Room API documentation
- Example scripts: Run the pre-built clean room examples in
docs/examples/(scripts 11–15) - Architecture: Read the Federated Clean Room feature documentation for the security model, lifecycle state machine, and compliance mappings
Lab Summary
| Step | Topic | Duration |
|---|---|---|
| 1 | Set up two SDK clients | 2 min |
| 2 | Create a clean room | 3 min |
| 3 | Invite WidgetCo | 2 min |
| 4 | WidgetCo accepts | 2 min |
| 5 | Set computation template | 5 min |
| 6 | Mutual attestation | 5 min |
| 7 | Execution | 5 min |
| 8 | Review and release | 5 min |
| 9 | Inspect dual provenance | 5 min |
| 10 | Cleanup and review | 2 min |
| Total | ~36 min |