Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aff1da02f4 | ||
|
|
0837042865 | ||
|
|
32d7116ce7 | ||
|
|
b879687bc4 |
No files matched your search
@@ -0,0 +1,30 @@
|
||||
name: Bounded Stage v4 credential acceptance window
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- ci/v4-stage-resume-1a00-860324e
|
||||
jobs:
|
||||
acceptance-window:
|
||||
if: github.ref == 'refs/heads/ci/v4-stage-resume-1a00-860324e'
|
||||
runs-on: canina
|
||||
timeout-minutes: 12
|
||||
steps:
|
||||
- name: Bounded Stage acceptance with guaranteed generation-fenced close
|
||||
shell: bash
|
||||
env:
|
||||
BRANCH: ${{ github.ref_name }}
|
||||
DEPLOY_SHA: ${{ github.sha }}
|
||||
GITHUB_RUN_ATTEMPT: ${{ github.run_attempt }}
|
||||
DEPLOY_KEY: ${{ secrets.DEPLOY_KEY }}
|
||||
DEPLOY_KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
set +x
|
||||
[[ "$BRANCH" == ci/v4-stage-resume-1a00-860324e && "$DEPLOY_SHA" =~ ^[a-f0-9]{40}$ && "$GITHUB_RUN_ATTEMPT" == 1 ]] || exit 2
|
||||
umask 077
|
||||
scratch=$(mktemp -d)
|
||||
trap 'rm -rf "$scratch"' EXIT
|
||||
for file in ci-stage-acceptance.sh ci-stage-test-principal.sh stage-editorial-acceptance.py; do
|
||||
wget --no-proxy -qO "$scratch/$file" "https://git.parsaaghayi.ir/parsa/canina/raw/commit/$DEPLOY_SHA/scripts/$file"
|
||||
done
|
||||
bash "$scratch/ci-stage-acceptance.sh"
|
||||
@@ -0,0 +1,44 @@
|
||||
# Bounded unattended Stage acceptance
|
||||
|
||||
Parent review/activation only: push exact branch
|
||||
`ci/v4-stage-acceptance-timeout-860324e` once. No push or model execution was
|
||||
performed while preparing this branch. Do not merge this one-shot workflow into
|
||||
develop. The previous session/branch must never be reused.
|
||||
|
||||
Pinned deployed SHA: `860324e3a91b31c2b6d4e784e458f6d120582cb8`.
|
||||
Fixed session: `v4-ci-timeout-860324e-20261024`, TTL600 seconds, acceptance
|
||||
hard window480 seconds. Exact branch plus run_attempt1 required. Durable
|
||||
exclusive session intent rejects subsequent opens even if the CI attempt field
|
||||
is reset. EXIT always attempts existing generation-fenced close; durable timer
|
||||
retains cleanup through runner/SSH loss. Nothing redesigns account provisioning.
|
||||
|
||||
The tracked host Python script requires the exact SHA's successful deploy log,
|
||||
backend artifact and installed editorial package SHA. It reads the Stage private
|
||||
login handle and existing PMO worker credential only into process memory; no
|
||||
public bootstrap, secret stdout, direct DB access or Production writes.
|
||||
|
||||
It copies the exact topic and criteria from the unique FAILED v5 task starting
|
||||
`4a109`, preserves all prior FAILED editorial ledgers (must total unknown60),
|
||||
creates one fixed-request-id20 proposal through PMO transport, reviews Gate1 as
|
||||
the independently authenticated temporary SUPER_ADMIN, queues via PMO, then runs
|
||||
the installed runner once as hermes. Explicit owner authorization for this
|
||||
bounded Stage test is required; this is not independent content QA.
|
||||
|
||||
Runner total330 seconds plus preflight/recovery stays within the480 bound;
|
||||
profile cap120 and CLI30 headroom remain unchanged. If it stops in RUNNING,
|
||||
the script waits for lease expiry and uses the existing narrow editorial-failure
|
||||
HTTP contract, preserving unknown20. No retry or reconciliation/zero-cost claim.
|
||||
Hard process/transport loss can prevent this failure fence; state then requires
|
||||
read-back, not a new attempt. Account close still has durable600 backstop.
|
||||
|
||||
Success requires authenticated status VERIFYING, actual artifact bytes/digest
|
||||
and task/deployed-SHA binding, PENDING_INDEPENDENT_QA, fresh reserved20 and
|
||||
unchanged prior unknown60. No publication, image generation, Production changes,
|
||||
cron, fabricated QA, fabricated cost or provider503 attribution.
|
||||
|
||||
Checks: `python3 scripts/test_stage_editorial_acceptance.py`,
|
||||
`python3 scripts/test_ci_stage_acceptance.py`, existing cleanup tests and runner
|
||||
tests. Transport fixtures exercise open/accept/finally-close and failure-close;
|
||||
they are not live acceptance. Parent must review the SSH sudo streaming Python
|
||||
execution boundary before activation. CI1454 was observed successful for the
|
||||
pinned SHA; that observation is also rechecked by the script before model work.
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env bash
|
||||
# One bounded Stage acceptance only; never deploy, retry, reconcile or publish.
|
||||
set -euo pipefail
|
||||
set +x
|
||||
[[ $# == 0 && ${GITHUB_ACTIONS:-${GITEA_ACTIONS:-}} == true && ${BRANCH:-} == ci/v4-stage-resume-1a00-860324e && ${GITHUB_RUN_ATTEMPT:-} == 1 && ${DEPLOY_SHA:-} =~ ^[a-f0-9]{40}$ ]] || exit 2
|
||||
# Separate workflow source SHA from the immutable, already-deployed Stage artifact.
|
||||
export DEPLOY_SHA=860324e3a91b31c2b6d4e784e458f6d120582cb8
|
||||
export STAGE_TEST_APPROVAL=owner-authorized-stage-editorial
|
||||
export STAGE_TEST_SESSION=v4-ci-resume-1a00-20261024
|
||||
export STAGE_TEST_TTL_SECONDS=600
|
||||
wrapper="$(dirname "${BASH_SOURCE[0]}")/ci-stage-test-principal.sh"
|
||||
close() {
|
||||
rc=$?
|
||||
trap - EXIT HUP INT TERM
|
||||
export STAGE_TEST_ACTION=close
|
||||
if ! bash "$wrapper"; then
|
||||
printf 'Stage close pending: durable 600-second cleanup intent retained\n' >&2
|
||||
rc=1
|
||||
fi
|
||||
exit "$rc"
|
||||
}
|
||||
# Install before open: failed/partial open must also attempt generation-fenced close.
|
||||
trap close EXIT
|
||||
trap 'exit 130' INT
|
||||
trap 'exit 143' TERM HUP
|
||||
export STAGE_TEST_ACTION=open
|
||||
bash "$wrapper"
|
||||
export STAGE_TEST_ACTION=accept
|
||||
bash "$wrapper"
|
||||
@@ -3,7 +3,15 @@
|
||||
set -euo pipefail
|
||||
set +x
|
||||
fail() { printf 'ERROR: %s\n' "$1" >&2; exit 2; }
|
||||
[[ ${GITHUB_ACTIONS:-${GITEA_ACTIONS:-}} == true && ${BRANCH:-} == develop && $# == 0 ]] || fail 'CI-only Stage deployment; Production is blocked'
|
||||
[[ ${GITHUB_ACTIONS:-${GITEA_ACTIONS:-}} == true && $# == 0 ]] || fail 'CI-only Stage operation'
|
||||
case ${BRANCH:-} in
|
||||
develop) ;;
|
||||
ci/v4-stage-resume-1a00-860324e)
|
||||
[[ ${DEPLOY_SHA:-} == 860324e3a91b31c2b6d4e784e458f6d120582cb8 && ${STAGE_TEST_SESSION:-} == v4-ci-resume-1a00-20261024 && ${STAGE_TEST_TTL_SECONDS:-} == 600 ]] || fail 'fixed acceptance scope required'
|
||||
;;
|
||||
*) fail 'Stage branch required; Production is blocked' ;;
|
||||
esac
|
||||
[[ ${STAGE_TEST_ACTION:-} != open || ${BRANCH:-} != ci/v4-stage-resume-1a00-860324e || ${GITHUB_RUN_ATTEMPT:-} == 1 ]] || fail 'acceptance reruns blocked'
|
||||
[[ ${DEPLOY_SHA:-} =~ ^[0-9a-f]{40}$ ]] || fail 'immutable DEPLOY_SHA required'
|
||||
# Repository secret DEPLOY_KEY is the historical approved devops SSH credential.
|
||||
# Never fall back to baked-in runner keys, agent forwarding or docker.sock.
|
||||
@@ -17,6 +25,11 @@ printf '%s\n' "$DEPLOY_KNOWN_HOSTS" > "$scratch/known_hosts"
|
||||
printf '%s\n' "$DEPLOY_KEY" > "$scratch/key"
|
||||
unset DEPLOY_KEY DEPLOY_KNOWN_HOSTS
|
||||
ssh-keygen -F '[87.248.133.138]:2234' -f "$scratch/known_hosts" >/dev/null || fail 'DEPLOY_KNOWN_HOSTS has no pinned deployment endpoint'
|
||||
[[ ${STAGE_TEST_SESSION:-} =~ ^[a-z0-9-]{8,64}$ && ${STAGE_TEST_TTL_SECONDS:-} =~ ^[0-9]+$ && ${STAGE_TEST_ACTION:-} =~ ^(open|close)$ && ${STAGE_TEST_APPROVAL:-} == owner-authorized-stage-editorial ]] || fail 'explicit owner Stage test grant required'
|
||||
[[ ${STAGE_TEST_SESSION:-} =~ ^[a-z0-9-]{8,64}$ && ${STAGE_TEST_TTL_SECONDS:-} =~ ^[0-9]+$ && ${STAGE_TEST_ACTION:-} =~ ^(open|close|accept)$ && ${STAGE_TEST_APPROVAL:-} == owner-authorized-stage-editorial ]] || fail 'explicit owner Stage test grant required'
|
||||
[[ $STAGE_TEST_TTL_SECONDS -ge 60 && $STAGE_TEST_TTL_SECONDS -le 3600 ]] || exit 2
|
||||
if [[ $STAGE_TEST_ACTION == accept ]]; then
|
||||
[[ $BRANCH == ci/v4-stage-resume-1a00-860324e && $GITHUB_RUN_ATTEMPT == 1 ]] || fail 'acceptance scope required'
|
||||
ssh -F /dev/null -T -p 2234 -i "$scratch/key" -o BatchMode=yes -o IdentitiesOnly=yes -o IdentityAgent=none -o StrictHostKeyChecking=yes -o UserKnownHostsFile="$scratch/known_hosts" -o GlobalKnownHostsFile=/dev/null -o ConnectTimeout=15 devops@87.248.133.138 "sudo -n timeout --signal=TERM --kill-after=10 480 python3 -" < "$(dirname "${BASH_SOURCE[0]}")/stage-editorial-acceptance.py"
|
||||
exit $?
|
||||
fi
|
||||
ssh -F /dev/null -T -p 2234 -i "$scratch/key" -o BatchMode=yes -o IdentitiesOnly=yes -o IdentityAgent=none -o StrictHostKeyChecking=yes -o UserKnownHostsFile="$scratch/known_hosts" -o GlobalKnownHostsFile=/dev/null -o ConnectTimeout=15 devops@87.248.133.138 "sudo -n env CI=true STAGE_TEST_APPROVAL=owner-authorized-stage-editorial bash /opt/services/canina/releases/$DEPLOY_SHA/scripts/stage-test-principal-host.sh $DEPLOY_SHA $STAGE_TEST_SESSION $STAGE_TEST_TTL_SECONDS $STAGE_TEST_ACTION"
|
||||
@@ -0,0 +1,111 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fixed owner-authorized Stage acceptance. No automatic retry or cost reconciliation."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
SHA='860324e3a91b31c2b6d4e784e458f6d120582cb8'
|
||||
SESSION='v4-ci-resume-1a00-20261024'
|
||||
TASK='1a00bc08-3ca4-4519-ae1e-9eec7b098756'
|
||||
|
||||
def renew_existing(a):
|
||||
route='tasks/'+TASK
|
||||
row=a(route)
|
||||
if row['id']!=TASK or row['state']!='READY' or row['runs'] or row['budgetLedger'] or row['budgetLimitCents']!=20 or row['metadata']['commitSha']!=SHA:
|
||||
raise ValueError('Only exact unstarted zero-reservation READY task allowed')
|
||||
approved=a(route+'/gates/1/decide',{'decision':'APPROVED','expectedVersion':row['version'],'idempotencyKey':SESSION+':renew-gate1','expiresAt':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime(time.time()+450)),'notes':'Owner-authorized continuation of existing unstarted task only; max20 existing budget; no QA/publication/Production authority.'})
|
||||
if approved['state']!='READY': raise ValueError('Gate1 must enqueue READY')
|
||||
refreshed=a(route)
|
||||
if refreshed['state']!='READY' or refreshed['version']!=approved['version'] or refreshed['runs'] or refreshed['budgetLedger']:
|
||||
raise ValueError('Renewal refresh mismatch')
|
||||
return TASK
|
||||
|
||||
def command(args,timeout=15):
|
||||
return subprocess.check_output(args,stderr=subprocess.DEVNULL,timeout=timeout)
|
||||
|
||||
def http(base,token,route,body=None,method=None):
|
||||
req=urllib.request.Request(base+'/'+route,data=None if body is None else json.dumps(body).encode(),headers={'Authorization':'Bearer '+token,'Content-Type':'application/json'},method=method or ('GET' if body is None else 'POST'))
|
||||
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),NoRedirect())
|
||||
with opener.open(req,timeout=10) as r:
|
||||
raw=r.read(262145)
|
||||
if len(raw)>262144: raise ValueError('Response bound')
|
||||
return json.loads(raw)
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self,req,fp,code,msg,headers,newurl): return None
|
||||
|
||||
def ci_success(log):
|
||||
return SHA in log and 'Deployment for develop completed successfully!' in log and '🏁 Job succeeded' in log
|
||||
|
||||
def verify_artifact(status,task):
|
||||
artifact=status.get('artifact')
|
||||
if status['state']!='VERIFYING' or not artifact: raise ValueError('Acceptance incomplete')
|
||||
if hashlib.sha256(artifact['bytes'].encode()).hexdigest()!=artifact['sha256']: raise ValueError('Digest mismatch')
|
||||
binding=json.loads(artifact['bytes'])
|
||||
if binding['taskId']!=task or binding['commitSha']!=SHA or status['qaStatus']!='PENDING_INDEPENDENT_QA': raise ValueError('Artifact binding mismatch')
|
||||
return artifact
|
||||
|
||||
def main():
|
||||
if os.getuid()!=0 or Path('/.dockerenv').exists(): raise ValueError('Host only')
|
||||
logs=Path('/opt/services/git/gitea/gitea/gitea/actions_log/parsa/canina')
|
||||
if not any(ci_success(p.read_text()) for p in logs.glob('*/*.log')): raise ValueError('Exact deployed SHA CI success required')
|
||||
actual=command(['docker','exec','canino_backend_stage','cat','/app/STAGE_TEST_ARTIFACT_SHA']).decode().strip()
|
||||
deployed=json.loads(command(['docker','exec','canina-hermes','cat','/opt/data/editorial-v4/deployment.json']))
|
||||
if actual!=SHA or deployed.get('commitSha')!=SHA: raise ValueError('Deployment mismatch')
|
||||
# Strict private backend IP; no public bootstrap endpoint or direct DB writes.
|
||||
networks=json.loads(command(['docker','inspect','--format','{{json .NetworkSettings.Networks}}','canino_backend_stage']))
|
||||
ip=networks['stage_hermes_inventory_backend']['IPAddress']
|
||||
import ipaddress
|
||||
if not ipaddress.ip_address(ip).is_private: raise ValueError('Private backend required')
|
||||
base='http://'+ip+':3000/api'
|
||||
handle=json.loads(command(['docker','exec','canino_backend_stage','cat','/app/private-stage-test/'+SESSION+'.json']))
|
||||
if handle['user']['role']!='SUPER_ADMIN' or handle['user']['id']=='pmo': raise ValueError('Independent reviewer required')
|
||||
admin=handle['accessToken']; del handle
|
||||
worker=command(['docker','exec','--user','hermes','canina-hermes','cat','/opt/data/editorial-v4/credentials/editorial-pmo-token']).decode().strip()
|
||||
a=lambda route,body=None,method=None:http(base,admin,'admin/orchestration/'+route,body,method)
|
||||
w=lambda route,body=None:http(base,worker,'internal/prepare-worker/'+route,body)
|
||||
tasks=a('tasks')
|
||||
# Preserve all old unknown costs and fence previous failed attempts.
|
||||
failed=[t for t in tasks if t.get('key','').startswith('editorial-v1:') and t['state']=='FAILED']
|
||||
frozen={t['id']:a('tasks/'+t['id'])['budgetLedger'] for t in failed}
|
||||
unknown=sum(sum(x['amountCents'] for x in ledger) for ledger in frozen.values())
|
||||
if unknown!=60: raise ValueError('Prior unknown reservation must be 60')
|
||||
task=renew_existing(a); route='tasks/'+task
|
||||
# Existing Gate1 renewal atomically retains READY; no queue or proposal request.
|
||||
# Exactly one process, as hermes. Installed runner has 120-second profile cap,
|
||||
# CLI headroom30 and allowlisted timing evidence. Total330 fits window480.
|
||||
code="import sys,json;sys.path.insert(0,'/opt/data/editorial-v4/runtime-package');import runner;from pathlib import Path;runner.run(Path('/opt/data'),sys.argv[1],total_seconds=330)"
|
||||
try:
|
||||
rc=subprocess.run(['docker','exec','--user','hermes','canina-hermes','python3','-c',code,task],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=430).returncode
|
||||
except subprocess.TimeoutExpired:
|
||||
# No second runner; read persisted state and fence only after its lease expires.
|
||||
rc=1
|
||||
status=w('editorial-proposals/'+task)
|
||||
if status['state']=='RUNNING':
|
||||
# Let last heartbeat lease expire, then fence the artifact-free unknown attempt.
|
||||
time.sleep(31)
|
||||
row=a(route)
|
||||
runs=[r for r in row['runs'] if r['status']=='RUNNING']
|
||||
if len(runs)!=1: raise ValueError('Ambiguous recovery')
|
||||
a(route+'/editorial-failure',{'runId':runs[0]['id'],'expectedVersion':row['version'],'idempotencyKey':SESSION+':stopped','reason':'Bounded acceptance stopped; cost unknown and reservation retained; no retry.'})
|
||||
status=w('editorial-proposals/'+task)
|
||||
for old,ledger in frozen.items():
|
||||
row=a('tasks/'+old)
|
||||
if row['state']!='FAILED' or row['budgetLedger']!=ledger: raise ValueError('Prior fence changed')
|
||||
row=a(route)
|
||||
if sum(x['amountCents'] for x in row['budgetLedger'])!=20 or any(x['kind']=='RECONCILE' for x in row['budgetLedger']): raise ValueError('Reservation changed')
|
||||
if rc: raise ValueError('Acceptance incomplete; fenced unknown20')
|
||||
artifact=verify_artifact(status,task)
|
||||
print(json.dumps({'taskId':task,'state':status['state'],'artifactSha256':artifact['sha256'],'qaStatus':status['qaStatus'],'priorUnknownReservedCents':60,'freshReservedCents':20,'commitSha':SHA}))
|
||||
|
||||
if __name__=='__main__':
|
||||
try: main()
|
||||
except Exception:
|
||||
print('Stage acceptance stopped; no retry or cost reconciliation; read authenticated status',file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,71 @@
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parent
|
||||
SHA = '860324e3a91b31c2b6d4e784e458f6d120582cb8'
|
||||
|
||||
class AcceptanceTests(unittest.TestCase):
|
||||
def run_driver(self, branch='ci/v4-stage-resume-1a00-860324e', fail_open=False, attempt='1', fail_accept=False):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p = pathlib.Path(d)
|
||||
(p/'ssh').write_text('#!/bin/bash\nprintf "%s\\n" "${@: -1}" >> "$CALLS"\n[[ "$FAIL_OPEN" != true || "${@: -1}" != *" open" ]] || exit 1\n[[ "$FAIL_ACCEPT" != true || "${@: -1}" != *"480 python3 -" ]]\n')
|
||||
(p/'ssh-keygen').write_text('#!/bin/bash\nexit 0\n')
|
||||
(p/'sleep').write_text('#!/bin/bash\n[[ "$1" == 480 ]]\n')
|
||||
for name in ('ssh','ssh-keygen','sleep'):
|
||||
(p/name).chmod(0o755)
|
||||
env = dict(os.environ, PATH=d+':'+os.environ['PATH'], GITHUB_ACTIONS='true', BRANCH=branch,
|
||||
GITHUB_RUN_ATTEMPT=attempt, DEPLOY_SHA='a'*40, DEPLOY_KEY='NEVER-PRINT-KEY',
|
||||
DEPLOY_KNOWN_HOSTS='test-host-pin', CALLS=str(p/'calls'),
|
||||
FAIL_OPEN=str(fail_open).lower(), FAIL_ACCEPT=str(fail_accept).lower())
|
||||
result = subprocess.run(['bash',str(ROOT/'ci-stage-acceptance.sh')],env=env,capture_output=True,text=True)
|
||||
calls = (p/'calls').read_text().splitlines() if (p/'calls').exists() else []
|
||||
self.assertNotIn('NEVER-PRINT-KEY',result.stdout+result.stderr)
|
||||
return result,calls
|
||||
|
||||
def test_fixed_stage_open_then_finally_close(self):
|
||||
result,calls = self.run_driver()
|
||||
self.assertEqual(result.returncode,0,result.stderr)
|
||||
prefix = 'sudo -n env CI=true STAGE_TEST_APPROVAL=owner-authorized-stage-editorial bash /opt/services/canina/releases/'+SHA+'/scripts/stage-test-principal-host.sh '+SHA+' v4-ci-resume-1a00-20261024 600 '
|
||||
self.assertEqual(calls[0],prefix+'open')
|
||||
self.assertIn('timeout --signal=TERM --kill-after=10 480 python3 -',calls[1])
|
||||
self.assertEqual(calls[2],prefix+'close')
|
||||
|
||||
def test_failed_acceptance_still_closes(self):
|
||||
result,calls = self.run_driver(fail_accept=True)
|
||||
self.assertNotEqual(result.returncode,0)
|
||||
self.assertEqual(len(calls),3)
|
||||
self.assertTrue(calls[-1].endswith(' close'))
|
||||
|
||||
def test_failed_open_still_closes(self):
|
||||
result,calls = self.run_driver(fail_open=True)
|
||||
self.assertNotEqual(result.returncode,0)
|
||||
self.assertEqual(len(calls),2)
|
||||
self.assertTrue(calls[0].endswith(' open'))
|
||||
self.assertTrue(calls[1].endswith(' close'))
|
||||
|
||||
def test_wrong_branch_and_rerun_have_no_host_effect(self):
|
||||
for branch in ('main','develop','ci/other'):
|
||||
result,calls = self.run_driver(branch=branch)
|
||||
self.assertNotEqual(result.returncode,0)
|
||||
self.assertEqual(calls,[])
|
||||
result,calls = self.run_driver(attempt='2')
|
||||
self.assertNotEqual(result.returncode,0)
|
||||
self.assertEqual(calls,[])
|
||||
|
||||
def test_transport_scope_and_pinned_ssh_contract(self):
|
||||
text = (ROOT/'ci-stage-test-principal.sh').read_text()
|
||||
for value in ('StrictHostKeyChecking=yes','IdentitiesOnly=yes','IdentityAgent=none','GlobalKnownHostsFile=/dev/null'):
|
||||
self.assertIn(value,text)
|
||||
for branch,sha,session,ttl in [('main',SHA,'v4-ci-resume-1a00-20261024','600'),
|
||||
('ci/v4-stage-resume-1a00-860324e','b'*40,'v4-ci-resume-1a00-20261024','600'),
|
||||
('ci/v4-stage-resume-1a00-860324e',SHA,'different-session','600'),
|
||||
('ci/v4-stage-resume-1a00-860324e',SHA,'v4-ci-resume-1a00-20261024','601')]:
|
||||
env = dict(os.environ,GITHUB_ACTIONS='true',BRANCH=branch,DEPLOY_SHA=sha,
|
||||
STAGE_TEST_SESSION=session,STAGE_TEST_TTL_SECONDS=ttl,STAGE_TEST_ACTION='open')
|
||||
result = subprocess.run(['bash',str(ROOT/'ci-stage-test-principal.sh')],env=env,capture_output=True)
|
||||
self.assertNotEqual(result.returncode,0)
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -0,0 +1,59 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
p=Path(__file__).with_name('stage-editorial-acceptance.py')
|
||||
spec=importlib.util.spec_from_file_location('acceptance',p)
|
||||
assert spec is not None and spec.loader is not None
|
||||
m=importlib.util.module_from_spec(spec)
|
||||
if p.exists(): spec.loader.exec_module(m)
|
||||
|
||||
class AcceptanceTests(unittest.TestCase):
|
||||
def test_gate1_uses_actual_atomic_ready_contract(self):
|
||||
source=p.read_text()
|
||||
self.assertIn("approved['state']!='READY'",source)
|
||||
self.assertNotIn("approved['state']!='GATE1_APPROVED'",source)
|
||||
self.assertNotIn("w('editorial-queue'",source)
|
||||
def test_no_new_proposal_or_budget(self):
|
||||
source=p.read_text()
|
||||
self.assertNotIn("w('editorial-proposals',",source)
|
||||
self.assertNotIn('def proposal(',source)
|
||||
self.assertIn("row['budgetLedger']",source)
|
||||
|
||||
class ContinuationTests(unittest.TestCase):
|
||||
def test_renew_existing_ready_refreshes_version_and_never_proposes(self):
|
||||
task='1a00bc08-3ca4-4519-ae1e-9eec7b098756'
|
||||
calls=[]
|
||||
row={'id':task,'state':'READY','version':3,'runs':[],'budgetLedger':[],'budgetLimitCents':20,'metadata':{'commitSha':m.SHA}}
|
||||
def api(route,body=None):
|
||||
calls.append((route,body))
|
||||
if body is None: return row.copy()
|
||||
self.assertEqual(body['expectedVersion'],3)
|
||||
self.assertEqual(body['decision'],'APPROVED')
|
||||
self.assertIn('renew',body['idempotencyKey'])
|
||||
row['version']=4
|
||||
return {'state':'READY','version':4}
|
||||
self.assertTrue(hasattr(m,'renew_existing'),'missing existing READY renewal')
|
||||
self.assertEqual(m.renew_existing(api),task)
|
||||
self.assertEqual([r for r,b in calls],['tasks/'+task,'tasks/'+task+'/gates/1/decide','tasks/'+task])
|
||||
def test_started_task_is_denied_before_approval(self):
|
||||
row={'id':'1a00bc08-3ca4-4519-ae1e-9eec7b098756','state':'READY','version':3,'runs':[{'id':'started'}],'budgetLedger':[],'budgetLimitCents':20,'metadata':{'commitSha':m.SHA}}
|
||||
self.assertTrue(hasattr(m,'renew_existing'),'missing existing READY renewal')
|
||||
with self.assertRaises(ValueError): m.renew_existing(lambda route:row)
|
||||
|
||||
class ArtifactTests(unittest.TestCase):
|
||||
def test_digest_and_binding_must_match(self):
|
||||
self.assertTrue(hasattr(m,'verify_artifact'), 'missing artifact verifier')
|
||||
import json,hashlib
|
||||
raw=json.dumps({'taskId':'task','commitSha':m.SHA,'brief':{'candidates':[]}})
|
||||
status={'taskId':'task','state':'VERIFYING','qaStatus':'PENDING_INDEPENDENT_QA','artifact':{'bytes':raw,'sha256':hashlib.sha256(raw.encode()).hexdigest()}}
|
||||
m.verify_artifact(status,'task')
|
||||
status['artifact']['bytes']+=' '
|
||||
with self.assertRaises(ValueError): m.verify_artifact(status,'task')
|
||||
def test_ci_gate_requires_exact_sha_success(self):
|
||||
self.assertTrue(hasattr(m,'ci_success'), 'missing CI exact SHA gate')
|
||||
self.assertFalse(m.ci_success('Deployment for develop completed successfully!'))
|
||||
self.assertFalse(m.ci_success(m.SHA+' Job failed'))
|
||||
self.assertTrue(m.ci_success(m.SHA+' Deployment for develop completed successfully! 🏁 Job succeeded'))
|
||||
|
||||
if __name__=='__main__': unittest.main()
|
||||
Reference in new issue
Block a user