Files
ss-tools/scripts/full_flow_finance/release.py
busya bcc69f4bbe feat(dashboard-testing): add sampled traversal and ClickHouse test lab
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.
2026-10-02 10:54:42 +03:00

201 lines
10 KiB
Python

#!/usr/bin/env python3
# #region FullFlow.FinanceRelease [C:4] [TYPE Module] [SEMANTICS fixture,release,gitea,approval]
# @BRIEF Run the isolated finance dashboard's public export and approved release pipeline.
# @PRE Existing private lab env, seeded DEV finance assets and actual uncapped pagination proof.
# @POST Actual HTTP evidence is retained; no release/deployment row is synthesized.
# @RELATION DEPENDS_ON -> [Tooling.FullFlowVerification.Driver]
# @RATIONALE A separate repository preserves the prior sales release and catalog history.
# @REJECTED Reusing the sales driver's hardcoded repository would bind finance to sales Git assets.
import argparse
import json
import os
import stat
import sys
from pathlib import Path
import httpx
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "full_flow"))
from verify import Driver # noqa: E402
from common import Blocked # noqa: E402
# #region FullFlow.FinanceRelease.Assets [C:3] [TYPE Function]
# @BRIEF Normalize known Superset startup-prefixed reports while preserving original stdout.
# @PRE Report is an isolated fixture seed output, never a credential dump.
def assets(path):
raw = path.read_text()
prefixed = False
try:
value = json.loads(raw)
except json.JSONDecodeError:
lines = raw.strip().splitlines()
if len(lines) != 2 or not lines[0].startswith("Loaded your LOCAL configuration at ["):
raise ValueError("Unexpected seed report prefix") from None
value = json.loads(lines[-1])
prefixed = True
if value.get("mode") != "DEV-native-fixture-assets" or value.get("slug") != "finance-million":
raise ValueError("Expected seeded finance DEV asset report")
if prefixed:
backup = path.with_suffix(".stdout.log")
if not backup.exists():
backup.write_text(raw)
path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n")
return value
# #endregion FullFlow.FinanceRelease.Assets
# #region FullFlow.FinanceRelease.PrivateEnvironment [C:4] [TYPE Function]
# @BRIEF Load only the existing private fixture env without exposing its values.
# @PRE Owner-only regular env file; this command does not mutate its secrets.
def private_environment(path):
info = path.lstat()
if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o600:
raise ValueError("Private lab env must be a regular mode0600 file")
for line in path.read_text().splitlines():
if "=" in line and not line.startswith("#"):
key, value = line.split("=", 1)
os.environ[key] = value.strip().strip("\"'")
# #endregion FullFlow.FinanceRelease.PrivateEnvironment
# #region FullFlow.FinanceRelease.GitConfiguration [C:3] [TYPE Function]
# @BRIEF Reuse the isolated Gitea credential locator through its normal public API.
def git_configuration(driver):
configs = driver.call("git-configurations", "GET", "/api/git/config")
config = next((c for c in configs if c["url"] == "http://gitea:3000"), None)
if config is None:
return driver.call("register-local-gitea", "POST", "/api/git/config", {
"name": "Docker Gitea", "provider": "GITEA", "url": "http://gitea:3000",
"pat": driver.git_token, "default_branch": "dev"})
driver.call("refresh-private-token", "PUT", f"/api/git/config/{config['id']}",
{"pat": driver.git_token})
return config
# #endregion FullFlow.FinanceRelease.GitConfiguration
# #region FullFlow.FinanceRelease.Repository [C:4] [TYPE Function]
# @BRIEF Bind only this dashboard to its own real local Git repository.
def repository(driver, repo):
config = git_configuration(driver)
endpoint = f"/api/git/config/{config['id']}/gitea/repos"
repos = driver.call("gitea-repositories", "GET", endpoint)
if not any(r["full_name"] == "admin/finance-million-dashboard" for r in repos):
driver.call("create-finance-repository", "POST", endpoint, {
"name": "finance-million-dashboard", "private": True,
"auto_init": True, "default_branch": "dev"})
driver.call("finance-repository-init", "POST", repo+"/init?env_id=full-flow-dev", {
"config_id": config["id"], "remote_url": "http://gitea:3000/admin/finance-million-dashboard.git",
"fingerprint_version": 2})
with httpx.Client(base_url="http://127.0.0.1:18300", trust_env=False, timeout=30,
headers={"Authorization": "token " + driver.git_token}) as git:
branches(driver, git)
# #endregion FullFlow.FinanceRelease.Repository
# #region FullFlow.FinanceRelease.Branches [C:3] [TYPE Function]
# @BRIEF Create missing stage branches in the authorized local fixture repository.
def branches(driver, git):
path = "/api/v1/repos/admin/finance-million-dashboard/branches"
response = git.get(path)
response.raise_for_status()
observed = {b["name"] for b in response.json()}
for stage in ("preprod", "prod"):
if stage not in observed:
created = git.post(path, json={"old_branch_name": "dev", "new_branch_name": stage})
created.raise_for_status()
response = git.get(path)
response.raise_for_status()
names = {b["name"] for b in response.json()}
driver.require("real-finance-stage-branches", {"dev", "preprod", "prod"} <= names,
observed=sorted(names))
# #endregion FullFlow.FinanceRelease.Branches
# #region FullFlow.FinanceRelease.Export [C:4] [TYPE Function]
# @BRIEF Export DEV, commit and push, then deploy and validate PREPROD through public APIs.
def export(driver, repo, metadata):
suffix = "?env_id=full-flow-dev"
driver.call("require-finance-prod-approval", "PUT", repo+"/release-policy"+suffix,
{"require_prod_approval": True, "approval_roles": ["Admin"],
"require_approval_comment": True, "block_publish_on_drift": True})
driver.call("git-author-profile", "PATCH", "/api/profile/preferences", {
"git_username": "full-flow-admin", "git_email": "full-flow@example.test",
"git_personal_access_token": driver.git_token})
driver.call("export-finance-dev", "POST", repo+"/sync"+suffix+"&source_env_id=full-flow-dev")
driver.call("commit-finance-dev", "POST", repo+"/commit"+suffix,
{"message": "Synthetic finance million-row fixture", "files": []})
driver.call("push-finance-dev", "POST", repo+"/push"+suffix)
driver.call("reject-direct-finance-prod", "POST", repo+"/deploy"+suffix,
{"stage": "prod"}, expected=(409,))
driver.call("deploy-finance-preprod", "POST", repo+"/deploy"+suffix, {"stage": "preprod"})
driver.call("reject-unvalidated-finance-release", "POST", repo+"/releases"+suffix,
metadata, expected=(409,))
validation = driver.call("validate-finance-preprod", "POST", repo+"/deployment-validation"+suffix,
{"stage": "preprod", "comment": "Authorized synthetic finance review"})
stage = next((s for s in validation["environments"] if s["stage"] == "preprod"), {})
driver.require("finance-preprod-validated-exact", stage.get("validation_status") == "validated"
and stage.get("drift_status") == "in_sync", deployment=stage)
# #endregion FullFlow.FinanceRelease.Export
# #region FullFlow.FinanceRelease.Publish [C:4] [TYPE Function]
# @BRIEF Require approval and publish the same immutable PREPROD-tested release to PROD.
def publish(driver, repo, metadata):
suffix = "?env_id=full-flow-dev"
release = driver.call("create-finance-release", "POST", repo+"/releases"+suffix,
metadata, expected=(201,))
driver.ids["release_id"] = release["id"]
driver.require("finance-release-awaits-human", release["status"] == "awaiting_approval")
approved = driver.call("approve-finance-release", "POST",
repo+f"/releases/{release['id']}/approve"+suffix,
{"comment": "User-authorized isolated finance fixture approval"})
identity = ("id", "version", "commit_hash", "content_hash", "deployment_id")
driver.require("finance-approval-preserves-identity",
all(approved.get(k) == release.get(k) for k in identity))
driver.call("publish-finance-to-prod", "POST", repo+f"/releases/{release['id']}/publish"+suffix)
ledger = driver.call("finance-release-ledger", "GET", repo+"/releases"+suffix)
current = next(r for r in ledger if r["id"] == release["id"])
driver.require("finance-published-exact-commit", current["status"] == "published"
and current["commit_hash"] == release["commit_hash"])
driver.output.joinpath("published-release.json").write_text(json.dumps(current, indent=2)+"\n")
# #endregion FullFlow.FinanceRelease.Publish
# #region FullFlow.FinanceRelease.Main [C:3] [TYPE Function]
# @BRIEF Execute only the finance release packet and retain typed stop evidence.
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--env-file", type=Path, required=True)
parser.add_argument("--assets", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--version", default="v0.1.0-finance-million")
args = parser.parse_args()
private_environment(args.env_file)
asset = assets(args.assets)
driver = Driver({"dashboard_id": asset["dashboard_id"]}, args.output)
driver.secrets.append(os.environ["CLICKHOUSE_PASSWORD"])
driver.phase = "finance-release"
driver.ids["dashboard_id"] = asset["dashboard_id"]
repo = f"/api/git/repositories/{asset['dashboard_id']}"
metadata = {"name": "Synthetic finance million-row dashboard", "version": args.version,
"notes": "Two physical 1,250,000-row synthetic sources; server-paginated snapshots"}
try:
driver.login()
driver.setup()
repository(driver, repo)
export(driver, repo, metadata)
publish(driver, repo, metadata)
except (Blocked, KeyError, StopIteration, ValueError, httpx.HTTPError) as exc:
driver.record("finance-release-stopped", "BLOCKED", reason=str(exc))
finally:
driver.flush()
driver.client.close()
return int(any(s["status"] == "BLOCKED" for s in driver.steps))
# #endregion FullFlow.FinanceRelease.Main
if __name__ == "__main__":
raise SystemExit(main())
# #endregion FullFlow.FinanceRelease