import importlib.util
import json
from pathlib import Path
import subprocess
from datetime import datetime

R=Path(__file__).parent
spec=importlib.util.spec_from_file_location('medium4_task',R/'run.py')
m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
JOB='20260916-medium4-sixteen'
DOCS=Path('/workspace/users/root/codex-ops-docs')
OWNER='docs/profiles/ltb1021/topics/runtime-lifecycle/'
PATHS=[OWNER+'README.ko.md',OWNER+'runs/20260916T165236+0900-run-medium4-sixteen.md']


def call(args,label):
    result=subprocess.run(args,capture_output=True,text=True,timeout=60)
    m.p.save(label+'.json',dict(returncode=result.returncode,stdout=result.stdout,stderr=result.stderr))
    assert result.returncode==0,(label,result.stderr,result.stdout)
    print(label,result.stdout[:2500],flush=True)
    return result.stdout


assert m.p.read('outcome.json')['sixteen']=='target_not_met'
assert m.p.read('readback.json')['removed_children']==13
call(['python3',str(DOCS/'servers/test/users/ltb1021/portfolio_logs/scripts/create_portfolio_candidate.py'),
    '--run-dir',str(R),'--confidence','MEDIUM','--repo','contextra-analytics',
    '--track-key','contextra-analytics:pipeline:runtime:runtime-lifecycle','--closeout-job',JOB,
    '--evidence-state','runtime_validated','--confidentiality','internal',
    '--reason','instance4로16채널 기동과 수명은 확인했으나 채널별10FPS 목표는 미달이다. 최종 성능 개선 milestone은 후속 수용까지 보류한다.',
    '--verify','4/8채널 수용,12/16 미달. 실제13개 child 정상 회수와 등록 보존, 기존3채널 약10FPS 복구 확인.'], 'portfolio-candidate')
m.p.save('receipt.json',dict(schema_version='ltb1021.codex_hub.report_receipt.v1',receipt_id=JOB+'-r01',
    timestamp=datetime.now().astimezone().isoformat(),session_alias='work-session',
    task='Medium instance4와 재사용16채널 단계별 처리량 시험',
    results=['기존 process image/engine/maxbatch1을 유지하고 Medium instance만4로 actual/persistent 반영했다.',
        '추가13개 등록/설정을 선완료하고4/8/12/16으로 상승했다.4/8은약10FPS,12는약8.5FPS,16은약6.3FPS로 목표미달이다.',
        '16채널에서 Triton 합계약100FPS·평균대기약569ms, 결과queue최대1·stale/drop0을 확인했다. instance별 분배는 미측정이다.',
        '13개 child 정상 회수 후 등록/preset/autostart=false 보존. 기존3개 running과instance4 유지, Owner/run/표본JSONCSV를 기록했다.'],
    verify=['상승시험1회,4/8/12 각20초·16 60초. 준비helper 부분설정 비교오류를 기동 전에1회 교정했다.',
        '모델config/engine hash,16개 독립PID/전용worker,Redis100개/TTL,정상Stop/reap와기존3개복구확인. source/image build와전체회귀는없다.'],
    commits=[],remaining=['각16채널10FPS 목표 미달. 다음은 공유Triton/TensorRT 실행스케줄링과요청대기경계의표적확인이다.',
        'Tracking/Scenario On·Pose·장시간·실제Web동기화는후속이다.']))
call(['codex-report-receipt','--profile','ltb1021','--session-alias','work-session','--receipt',str(R/'receipt.json')],'report-result')
changed=set(subprocess.check_output(['git','diff','--name-only'],cwd=m.REPO,text=True).splitlines())
changed.update(subprocess.check_output(['git','ls-files','--others','--exclude-standard'],cwd=m.REPO,text=True).splitlines())
assert changed==set(PATHS)
assert not subprocess.check_output(['git','diff','--cached','--name-only'],cwd=m.REPO,text=True).strip()
call(['git','-C',str(m.REPO),'diff','--check'],'diff-check')
out=Path('/tmp/codex/ltb1021/git-closeout')/JOB
manifest=out/'manifest.json'
args=['codex-git-closeout','prepare','--repository',str(m.REPO),'--output',str(manifest),'--job-id',JOB,
    '--profile','ltb1021','--session-alias','work-session',
    '--title','docs(runtime): Medium instance4 단계별 처리량과 재사용16채널 결과 기록',
    '--message','Why=프로세스 분리 경로의 다채널 수용 여부를 instance4 한 설정으로 확인하고 반복 시험용 등록을 보존한다.',
    '--message','What=기존 image/engine/maxbatch1에서4/8/12/16 상승시험을 수행하고 채널별 FPS·Triton 대기·자원·회수 결과를 Owner와 run에 기록했다.',
    '--message','Impact=마지막 수용8채널,16채널 각약6.3FPS로10FPS 목표미달이다. instance4와기존3채널 running,추가13개 stopped 등록/preset을유지한다. source/image 변경은없다.',
    '--message','Verify=4/8/12 각20초·16 60초 관측,16개 독립PID/worker·Redis100개/TTL·13개 정상Stop/reap·기존3채널복구확인. 설정/engine hash와기존입력·인증·Redis·비대상보존을확인했다.',
    '--message','Rollback=활성채널 정상Stop/reap 뒤 private 원장의 Medium config.pbtxt를CAS복원하고 Analytics 반영 후 기존3개만Start한다. 추가13개등록과preset은보존한다.',
    '--verify','Single ascent completed; 4/8 accepted, 12/16 target miss; no performance success inflation',
    '--verify','13 actual child reaps; retained registrations; original3 recovery; model/persistent readback PASS',
    '--verify','git diff --check PASS']
for path in PATHS:args+=['--path',path]
call(args,'git-prepare');digest=json.loads(manifest.read_text())['plan_hash']
batch=out/'batch.json'
call(['codex-git-closeout','batch-prepare','--output',str(batch),'--batch-id',JOB+'-batch','--profile','ltb1021',
    '--session-alias','work-session','--expected-group-count','1','--repository-label','contextra-analytics',
    '--manifest',str(manifest),'--expect-plan-hash',digest],'batch-prepare')
hash_=json.loads(batch.read_text())['plan_hash']
for action in ('batch-plan','batch-present'):
    call(['codex-git-closeout',action,'--batch-manifest',str(batch),'--expect-batch-plan-hash',hash_],action)
m.p.save('completion.json',dict(at=datetime.now().astimezone().isoformat(),stage='complete',git_mutations=False,
    runtime='instance4/original3 running/added13 stopped registered',sixteen_target='not_met',last_accepted=8,
    reports='written',portfolio='MEDIUM candidate only',batch=str(batch),batch_hash=hash_,
    resume='Do not repeat registration, model reflection or ascent. Read actual state and outcome.json before the next task.'))
