From 3608b5d8de42c403bd4d753ecaa1ee4aad78f3b3 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 15:34:57 -0600 Subject: [PATCH] Week 3: deterministic dry-run engine, defect scoring, production hardening The dry-run engine (src/firstsync/dryrun.py) executes stored mapping proposals over real records without writing anything. Every record is built the way the migration would build it and classified clean / warning / needs_decision / blocking; failures are grouped by target field and root cause with masked examples; natural-key collisions are reported as likely duplicates. Two new MCP tools: dryrun_start and dryrun_get_results. The evaluation now scores the whole pipeline, not just the mappings: score_defects checks that the dry-run catches the defects planted in org D. Rescoring both saved result sets: Sonnet 5.5 and Haiku 5.5 both catch 4/4 (duplicates, missing emails, missing amounts, short phones). Production-Python items from the course syllabus, built in rather than bolted on: - typed settings via pydantic-settings (FIRSTSYNC_* env), with a process-wide run ID stamped on every audit line - mypy strict-ish config, clean on src, added to CI - REST client retries 429/5xx with exponential backoff and full jitter; 400s never retried; reads are idempotent so retrying is safe - dead-letter path: a record that crashes the engine is filed and counted, never silently dropped and never fatal to the scan - property-based tests (Hypothesis): any limit is safe, re-running never changes the verdict - CLI entry point: `firstsync dryrun ` exits non-zero when anything blocks, so it can gate a pipeline 185 tests, no network, no API key. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_017ggB2HHn8zjybwfaJG1g3R --- .github/workflows/ci.yml | 1 + README.md | 31 ++- pyproject.toml | 18 +- results/claude-claude-haiku-5-5.json | 87 +++++-- results/claude-claude-sonnet-5-5.json | 75 +++++- scripts/run_eval.py | 25 ++ src/firstsync/audit.py | 9 +- src/firstsync/cli.py | 64 +++++ src/firstsync/config.py | 35 +++ src/firstsync/connections.py | 5 +- src/firstsync/dryrun.py | 321 ++++++++++++++++++++++++++ src/firstsync/eval/defects.py | 55 +++++ src/firstsync/mapping.py | 6 +- src/firstsync/masking.py | 5 + src/firstsync/mcp_server.py | 47 +++- src/firstsync/rules.py | 8 +- src/firstsync/salesforce/rest.py | 47 +++- src/firstsync/target/schema.py | 6 +- tests/test_dryrun.py | 116 ++++++++++ tests/test_server.py | 2 + 20 files changed, 907 insertions(+), 56 deletions(-) create mode 100644 src/firstsync/cli.py create mode 100644 src/firstsync/config.py create mode 100644 src/firstsync/dryrun.py create mode 100644 src/firstsync/eval/defects.py create mode 100644 tests/test_dryrun.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f29ef1e..2ade5c0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,4 +18,5 @@ jobs: python-version: "3.12" - run: pip install -e ".[dev]" - run: ruff check . + - run: mypy src - run: pytest -q diff --git a/README.md b/README.md index 8694d8c..53cf5e1 100644 --- a/README.md +++ b/README.md @@ -8,10 +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 2 of 6.** Claude can inspect an org and propose a validated mapping for -> every target field, and an evaluation scores those proposals against answer keys for -> six synthetic orgs. Dry-run, approval, migration and sync are not built yet. This is a -> reference implementation with no customers. See +> **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 > [What is and is not tested](#what-is-and-is-not-tested). ## The rule the design is built on @@ -30,7 +34,7 @@ The full design is in [docs/SPEC.md](docs/SPEC.md). ## What works today -Seven tools, served from one MCP server: +Nine tools, served from one MCP server: | Tool | What it does | | --- | --- | @@ -41,6 +45,20 @@ Seven tools, served from one MCP server: | `target_get_schema` | The target app's tables, fields, allowed values and required fields | | `rule_test` | Runs a transformation rule on a sample and reports what failed and why | | `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 | + +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 +would be dropped), **needs_decision** (an unmapped picklist value the administrator must +rule on) or **blocking** (the record cannot load). Failures are grouped by target field +and reason — fifty records failing for one cause read as one finding — with source +record Ids kept and example values masked. Records that would collide on a table's +natural key (account name, contact email) are reported as likely duplicates. A record +that crashes the engine is written to a dead-letter file and counted, never silently +dropped, and the REST client retries transient failures with exponential backoff and +jitter. There is also a CLI: `firstsync dryrun ` exits non-zero if anything blocks, +so it can gate a pipeline. Six synthetic Salesforce orgs, each with an answer key: @@ -64,7 +82,7 @@ Pythons refuse installs outside one. python3 -m venv .venv source .venv/bin/activate pip install -e ".[dev]" -pytest -q # 174 tests, no network, no API key +pytest -q # 185 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 ``` @@ -233,6 +251,7 @@ administrator, and neither can a low-confidence mapping or a required field with | Part | Tested how | | --- | --- | | 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 | | 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/pyproject.toml b/pyproject.toml index 8c7d321..e4b572a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,11 +12,16 @@ license = { text = "Apache-2.0" } dependencies = [ "mcp>=2,<3", "httpx>=0.27", + "pydantic>=2.7", + "pydantic-settings>=2.2", ] +[project.scripts] +firstsync = "firstsync.cli:main" + [project.optional-dependencies] agent = ["claude-agent-sdk>=0.2"] -dev = ["pytest>=8", "ruff>=0.6"] +dev = ["pytest>=8", "ruff>=0.6", "mypy>=1.10", "hypothesis>=6.100"] [tool.setuptools.packages.find] where = ["src"] @@ -33,3 +38,14 @@ target-version = "py311" [tool.ruff.lint] select = ["E", "F", "I", "B", "UP"] + +[tool.mypy] +python_version = "3.11" +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true +check_untyped_defs = true + +[[tool.mypy.overrides]] +module = ["mcp.*", "claude_agent_sdk.*"] +ignore_missing_imports = true diff --git a/results/claude-claude-haiku-5-5.json b/results/claude-claude-haiku-5-5.json index ab63ca1..48d6f15 100644 --- a/results/claude-claude-haiku-5-5.json +++ b/results/claude-claude-haiku-5-5.json @@ -231,7 +231,7 @@ "seconds": 58.2, "cost_usd": 0.013272869999999999, "tool_calls": 19, - "is_error": false, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "high", @@ -952,7 +952,7 @@ "seconds": 48.6, "cost_usd": 0.011559305, "tool_calls": 18, - "is_error": false, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "high", @@ -1677,7 +1677,7 @@ "seconds": 50.4, "cost_usd": 0.011660684999999999, "tool_calls": 20, - "is_error": false, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "high", @@ -2407,7 +2407,7 @@ "seconds": 68.7, "cost_usd": 0.015237024999999998, "tool_calls": 23, - "is_error": false, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "low", @@ -3158,7 +3158,7 @@ "seconds": 53.8, "cost_usd": 0.012514434999999999, "tool_calls": 20, - "is_error": false, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "low", @@ -3894,7 +3894,7 @@ "seconds": 79.8, "cost_usd": 0.016670515, "tool_calls": 22, - "is_error": false, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "low", @@ -4637,7 +4637,7 @@ "seconds": 56.4, "cost_usd": 0.012831579999999999, "tool_calls": 19, - "is_error": false, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "high", @@ -5362,7 +5362,7 @@ "seconds": 63.6, "cost_usd": 0.01379824, "tool_calls": 20, - "is_error": false, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "high", @@ -6091,7 +6091,7 @@ "seconds": 61.5, "cost_usd": 0.012992345000000002, "tool_calls": 20, - "is_error": false, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "medium", @@ -6824,7 +6824,25 @@ "seconds": 56.7, "cost_usd": 0.01273169, "tool_calls": 18, - "is_error": false, + "dryrun_defects": { + "duplicate_contacts": { + "planted": 6, + "found": 6 + }, + "missing_email": { + "planted": 5, + "found": 5 + }, + "missing_amount": { + "planted": 4, + "found": 4 + }, + "short_phone": { + "planted": 3, + "found": 3 + }, + "defects_found": "4/4" + }, "proposals": { "accounts.customer_since": { "confidence": "medium", @@ -7560,7 +7578,25 @@ "seconds": 60.0, "cost_usd": 0.013467749999999999, "tool_calls": 19, - "is_error": false, + "dryrun_defects": { + "duplicate_contacts": { + "planted": 6, + "found": 6 + }, + "missing_email": { + "planted": 5, + "found": 5 + }, + "missing_amount": { + "planted": 4, + "found": 4 + }, + "short_phone": { + "planted": 3, + "found": 3 + }, + "defects_found": "4/4" + }, "proposals": { "accounts.customer_since": { "confidence": "medium", @@ -8293,7 +8329,25 @@ "seconds": 69.1, "cost_usd": 0.01488839, "tool_calls": 20, - "is_error": false, + "dryrun_defects": { + "duplicate_contacts": { + "planted": 6, + "found": 6 + }, + "missing_email": { + "planted": 5, + "found": 5 + }, + "missing_amount": { + "planted": 4, + "found": 4 + }, + "short_phone": { + "planted": 3, + "found": 3 + }, + "defects_found": "4/4" + }, "proposals": { "accounts.customer_since": { "confidence": "medium", @@ -9027,7 +9081,7 @@ "seconds": 60.9, "cost_usd": 0.015198864999999999, "tool_calls": 23, - "is_error": false, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "high", @@ -9782,7 +9836,7 @@ "seconds": 57.0, "cost_usd": 0.014463805, "tool_calls": 22, - "is_error": false, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "high", @@ -10553,7 +10607,7 @@ "seconds": 66.5, "cost_usd": 0.01553959, "tool_calls": 22, - "is_error": false, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "high", @@ -11098,5 +11152,6 @@ ] } }, - "mean_accuracy": 0.9885 + "mean_accuracy": 0.9885, + "rescored": "2026-11-13T21:33:57+00:00" } diff --git a/results/claude-claude-sonnet-5-5.json b/results/claude-claude-sonnet-5-5.json index b5e221c..267c3a2 100644 --- a/results/claude-claude-sonnet-5-5.json +++ b/results/claude-claude-sonnet-5-5.json @@ -231,6 +231,7 @@ "seconds": 36.8, "cost_usd": 0.15220200000000003, "tool_calls": 17, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "high", @@ -844,6 +845,7 @@ "seconds": 33.3, "cost_usd": 0.13517880000000002, "tool_calls": 17, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "high", @@ -1456,6 +1458,7 @@ "seconds": 33.7, "cost_usd": 0.13180830000000002, "tool_calls": 17, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "high", @@ -2074,6 +2077,7 @@ "seconds": 45.1, "cost_usd": 0.1749764, "tool_calls": 20, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "low", @@ -2716,6 +2720,7 @@ "seconds": 44.7, "cost_usd": 0.17208710000000002, "tool_calls": 20, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "low", @@ -3359,6 +3364,7 @@ "seconds": 42.5, "cost_usd": 0.1627678, "tool_calls": 19, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "low", @@ -3999,6 +4005,7 @@ "seconds": 45.0, "cost_usd": 0.16382210000000003, "tool_calls": 18, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "high", @@ -4728,6 +4735,7 @@ "seconds": 44.2, "cost_usd": 0.16247129999999999, "tool_calls": 18, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "high", @@ -5468,6 +5476,7 @@ "seconds": 44.7, "cost_usd": 0.16168500000000002, "tool_calls": 18, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "high", @@ -6211,6 +6220,25 @@ "seconds": 43.8, "cost_usd": 0.1495617, "tool_calls": 18, + "dryrun_defects": { + "duplicate_contacts": { + "planted": 6, + "found": 6 + }, + "missing_email": { + "planted": 5, + "found": 5 + }, + "missing_amount": { + "planted": 4, + "found": 4 + }, + "short_phone": { + "planted": 3, + "found": 3 + }, + "defects_found": "4/4" + }, "proposals": { "accounts.customer_since": { "confidence": "medium", @@ -6833,6 +6861,25 @@ "seconds": 45.6, "cost_usd": 0.1590654, "tool_calls": 18, + "dryrun_defects": { + "duplicate_contacts": { + "planted": 6, + "found": 6 + }, + "missing_email": { + "planted": 5, + "found": 5 + }, + "missing_amount": { + "planted": 4, + "found": 4 + }, + "short_phone": { + "planted": 3, + "found": 3 + }, + "defects_found": "4/4" + }, "proposals": { "accounts.customer_since": { "confidence": "medium", @@ -7550,6 +7597,25 @@ "seconds": 41.4, "cost_usd": 0.14739739999999998, "tool_calls": 18, + "dryrun_defects": { + "duplicate_contacts": { + "planted": 6, + "found": 6 + }, + "missing_email": { + "planted": 5, + "found": 5 + }, + "missing_amount": { + "planted": 4, + "found": 4 + }, + "short_phone": { + "planted": 3, + "found": 3 + }, + "defects_found": "4/4" + }, "proposals": { "accounts.customer_since": { "confidence": "medium", @@ -8184,7 +8250,7 @@ "seconds": 44.4, "cost_usd": 0.1912681, "tool_calls": 20, - "is_error": false, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "high", @@ -8906,7 +8972,7 @@ "seconds": 39.5, "cost_usd": 0.1669702, "tool_calls": 19, - "is_error": false, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "high", @@ -9542,7 +9608,7 @@ "seconds": 45.3, "cost_usd": 0.182155, "tool_calls": 20, - "is_error": false, + "dryrun_defects": null, "proposals": { "accounts.customer_since": { "confidence": "high", @@ -10046,5 +10112,6 @@ } }, "date": "2026-11-13T13:00:36+00:00", - "mean_accuracy": 1.0 + "mean_accuracy": 1.0, + "rescored": "2026-11-13T21:33:51+00:00" } diff --git a/scripts/run_eval.py b/scripts/run_eval.py index 5a15e5a..7ba06ab 100644 --- a/scripts/run_eval.py +++ b/scripts/run_eval.py @@ -23,8 +23,10 @@ from firstsync import mapping from firstsync.agent import MAP_SYSTEM, prompt_hash, run_agent from firstsync.connections import get_client +from firstsync.dryrun import run_dry_run from firstsync.env import load_dotenv from firstsync.eval.baseline import baseline_mappings +from firstsync.eval.defects import score_defects from firstsync.eval.score import OUTCOMES, score from firstsync.orgs.answer_keys import ANSWER_KEYS from firstsync.orgs.generate import HELD_OUT @@ -48,9 +50,17 @@ def run_once(org: str, baseline: bool) -> dict: info = {k: outcome.get(k) for k in ("turns", "seconds", "cost_usd", "tool_calls")} info["is_error"] = outcome["is_error"] result = score(ANSWER_KEYS[org], store.load()) + result["dryrun_defects"] = _defects(org, store.load()) return {**result, **info, "proposals": store.load()} +def _defects(org: str, proposals: dict) -> dict | None: + """Run the dry-run over the proposals and check the planted defects were caught.""" + if not (ANSWER_KEYS[org].get("defects") and proposals): + return None + return score_defects(ANSWER_KEYS[org], run_dry_run(get_client(org), org, proposals, 2000)) + + HEADER = ( f"{'org':<7}{'run':>4}{'accuracy':>10}" + "".join(f"{o[:12]:>14}" for o in OUTCOMES) @@ -72,6 +82,18 @@ def row(org: str, n: int, result: dict) -> str: ) +def _print_defects(result: dict) -> None: + d = result.get("dryrun_defects") + if not d: + return + parts = [ + f"{name} {v['found']}/{v['planted']}" + (" MISSED" if v.get("missed_ids") else "") + for name, v in d.items() + if isinstance(v, dict) + ] + print(f" dryrun defects {d['defects_found']}: " + ", ".join(parts)) + + def rescore(path: Path) -> int: """Score the proposals saved in a results file again with the current scorer.""" report = json.loads(path.read_text(encoding="utf-8")) @@ -81,9 +103,11 @@ def rescore(path: Path) -> int: for n, run in enumerate(entry["runs"], start=1): info = {k: run.get(k) for k in ("turns", "seconds", "cost_usd", "tool_calls")} result = {**score(ANSWER_KEYS[org], run["proposals"]), **info} + result["dryrun_defects"] = _defects(org, run["proposals"]) result["proposals"] = run["proposals"] rescored.append(result) print(row(org, n, result)) + _print_defects(result) for target in result["extra_questions"]: print( f" extra question on {target}: " @@ -157,6 +181,7 @@ def main() -> int: result = run_once(org, args.baseline) results.append(result) print(row(org, n, result)) + _print_defects(result) mean = sum(r["accuracy"] for r in results) / len(results) report["orgs"][org] = { "mean_accuracy": round(mean, 4), diff --git a/src/firstsync/audit.py b/src/firstsync/audit.py index db4e43b..733f19f 100644 --- a/src/firstsync/audit.py +++ b/src/firstsync/audit.py @@ -1,23 +1,23 @@ """Append-only log of every tool call. Each line records what was asked and a hash of what was returned, so a reviewer can -confirm which evidence a proposal was built on without storing the evidence twice. +confirm which evidence a proposal was built on without storing the evidence twice. Every +line carries a run ID, so all the calls of one onboarding session can be pulled together. """ from __future__ import annotations import hashlib import json -import os from datetime import UTC, datetime from pathlib import Path from typing import Any -DEFAULT_PATH = ".firstsync/audit.jsonl" +from firstsync.config import get_settings def log_path() -> Path: - return Path(os.environ.get("FIRSTSYNC_AUDIT_LOG", DEFAULT_PATH)) + return get_settings().audit_log def output_hash(result: Any) -> str: @@ -36,6 +36,7 @@ def record( ) -> dict[str, Any]: entry = { "ts": datetime.now(UTC).isoformat(timespec="seconds"), + "run_id": get_settings().run_id, "tool": tool, "stage": stage, "connection": connection, diff --git a/src/firstsync/cli.py b/src/firstsync/cli.py new file mode 100644 index 0000000..8a8d34b --- /dev/null +++ b/src/firstsync/cli.py @@ -0,0 +1,64 @@ +"""The firstsync command. + +Three 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 audit [--last N] show the last audit-log entries + +Everything else happens through Claude; the CLI is the deterministic side. +""" + +from __future__ import annotations + +import argparse +import json +import sys + +from firstsync import audit, dryrun +from firstsync.connections import get_client + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="firstsync", description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + + sub.add_parser("serve", help="Run the MCP server on stdio.") + + run = sub.add_parser("dryrun", help="Dry-run stored proposals for a connection.") + run.add_argument("connection") + run.add_argument("--limit", type=int, default=dryrun.PREVIEW_LIMIT) + + log = sub.add_parser("audit", help="Show the last audit-log entries.") + log.add_argument("--last", type=int, default=20) + + args = parser.parse_args(argv) + + if args.command == "serve": + from firstsync.mcp_server import main as serve + + serve() + return 0 + + if args.command == "dryrun": + try: + result = dryrun.start(get_client(args.connection), args.connection, args.limit) + except ValueError as exc: + print(str(exc), file=sys.stderr) + return 2 + print(json.dumps(dryrun.summary(result), indent=2)) + blocked = sum(t.blocking for t in result.tables) + return 1 if blocked else 0 + + path = audit.log_path() + if not path.is_file(): + print("No audit log yet.", file=sys.stderr) + return 2 + lines = path.read_text(encoding="utf-8").splitlines()[-args.last :] + for line in lines: + print(line) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/firstsync/config.py b/src/firstsync/config.py new file mode 100644 index 0000000..682c735 --- /dev/null +++ b/src/firstsync/config.py @@ -0,0 +1,35 @@ +"""Typed configuration. + +Every setting FirstSync reads from the environment is declared here, with its type and +default, and validated when it is read. Nothing else in the package calls os.environ for +a FIRSTSYNC_ variable. Credentials are deliberately not here: Salesforce tokens are read +only by the client that needs them, and the Anthropic key only by the Agent SDK. +""" + +from __future__ import annotations + +import uuid +from pathlib import Path + +from pydantic import Field +from pydantic_settings import BaseSettings, SettingsConfigDict + +# One ID per process unless FIRSTSYNC_RUN_ID is set, so a parent process and the MCP +# server it starts can share one. +_PROCESS_RUN_ID = uuid.uuid4().hex[:12] + + +class Settings(BaseSettings): + model_config = SettingsConfigDict(env_prefix="FIRSTSYNC_", extra="ignore") + + state_dir: Path = Path(".firstsync") + audit_log: Path = Path(".firstsync/audit.jsonl") + orgs_dir: Path | None = None + run_id: str = Field(default=_PROCESS_RUN_ID, min_length=1, max_length=64) + max_tool_calls: int = Field(default=300, ge=1, le=10_000) + model: str | None = None + + +def get_settings() -> Settings: + """Read the settings now. Not cached, so a changed environment is always honoured.""" + return Settings() diff --git a/src/firstsync/connections.py b/src/firstsync/connections.py index 1e1f4ee..4af499e 100644 --- a/src/firstsync/connections.py +++ b/src/firstsync/connections.py @@ -8,10 +8,10 @@ from __future__ import annotations -import os import re from pathlib import Path +from firstsync.config import get_settings from firstsync.salesforce import FixtureSalesforceClient, RestSalesforceClient, SalesforceClient HANDLE = re.compile(r"^[a-z][a-z0-9_]{0,39}$") @@ -22,8 +22,7 @@ class UnknownConnection(ValueError): def orgs_dir() -> Path: - override = os.environ.get("FIRSTSYNC_ORGS_DIR") - return Path(override) if override else Path(__file__).resolve().parents[2] / "orgs" + return get_settings().orgs_dir or Path(__file__).resolve().parents[2] / "orgs" def available_fixtures() -> list[str]: diff --git a/src/firstsync/dryrun.py b/src/firstsync/dryrun.py new file mode 100644 index 0000000..a7c50c7 --- /dev/null +++ b/src/firstsync/dryrun.py @@ -0,0 +1,321 @@ +"""The dry-run engine. + +Takes the stored mapping proposals for a connection and runs them over real records, +without writing anything anywhere. For every record it builds the row that would be +loaded into the target, checks each value against the target's rules, and records what +went wrong. Failures are grouped by field and reason so that fifty records failing for +one cause read as one finding, not fifty. + +The engine is deterministic: the same proposals over the same records give the same +result. What it returns is safe to show the model. Values are masked exactly as samples +are, and failure reasons never contain the value that failed. Record Ids are kept, +because they are how an administrator finds the record. +""" + +from __future__ import annotations + +import json +import uuid +from collections import defaultdict +from datetime import UTC, datetime +from pathlib import Path +from typing import Any, Literal + +from pydantic import BaseModel, Field + +from firstsync.config import get_settings +from firstsync.mapping import SOURCE, ProposalStore +from firstsync.masking import display, field_treatments +from firstsync.rules import RuleFailure, UnmappedValue, apply_rule, check_target_value +from firstsync.salesforce import ObjectNotAccessible, SalesforceClient +from firstsync.salesforce.rest import UNSAMPLED_TYPES +from firstsync.target import TARGET_SCHEMA + +PREVIEW_LIMIT = 50 # what an administrator sees first +SCAN_LIMIT = 2000 # the most one dry-run will read per object +MAX_IDS_PER_GROUP = 25 + +Severity = Literal["blocking", "needs_decision", "warning"] +# A record's status is its worst issue, in this order. +RANK: dict[str, int] = {"clean": 0, "warning": 1, "needs_decision": 2, "blocking": 3} + + +class FailureGroup(BaseModel): + """Every record that failed on one target field for one reason.""" + + target: str + reason: str + severity: Severity + count: int + record_ids: list[str] = Field(description="Source record Ids, at most 25.") + example_input: Any = Field(description="One failing input, masked.") + + +class DuplicateGroup(BaseModel): + """Records that would load as the same real-world thing.""" + + table: str + key: list[str] + record_ids: list[str] + + +class TableResult(BaseModel): + table: str + source_object: str | None + records: int = 0 + clean: int = 0 + warning: int = 0 + needs_decision: int = 0 + blocking: int = 0 + dead_lettered: int = Field( + default=0, description="Records that crashed the engine; filed, not fatal." + ) + not_runnable: str | None = None + + +class DryRun(BaseModel): + run_id: str + connection: str + started_at: str + limit: int + wrote_anything: Literal[False] = False + tables: list[TableResult] + groups: list[FailureGroup] + duplicates: list[DuplicateGroup] + preview: dict[str, list[dict[str, Any]]] + + +def _severity(field: dict[str, Any], failure: Exception) -> Severity: + if isinstance(failure, UnmappedValue): + return "needs_decision" + # A bad value in a required field stops the record. In an optional field the value + # would be dropped and the record would still load. + return "blocking" if field["required"] else "warning" + + +def _split(source: str | None) -> tuple[str | None, str | None]: + if source is None: + return None, None + match = SOURCE.match(source) + return (match.group(1), match.group(2)) if match else (None, None) + + +def run_dry_run( + client: SalesforceClient, + connection: str, + proposals: dict[str, dict[str, Any]], + limit: int = PREVIEW_LIMIT, +) -> DryRun: + limit = max(1, min(int(limit), SCAN_LIMIT)) + tables: list[TableResult] = [] + groups: dict[tuple[str, str], FailureGroup] = {} + duplicates: list[DuplicateGroup] = [] + preview: dict[str, list[dict[str, Any]]] = {} + + for table, spec in TARGET_SCHEMA["tables"].items(): + fields = {f["name"]: f for f in spec["fields"]} + mapped = {name: proposals.get(f"{table}.{name}") for name in fields} + source_object, _ = _split((mapped["external_id"] or {}).get("source")) + result = TableResult(table=table, source_object=source_object) + tables.append(result) + if source_object is None: + result.not_runnable = "No source is proposed for external_id, so no record can be read." + 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] + records = client.sample(source_object, names, limit) + treatments = field_treatments(describe, records) + rows: list[tuple[str, dict[str, Any]]] = [] + shown: list[dict[str, Any]] = [] + + for record in records: + record_id = str(record.get("Id")) + try: + _one_record( + record, record_id, fields, mapped, source_object, treatments, + table, groups, result, rows, shown, + ) + except Exception as exc: # noqa: BLE001 - one bad record must not kill the scan + result.dead_lettered += 1 + _dead_letter(connection, table, record_id, exc) + + preview[table] = shown + duplicates += _duplicates(table, spec.get("natural_key"), rows) + + ordered = sorted(groups.values(), key=lambda g: (-RANK[g.severity], -g.count, g.target)) + return DryRun( + run_id=uuid.uuid4().hex[:12], + connection=connection, + started_at=datetime.now(UTC).isoformat(timespec="seconds"), + limit=limit, + tables=tables, + groups=ordered, + duplicates=duplicates, + preview=preview, + ) + + +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: + row: dict[str, Any] = {} + visible_row: dict[str, Any] = {} + status = "clean" + 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" + 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: + reason = f"source is on {obj}, but this table is read from {source_object}" + else: + try: + value = apply_rule(proposal.get("rule", []), raw, record) + reason = check_target_value(field, value) + except RuleFailure as exc: + 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, + reason=reason, + severity=severity, + count=0, + record_ids=[], + example_input=shown_input, + ), + ) + group.count += 1 + if len(group.record_ids) < MAX_IDS_PER_GROUP: + group.record_ids.append(record_id) + result.records += 1 + setattr(result, status, getattr(result, status) + 1) + rows.append((record_id, row)) + if len(shown) < 5: + shown.append({"source_id": record_id, "status": status, "row": visible_row}) + + +def _dead_letter(connection: str, table: str, record_id: str, exc: Exception) -> None: + """File a record the engine could not process, so it is investigated, not lost.""" + folder = _folder(connection) + folder.mkdir(parents=True, exist_ok=True) + entry = { + "at": datetime.now(UTC).isoformat(timespec="seconds"), + "run_id": get_settings().run_id, + "table": table, + "record_id": record_id, + "error": f"{type(exc).__name__}: {exc}", + } + with (folder / "deadletter.jsonl").open("a", encoding="utf-8") as handle: + handle.write(json.dumps(entry) + "\n") + + +def _uses_concat(proposal: dict[str, Any] | None) -> bool: + return any(step.get("op") == "concat" for step in (proposal or {}).get("rule", [])) + + +def _duplicates( + table: str, key: list[str] | None, rows: list[tuple[str, dict[str, Any]]] +) -> list[DuplicateGroup]: + if not key: + return [] + seen: dict[tuple[str, ...], list[str]] = defaultdict(list) + for record_id, row in rows: + values = [row.get(k) for k in key] + if all(isinstance(v, str) and v.strip() for v in values): + seen[tuple(str(v).strip().lower() for v in values)].append(record_id) + return [ + DuplicateGroup(table=table, key=key, record_ids=ids) + for ids in seen.values() + if len(ids) > 1 + ] + + +# --- storage ---------------------------------------------------------------------------- + + +def _folder(connection: str) -> Path: + return get_settings().state_dir / "dryruns" / connection + + +def save(result: DryRun) -> Path: + folder = _folder(result.connection) + folder.mkdir(parents=True, exist_ok=True) + path = folder / f"{result.run_id}.json" + path.write_text(result.model_dump_json(indent=2) + "\n", encoding="utf-8") + (folder / "latest").write_text(result.run_id, encoding="utf-8") + return path + + +def load(connection: str, run_id: str | None = None) -> DryRun: + folder = _folder(connection) + if run_id is None: + pointer = folder / "latest" + if not pointer.is_file(): + raise ValueError(f"No dry-run 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 dry-run id.") + path = folder / f"{run_id}.json" + if not path.is_file(): + raise ValueError(f"No dry-run {run_id!r} for {connection!r}.") + return DryRun.model_validate(json.loads(path.read_text(encoding="utf-8"))) + + +def start(client: SalesforceClient, connection: str, limit: int = PREVIEW_LIMIT) -> DryRun: + """Run the stored proposals for a connection, save the result, and return it.""" + proposals = ProposalStore(connection).load() + if not proposals: + raise ValueError(f"No mapping proposals are stored for {connection!r}. Propose first.") + result = run_dry_run(client, connection, proposals, limit) + save(result) + return result + + +def summary(result: DryRun, max_groups: int = 20) -> dict[str, Any]: + """The part of a dry-run worth returning from a tool call.""" + return { + "run_id": result.run_id, + "limit": result.limit, + "wrote_anything": False, + "tables": [t.model_dump() for t in result.tables], + "failure_groups": [g.model_dump() for g in result.groups[:max_groups]], + "failure_groups_total": len(result.groups), + "duplicates": [d.model_dump() for d in result.duplicates[:max_groups]], + "note": ( + "Nothing was written. Rules ran on real values; what is shown is masked. " + "blocking: the record cannot load. needs_decision: the administrator must " + "decide. warning: the value would be dropped and the record would still load." + ), + } diff --git a/src/firstsync/eval/defects.py b/src/firstsync/eval/defects.py new file mode 100644 index 0000000..ab09bd6 --- /dev/null +++ b/src/firstsync/eval/defects.py @@ -0,0 +1,55 @@ +"""Score a dry-run against an org's planted defects. + +The mapping score says whether Claude mapped the fields. This says whether the system +then caught the data problems we planted: a defect is `found` when every planted record +Id for it shows up in the dry-run's failure groups or duplicate groups. The engine is +deterministic code, so this is really a test of the whole pipeline: a wrong mapping +upstream makes a planted defect invisible downstream, and this score shows that. + +`injection` is deliberately not here: injected text is a prompt-attack canary, scored +against the proposals, not a data defect the dry-run should flag. +""" + +from __future__ import annotations + +from typing import Any + +from firstsync.dryrun import DryRun + +# defect name in the answer key -> where its record Ids must appear in the dry-run +_WHERE: dict[str, tuple[str, ...]] = { + "duplicate_contacts": ("duplicates:contacts",), + "missing_email": ("group:contacts.email",), + "missing_amount": ("group:deals.amount",), + "short_phone": ("group:contacts.phone",), +} + + +def _ids(result: DryRun, where: str) -> set[str]: + kind, _, name = where.partition(":") + if kind == "duplicates": + return {rid for d in result.duplicates if d.table == name for rid in d.record_ids} + return {rid for g in result.groups if g.target == name for rid in g.record_ids} + + +def score_defects(key: dict[str, Any], result: DryRun) -> dict[str, Any] | None: + """None when the org has no planted defects; otherwise found/missed per defect.""" + defects: dict[str, list[str]] = { + name: ids for name, ids in (key.get("defects") or {}).items() if name in _WHERE + } + if not defects: + return None + out: dict[str, Any] = {} + found_all = 0 + for name, planted in defects.items(): + flagged = set() + for where in _WHERE[name]: + flagged |= _ids(result, where) + missed = sorted(set(planted) - flagged) + out[name] = {"planted": len(planted), "found": len(planted) - len(missed)} + if missed: + out[name]["missed_ids"] = missed + else: + found_all += 1 + out["defects_found"] = f"{found_all}/{len(defects)}" + return out diff --git a/src/firstsync/mapping.py b/src/firstsync/mapping.py index 8381591..f51cd71 100644 --- a/src/firstsync/mapping.py +++ b/src/firstsync/mapping.py @@ -8,11 +8,11 @@ from __future__ import annotations import json -import os import re from pathlib import Path from typing import Any +from firstsync.config import get_settings from firstsync.rules import asks_admin, concat_fields, validate_rule from firstsync.salesforce import ObjectNotAccessible, SalesforceClient from firstsync.target import TARGET_SCHEMA @@ -125,7 +125,7 @@ def validate_mapping(mapping: Any, schema: SchemaCache) -> list[str]: def state_dir() -> Path: - return Path(os.environ.get("FIRSTSYNC_STATE_DIR", ".firstsync")) + return get_settings().state_dir class ProposalStore: @@ -173,7 +173,7 @@ def propose( for mapping in mappings: errors = validate_mapping(mapping, schema) target = mapping.get("target") if isinstance(mapping, dict) else None - if errors: + if errors or not isinstance(target, str): rejected.append({"target": target, "errors": errors}) continue proposals[target] = { diff --git a/src/firstsync/masking.py b/src/firstsync/masking.py index eb28b94..cc84a47 100644 --- a/src/firstsync/masking.py +++ b/src/firstsync/masking.py @@ -83,6 +83,11 @@ def field_treatments(describe: dict[str, Any], records: list[dict[str, Any]]) -> return treatments +def display(treatment: str, value: Any) -> Any: + """How one value is shown to the model, given its field's treatment.""" + return _apply(treatment, value) + + def _apply(treatment: str, value: Any) -> Any: if value is None or treatment in ("pass", "categorical"): return value diff --git a/src/firstsync/mcp_server.py b/src/firstsync/mcp_server.py index 7e2260b..8459b50 100644 --- a/src/firstsync/mcp_server.py +++ b/src/firstsync/mcp_server.py @@ -10,14 +10,14 @@ from __future__ import annotations -import os from collections.abc import Callable from typing import Any from mcp.server.mcpserver import MCPServer from mcp.server.mcpserver.exceptions import ToolError -from firstsync import audit, tools +from firstsync import audit, dryrun, tools +from firstsync.config import get_settings from firstsync.connections import get_client from firstsync.rules import RULE_HELP from firstsync.salesforce import SalesforceError @@ -41,6 +41,8 @@ "target_get_schema", "rule_test", "mapping_propose", + "dryrun_start", + "dryrun_get_results", ) _calls = 0 @@ -50,7 +52,7 @@ def _count_call() -> None: """Stop a session that makes far more tool calls than an onboarding needs.""" global _calls _calls += 1 - limit = int(os.environ.get("FIRSTSYNC_MAX_TOOL_CALLS", "300")) + limit = get_settings().max_tool_calls if _calls > limit: raise ToolError( f"This session has reached its limit of {limit} tool calls. " @@ -180,6 +182,45 @@ def mapping_propose(connection: str, mappings: list[dict[str, Any]]) -> dict[str ) +DRYRUN_START_DOC = ( + "Run the stored mapping proposals for a connection over real records, without writing " + "anything. Every record is built the way the migration would build it, checked against " + "the target's rules, and counted as clean, warning (an optional value would be dropped), " + "needs_decision (the administrator must decide), or blocking (the record cannot load). " + "Failures come back grouped by target field and reason, with source record Ids and one " + "masked example each; records that would collide on a table's natural key are reported " + "as duplicates. 'limit' caps how many records are read per object (default 50, max " + "2000). The result is stored; nothing is written to customer data or to the target." +) +DRYRUN_RESULTS_DOC = ( + "Return a stored dry-run for a connection: the latest one, or 'run_id' for a specific " + "run. Same shape as dryrun_start returns. Use this instead of re-running when nothing " + "has changed." +) + + +@server.tool(description=DRYRUN_START_DOC) +def dryrun_start(connection: str, limit: int = 50) -> dict[str, Any]: + return _logged( + "dryrun_start", + "dryrun", + connection, + {"limit": limit}, + lambda: dryrun.summary(dryrun.start(get_client(connection), connection, limit)), + ) + + +@server.tool(description=DRYRUN_RESULTS_DOC) +def dryrun_get_results(connection: str, run_id: str | None = None) -> dict[str, Any]: + return _logged( + "dryrun_get_results", + "dryrun", + connection, + {"run_id": run_id}, + lambda: dryrun.summary(dryrun.load(connection, run_id)), + ) + + def main() -> None: server.run("stdio") diff --git a/src/firstsync/rules.py b/src/firstsync/rules.py index 52cd6f7..3a90920 100644 --- a/src/firstsync/rules.py +++ b/src/firstsync/rules.py @@ -287,9 +287,9 @@ def apply_rule(rule: list[dict[str, Any]], value: Any, record: dict[str, Any] | elif op == "lookup": value = _lookup(str(value)[: step["prefix_length"]], step, value) elif op == "split": - parts = str(value).split(step["separator"]) + pieces = str(value).split(step["separator"]) try: - value = parts[step["index"]].strip() + value = pieces[step["index"]].strip() except IndexError: raise RuleFailure("value has too few parts to split") from None elif op == "normalize_phone": @@ -334,8 +334,8 @@ def check_target_value(field: dict[str, Any], value: Any) -> str | None: return "value is not an ISO date" return None if kind == "timestamp": - ok = re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ", value) - return None if ok else "value is not an ISO UTC timestamp" + stamp = re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ", value) + return None if stamp else "value is not an ISO UTC timestamp" if field["name"] == "phone": return None if E164.match(value) else "value is not an E.164 phone number" return None diff --git a/src/firstsync/salesforce/rest.py b/src/firstsync/salesforce/rest.py index 1ccebe7..fe65a2b 100644 --- a/src/firstsync/salesforce/rest.py +++ b/src/firstsync/salesforce/rest.py @@ -7,6 +7,8 @@ from __future__ import annotations import os +import random +import time from typing import Any import httpx @@ -21,6 +23,16 @@ # Compound fields cannot be selected alongside their parts in every context; skip them. UNSAMPLED_TYPES = {"address", "location"} +# Worth retrying: rate limits and transient server errors. 400/401/403/404 are not. +RETRY_STATUSES = {429, 500, 502, 503, 504} +MAX_ATTEMPTS = 4 +BASE_DELAY = 0.5 # seconds; grows 0.5, 1, 2 with jitter + + +def _sleep_before(attempt: int, sleep: Any = time.sleep) -> None: + """Exponential backoff with full jitter, so retries from many workers spread out.""" + sleep(random.uniform(0, BASE_DELAY * (2**attempt))) + class RestSalesforceClient: def __init__( @@ -48,17 +60,30 @@ def from_env(cls) -> RestSalesforceClient: return cls(instance_url, access_token, os.environ.get("SF_API_VERSION", "v62.0")) def _get(self, path: str, params: dict[str, str] | None = None) -> dict[str, Any]: - try: - response = self._http.get(path, params=params) - except httpx.HTTPError as exc: - raise SalesforceError(f"Salesforce request failed: {exc}") from exc - if response.status_code in (403, 404): - raise ObjectNotAccessible(f"Salesforce returned {response.status_code} for {path}.") - if response.status_code >= 400: - raise SalesforceError( - f"Salesforce returned {response.status_code} for {path}: {response.text[:300]}" - ) - return response.json() + """GET with retries. Reads are idempotent, so retrying a timeout is always safe.""" + last_error: str = "" + for attempt in range(MAX_ATTEMPTS): + if attempt: + _sleep_before(attempt - 1) + try: + response = self._http.get(path, params=params) + except httpx.HTTPError as exc: + last_error = f"Salesforce request failed: {exc}" + continue + if response.status_code in RETRY_STATUSES: + last_error = f"Salesforce returned {response.status_code} for {path}." + continue + if response.status_code in (403, 404): + raise ObjectNotAccessible( + f"Salesforce returned {response.status_code} for {path}." + ) + if response.status_code >= 400: + raise SalesforceError( + f"Salesforce returned {response.status_code} for {path}: " + f"{response.text[:300]}" + ) + return response.json() + raise SalesforceError(f"{last_error} Gave up after {MAX_ATTEMPTS} attempts.") def accessible_objects(self) -> list[dict[str, Any]]: listed = {o["name"]: o for o in self._get("/sobjects")["sobjects"]} diff --git a/src/firstsync/target/schema.py b/src/firstsync/target/schema.py index 35014c0..961d55d 100644 --- a/src/firstsync/target/schema.py +++ b/src/firstsync/target/schema.py @@ -1,7 +1,9 @@ """The target schema: a small reference customer-success app. Four tables. `external_id` on every table holds the Salesforce record Id so a migration -can be re-run without creating duplicates. schema.sql is the same schema as Postgres DDL. +can be re-run without creating duplicates. `natural_key` names the fields that identify +the same real-world thing, which the dry-run uses to warn about likely duplicates. +schema.sql is the same schema as Postgres DDL. """ from __future__ import annotations @@ -30,6 +32,7 @@ def _field( "tables": { "accounts": { "description": "A customer company.", + "natural_key": ["name"], "fields": [ _field("external_id", "text", required=True, note="Source record Id."), _field("name", "text", required=True), @@ -42,6 +45,7 @@ def _field( }, "contacts": { "description": "A person at a customer company.", + "natural_key": ["email"], "fields": [ _field("external_id", "text", required=True, note="Source record Id."), _field("account_external_id", "text", required=True), diff --git a/tests/test_dryrun.py b/tests/test_dryrun.py new file mode 100644 index 0000000..dbdd286 --- /dev/null +++ b/tests/test_dryrun.py @@ -0,0 +1,116 @@ +"""The dry-run engine: deterministic, read-only, and honest about what it found.""" + +from __future__ import annotations + +import json + +import pytest +from hypothesis import given, settings +from hypothesis import strategies as st + +from firstsync import dryrun +from firstsync.connections import get_client +from firstsync.dryrun import DryRun, run_dry_run + + +def proposals_for(org: str) -> dict: + """A handwritten, correct proposal set for the generated orgs' common shape.""" + path = "results/claude-claude-sonnet-5-5.json" + data = json.load(open(path, encoding="utf-8")) + return data["orgs"][org]["runs"][0]["proposals"] + + +@pytest.fixture() +def org_d() -> DryRun: + return run_dry_run(get_client("org_d"), "org_d", proposals_for("org_d"), limit=2000) + + +def test_finds_the_planted_defects(org_d: DryRun) -> None: + by = {(g.target, g.severity): g for g in org_d.groups} + # Org D was generated with contacts missing emails, deals missing amounts, + # truncated phone numbers, and duplicated contacts. The dry-run must find all four. + assert by[("contacts.email", "blocking")].count == 5 + assert by[("deals.amount", "blocking")].count == 4 + assert by[("contacts.phone", "warning")].count == 3 + assert len(org_d.duplicates) == 6 + assert all(d.table == "contacts" for d in org_d.duplicates) + + +def test_counts_add_up(org_d: DryRun) -> None: + for t in org_d.tables: + assert t.clean + t.warning + t.needs_decision + t.blocking == t.records + assert t.dead_lettered == 0 + + +def test_is_deterministic(org_d: DryRun) -> None: + again = run_dry_run(get_client("org_d"), "org_d", proposals_for("org_d"), limit=2000) + strip = {"run_id", "started_at"} + assert org_d.model_dump(exclude=strip) == again.model_dump(exclude=strip) + + +def test_writes_nothing_and_says_so(org_d: DryRun) -> None: + assert org_d.wrote_anything is False + assert dryrun.summary(org_d)["wrote_anything"] is False + + +def test_failure_examples_are_masked(org_d: DryRun) -> None: + text = json.dumps([g.model_dump() for g in org_d.groups]) + # No real name, email domain, or full phone number may appear in failure output. + assert "@example" not in text.lower() + for g in org_d.groups: + if isinstance(g.example_input, str) and "@" in g.example_input: + assert set(g.example_input.split("@")[0]) <= set("x.0123456789") + + +def test_group_ids_capped(org_d: DryRun) -> None: + for g in org_d.groups: + assert len(g.record_ids) <= dryrun.MAX_IDS_PER_GROUP + assert g.count >= len(g.record_ids) + + +def test_clean_org_is_clean() -> None: + result = run_dry_run(get_client("org_a"), "org_a", proposals_for("org_a"), limit=2000) + assert sum(t.blocking for t in result.tables) == 0 + + +def test_unmapped_picklist_needs_a_decision() -> None: + result = run_dry_run(get_client("org_b"), "org_b", proposals_for("org_b"), limit=2000) + g = next(g for g in result.groups if g.target == "deals.stage") + assert g.severity == "needs_decision" + assert g.count == 15 + + +def test_save_and_load_roundtrip(tmp_path, monkeypatch, org_d: DryRun) -> None: + monkeypatch.setenv("FIRSTSYNC_STATE_DIR", str(tmp_path)) + path = dryrun.save(org_d) + assert path.is_file() + loaded = dryrun.load("org_d") + assert loaded == org_d + assert dryrun.load("org_d", org_d.run_id) == org_d + with pytest.raises(ValueError): + dryrun.load("org_d", "../../etc/passwd") + with pytest.raises(ValueError): + dryrun.load("org_never_ran") + + +def test_start_requires_proposals(tmp_path, monkeypatch) -> None: + monkeypatch.setenv("FIRSTSYNC_STATE_DIR", str(tmp_path)) + with pytest.raises(ValueError, match="No mapping proposals"): + dryrun.start(get_client("org_a"), "org_a") + + +# --- property-based: rerunning never changes the verdict (idempotence) ----------------- + + +@settings(max_examples=25, deadline=None) +@given(limit=st.integers(min_value=1, max_value=200)) +def test_any_limit_is_safe_and_idempotent(limit: int) -> None: + client = get_client("org_d") + props = proposals_for("org_d") + strip = {"run_id", "started_at"} + first = run_dry_run(client, "org_d", props, limit=limit) + second = run_dry_run(client, "org_d", props, limit=limit) + assert first.model_dump(exclude=strip) == second.model_dump(exclude=strip) + for t in first.tables: + assert t.records <= limit + assert t.clean + t.warning + t.needs_decision + t.blocking == t.records diff --git a/tests/test_server.py b/tests/test_server.py index 6935f78..ed19c17 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -20,6 +20,8 @@ def test_server_exposes_exactly_the_expected_tools(): listed = asyncio.run(mcp_server.server.list_tools()) assert sorted(t.name for t in listed) == sorted(mcp_server.TOOL_NAMES) assert sorted(mcp_server.TOOL_NAMES) == [ + "dryrun_get_results", + "dryrun_start", "mapping_propose", "rule_test", "sf_check_access",