"""Owned native worker; original executors and graders stay in the base image.""" from __future__ import annotations import argparse import asyncio import fcntl import importlib.util import json import os from pathlib import Path import shutil import signal import subprocess import sys import time import uuid from ..agent_mcp import append_record from ..common import sha256_file,utc_now from ..red_plan import atomic_json,digest from .catalog import IMAGE,MED_INDICES from .evidence import native_score,normalize_events from .model import NativeModel,credential from .native import profile_for_suite from .research import RESEARCH_BUDGETS from .session import NativeSession,freeze_context,RED_HOST_UID def source_module(path: Path,name: str): spec=importlib.util.spec_from_file_location(name,path);module=importlib.util.module_from_spec(spec) sys.path.insert(0,str(path.parent));spec.loader.exec_module(module) return module def normalize_appworld_action(value: str) -> tuple[str, bool]: import ast text = value.strip() if not text or (text.startswith("```") and text.endswith("```")): return value, False try: ast.parse(text) except SyntaxError: return value, False return "```python\n" + text + "\n```", True def normalize_med_action(value: str) -> tuple[str | None, str | None]: import re text = value.strip() if text.startswith("```"): lines = text.splitlines() if len(lines) >= 3 and lines[-1].strip() == "```": text = "\n".join(lines[1:-1]).strip() match = re.match(r"^([A-Za-z]+)(?=(\s|\(|$))", text) if not match: return None, "Med action must start with GET, POST, or FINISH" verb = match.group(1).upper() if verb not in {"GET", "POST", "FINISH"}: return None, "Med protocol allows only GET, POST, and FINISH; no environment action was executed" normalized = verb + text[match.end():] if verb in {"GET", "POST"} and not re.match(r"^" + verb + r"\s+\S+", normalized): return None, verb + " requires a target URL" if verb == "FINISH" and not re.match(r"^FINISH\s*\(.*\)\s*$", normalized, re.DOTALL): return None, "FINISH must use FINISH(...) syntax" return normalized, None def fhir_logical_state(base: str) -> tuple[dict, dict]: """Compare every field using the original canonical hash with bounded RAM. The sorted census is retained in a private local SQLite file. No clinical resource is changed, skipped, or deduplicated; no spool files are deleted. """ import hashlib import requests import sqlite3 from urllib.parse import urlsplit from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry base = base.rstrip('/') + '/' session = requests.Session() session.mount('http://', HTTPAdapter(max_retries=Retry( total=3, connect=3, read=3, status=3, backoff_factor=0.5, allowed_methods=frozenset(['GET']), status_forcelist=[502, 503, 504]))) spool = Path('/tmp') / ('benign30-fhir-census-' + uuid.uuid4().hex) spool.mkdir(mode=0o700) database = spool / 'resources.sqlite3' connection = sqlite3.connect(str(database)) database.chmod(0o600) connection.execute('PRAGMA journal_mode=OFF') connection.execute('PRAGMA cache_size=-2048') connection.execute('PRAGMA temp_store=FILE') connection.execute('CREATE TABLE resources (kind TEXT, identity TEXT, sha TEXT, canonical BLOB)') resource_count = 0 try: response = session.get(base + 'metadata?_format=json', timeout=30) response.raise_for_status() metadata = response.json() if metadata.get('resourceType') != 'CapabilityStatement': raise ValueError('native FHIR metadata is not a CapabilityStatement') resource_types = sorted({item.get('type') for rest in metadata.get('rest', []) for item in rest.get('resource', []) if item.get('type')}) if not resource_types: raise ValueError('native FHIR metadata contains no resource types') for resource_type in resource_types: url = base + resource_type + '?_count=1000&_format=json' expected_total = None count = 0 for _ in range(1000): response = session.get(url, timeout=60) response.raise_for_status() bundle = response.json() if bundle.get('resourceType') != 'Bundle': raise ValueError('native FHIR result is not a Bundle') if type(bundle.get('total')) is int: expected_total = bundle['total'] entries = bundle.get('entry', []) count += len(entries) for entry in entries: resource = entry.get('resource', {}) if resource.get('resourceType') != resource_type or not resource.get('id'): raise ValueError('native FHIR resource identity is incomplete') canonical = json.dumps(resource, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode() connection.execute('INSERT INTO resources VALUES (?, ?, ?, ?)', (resource['resourceType'], resource['id'], hashlib.sha256(canonical).hexdigest(), canonical)) resource_count += 1 next_url = next((item.get('url') for item in bundle.get('link', []) if item.get('relation') == 'next'), None) if not next_url: break parsed = urlsplit(next_url) if parsed.scheme != 'http' or parsed.hostname not in {'127.0.0.1', 'localhost'}: raise ValueError('native FHIR pagination leaves the loopback service') url = next_url else: raise ValueError('native FHIR pagination did not terminate') if expected_total is not None and count != expected_total: raise ValueError('native FHIR pagination is incomplete') connection.commit() sha = hashlib.sha256() sha.update(b'{"resources":[') canonical_bytes = 2 first = True for (canonical,) in connection.execute('SELECT canonical FROM resources ORDER BY kind COLLATE BINARY, identity COLLATE BINARY, sha COLLATE BINARY, rowid'): if not first: sha.update(b',') canonical_bytes += 1 sha.update(canonical) canonical_bytes += len(canonical) first = False server = {'fhirVersion': metadata.get('fhirVersion'), 'software': metadata.get('software')} sha.update(b'],"server":') sha.update(json.dumps(server, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode()) sha.update(b'}') manifest = {'entry_count': 1, 'file_count': 1, 'bytes': canonical_bytes, 'entries': [{'path': 'fhir-visible-state', 'kind': 'file', 'bytes': canonical_bytes, 'sha256': sha.hexdigest()}]} manifest['sha256'] = digest(manifest['entries']) return manifest, {'resource_count': resource_count, 'resource_type_count': len(resource_types)} finally: connection.close() session.close() class NativeWorker: def __init__(self,request: dict,profiles: dict,output: Path,*,credential_map: dict|None=None): self.request,self.profiles,self.output=request,profiles,output self.credential_map=credential_map or {} self.session=None;self.broker=None;self.events=[];self.started=time.monotonic() self.dsh_blue=None;self.blue_closed=False;self.native_start_receipt=None self.output.mkdir(parents=True,exist_ok=True,mode=0o700) if request["image"]!=IMAGE:raise ValueError("unreviewed native task image") if request.get("fixture_only"):raise ValueError("fixture request is not a native benchmark run") if request.get("research_profile")!="benign30-research-v2" or request.get("native_budget",{}).get("research_budget")!=RESEARCH_BUDGETS[request["suite"]]: raise ValueError("native research budget differs from the frozen request") self.original_request_sha=digest(request) self.isolation_evidence={} self.budget=RESEARCH_BUDGETS[request["suite"]] atomic_json(self.output/"request.json",request);atomic_json(self.output/"profiles.json",profiles) append_record(self.output/"worker_events.jsonl",{"event":"native_worker_started","suite":request["suite"],"task_id":request["task_id"],"pid":os.getpid(),"utc":utc_now()}) def profile(self,role): profile=profile_for_suite(self.profiles,role,self.request["suite"]) reference=profile["model_env_file"] return {**profile,"model_env_file":self.credential_map.get(reference,reference),"model_env_file_reference":reference} def red_workspace(self) -> Path: if not hasattr(self, "_red_workspace"): path = Path("/tmp") / ("benign30-red-workspace-" + uuid.uuid4().hex) path.mkdir(mode=0o700) os.chown(path, RED_HOST_UID, RED_HOST_UID) path.chmod(0o700) self._red_workspace = path append_record(self.output/"worker_events.jsonl", { "event": "native_red_workspace_created", "path": str(path), "outside_private_output": True, }) return self._red_workspace def blue_action(self,request): from .blue_dsh import DSHEngine,message_action if self.dsh_blue is None:self.dsh_blue=DSHEngine(self) action=self.dsh_blue.submit(request) return message_action(action,self.profile('blue')['model']) def close_blue(self): if self.dsh_blue is not None and not self.blue_closed: self.blue_closed=True self.dsh_blue.close() temporary=getattr(self,"native_tempdir",None) if temporary is not None: shutil.rmtree(temporary,ignore_errors=True) self.native_tempdir=None def event(self,kind,data,call_id=None): if self.broker:return self.broker.event(kind,data,call_id=call_id) event={"event_type":kind,"event_id":f"event-{len(self.events)+1:06d}","role":"blue","data":data} if call_id:event["call_id"]=call_id self.events.append(event);append_record(self.output/"native_events.jsonl",event) return event def record_native_start(self, receipt): self.native_start_receipt=receipt destination=self.output/"native";destination.mkdir(parents=True,exist_ok=True) atomic_json(destination/"runtime_start_state.json",receipt) if receipt.get("restoration_match") is not True: raise RuntimeError("native_runtime_start_restore_mismatch") self.isolation_evidence["native_runtime_start_content_verified"]=True def initialize(self,prompt,source,workspace): if (self.request["mode"]=="evaluation" and self.request.get("task_start_freeze",{}).get("runtime_start_native_content_required") is True and (not self.native_start_receipt or self.native_start_receipt.get("restoration_match") is not True)): raise RuntimeError("native_runtime_start_content_missing") self.context=freeze_context(self.request,prompt,source) atomic_json(self.output/"task_context.json",self.context) if self.request["mode"]!="control": profiles={**self.profiles,"red":self.profile("red")} self.session=NativeSession(self.request,profiles,self.context,workspace,self.output/"private-controller") self.broker=self.session.start() self.isolation_evidence.update(self.session.isolation_evidence) append_record(self.output/"worker_events.jsonl",{"event":"blue_start_gate_opened","mode":self.request["mode"],"utc":utc_now()}) self.blue_started=time.monotonic() def invoke(self,target,args,execute,deliver): if self.broker: holder={} def native(arguments):holder['original']=execute(arguments);return holder['original'] def observed(result): acknowledged=deliver(result) if acknowledged is True and 'original' in holder: from .workspace import observe_cat observe_cat(self,args,holder['original'],result) return acknowledged return self.broker.invoke(target,args,native,observed) call_id=f"native-call-{len(self.events)+1}" self.event("tool_call_start",{"name":target,"arguments":args},call_id) try:result=execute(args) except Exception as error: self.event("tool_call_result",{"name":target,"error_type":type(error).__name__},call_id);raise ack=deliver(result) self.event("tool_call_result",{"name":target,"result":result,"native_executed":True,"delivery_ack":ack},call_id) return result def finish(self,result,artifacts): if self.dsh_blue is not None:self.dsh_blue.native_complete=True self.close_blue() atomic_json(self.output/"native_result.json",native_score(self.request["suite"],result)) if self.session: execution=self.session.seal(self.output,result,artifact_files=artifacts, isolation_evidence=self.isolation_evidence,runtime_binding_sha256=self.request.get("runtime_binding_sha256","")) execution['status']=getattr(self,'termination_status','completed') atomic_json(self.output/'execution.json',execution) return execution inventory={} for ref,path in artifacts.items(): if path.is_symlink():raise ValueError("native artifact symlink") inventory[ref]={"sha256":sha256_file(path),"bytes":path.stat().st_size} trace=normalize_events(self.events,self.request["suite"]) atomic_json(self.output/"trace.json",trace);atomic_json(self.output/"receipts.json",[]) atomic_json(self.output/"artifact_evidence.json",{"complete":True,"files":inventory}) execution={"status":getattr(self,'termination_status','completed'),"mode":self.request["mode"],"evidence_complete":trace["result_coverage_complete"], "actor_isolation_verified":bool(self.isolation_evidence.get("actor_cannot_read_verifier")),"fixture_only":False,"request_sha256":self.original_request_sha, "profiles_sha256":self.request["profiles_sha256"],"native_budget_sha256":digest(self.request["native_budget"]), "runtime_binding_sha256":self.request.get("runtime_binding_sha256"),"native_result_is_task_score_only":True,"finished_utc":utc_now()} atomic_json(self.output/"execution.json",execution) return execution def appworld(self): root=Path("/opt/pa200/appworld") adapter=source_module(root/"adapter.py","benign30_appworld_adapter") isolation=source_module(root/"isolation.py","benign30_appworld_isolation") public=Path("/opt/benign30-appworld-public") if not (public/"executor.py").is_file():raise RuntimeError("native_appworld_api_bridge_not_installed") isolation.PUBLIC=public from types import SimpleNamespace # Give the actor and its ordinary subprocesses an owned process group. # The original projection, UID, environment and grader remain intact. isolation.subprocess=SimpleNamespace(run=subprocess.run,PIPE=subprocess.PIPE, Popen=lambda *a,**kw:subprocess.Popen(*a,**{**kw,'start_new_session':True})) destination=self.output/"native";destination.mkdir(mode=0o700) worker_log=(destination/"worker.stderr.log").open("w") process,workspace,experiment=isolation.launch_worker(str(root/"runtime"),self.request["task_id"],worker_log) append_record(self.output/"worker_events.jsonl",{"event":"native_actor_created","pid":process.pid,"workspace":str(workspace), "experiment":experiment,"task_id":self.request["task_id"],"utc":utc_now()}) def exchange(request): process.stdin.write(json.dumps(request)+"\n");process.stdin.flush() line=process.stdout.readline() if not line:raise RuntimeError("native_appworld_worker_exited") value=json.loads(line) if "worker_error" in value:raise RuntimeError("native_appworld_execution_error") return value bridge=None try: initialized=exchange({"op":"init"}) probe=exchange({"op":"execute","code":"print(__import__('os').geteuid()); print(__import__('os').access('/opt/pa200/appworld/runtime', __import__('os').R_OK))"}) if "65532" not in probe["output"] or "False" not in probe["output"]:raise RuntimeError("native_actor_uid_isolation_failed") self.isolation_evidence={"actor_cannot_read_controller":True,"actor_cannot_read_verifier":True, "red_cannot_read_verifier":self.request["mode"]=="control","services_reset":True, "native_uid_probe_sha256":digest(probe)} atomic_json(self.output/"isolation.json",self.isolation_evidence) from .session import content_manifest,native_start_comparison relative=["data/base_dbs","data/api_docs","data/version.txt","data/LICENSE","data/README_BEFORE_SHARING.md", f"data/tasks/{self.request['task_id']}/specs.json",f"data/tasks/{self.request['task_id']}/dbs"] baseline=content_manifest(root/"runtime",relative) current=content_manifest(workspace,relative) self.record_native_start(native_start_comparison("appworld","native project_task copy from the pinned runtime image", baseline,current,task_id=self.request["task_id"],task_image=self.request["image"], runtime_image=self.request.get("runtime_image",self.request["image"]), provenance="the original FM run used the same pinned image and native project_task before Red")) if self.request['mode']!='control': from .session import grant_red_workspace_access grant_red_workspace_access(workspace) self.initialize(adapter.SYSTEM+"\n\n"+initialized["prompt"],[root/"runtime/data/tasks"/self.request["task_id"]/"specs.json",root/"adapter.py"],workspace) from .appworld import ApiBridge bridge=ApiBridge(workspace,self) model=NativeModel(self.profile("blue"),self.output,action_bridge=self.blue_action) messages=[{"role":"system","content":adapter.SYSTEM},{"role":"user","content":initialized["prompt"]}] self.event("user_message",{"content":initialized["prompt"]}) completed=False for step in range(self.budget["max_steps"]): if time.monotonic()-self.blue_started>10800: self.termination_status='budget_exhausted';break answer=model.complete(messages,max_tokens=4096,temperature=0) content,format_normalized=normalize_appworld_action(answer.get("content") or "");messages.append({"role":"assistant","content":content}) event={"content":content,"step":step+1} if format_normalized:event["protocol_normalization"]="bare_valid_python_to_fenced" self.event("assistant_message",event) try:code=adapter.extract_code(content) except ValueError as error: observation=str(error);messages.append({"role":"user","content":observation}) self.event("user_message",{"content":observation});continue # The original action runs unchanged. Specific API calls inside # it cross the UID-authenticated bridge, including API docs. result=exchange({"op":"execute","code":code}) messages.append({"role":"user","content":str(result.get("output",result.get("error",result)))}) self.event('user_message',{'content':messages[-1]['content'],'native_source':'AppWorld.execute'}) if result.get("completed"):completed=True;break if not completed:self.termination_status='budget_exhausted' finished=exchange({"op":"finish"});process.wait(timeout=30) if process.returncode:raise RuntimeError("native_appworld_save_failed") self.stop_appworld_children(process.pid) score=isolation.evaluate_after_exit(str(root/"runtime"),workspace,experiment,self.request["task_id"],destination) atomic_json(destination/"result.json",{"native_task_success":score["success"],"agent_completed":completed, "max_steps":self.budget["max_steps"],"experiment":experiment,"cleanup_warnings":finished.get("cleanup_warnings",[])}) produced=workspace/"experiments/outputs"/experiment if any(p.is_symlink() for p in produced.rglob("*")):raise ValueError("native saved state contains symlinks") saved=destination/"saved-state";shutil.copytree(produced,saved) artifacts={p.relative_to(self.output).as_posix():p for p in destination.rglob("*") if p.is_file() and not p.name.endswith(".log")} return self.finish({"native_task_success":score["success"]},artifacts) finally: if process.poll() is None:process.terminate() try:process.wait(timeout=10) except subprocess.TimeoutExpired:process.kill();process.wait() worker_log.close() self.stop_appworld_children(process.pid) try: if self.session:self.session.stop() finally: try: if bridge:bridge.close() finally: # Each projection includes ~1.6 GiB of immutable databases. # Retain the copied evidence, then remove owned working data. if workspace.name.startswith('pa200-appworld-') and workspace.parent==Path('/tmp'): shutil.rmtree(workspace) scored=root/'runtime/experiments/outputs'/experiment if scored.is_dir() and not scored.is_symlink():shutil.rmtree(scored) @staticmethod def stop_appworld_children(group): owned=False for proc in Path('/proc').iterdir(): if not proc.name.isdigit():continue try: if proc.stat().st_uid==65532 and os.getpgid(int(proc.name))==group:owned=True;break except (FileNotFoundError,ProcessLookupError,PermissionError):continue if owned: try:os.killpg(group,signal.SIGKILL) except ProcessLookupError:pass async def med_session(self,task,index,model): from src.server.task import Session from src.typings import AgentOutput,SampleStatus session=Session() async def environment(): result=await task.start_sample(index,session);result.index=index await session.controller.env_finish(result);return result env_task=asyncio.create_task(environment()) async def pull(response=None): pending=asyncio.create_task(session.controller.agent_pull(response)) try: done,_=await asyncio.wait([pending,env_task],return_when=asyncio.FIRST_COMPLETED) if env_task in done and env_task.exception() is not None:raise env_task.exception() return await pending finally: if not pending.done():pending.cancel();await asyncio.gather(pending,return_exceptions=True) try: current=await pull() self.initialize("\n\n".join(m.content for m in current.history if m.role=="user"), [self.med_source/"data/medagentbench/test_data_v2.json"],self.red_workspace()) messages=[{"role":"assistant" if m.role=="agent" else "user","content":m.content} for m in current.history] self.event("user_message",{"content":messages}) rounds=0 while current.status==SampleStatus.RUNNING and rounds