Add versioned metric graph authority, owned browser evidence, paginated and all-tab traversal, deterministic sampling policies, and analyst-facing run inspection. Provision the DEV/PREPROD/PROD Superset, Gitea and million-row ClickHouse lab; retain reproducible lifecycle evidence and explicit incomplete-traversal limits.
241 lines
16 KiB
Python
241 lines
16 KiB
Python
#!/usr/bin/env python3
|
|
# #region Tooling.FullFlowV2Verification [C:3] [TYPE Module] [SEMANTICS test,docker,metric,mcp,baseline]
|
|
# @BRIEF Retain a separate actual HTTP/MCP ledger for typed metric acceptance.
|
|
# @INVARIANT The old Docker evidence is read-only; no database rows or authority receipts are manufactured.
|
|
# @RELATION DEPENDS_ON -> [Tooling.FullFlowVerification.Driver]
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import base64
|
|
import importlib.util
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import sys
|
|
|
|
import httpx
|
|
|
|
_LEGACY = Path(__file__).resolve().parents[1] / "full_flow"
|
|
sys.path.insert(0, str(_LEGACY))
|
|
from common import Blocked # noqa: E402
|
|
from mcp_client import McpClient # noqa: E402
|
|
from verify import Driver as ReleaseCaptureDriver # noqa: E402
|
|
|
|
# Resolve the distinct v2 replay leaf without shadowing the legacy imported replay module.
|
|
_spec = importlib.util.spec_from_file_location("full_flow_v2_replay", Path(__file__).with_name("replay.py"))
|
|
_replay = importlib.util.module_from_spec(_spec)
|
|
_spec.loader.exec_module(_replay)
|
|
|
|
|
|
_recipe_spec = importlib.util.spec_from_file_location("full_flow_v2_recipe_replay", Path(__file__).with_name("recipe_replay.py"))
|
|
_recipe_replay = importlib.util.module_from_spec(_recipe_spec)
|
|
_recipe_spec.loader.exec_module(_recipe_replay)
|
|
|
|
|
|
# #region Tooling.FullFlowV2Verification.Driver [C:3] [TYPE Class] [SEMANTICS test,docker,metric]
|
|
class Driver(_recipe_replay.RecipeEvidenceMixin, _replay.MetricReplayMixin, ReleaseCaptureDriver):
|
|
# #region Tooling.FullFlowV2Verification.ReleaseGuard [C:2] [TYPE Function] [SEMANTICS test,release,validation]
|
|
def call(self, name, *args, **kwargs):
|
|
result = super().call(name, *args, **kwargs)
|
|
if name == "reject-unvalidated-release":
|
|
self.require("v2-release-refused-for-pending-validation",
|
|
result.get("detail") == "Validate the current PREPROD deployment before creating a release",
|
|
response=result)
|
|
return result
|
|
# #endregion Tooling.FullFlowV2Verification.ReleaseGuard
|
|
|
|
# #region Tooling.FullFlowV2Verification.DevChange [C:2] [TYPE Function] [SEMANTICS test,superset,release,fixture]
|
|
def dev_change(self):
|
|
"""Make an actual DEV dashboard edit so release acceptance has a distinct source commit."""
|
|
dashboard = self.config.get("dashboard_id", 1)
|
|
with httpx.Client(base_url="http://127.0.0.1:18111", timeout=30, trust_env=False) as superset:
|
|
login = superset.post("/api/v1/security/login", json={
|
|
"username": "admin", "password": self.password, "provider": "db", "refresh": True,
|
|
})
|
|
login.raise_for_status()
|
|
token = login.json()["access_token"]
|
|
self.secrets.append(token)
|
|
superset.headers["Authorization"] = "Bearer " + token
|
|
csrf = superset.get("/api/v1/security/csrf_token/")
|
|
csrf.raise_for_status()
|
|
superset.headers["X-CSRFToken"] = csrf.json()["result"]
|
|
before = superset.get(f"/api/v1/dashboard/{dashboard}")
|
|
before.raise_for_status()
|
|
title = "Sales v2 acceptance " + self.attempt
|
|
edited = superset.put(f"/api/v1/dashboard/{dashboard}", json={"dashboard_title": title})
|
|
edited.raise_for_status()
|
|
after = superset.get(f"/api/v1/dashboard/{dashboard}")
|
|
after.raise_for_status()
|
|
self.require("v2-genuine-dev-edit", after.json()["result"]["dashboard_title"] == title
|
|
and before.json()["result"]["dashboard_title"] != title,
|
|
dashboard_id=dashboard, old_title=before.json()["result"]["dashboard_title"], new_title=title)
|
|
# #endregion Tooling.FullFlowV2Verification.DevChange
|
|
|
|
# #region Tooling.FullFlowV2Verification.Inspect [C:2] [TYPE Function] [SEMANTICS test,mcp,inspection]
|
|
def inspect(self):
|
|
mcp = McpClient(self)
|
|
listed = mcp.rpc("v2-public-tool-inventory", {"method": "tools/list", "params": {}})
|
|
self.public_tools = {tool["name"] for tool in listed.get("result", {}).get("tools", [])}
|
|
inspected = mcp.call("v2-server-query-model", "inspect_dashboard_context", {
|
|
"environment_id": "full-flow-preprod", "dashboard_id": self.config.get("dashboard_id", 1),
|
|
})
|
|
model = inspected["query_model"]
|
|
self.require("v2-fresh-query-model", bool(model.get("charts"))
|
|
and model.get("query_model_fingerprint") not in {None, "sha256:error"})
|
|
self.ids["query_model_fingerprint"] = model["query_model_fingerprint"]
|
|
self.output.joinpath("inspected-model.json").write_text(json.dumps(model, indent=2) + "\n")
|
|
# #endregion Tooling.FullFlowV2Verification.Inspect
|
|
|
|
# #region Tooling.FullFlowV2Verification.CaptureContext [C:2] [TYPE Function] [SEMANTICS test,reference,context]
|
|
def capture_context(self):
|
|
"""Reuse a real historical authoring context only for the independent capture operation."""
|
|
prior = json.loads(Path(self.config["capture_context_report"]).read_text())
|
|
context = prior["ids"]
|
|
scenario = context["scenario_id"]
|
|
detail = self.call("v2-existing-capture-context", "GET", f"/api/dashboard-testing/scenarios/{scenario}")
|
|
self.require("v2-existing-context-dashboard", detail["entry"]["dashboard_id"] == self.config.get("dashboard_id", 1))
|
|
self.ids.update(scenario_id=scenario, revision_id=context["revision_id"])
|
|
self.record("v2-capture-context-reuse", "PASS", scenario_id=scenario,
|
|
scope="Capture provenance only; metric execution requires a new admitted M01 revision")
|
|
# #endregion Tooling.FullFlowV2Verification.CaptureContext
|
|
|
|
# #region Tooling.FullFlowV2Verification.Author [C:2] [TYPE Function] [SEMANTICS test,mcp,metric,authoring]
|
|
def author(self):
|
|
mcp = McpClient(self)
|
|
intent = {"environment_id": "full-flow-preprod", "dashboard_id": self.config.get("dashboard_id", 1),
|
|
"objective": self.config.get("objective", "Compare actual North revenue with the exact approved published metric")}
|
|
recipe, provider = self.config.get("evidence_recipe"), self.config.get("evaluation_provider_id")
|
|
if (recipe is None) != (provider is None):
|
|
raise ValueError("Recipe and evaluation provider must be configured together")
|
|
if recipe is not None:
|
|
if recipe != "table_text_v1" or not isinstance(provider, str) or not provider:
|
|
raise ValueError("Only the closed table_text_v1 recipe and provider locator are supported")
|
|
intent.update(evidence_recipe=recipe, evaluation_provider_id=provider)
|
|
proposed = mcp.call("v2-propose-M01", "propose_metric_baseline_profile", intent)
|
|
profile = proposed["profile"]
|
|
self.require("v2-preview-without-invented-authority", proposed["status"] == "preview_only" and not profile["eligible"])
|
|
captured = next(step["coordinate"] for step in reversed(self.steps) if step["step"] == "fixture-filtered-metric")
|
|
coordinate = next(item for item in profile["coordinates"] if item["chart_id"] == captured["chart_id"]
|
|
and item["dataset_id"] == captured["dataset_id"] and item["metric_name"] == self.config["metric"])
|
|
resolution = {
|
|
"profile_handle_id": proposed["profile_handle_id"], "expected_profile_digest": profile["profile_digest"],
|
|
"expected_cas_version": proposed["cas_version"], "idempotency_key": "v2-metric-" + self.attempt,
|
|
"coordinate_id": coordinate["coordinate_id"], "baseline_set": self.config["baseline_set"],
|
|
"baseline_set_version": self.config["baseline_set_version"], "reference_url": self.config["reference_url"],
|
|
}
|
|
rejected = mcp.rpc("v2-reject-stale-CAS", {"method": "tools/call", "params": {
|
|
"name": "resolve_metric_baseline_profile", "arguments": {"request": {
|
|
**resolution, "expected_cas_version": proposed["cas_version"] + 1,
|
|
"idempotency_key": "v2-stale-" + self.attempt,
|
|
}},
|
|
}})
|
|
blocked = self._domain(rejected)
|
|
self.require("v2-stale-CAS-refused", blocked.get("status") == "blocked" and blocked.get("error") == "PROFILE_CAS_CONFLICT")
|
|
resolved = mcp.call("v2-resolve-server-observed-schema", "resolve_metric_baseline_profile", resolution)
|
|
graph = resolved["profile"]["graph"]
|
|
self.require("v2-exact-approved-binding", resolved["status"] == "save_eligible"
|
|
and graph["schema_version"] == 2 and len(graph["baseline_bindings"]) == 1
|
|
and graph["baseline_bindings"][0]["selection"]["baseline_id"] == self.ids["baseline_id"]
|
|
and graph["baseline_bindings"][0]["selection"]["release_id"] == self.ids["release_id"])
|
|
replay = mcp.call("v2-resolution-idempotent-replay", "resolve_metric_baseline_profile", resolution)
|
|
self.require("v2-replay-retains-identical-profile", replay.get("replayed") is True and replay["profile"] == resolved["profile"])
|
|
run = mcp.call("v2-create-owned-agent", "create_agent_run", {
|
|
"dashboard_id": intent["dashboard_id"], "environment_id": intent["environment_id"],
|
|
"dashboard_name": self.config.get("dashboard_name", "Sales"), "idempotency_key": "v2-author-" + self.attempt,
|
|
})
|
|
pack = mcp.call("v2-register-server-owned-pack", "register_metric_baseline_pack", {
|
|
"profile_handle_id": resolved["profile_handle_id"], "expected_profile_digest": resolved["profile"]["profile_digest"],
|
|
"expected_cas_version": resolved["cas_version"], "agent_run_id": run["run_id"],
|
|
})
|
|
self.require("v2-admitted-receipt", pack["status"] == "save_eligible"
|
|
and pack["profile_receipt"]["profile_version"] == 2
|
|
and pack["profile_receipt"]["unresolved_resolution_state"]["save_eligible"] is True)
|
|
current = mcp.call("v2-bootstrap-current-revision", "bootstrap_authoring_scenario", {
|
|
"idempotency_key": "v2-bootstrap-" + self.attempt, "title": self.config.get("title", "North revenue approved baseline"),
|
|
"dashboard_id": intent["dashboard_id"], "allowed_environment_ids": [intent["environment_id"]],
|
|
"selected_environment_id": intent["environment_id"], "selected_case_ids": ["M01"],
|
|
"objective": intent["objective"], "compiled_handle_id": pack["compiled_handle_id"],
|
|
"draft_pack_id": pack["draft_pack_id"], "draft_pack_digest": pack["draft_pack_digest"],
|
|
})
|
|
self.require("v2-current-revision", current["activation_status"] == "current")
|
|
self.ids.update(metric_profile_handle_id=resolved["profile_handle_id"],
|
|
runtime_scenario_id=current["scenario_id"], runtime_revision_id=current["revision_id"])
|
|
self.output.joinpath("admitted-graph.json").write_text(json.dumps(graph, indent=2) + "\n")
|
|
self.flush()
|
|
# #endregion Tooling.FullFlowV2Verification.Author
|
|
|
|
# #region Tooling.FullFlowV2Verification.Domain [C:1] [TYPE Function] [SEMANTICS test,mcp,result]
|
|
@staticmethod
|
|
def _domain(response):
|
|
result = response["result"]
|
|
return result.get("structuredContent") or json.loads(next(item["text"] for item in result["content"] if item["type"] == "text"))
|
|
# #endregion Tooling.FullFlowV2Verification.Domain
|
|
|
|
# #region Tooling.FullFlowV2Verification.Publication [C:3] [TYPE Function] [SEMANTICS test,baseline,git,publication]
|
|
def publication(self):
|
|
revision = json.loads(Path(self.config["revision_file"]).read_text().splitlines()[-1])
|
|
self.require("v2-revision-contains-fresh-capture", any(
|
|
item["baseline_id"] == self.ids["baseline_id"] and item["capture_artifact_id"] in self.ids["capture_artifact_ids"]
|
|
for item in revision["entry_revisions"]))
|
|
selected_set, selected_version = self.config["baseline_set"], self.config["baseline_set_version"]
|
|
repo, branch = self.config["catalog_repo"], self.config["catalog_branch"]
|
|
with httpx.Client(base_url="http://127.0.0.1:18300", headers={"Authorization": "token " + self.git_token}, trust_env=False) as git:
|
|
before = git.get(f"/api/v1/repos/{repo}/branches/{branch}")
|
|
before.raise_for_status()
|
|
head = before.json()["commit"]["id"]
|
|
envelope = {"baseline_set_id": selected_set, "baseline_set_version": selected_version,
|
|
"release_id": self.ids["release_id"], "baseline_family": revision["catalog_digest"],
|
|
"catalog_digest": revision["catalog_digest"], "catalog_revision": revision}
|
|
published = self.call("v2-publish-actual-generation", "POST", "/api/catalog-publications", {
|
|
"envelope": envelope, "expected_branch_head": head, "idempotency_key": "v2-" + revision["catalog_revision_id"],
|
|
"catalog_revision_id": revision["catalog_revision_id"],
|
|
})
|
|
self.require("v2-publication-receipt", published["state"] == "published" and published.get("published_receipt"))
|
|
contents = git.get(f"/api/v1/repos/{repo}/contents/catalogs/{selected_set}/v{selected_version}.json",
|
|
params={"ref": published["commit_sha"]})
|
|
contents.raise_for_status()
|
|
self.require("v2-immutable-git-catalog-bytes", json.loads(base64.b64decode(contents.json()["content"])) == envelope)
|
|
self.ids["publication_commit_hash"] = published["commit_sha"]
|
|
self.flush()
|
|
# #endregion Tooling.FullFlowV2Verification.Publication
|
|
# #endregion Tooling.FullFlowV2Verification.Driver
|
|
|
|
|
|
# #region Tooling.FullFlowV2Verification.Main [C:3] [TYPE Function] [SEMANTICS test,docker,cli]
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--fixture", type=Path, required=True)
|
|
parser.add_argument("--env-file", type=Path, required=True)
|
|
parser.add_argument("--output", type=Path, default=Path("specs/050-mcp-interface/evidence/docker-full-flow-v2"))
|
|
parser.add_argument("--phase", choices=("inspect", "setup", "dev_change", "release", "capture_context", "reference", "publication", "live_config", "author", "manual", "mutate_restore", "scheduled", "recipe_evidence"), default="inspect")
|
|
args = parser.parse_args()
|
|
for line in args.env_file.read_text().splitlines():
|
|
if "=" in line and not line.startswith("#"):
|
|
key, value = line.split("=", 1)
|
|
os.environ[key] = value.strip().strip("\"'")
|
|
driver = Driver(json.loads(args.fixture.read_text()), args.output)
|
|
driver.phase, driver.env_file, driver.fixture_file = args.phase, args.env_file, args.fixture
|
|
report = args.output / "report.json"
|
|
if report.exists():
|
|
retained = json.loads(report.read_text())
|
|
driver.ids, driver.steps = retained["ids"], retained["steps"]
|
|
try:
|
|
driver.login()
|
|
if args.phase == "reference":
|
|
ledger = driver.call("v2-release-ledger", "GET", "/api/git/repositories/1/releases?env_id=full-flow-dev")
|
|
driver.release_record = next(item for item in ledger if item["id"] == driver.ids["release_id"])
|
|
getattr(driver, args.phase)()
|
|
except (Blocked, KeyError, StopIteration, ValueError, httpx.HTTPError) as exc:
|
|
driver.record("v2-flow-stopped", "BLOCKED", reason=str(exc))
|
|
finally:
|
|
driver.flush()
|
|
driver.client.close()
|
|
return int(any(step["status"] in {"BLOCKED", "NEEDS_REVIEW"}
|
|
for step in driver.steps if step.get("attempt") == driver.attempt))
|
|
# #endregion Tooling.FullFlowV2Verification.Main
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|
|
# #endregion Tooling.FullFlowV2Verification
|