Files
ss-tools/scripts/full_flow_finance/verify.py

134 lines
7.4 KiB
Python

#!/usr/bin/env python3
# #region FullFlow.FinanceLifecycle [C:4] [TYPE Module] [SEMANTICS fixture,baseline,mcp,mutation,cron]
# @BRIEF Run genuine finance baseline publication and exact M01 lifecycle through existing public APIs.
# @PRE Capture ledger is approved, revision journal extracted read-only, and private lab env exists.
# @INVARIANT Expected value is independently fixed; no execution or publication receipt is manufactured.
# @RELATION DEPENDS_ON -> [Tooling.FullFlowV2Verification.Driver]
# @RELATION DEPENDS_ON -> [FullFlow.FinanceMutation]
import argparse
from decimal import Decimal
import importlib.util
import json
import os
from pathlib import Path
import subprocess
import httpx
from release import Blocked, private_environment
_spec = importlib.util.spec_from_file_location('finance_existing_v2_driver', Path(__file__).resolve().parents[1] / 'full_flow_v2' / 'verify.py')
_v2 = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_v2)
# #region FullFlow.FinanceLifecycle.Driver [C:4] [TYPE Class]
# @BRIEF Reuse the real owner/CAS M01 chain with finance-specific immutable pin and source mutation.
class Driver(_v2.Driver):
# #region FullFlow.FinanceLifecycle.Pin [C:3] [TYPE Function]
# @POST Pin matches the actual approved capture/release and exactly one sales-only filter.
def verify_published_pin(self, name, result):
pin = result.get('provenance', {}).get('target_snapshot', {}).get('baseline_pin') or {}
entries = [item for item in pin.get('entries', []) if item.get('baseline_id') == self.ids['baseline_id']]
self.require(name+'-unique', len(entries) == 1)
entry = entries[0]
filters = entry.get('reference_source', {}).get('resolved_native_filters', [])
self.require(name, pin.get('release_id') == self.ids['release_id']
and pin.get('baseline_set_id') == self.config['baseline_set']
and pin.get('baseline_set_version') == self.config['baseline_set_version']
and entry.get('capture_artifact_id') in self.ids['capture_artifact_ids']
and len(filters) == 1 and filters[0].get('filter_id') == 'NATIVE_FILTER-FINANCE-METRIC'
and filters[0].get('column') == 'metric_selector'
and filters[0].get('value', {}).get('values') == ['sales_debt'], baseline_pin=pin)
# #endregion FullFlow.FinanceLifecycle.Pin
# #region FullFlow.FinanceLifecycle.MutationCommand [C:3] [TYPE Function]
# @PRE Root-authorized isolated compose project; never ordinary backend.env or external production.
# @POST Safe numeric report retained; raw command errors and secrets are not emitted.
def mutation_command(self, action):
command = ['docker', 'compose', '-p', 'ss-tools-full-flow', '--env-file', str(self.env_file),
'-f', 'docker-compose.full-flow.yml', '-f', 'docker-compose.full-flow.finance.yml',
'exec', '-T', 'superset-dev', '/app/.venv/bin/python',
'/fixture/mutate_finance_fixture.py', '--action', action]
result = subprocess.run(command, capture_output=True, text=True, timeout=180)
self.require('finance-source-'+action+'-command', result.returncode == 0,
return_code=result.returncode, stderr_present=bool(result.stderr))
report = json.loads(result.stdout.splitlines()[-1])
self.record('finance-source-'+action, 'PASS', mutation=report)
return report
# #endregion FullFlow.FinanceLifecycle.MutationCommand
# #region FullFlow.FinanceLifecycle.MutateRestore [C:4] [TYPE Function]
# @POST Real +1 source/snapshot deviation fails against unchanged pin; restored source passes.
# @SIDE_EFFECT Alters only known generated values and restores even when run verification refuses.
# @RELATION CALLS -> [FullFlow.FinanceLifecycle.MutationCommand]
def mutate_restore(self):
before = self.mutation_command('check')
self.require('finance-original-source', before['observed'] == [10001, 20002, 100010])
try:
self.mutation_command('mutate')
self.metric_run('mutated', 'failed')
finally:
restored = self.mutation_command('restore')
self.require('finance-source-restored', restored['after'] == [10001, 20002, 100010])
self.metric_run('restored', 'passed')
# #endregion FullFlow.FinanceLifecycle.MutateRestore
# #region FullFlow.FinanceLifecycle.Scheduled [C:3] [TYPE Function]
# @POST Independent scheduler terminal outcome includes both actual producer and exact comparison.
def scheduled(self):
super().scheduled()
result = json.loads((self.output/'scheduled-result.json').read_text())
rows = result['snapshot']['steps']
producer = next(row for row in rows if row['logical_step_id'] == 'phase-3-M01-execute_metric')
compared = next(row for row in rows if row['logical_step_id'] == 'phase-4-M01-compare_to_baseline')
payload = compared['step_outcome']
values = payload.get('step_outcome', payload)['comparison']
self.require('finance-cron-actual-oracle', producer['status'] == 'passed' and bool(producer['artifact_refs'])
and compared['status'] == 'passed'
and Decimal(values['expected']['canonical_value']) == Decimal('2624875000')
and Decimal(values['actual']['canonical_value']) == Decimal('2624875000'), comparison=values)
# #endregion FullFlow.FinanceLifecycle.Scheduled
# #endregion FullFlow.FinanceLifecycle.Driver
# #region FullFlow.FinanceLifecycle.Main [C:3] [TYPE Function]
# @BRIEF Resume only actual ledgers and retain a separate finance lifecycle report.
# @RELATION CALLS -> [FullFlow.FinanceRelease.PrivateEnvironment]
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--env-file', type=Path, required=True)
parser.add_argument('--fixture', type=Path, required=True)
parser.add_argument('--capture-output', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--phase', choices=('publication', 'live_config', 'author', 'manual', 'mutate_restore', 'scheduled'), required=True)
args = parser.parse_args()
from common import artifact_path
args.output = artifact_path(args.output)
args.capture_output = artifact_path(args.capture_output)
private_environment(args.env_file)
config = json.loads(args.fixture.read_text())
config['scheduled_wait_seconds'] = 180
driver = Driver(config, args.output)
driver.secrets.append(os.environ['CLICKHOUSE_PASSWORD'])
driver.env_file, driver.fixture_file, driver.phase = args.env_file, args.fixture, args.phase
retained = args.output/'report.json'
origin = retained if retained.exists() else args.capture_output/'report.json'
previous = json.loads(origin.read_text())
driver.ids, driver.steps = previous['ids'], previous['steps']
try:
driver.login()
getattr(driver, args.phase)()
except (Blocked, KeyError, StopIteration, ValueError, httpx.HTTPError) as exc:
driver.record('finance-lifecycle-stopped', 'BLOCKED', reason=str(exc))
finally:
driver.flush()
driver.client.close()
return int(any(s['status'] in {'BLOCKED', 'NEEDS_REVIEW'} for s in driver.steps if s.get('attempt') == driver.attempt))
# #endregion FullFlow.FinanceLifecycle.Main
if __name__ == '__main__':
raise SystemExit(main())
# #endregion FullFlow.FinanceLifecycle