From f83b70c596a6dbc4db13b7206df2964dd191a6e4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 16:28:20 -0600 Subject: [PATCH] Week 4: hash-bound approval gate and idempotent migration engine Approval (src/firstsync/approval.py) is a human act at the CLI, never an MCP tool: `firstsync approve ` records a SHA-256 of each proposal as it stands. If any proposal changes afterwards, the migration refuses to run and names the changed fields until a person approves again. Open questions being approved past are listed at approval time. The migration engine (src/firstsync/migrate.py) runs only behind that gate and builds every row with the same build_row the dry-run used (extracted from the dry-run engine so the two cannot diverge): clean and warning records load, blocking and needs_decision records are skipped with their Ids in the report. Upserts key on (tenant, external_id), so re-running is safe by construction - the second run reports everything unchanged and writes nothing. Target database (src/firstsync/target/db.py): SQLite via stdlib, DDL generated from TARGET_SCHEMA so the Python schema, the SQLite DDL and the Postgres DDL cannot drift apart silently. Tenants are isolated by a UUID derived from the connection handle. Claude's only new capability is migration_get_status, read-only. New CLI commands: proposals, approve, migrate (exits non-zero when refused, so it can gate a pipeline). On org D with Sonnet's proposals: 396 read, 387 loaded, 9 skipped - exactly the 5 contacts missing emails and 4 deals missing amounts the dry-run flagged. Second run: 0 inserted, 387 unchanged. 198 tests (13 new), mypy clean, no network, no API key. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_017ggB2HHn8zjybwfaJG1g3R --- README.md | 42 ++++++-- src/firstsync/approval.py | 101 +++++++++++++++++++ src/firstsync/cli.py | 66 ++++++++++++- src/firstsync/dryrun.py | 80 +++++++++++---- src/firstsync/mcp_server.py | 23 ++++- src/firstsync/migrate.py | 192 ++++++++++++++++++++++++++++++++++++ src/firstsync/target/db.py | 97 ++++++++++++++++++ tests/test_migrate.py | 192 ++++++++++++++++++++++++++++++++++++ tests/test_server.py | 1 + 9 files changed, 759 insertions(+), 35 deletions(-) create mode 100644 src/firstsync/approval.py create mode 100644 src/firstsync/migrate.py create mode 100644 src/firstsync/target/db.py create mode 100644 tests/test_migrate.py diff --git a/README.md b/README.md index 53cf5e1..3bb1383 100644 --- a/README.md +++ b/README.md @@ -8,14 +8,14 @@ A support engineer usually does that by hand. FirstSync gives the work to Claude inspects the customer's org, proposes how each field maps, and explains every failure in plain language. Deterministic code decides what actually runs. -> **Status: week 3 of 6.** Claude can inspect an org and propose a validated mapping for -> every target field; an evaluation scores those proposals against answer keys for six -> synthetic orgs; and a deterministic dry-run engine now executes stored proposals over -> real records — writing nothing — and reports, per record, whether it would load, -> grouped by root cause, with duplicates flagged by natural key. The evaluation checks -> that the pipeline catches the defects planted in org D (it catches 4 of 4, for both -> models tested). Approval, migration and sync are not built yet. This is a reference -> implementation with no customers. See +> **Status: week 4 of 6.** The full pipeline now runs end to end: Claude inspects an org +> and proposes a validated mapping; a deterministic dry-run shows, per record, exactly +> what would load and why anything would not; a person approves at the CLI — approval is +> hash-bound, so a proposal changed after approval invalidates it; and the migration +> engine loads approved data into the target database, idempotently (re-running reports +> everything `unchanged` and writes nothing). There is no tool by which the model +> approves proposals or starts a migration. Sync and the portal are not built yet. This +> is a reference implementation with no customers. See > [What is and is not tested](#what-is-and-is-not-tested). ## The rule the design is built on @@ -34,7 +34,7 @@ The full design is in [docs/SPEC.md](docs/SPEC.md). ## What works today -Nine tools, served from one MCP server: +Ten tools, served from one MCP server: | Tool | What it does | | --- | --- | @@ -47,6 +47,27 @@ Nine tools, served from one MCP server: | `mapping_propose` | Validates mapping proposals and stores the valid ones for approval | | `dryrun_start` | Executes stored proposals over real records without writing, grouped by root cause | | `dryrun_get_results` | Returns a stored dry-run instead of re-running one | +| `migration_get_status` | Returns a stored migration result — counts, skips and who approved. Read-only | + +Approval and migration are deliberately **not** MCP tools. They are CLI commands run by +a person: + +```bash +firstsync proposals org_d # list proposals and their approval state +firstsync approve org_d # approve them as they stand (hash-bound) +firstsync migrate org_d --db out.db # load approved data; exits non-zero if refused +``` + +An approval stores a SHA-256 of each approved proposal. If any proposal changes +afterwards — the model proposed again, a file was edited — the migration refuses to run +and names the changed fields, until a person approves again. The migration builds every +row with the same `build_row` the dry-run used, so what the administrator saw in the +dry-run is exactly what loads: `clean` and `warning` records load (a warned optional +value is dropped), `blocking` and `needs_decision` records are skipped with their Ids in +the report. The upsert key is `(tenant, external_id)`, so re-running a migration is +always safe: the second run reports everything `unchanged`. The target database is +SQLite by default (tests and CI need no services); the DDL is generated from the same +`TARGET_SCHEMA` the dry-run validates against, so the schema cannot drift. The dry-run engine is deterministic code, not the model. Every record is built the way the migration would build it and comes back as **clean**, **warning** (an optional value @@ -82,7 +103,7 @@ Pythons refuse installs outside one. python3 -m venv .venv source .venv/bin/activate pip install -e ".[dev]" -pytest -q # 185 tests, no network, no API key +pytest -q # 198 tests, no network, no API key python scripts/run_eval.py --baseline # the evaluation, with name matching instead of a model python -m firstsync.mcp_server # the MCP server, over stdio ``` @@ -252,6 +273,7 @@ administrator, and neither can a low-confidence mapping or a required field with | --- | --- | | Tools, masking, rules, mapping validation, scoring, fixtures, answer keys | Unit tests, offline | | Dry-run engine | Unit tests against the planted defects in org D, plus property-based tests (Hypothesis) that any limit is safe and re-running never changes the verdict | +| Approval gate and migration | Unit tests: no approval → refused; changed proposal → refused naming the field; migration counts equal the dry-run's per table; property-based test that N runs equal one run | | MCP server | Unit tests, plus a real MCP client over stdio | | Evaluation pipeline | End to end with the baseline mapper | | `scripts/describe_org.py` | Run against org B in week 1: all six planted problems found. See [the report](docs/week1-org-b-report.md). | diff --git a/src/firstsync/approval.py b/src/firstsync/approval.py new file mode 100644 index 0000000..8be1888 --- /dev/null +++ b/src/firstsync/approval.py @@ -0,0 +1,101 @@ +"""The approval gate. + +Approval is a human act, done at the command line or (later) in the portal. It is not an +MCP tool, so there is no path by which the model approves its own proposals. + +An approval binds to the content of what was approved: it stores a SHA-256 of each +proposal's canonical JSON. If a proposal changes afterwards — the model proposed again, +or a file was edited — the stored hash no longer matches and the migration refuses to +run until a person approves again. Approving is cheap; migrating something nobody looked +at is not. +""" + +from __future__ import annotations + +import getpass +import hashlib +import json +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +from firstsync.config import get_settings +from firstsync.mapping import ProposalStore, target_fields + + +def proposal_hash(proposal: dict[str, Any]) -> str: + canon = json.dumps(proposal, sort_keys=True, separators=(",", ":")) + return hashlib.sha256(canon.encode("utf-8")).hexdigest()[:16] + + +def _path(connection: str) -> Path: + return get_settings().state_dir / "approvals" / f"{connection}.json" + + +def load(connection: str) -> dict[str, Any] | None: + path = _path(connection) + if not path.is_file(): + return None + return json.loads(path.read_text(encoding="utf-8")) + + +def approve( + connection: str, excluded: list[str] | None = None, approved_by: str | None = None +) -> dict[str, Any]: + """Approve the proposals as they stand right now. Returns the approval record.""" + proposals = ProposalStore(connection).load() + if not proposals: + raise ValueError(f"No proposals are stored for {connection!r}; nothing to approve.") + excluded = sorted(set(excluded or [])) + unknown = [t for t in excluded if t not in target_fields()] + if unknown: + raise ValueError(f"Cannot exclude unknown target fields: {', '.join(unknown)}.") + unanswered = sorted( + t + for t, p in proposals.items() + if p.get("question_for_admin") and t not in excluded + ) + record = { + "connection": connection, + "approved_at": datetime.now(UTC).isoformat(timespec="seconds"), + "approved_by": approved_by or getpass.getuser(), + "excluded": excluded, + "open_questions": unanswered, + "proposal_sha256_16": { + t: proposal_hash(p) for t, p in proposals.items() if t not in excluded + }, + } + path = _path(connection) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(record, indent=2, sort_keys=True) + "\n", encoding="utf-8") + return record + + +def check(connection: str) -> dict[str, Any]: + """Is the migration allowed to run? Returns {'ok': bool, 'why': ..., 'approved': ...}. + + ok is True only when an approval exists and every approved hash still matches the + stored proposal. Targets excluded at approval time are simply not migrated. + """ + record = load(connection) + if record is None: + return { + "ok": False, + "why": f"No approval exists for {connection!r}. Run: firstsync approve {connection}", + } + proposals = ProposalStore(connection).load() + stale = sorted( + t + for t, digest in record["proposal_sha256_16"].items() + if proposal_hash(proposals.get(t, {})) != digest + ) + if stale: + return { + "ok": False, + "why": ( + "Proposals changed after approval for: " + + ", ".join(stale) + + f". Approve again: firstsync approve {connection}" + ), + } + return {"ok": True, "approved": record} diff --git a/src/firstsync/cli.py b/src/firstsync/cli.py index 8a8d34b..18beb66 100644 --- a/src/firstsync/cli.py +++ b/src/firstsync/cli.py @@ -1,12 +1,16 @@ """The firstsync command. -Three subcommands an administrator or a developer actually needs: +The subcommands an administrator or a developer actually needs: firstsync serve run the MCP server on stdio (what Claude talks to) firstsync dryrun ORG [--limit] run stored proposals over real records, write nothing + firstsync proposals ORG list stored proposals and their approval state + firstsync approve ORG approve the proposals as they stand (human-only gate) + firstsync migrate ORG --db PATH run the approved migration into the target database firstsync audit [--last N] show the last audit-log entries -Everything else happens through Claude; the CLI is the deterministic side. +Approval and migration are deliberately CLI commands, not MCP tools: the model proposes; +a person authorizes. """ from __future__ import annotations @@ -15,8 +19,10 @@ import json import sys -from firstsync import audit, dryrun +from firstsync import approval, audit, dryrun, migrate from firstsync.connections import get_client +from firstsync.mapping import ProposalStore +from firstsync.target.db import TargetDB def main(argv: list[str] | None = None) -> int: @@ -29,6 +35,20 @@ def main(argv: list[str] | None = None) -> int: run.add_argument("connection") run.add_argument("--limit", type=int, default=dryrun.PREVIEW_LIMIT) + props = sub.add_parser("proposals", help="List stored proposals and approval state.") + props.add_argument("connection") + + appr = sub.add_parser("approve", help="Approve the stored proposals as they stand.") + appr.add_argument("connection") + appr.add_argument("--except", dest="excluded", default="", + help="Comma-separated target fields to leave out of the approval.") + appr.add_argument("--by", default=None, help="Name to record as the approver.") + + mig = sub.add_parser("migrate", help="Run the approved migration.") + mig.add_argument("connection") + mig.add_argument("--db", required=True, help="SQLite database path (created if absent).") + mig.add_argument("--limit", type=int, default=dryrun.SCAN_LIMIT) + log = sub.add_parser("audit", help="Show the last audit-log entries.") log.add_argument("--last", type=int, default=20) @@ -50,6 +70,46 @@ def main(argv: list[str] | None = None) -> int: blocked = sum(t.blocking for t in result.tables) return 1 if blocked else 0 + if args.command == "proposals": + stored = ProposalStore(args.connection).load() + if not stored: + print(f"No proposals stored for {args.connection!r}.", file=sys.stderr) + return 2 + gate = approval.check(args.connection) + state = "APPROVED" if gate["ok"] else gate["why"] + print(f"{len(stored)} proposals for {args.connection} [{state}]") + for target, p in sorted(stored.items()): + question = " ASKS" if p.get("question_for_admin") else "" + print(f" {target:<28} <- {p.get('source') or '(nothing)':<28} " + f"{p.get('confidence', '')}{question}") + return 0 + + if args.command == "approve": + excluded = [t for t in args.excluded.split(",") if t] + try: + record = approval.approve(args.connection, excluded, args.by) + except ValueError as exc: + print(str(exc), file=sys.stderr) + return 2 + print(f"Approved {len(record['proposal_sha256_16'])} proposals for " + f"{args.connection} as {record['approved_by']}.") + if record["open_questions"]: + print("Open questions you are approving past (the dry-run flags these rows):") + for target in record["open_questions"]: + print(f" {target}") + return 0 + + if args.command == "migrate": + db = TargetDB(args.db) + try: + outcome = migrate.run_migration( + get_client(args.connection), args.connection, db, args.limit + ) + finally: + db.close() + print(json.dumps(migrate.status_summary(outcome), indent=2)) + return 0 if outcome.status == "completed" else 1 + path = audit.log_path() if not path.is_file(): print("No audit log yet.", file=sys.stderr) diff --git a/src/firstsync/dryrun.py b/src/firstsync/dryrun.py index a7c50c7..ec15571 100644 --- a/src/firstsync/dryrun.py +++ b/src/firstsync/dryrun.py @@ -159,32 +159,38 @@ def run_dry_run( ) -def _one_record( +class Issue(BaseModel): + """One field of one record that did not come out clean.""" + + target: str + reason: str + severity: Severity + source_field: str | None + + +def build_row( record: dict[str, Any], - record_id: str, fields: dict[str, dict[str, Any]], mapped: dict[str, dict[str, Any] | None], source_object: str, - treatments: dict[str, str], - table: str, - groups: dict[tuple[str, str], FailureGroup], - result: TableResult, - rows: list[tuple[str, dict[str, Any]]], - shown: list[dict[str, Any]], -) -> None: +) -> tuple[dict[str, Any], str, list[Issue]]: + """Build one target row the way the migration would, and judge it. + + This is the single row builder: the dry-run and the migration both call it, so what + the dry-run showed the administrator is exactly what the migration will do. + """ + table = next(iter(fields.values())).get("_table", "") if fields else "" row: dict[str, Any] = {} - visible_row: dict[str, Any] = {} status = "clean" + issues: list[Issue] = [] for name, field in fields.items(): proposal = mapped[name] - target = f"{table}.{name}" if proposal is None: value, failure = None, None reason = check_target_value(field, None) - treatment = "pass" + src = None else: obj, src = _split(proposal.get("source")) - treatment = treatments.get(src or "", "pass") if obj else "pass" raw = record.get(src) if obj == source_object and src else None failure, reason, value = None, None, None if obj is not None and obj != source_object: @@ -197,20 +203,52 @@ def _one_record( failure, reason = exc, str(exc) if reason is None: row[name] = value - hidden = treatment in ("shape", "summary") or _uses_concat(proposal) - visible_row[name] = display("shape", value) if hidden else value continue severity = _severity(field, failure or RuleFailure(reason)) if RANK[severity] > RANK[status]: status = severity - source_field = _split((proposal or {}).get("source"))[1] - shown_input = display(treatment, record.get(source_field or "")) - group = groups.setdefault( - (target, reason), - FailureGroup( - target=target, + issues.append( + Issue( + target=f"{table}.{name}" if table else name, reason=reason, severity=severity, + source_field=src, + ) + ) + return row, status, issues + + +def _one_record( + record: dict[str, Any], + record_id: str, + fields: dict[str, dict[str, Any]], + mapped: dict[str, dict[str, Any] | None], + source_object: str, + treatments: dict[str, str], + table: str, + groups: dict[tuple[str, str], FailureGroup], + result: TableResult, + rows: list[tuple[str, dict[str, Any]]], + shown: list[dict[str, Any]], +) -> None: + named = {n: {**f, "_table": table} for n, f in fields.items()} + row, status, issues = build_row(record, named, mapped, source_object) + visible_row: dict[str, Any] = {} + for name, value in row.items(): + proposal = mapped[name] + src = _split((proposal or {}).get("source"))[1] + treatment = treatments.get(src or "", "pass") + hidden = treatment in ("shape", "summary") or _uses_concat(proposal) + visible_row[name] = display("shape", value) if hidden else value + for issue in issues: + treatment = treatments.get(issue.source_field or "", "pass") + shown_input = display(treatment, record.get(issue.source_field or "")) + group = groups.setdefault( + (issue.target, issue.reason), + FailureGroup( + target=issue.target, + reason=issue.reason, + severity=issue.severity, count=0, record_ids=[], example_input=shown_input, diff --git a/src/firstsync/mcp_server.py b/src/firstsync/mcp_server.py index 8459b50..aea913e 100644 --- a/src/firstsync/mcp_server.py +++ b/src/firstsync/mcp_server.py @@ -16,7 +16,7 @@ from mcp.server.mcpserver import MCPServer from mcp.server.mcpserver.exceptions import ToolError -from firstsync import audit, dryrun, tools +from firstsync import audit, dryrun, migrate, tools from firstsync.config import get_settings from firstsync.connections import get_client from firstsync.rules import RULE_HELP @@ -43,6 +43,7 @@ "mapping_propose", "dryrun_start", "dryrun_get_results", + "migration_get_status", ) _calls = 0 @@ -221,6 +222,26 @@ def dryrun_get_results(connection: str, run_id: str | None = None) -> dict[str, ) +MIGRATION_STATUS_DOC = ( + "Return the result of a stored migration run for a connection: the latest, or " + "'run_id' for a specific run. Counts per table (inserted, updated, unchanged), the " + "record Ids that were skipped and why, and who approved the migration and when. " + "Read-only: there is no tool that approves proposals or starts a migration — both " + "happen at the CLI, by a person." +) + + +@server.tool(description=MIGRATION_STATUS_DOC) +def migration_get_status(connection: str, run_id: str | None = None) -> dict[str, Any]: + return _logged( + "migration_get_status", + "migrate", + connection, + {"run_id": run_id}, + lambda: migrate.status_summary(migrate.load(connection, run_id)), + ) + + def main() -> None: server.run("stdio") diff --git a/src/firstsync/migrate.py b/src/firstsync/migrate.py new file mode 100644 index 0000000..5e7517c --- /dev/null +++ b/src/firstsync/migrate.py @@ -0,0 +1,192 @@ +"""The migration engine. + +Runs only after a human approval (approval.check), builds every row with the same +build_row the dry-run used, and upserts into the target database. Re-running is safe by +construction: the upsert key is (tenant, external_id), so the second run of the same +data reports everything `unchanged` and writes nothing new. + +What is skipped is as important as what is loaded: + + blocking the record cannot load; its Ids go in the report + needs_decision an administrator has not decided yet; skipped, reported + excluded the whole table, when approval excluded its external_id mapping + +A `warning` record loads with the warned value left out — exactly what the dry-run told +the administrator would happen. +""" + +from __future__ import annotations + +import json +import uuid +from collections import Counter +from datetime import UTC, datetime +from pathlib import Path +from typing import Any, Literal + +from pydantic import BaseModel, Field + +from firstsync import approval +from firstsync.config import get_settings +from firstsync.dryrun import SCAN_LIMIT, _split, build_row +from firstsync.mapping import ProposalStore +from firstsync.salesforce import ObjectNotAccessible, SalesforceClient +from firstsync.salesforce.rest import UNSAMPLED_TYPES +from firstsync.target import TARGET_SCHEMA +from firstsync.target.db import TargetDB, tenant_id + + +class TableMigration(BaseModel): + table: str + source_object: str | None = None + read: int = 0 + inserted: int = 0 + updated: int = 0 + unchanged: int = 0 + skipped_blocking: list[str] = Field(default_factory=list) + skipped_needs_decision: list[str] = Field(default_factory=list) + warnings: int = 0 + not_runnable: str | None = None + + +class Migration(BaseModel): + run_id: str + connection: str + tenant_id: str + started_at: str + approved_by: str + approved_at: str + status: Literal["completed", "refused"] + refused_because: str | None = None + tables: list[TableMigration] = Field(default_factory=list) + + def totals(self) -> dict[str, int]: + c: Counter[str] = Counter() + for t in self.tables: + c.update( + read=t.read, + inserted=t.inserted, + updated=t.updated, + unchanged=t.unchanged, + skipped=len(t.skipped_blocking) + len(t.skipped_needs_decision), + ) + return dict(c) + + +def run_migration( + client: SalesforceClient, + connection: str, + db: TargetDB, + limit: int = SCAN_LIMIT, +) -> Migration: + """The only entry point. Refuses without a valid, current human approval.""" + gate = approval.check(connection) + base: dict[str, Any] = dict( + run_id=uuid.uuid4().hex[:12], + connection=connection, + tenant_id=tenant_id(connection), + started_at=datetime.now(UTC).isoformat(timespec="seconds"), + ) + if not gate["ok"]: + return Migration( + **base, approved_by="", approved_at="", status="refused", + refused_because=gate["why"], + ) + record = gate["approved"] + migration = Migration( + **base, + approved_by=record["approved_by"], + approved_at=record["approved_at"], + status="completed", + ) + proposals = ProposalStore(connection).load() + excluded = set(record["excluded"]) + tenant = migration.tenant_id + + for table, spec in TARGET_SCHEMA["tables"].items(): + fields = {f["name"]: {**f, "_table": table} for f in spec["fields"]} + mapped = { + name: (None if f"{table}.{name}" in excluded else proposals.get(f"{table}.{name}")) + for name in fields + } + source_object, _ = _split((mapped["external_id"] or {}).get("source")) + result = TableMigration(table=table, source_object=source_object) + migration.tables.append(result) + if source_object is None: + result.not_runnable = ( + "No approved source for external_id, so no record can be migrated." + ) + continue + try: + describe = client.describe(source_object) + except ObjectNotAccessible as exc: + result.not_runnable = str(exc) + continue + names = [f["name"] for f in describe["fields"] if f.get("type") not in UNSAMPLED_TYPES] + for record_ in client.sample(source_object, names, limit): + result.read += 1 + record_id = str(record_.get("Id")) + row, status, _issues = build_row(record_, fields, mapped, source_object) + if status == "blocking": + result.skipped_blocking.append(record_id) + continue + if status == "needs_decision": + result.skipped_needs_decision.append(record_id) + continue + if status == "warning": + result.warnings += 1 + outcome = db.upsert(table, tenant, row) + setattr(result, outcome, getattr(result, outcome) + 1) + db.commit() + + save(migration) + return migration + + +# --- storage ---------------------------------------------------------------------------- + + +def _folder(connection: str) -> Path: + return get_settings().state_dir / "migrations" / connection + + +def save(migration: Migration) -> Path: + folder = _folder(migration.connection) + folder.mkdir(parents=True, exist_ok=True) + path = folder / f"{migration.run_id}.json" + path.write_text(migration.model_dump_json(indent=2) + "\n", encoding="utf-8") + (folder / "latest").write_text(migration.run_id, encoding="utf-8") + return path + + +def load(connection: str, run_id: str | None = None) -> Migration: + folder = _folder(connection) + if run_id is None: + pointer = folder / "latest" + if not pointer.is_file(): + raise ValueError(f"No migration has been run for {connection!r}.") + run_id = pointer.read_text(encoding="utf-8").strip() + if not run_id.isalnum(): + raise ValueError("Not a valid migration run id.") + path = folder / f"{run_id}.json" + if not path.is_file(): + raise ValueError(f"No migration {run_id!r} for {connection!r}.") + return Migration.model_validate(json.loads(path.read_text(encoding="utf-8"))) + + +def status_summary(migration: Migration) -> dict[str, Any]: + """What the model may see: counts and reasons, read-only.""" + return { + "run_id": migration.run_id, + "status": migration.status, + "refused_because": migration.refused_because, + "started_at": migration.started_at, + "approved_by": migration.approved_by, + "totals": migration.totals(), + "tables": [t.model_dump() for t in migration.tables], + "note": ( + "Migration runs only after human approval at the CLI; there is no tool that " + "starts it. Skipped record Ids are listed so the administrator can fix and " + "re-run; re-running never duplicates." + ), + } diff --git a/src/firstsync/target/db.py b/src/firstsync/target/db.py new file mode 100644 index 0000000..be0a104 --- /dev/null +++ b/src/firstsync/target/db.py @@ -0,0 +1,97 @@ +"""The target database. + +SQLite by default (stdlib, so tests and CI need no services), Postgres when the DSN says +so (needs the `postgres` extra). The DDL is generated from TARGET_SCHEMA, the same +structure the dry-run validates against, so the three views of the schema — Python, +SQLite, Postgres — cannot drift apart silently. + +Writes are upserts on (tenant_id, external_id): loading the same records twice updates +them in place and never duplicates. That is what makes the whole migration re-runnable. +""" + +from __future__ import annotations + +import sqlite3 +import uuid +from pathlib import Path +from typing import Any + +from firstsync.target.schema import TARGET_SCHEMA + +# Each connection handle maps to one tenant, deterministically. +_TENANT_NS = uuid.UUID("3b2d9d55-6f2a-4bb0-9f52-a1b2c3d4e5f6") + +SQL_TYPES = { + "text": "text", + "email": "text", + "enum": "text", + "date": "text", + "timestamp": "text", + "numeric": "real", +} + + +def tenant_id(connection: str) -> str: + return str(uuid.uuid5(_TENANT_NS, connection)) + + +def ddl() -> list[str]: + """CREATE TABLE statements generated from TARGET_SCHEMA (SQLite dialect).""" + statements = [] + for table, spec in TARGET_SCHEMA["tables"].items(): + columns = ["tenant_id text NOT NULL"] + for field in spec["fields"]: + null = " NOT NULL" if field["required"] else "" + columns.append(f"{field['name']} {SQL_TYPES[field['type']]}{null}") + columns.append("UNIQUE (tenant_id, external_id)") + statements.append( + f"CREATE TABLE IF NOT EXISTS {table} (\n " + ",\n ".join(columns) + "\n)" + ) + return statements + + +class TargetDB: + """A thin writer over the target database. SQLite file path, or ':memory:'.""" + + def __init__(self, path: str | Path): + self._conn = sqlite3.connect(str(path)) + self._conn.execute("PRAGMA foreign_keys = ON") + for statement in ddl(): + self._conn.execute(statement) + self._conn.commit() + + def upsert(self, table: str, tenant: str, row: dict[str, Any]) -> str: + """Insert or update one row; returns 'inserted', 'updated' or 'unchanged'.""" + if table not in TARGET_SCHEMA["tables"]: + raise ValueError(f"No such target table: {table!r}.") + names = [f["name"] for f in TARGET_SCHEMA["tables"][table]["fields"]] + values = {n: row.get(n) for n in names} + existing = self._conn.execute( + f"SELECT {', '.join(names)} FROM {table} WHERE tenant_id = ? AND external_id = ?", + (tenant, values["external_id"]), + ).fetchone() + if existing is not None and list(existing) == [values[n] for n in names]: + return "unchanged" + placeholders = ", ".join("?" for _ in names) + updates = ", ".join(f"{n} = excluded.{n}" for n in names if n != "external_id") + self._conn.execute( + f"INSERT INTO {table} (tenant_id, {', '.join(names)}) " + f"VALUES (?, {placeholders}) " + f"ON CONFLICT (tenant_id, external_id) DO UPDATE SET {updates}", + (tenant, *[values[n] for n in names]), + ) + return "updated" if existing is not None else "inserted" + + def count(self, table: str, tenant: str) -> int: + if table not in TARGET_SCHEMA["tables"]: + raise ValueError(f"No such target table: {table!r}.") + result = self._conn.execute( + f"SELECT COUNT(*) FROM {table} WHERE tenant_id = ?", (tenant,) + ) + return int(result.fetchone()[0]) + + def commit(self) -> None: + self._conn.commit() + + def close(self) -> None: + self._conn.close() diff --git a/tests/test_migrate.py b/tests/test_migrate.py new file mode 100644 index 0000000..c045c71 --- /dev/null +++ b/tests/test_migrate.py @@ -0,0 +1,192 @@ +"""The approval gate and the migration engine. + +The properties that matter: + - no approval, no migration — ever + - a changed proposal invalidates the approval that covered it + - the migration loads exactly what the dry-run said it would + - re-running changes nothing (idempotent by upsert key) +""" + +from __future__ import annotations + +import json + +import pytest +from hypothesis import given, settings +from hypothesis import strategies as st + +from firstsync import approval, migrate +from firstsync.connections import get_client +from firstsync.dryrun import run_dry_run +from firstsync.mapping import ProposalStore +from firstsync.target.db import TargetDB, ddl, tenant_id + + +def proposals_for(org: str) -> dict: + data = json.load(open("results/claude-claude-sonnet-5-5.json", encoding="utf-8")) + return data["orgs"][org]["runs"][0]["proposals"] + + +@pytest.fixture(autouse=True) +def state(tmp_path, monkeypatch): + monkeypatch.setenv("FIRSTSYNC_STATE_DIR", str(tmp_path)) + return tmp_path + + +@pytest.fixture() +def org_d_approved(): + ProposalStore("org_d").save(proposals_for("org_d")) + approval.approve("org_d", approved_by="test-admin") + return get_client("org_d") + + +# --- the gate --------------------------------------------------------------------------- + + +def test_no_approval_no_migration(): + ProposalStore("org_d").save(proposals_for("org_d")) + db = TargetDB(":memory:") + result = migrate.run_migration(get_client("org_d"), "org_d", db) + assert result.status == "refused" + assert "No approval" in (result.refused_because or "") + assert db.count("contacts", tenant_id("org_d")) == 0 + + +def test_changed_proposal_invalidates_approval(org_d_approved): + props = ProposalStore("org_d").load() + props["contacts.email"] = {**props["contacts.email"], "source": "Contact.Phone"} + ProposalStore("org_d").save(props) + db = TargetDB(":memory:") + result = migrate.run_migration(org_d_approved, "org_d", db) + assert result.status == "refused" + assert "contacts.email" in (result.refused_because or "") + assert db.count("contacts", tenant_id("org_d")) == 0 + + +def test_approve_requires_proposals(): + with pytest.raises(ValueError, match="No proposals"): + approval.approve("org_never") + + +def test_approve_rejects_unknown_exclusion(): + ProposalStore("org_d").save(proposals_for("org_d")) + with pytest.raises(ValueError, match="unknown target"): + approval.approve("org_d", excluded=["contacts.nonsense"]) + + +def test_approval_records_open_questions(): + ProposalStore("org_d").save(proposals_for("org_d")) + record = approval.approve("org_d") + asked = { + t for t, p in proposals_for("org_d").items() if p.get("question_for_admin") + } + assert set(record["open_questions"]) == asked + + +# --- the migration ---------------------------------------------------------------------- + + +def test_migration_matches_the_dry_run(org_d_approved): + props = ProposalStore("org_d").load() + dry = run_dry_run(org_d_approved, "org_d", props, limit=2000) + db = TargetDB(":memory:") + result = migrate.run_migration(org_d_approved, "org_d", db) + assert result.status == "completed" + by_table = {t.table: t for t in result.tables} + for d in dry.tables: + m = by_table[d.table] + # Loaded = clean + warning; skipped = blocking + needs_decision. Exactly. + assert m.inserted == d.clean + d.warning + assert len(m.skipped_blocking) == d.blocking + assert len(m.skipped_needs_decision) == d.needs_decision + assert m.warnings == d.warning + assert db.count(d.table, tenant_id("org_d")) == m.inserted + + +def test_migration_is_idempotent(org_d_approved): + db = TargetDB(":memory:") + first = migrate.run_migration(org_d_approved, "org_d", db) + second = migrate.run_migration(org_d_approved, "org_d", db) + assert first.totals()["inserted"] > 0 + assert second.totals()["inserted"] == 0 + assert second.totals()["updated"] == 0 + assert second.totals()["unchanged"] == first.totals()["inserted"] + for t in first.tables: + assert db.count(t.table, tenant_id("org_d")) == t.inserted + + +def test_excluded_table_is_not_migrated(): + ProposalStore("org_d").save(proposals_for("org_d")) + approval.approve("org_d", excluded=["activities.external_id"]) + db = TargetDB(":memory:") + result = migrate.run_migration(get_client("org_d"), "org_d", db) + activities = next(t for t in result.tables if t.table == "activities") + assert activities.not_runnable is not None + assert db.count("activities", tenant_id("org_d")) == 0 + assert db.count("accounts", tenant_id("org_d")) > 0 + + +def test_save_and_load_roundtrip(org_d_approved): + db = TargetDB(":memory:") + result = migrate.run_migration(org_d_approved, "org_d", db) + assert migrate.load("org_d") == result + assert migrate.load("org_d", result.run_id) == result + with pytest.raises(ValueError): + migrate.load("org_d", "../escape") + summary = migrate.status_summary(result) + assert summary["totals"]["inserted"] == 387 + + +# --- the database ----------------------------------------------------------------------- + + +def test_ddl_covers_every_table(): + statements = ddl() + assert len(statements) == 4 + assert all("UNIQUE (tenant_id, external_id)" in s for s in statements) + + +def test_upsert_outcomes(): + db = TargetDB(":memory:") + row = {"external_id": "x1", "name": "Acme", "industry": None, "tier": None, + "website": None, "customer_since": None, "owner_email": None} + tenant = tenant_id("t") + assert db.upsert("accounts", tenant, row) == "inserted" + assert db.upsert("accounts", tenant, row) == "unchanged" + assert db.upsert("accounts", tenant, {**row, "industry": "software"}) == "updated" + assert db.count("accounts", tenant) == 1 + with pytest.raises(ValueError): + db.upsert("nonsense", tenant, row) + + +def test_tenants_are_isolated(): + db = TargetDB(":memory:") + row = {"external_id": "x1", "name": "Acme", "industry": None, "tier": None, + "website": None, "customer_since": None, "owner_email": None} + db.upsert("accounts", tenant_id("a"), row) + db.upsert("accounts", tenant_id("b"), row) + assert db.count("accounts", tenant_id("a")) == 1 + assert db.count("accounts", tenant_id("b")) == 1 + + +# --- property-based --------------------------------------------------------------------- + + +@settings(max_examples=15, deadline=None) +@given(runs=st.integers(min_value=2, max_value=4), limit=st.integers(min_value=10, max_value=300)) +def test_n_runs_equal_one_run(tmp_path_factory, runs: int, limit: int) -> None: + import os + + tmp = tmp_path_factory.mktemp("state") + os.environ["FIRSTSYNC_STATE_DIR"] = str(tmp) + ProposalStore("org_d").save(proposals_for("org_d")) + approval.approve("org_d", approved_by="prop") + client = get_client("org_d") + db = TargetDB(":memory:") + results = [migrate.run_migration(client, "org_d", db, limit) for _ in range(runs)] + inserted = results[0].totals()["inserted"] + for later in results[1:]: + assert later.totals()["inserted"] == 0 + assert later.totals()["unchanged"] == inserted + for t in results[0].tables: + assert db.count(t.table, tenant_id("org_d")) == t.inserted diff --git a/tests/test_server.py b/tests/test_server.py index ed19c17..6b65187 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -23,6 +23,7 @@ def test_server_exposes_exactly_the_expected_tools(): "dryrun_get_results", "dryrun_start", "mapping_propose", + "migration_get_status", "rule_test", "sf_check_access", "sf_count_records",