diff --git a/docs/APP_PERFORMANCE.md b/docs/APP_PERFORMANCE.md index 70ba72f4e..031419578 100644 --- a/docs/APP_PERFORMANCE.md +++ b/docs/APP_PERFORMANCE.md @@ -397,6 +397,20 @@ functions rather than rescanning the project. Advisory draft reports share bound trial bookkeeping; completed resume receipts flush immediately. Stopping a lane flushes advisory reports and queues follow-ups for its already committed results. +Autopilot gives every machine draft its turn before running the saved-source return +repair lane. The second phase re-reads eligibility and acquires fresh claims, retains +its existing per-function search bounds, and reports separate repair progress with +the same Stop control. Direct single-function calls retain their saved-source repair +behavior. Refresh functions by ID inside the pass rather than resolving them through +project routes, which can trigger saved-file synchronization. + +Try raw m2c output before generating optional variants or collecting callee evidence. +Autopilot trials use the existing lean search evaluation: full linking and exact-byte +verdicts remain mandatory; export/address/allocation diagnostics are generated by +interactive evaluation when requested. Pass workers share half-second claim cleanup +and identity reads. Selected expired or legacy speculative claims force immediate +cleanup, and the selected claim is still checked in the acquisition transaction. + ### Releases queued behind a compile A plain agent release takes the per-agent/function candidate lock before retaining the project diff --git a/src/decompnet/app/autopilot_claims.py b/src/decompnet/app/autopilot_claims.py new file mode 100644 index 000000000..0ce5910bf --- /dev/null +++ b/src/decompnet/app/autopilot_claims.py @@ -0,0 +1,53 @@ +"""Coalesce pass-wide lease maintenance while checking each selected claim atomically.""" +import threading +import time +from contextlib import contextmanager +from contextvars import ContextVar + +CLEANUP_SECONDS=.5 + +_current=ContextVar('autopilot_claim_maintenance',default=None) + + +class Batch: + def __init__(self): + self.lock=threading.Lock() + self.identity_time=float('-inf') + self.identity_ids=None + self.expired_at=float('-inf') + + def identities(self,net): + # Read the catalog before taking a separate project's write transaction. + with self.lock: + now=time.monotonic() + if self.identity_ids is None or now-self.identity_time>=CLEANUP_SECONDS: + self.identity_ids={'machine_ids':net._machine_agent_ids(), + 'nonexclusive_ids':net._nonexclusive_agent_ids()} + self.identity_time=now + return self.identity_ids + + +def identities(net,store): + if batch:=_current.get():return batch.identities(net) + return {} if store is net.store else {'machine_ids':net._machine_agent_ids(), + 'nonexclusive_ids':net._nonexclusive_agent_ids()} + + +def expire(net,db,fid,ids): + batch=_current.get() + if batch is None: + net._expire_claims(db,**ids);return + # Transactions on this pass's project store serialize this timestamp. Expired + # or legacy speculative claims on the selected function never wait for cadence. + claim=db.execute('SELECT agent_id,expires_at FROM claims WHERE function_id=?',(fid,)).fetchone() + if (time.monotonic()-batch.expired_at>=CLEANUP_SECONDS or claim and + (claim['expires_at'] dict: @@ -139,10 +142,17 @@ def check_stop(): outcome = "fail" finally: if acquired:background.release() - state["tried"] += 1 - if outcome in ("match", "near"): - state[{"match": "matched", "near": "near"}[outcome]] += 1 + counter='repair_done' if state['phase']=='repairs' else 'tried' + with queue_lock: + state[counter] = state.get(counter,0)+1 + if outcome in ("match", "near"): + state[{"match": "matched", "near": "near"}[outcome]] += 1 + if state['phase']=='repairs' and outcome=='match': + state['repair_matched']=state.get('repair_matched',0)+1 + from ..autopilot_claims import Batch + from ..autopilot_claims import scope as claim_scope + claim_batch=Batch() remaining = iter(ids) queue_lock = threading.Lock() def lane(): @@ -152,12 +162,14 @@ def lane(): from ..trial_bookkeeping import scope as bookkeeping # Keep bounded preparation/output caches private to this worker across # functions. Session.prepare rechecks exact include bytes on every use. - with session(), m2c_sessions.scope(state['_foreground']), streaming(self), bookkeeping(): + with session(), m2c_sessions.scope(state['_foreground']), streaming(self), bookkeeping(), claim_scope(claim_batch): while not state['stop'].is_set(): with queue_lock: fid = next(remaining, None) if fid is None:return - one(fid) + token=_draft_pipeline.set(True) + try:one(fid) + finally:_draft_pipeline.reset(token) from ..restore_effects import checkpoint checkpoint() try: @@ -165,19 +177,34 @@ def lane(): if count: with Executor(max_workers=count, purpose='Autopilot repair search', project=slug, stop=state['stop'].set) as pool: list(pool.map(lambda _: lane(), range(count))) + if not state['stop'].is_set() and self.is_rom(proj): + proj=self.project_store(proj['id']).one('SELECT * FROM projects WHERE id=?',proj['id']) + # Saved-source repair must not hold up the first machine draft + # of thousands of other functions. Re-read eligibility afterward. + repairs=[row['id'] for row in self.project_store(proj['id']).all( + "SELECT id FROM functions WHERE project_id=? AND status='open' AND best_source IS NOT NULL " + "AND id IN (SELECT value FROM json_each(?)) ORDER BY n_insns,vram",proj['id'],json.dumps(ids))] + state.update(phase='repairs',repair_total=len(repairs),repair_done=0) + remaining=iter(repairs) + try_one=self._autopilot_repair_one + if repairs: + with Executor(max_workers=min(count,len(repairs)),purpose='Autopilot saved-source repair', + project=slug,stop=state['stop'].set) as pool: + list(pool.map(lambda _: lane(),range(min(count,len(repairs))))) finally: state["state"] = "stopped" if state["stop"].is_set() else "done" state["finished_at"] = time.time() with self.project_store(proj['id']).tx() as db: cfg = json.loads(db.execute("SELECT config FROM projects WHERE id=?", (proj["id"],)).fetchone()["config"]) cfg["autopilot"] = {k: state.get(k) for k in ("total", "tried", "matched", "near", "twins", "started_at", - "finished_at", "no_drafts")} + "finished_at", "no_drafts", "repair_total", "repair_done", "repair_matched")} db.execute("UPDATE projects SET config=? WHERE id=?", (json.dumps(cfg), proj["id"])) drafts = state["matched"] - state.get("twins", 0) if drafts: # (twins announce their own) with self.project_store(proj['id']).tx() as db: + method='machine drafts and saved-source repairs' if state.get('repair_matched') else 'machine drafts' self._event(db, proj["id"], agent.id, "autopilot", - f"{drafts} of {state['tried']} functions matched from machine drafts") + f"{drafts} of {state['tried']} functions matched from {method}") def on_improvement(self, proj, function_id: int) -> None: from ..restore_effects import defer @@ -267,20 +294,25 @@ def _autopilot_one(self, agent, proj, fid: int) -> str: with self.progress.judging(proj["slug"], synchronize=False) if hasattr(self, "progress") else nullcontext(): return AutopilotMixin._autopilot_one_work(self, agent, proj, fid) - def _autopilot_one_work(self, agent, proj, fid: int) -> str: + def _autopilot_repair_one(self, agent, proj, fid): + with self.progress.judging(proj['slug'],synchronize=False) if hasattr(self,'progress') else nullcontext(): + return self._autopilot_one_work(agent,proj,fid,repair_only=True) + + def _autopilot_one_work(self, agent, proj, fid: int, *, repair_only=False) -> str: now = time.time() store = self.project_store(proj['id']) - identities = {} if store is self.store else { - 'machine_ids': self._machine_agent_ids(), 'nonexclusive_ids': self._nonexclusive_agent_ids()} + from .. import autopilot_claims + identities = autopilot_claims.identities(self,store) with store.tx() as db: - self._expire_claims(db, **identities) + autopilot_claims.expire(self,db,fid,identities) fn = db.execute("SELECT * FROM functions WHERE id=?", (fid,)).fetchone() if fn is None or fn["status"] != "open" or db.execute("SELECT 1 FROM claims WHERE function_id=?", (fid,)).fetchone(): return "skip" db.execute("INSERT INTO claims VALUES(?,?,?,?)", (fid, agent.id, now, now + 300)) try: from ..return_repair_autopilot import run as return_repair - if return_repair(self, agent, proj, fn): + if repair_only:return 'match' if return_repair(self,agent,proj,fn) else 'skip' + if not _draft_pipeline.get() and return_repair(self, agent, proj, fn): return 'match' ctx = self._context(proj["id"], fn["unit"]) plan, toolchain, context = self._draft_plan(fn, proj, ctx=ctx) @@ -323,25 +355,28 @@ def _autopilot_one_work(self, agent, proj, fid: int) -> str: return 'fail' # (its compiler named in it: the same draft is worth judging again with another compiler) note = f"/* machine draft (m2c) for {toolchain} {' '.join(own.get('flags', []))}, tried by autopilot */\n" - candidates = [('raw_m2c', f"{note}{seeds.M2C_MACROS}\n{draft}\n")] - from ..loop_storage_shapes import variants as loop_shapes - for family,source in loop_shapes(draft,fn['name'],ctx['header'],proj['arch'])[:2]: - candidates.append((family,f"{note}{seeds.M2C_MACROS}\n{source}\n")) - if (seeds.m2c_target(toolchain) or "").startswith("mips"): - # next to m2c's own draft, the same with its usual mistakes undone (m2cfix.py): few lines change - refined = m2cfix.refine_draft(draft, fn["name"], target_asm) - if refined: - candidates.append(('refined_m2c', f"{note}{seeds.M2C_MACROS}\n{refined}\n")) - from ..capture_followup_repairs import callee_evidence - from ..recent_capture_repairs import variants as captured_variants - known_callees=callee_evidence(self,proj,fn,draft) - for family,source in captured_variants(draft,fn['name'],'mips' if (seeds.m2c_target(toolchain) or '').startswith('mips') else '',target_asm,ctx['header'],known_callees): - if family in ('overlay_callee_alias','argument_home_slot','untouched_argument_forwarding'): + def draft_candidates(): + yield 'raw_m2c', f"{note}{seeds.M2C_MACROS}\n{draft}\n" + candidates = [] + from ..loop_storage_shapes import variants as loop_shapes + for family,source in loop_shapes(draft,fn['name'],ctx['header'],proj['arch'])[:2]: candidates.append((family,f"{note}{seeds.M2C_MACROS}\n{source}\n")) - for canonical in (False,True): - if array := m2cfix.stack_array(draft,fn['name'],canonical): - family = 'stack_array_indexed' if canonical else 'stack_array' - candidates.append((family, f"{note}{seeds.M2C_MACROS}\n{array}\n")) + if (seeds.m2c_target(toolchain) or "").startswith("mips"): + # next to m2c's own draft, the same with its usual mistakes undone (m2cfix.py): few lines change + refined = m2cfix.refine_draft(draft, fn["name"], target_asm) + if refined: + candidates.append(('refined_m2c', f"{note}{seeds.M2C_MACROS}\n{refined}\n")) + from ..capture_followup_repairs import callee_evidence + from ..recent_capture_repairs import variants as captured_variants + known_callees=callee_evidence(self,proj,fn,draft) + for family,source in captured_variants(draft,fn['name'],'mips' if (seeds.m2c_target(toolchain) or '').startswith('mips') else '',target_asm,ctx['header'],known_callees): + if family in ('overlay_callee_alias','argument_home_slot','untouched_argument_forwarding'): + candidates.append((family,f"{note}{seeds.M2C_MACROS}\n{source}\n")) + for canonical in (False,True): + if array := m2cfix.stack_array(draft,fn['name'],canonical): + family = 'stack_array_indexed' if canonical else 'stack_array' + candidates.append((family, f"{note}{seeds.M2C_MACROS}\n{array}\n")) + yield from candidates def local_candidates(): # Lazy fallback: successful normal drafts never pay for another m2c invocation. # Imported projects use their file-context drafting route; forwarding their saved @@ -377,7 +412,7 @@ def recovery_candidates(): from ..compiler_shape_repairs import machine_draft_copies from ..narrow_store_repairs import machine_drafts as narrow_drafts outcomes, seen = [], set() - for family, source in chain(narrow_drafts(machine_draft_copies(chain(candidates, local_candidates()), fn['name'], ctx['header']),fn['name'],ctx['header'],proj['arch']), recovery_candidates()): + for family, source in chain(narrow_drafts(machine_draft_copies(chain(draft_candidates(), local_candidates()), fn['name'], ctx['header']),fn['name'],ctx['header'],proj['arch']), recovery_candidates()): if source in seen: continue seen.add(source) @@ -389,7 +424,9 @@ def recovery_candidates(): report['compiled'] = True report['family'] = family report['compiled_source'] = source - cand, verdict, _ = self._evaluate(fn, proj, result.obj) if result.ok else (None, None, None) + from .judging import search_evaluation + with search_evaluation(): + cand, verdict, _ = self._evaluate(fn, proj, result.obj) if result.ok else (None, None, None) if cand is None: if result.ok: draft_reports.failure(report, 'link', family, 'Compiled C could not be evaluated against this target; review its symbols and data mapping.') @@ -411,9 +448,10 @@ def recovery_candidates(): break report['complete'] = True draft_reports.save(self, fid, report, project_id=proj['id']) - fresh = self._function(fn['name'], proj['slug']) - if fresh['status'] == 'open' and fresh['best_source'] != fn['best_source'] and return_repair(self, agent, proj, fresh): - return 'match' + if not _draft_pipeline.get(): + fresh = store.one('SELECT * FROM functions WHERE id=? AND project_id=?',fid,proj['id']) + if fresh is not None and fresh['status'] == 'open' and fresh['best_source'] != fn['best_source'] and return_repair(self, agent, proj, fresh): + return 'match' return min(outcomes or ['fail'], key=("match", "near", "far", "skip", "fail").index) finally: with self.project_store(proj['id']).tx() as db: diff --git a/src/decompnet/app/static/js/steering.js b/src/decompnet/app/static/js/steering.js index c3a215a47..5ec6113be 100644 --- a/src/decompnet/app/static/js/steering.js +++ b/src/decompnet/app/static/js/steering.js @@ -614,6 +614,11 @@ function renderAutopilot(ov) { if (!(Number(progress.total) > 0)) $('apSub').textContent += ' · Total not yet known'; $('apSub').textContent += ` · ${(tw?.matched || 0).toLocaleString()} verified matches${perm}`; $("apBtn").textContent = "Stop"; + } else if (running && ap.phase === 'repairs') { + $("apTitle").textContent = `Autopilot: repairing saved C · ${ap.matched.toLocaleString()} matched for free`; + $("apSub").textContent = `${(ap.repair_done || 0).toLocaleString()} of ${(ap.repair_total || 0).toLocaleString()} checked after ${ap.tried.toLocaleString()} machine drafts. Agents work alongside it.${perm}`; + updateWorkProgress({_workBar: $('apBar'), _workStatus: {textContent: ''}}, {phase: 'Repairing saved C', done: ap.repair_done || 0, total: ap.repair_total || 0}); + $("apBtn").textContent = "Stop"; } else if (running) { $("apTitle").textContent = `Autopilot: trying each function's machine draft · ${ap.matched.toLocaleString()} matched for free`; $("apSub").textContent = `${ap.tried.toLocaleString()} of ${ap.total.toLocaleString()} tried${ap.near ? ` · ${ap.near} more are 90%+ there` : ""}${ap.twins ? ` · ${ap.twins.toLocaleString()} from reused C` : ""}. Agents work alongside it.${perm}`; @@ -627,6 +632,7 @@ function renderAutopilot(ov) { if (twinsDone) parts.push(`${twinsDone.toLocaleString()} from reused C`); if (tw && tw.asm) parts.push(`${tw.asm.toLocaleString()} copies of assembly set aside (not for agents)`); if (ap && ap.tried) parts.push(`${ap.tried.toLocaleString()} machine drafts tried${ap.near ? `, ${ap.near} more 90%+ there` : ""}`); + if (ap && ap.repair_done) parts.push(`${ap.repair_done.toLocaleString()} saved-source repairs checked`); if (ap && ap.no_drafts && !ap.tried) $("apTitle").textContent = "Autopilot could not try machine drafts"; $("apSub").textContent = (parts.length ? parts.join(" · ") + ". " : "") + (ap && ap.no_drafts ? ap.no_drafts : "Run it again after agents add types and names: drafts get better.") + perm; $("apBtn").textContent = "Run again"; diff --git a/tests/gui_transfers.js b/tests/gui_transfers.js index e620b5c3c..f7e2d4c82 100644 --- a/tests/gui_transfers.js +++ b/tests/gui_transfers.js @@ -182,6 +182,22 @@ async function autopilotProgressChecks() { assert.equal(get('apBar').className,'workbar'); assert.equal(get('apBar')['aria-valuenow'],undefined); assert.match(get('apSub').textContent,/Fingerprinting.*Total not yet known/); + const repairing={...ov,twins:null,autopilot:{state:'running',phase:'repairs',matched:3,tried:40,total:40,repair_done:2,repair_total:8}}; + ctx.renderAutopilot(repairing); + assert.match(get('apTitle').textContent,/repairing saved C/); + assert.match(get('apSub').textContent,/2 of 8.*40 machine drafts/); + assert.equal(get('apBar')['aria-valuenow'],'2'); + assert.equal(get('apBar').style['--work-progress'],'25%'); + assert.equal(get('apBtn').textContent,'Stop'); + // Reopening/refreshing uses the same server-owned phase and counters. + ctx.renderAutopilot(repairing); + assert.match(get('apSub').textContent,/2 of 8/); + ctx.api=async (_url,options)=>{action=options.body.action;return {...repairing,autopilot:{...repairing.autopilot,state:'stopped'}};}; + await get('apBtn').onclick(); + assert.equal(action,'stop'); + assert.equal(get('apBar').hidden,true); + assert.match(get('apSub').textContent,/2 saved-source repairs checked/); + } checks().then(autopilotProgressChecks).catch(error=>{console.error(error);process.exitCode=1;}); diff --git a/tests/test_autopilot_critical_path.py b/tests/test_autopilot_critical_path.py new file mode 100644 index 000000000..23dc38507 --- /dev/null +++ b/tests/test_autopilot_critical_path.py @@ -0,0 +1,144 @@ +"""Draft throughput preserves exact verdicts, live claims, and the saved-source lane.""" +import threading +from types import SimpleNamespace + +import pytest + +from decompnet.app import autopilot_claims, draft_reports +from decompnet.app.engine import RomNetwork +from decompnet.app.engine.autopilot import _draft_pipeline +from decompnet.app.engine.judging import _search_evaluation +from tests.test_loading import tiny_game +from tests.test_overlay_drafts import network # noqa: F401 + + +@pytest.mark.parametrize('exact',[True,False]) +def test_raw_draft_precedes_optional_repairs_and_uses_exact_verdict(network,monkeypatch,exact): # noqa: F811 + net,proj,fn=network;events=[];records=[] + source=f'int {fn["name"]}(int x) {{ return x ? 1 : 2; }}' + monkeypatch.setattr(net,'_draft_plan',lambda *a,**kw:('plan','gcc-2.7.2-kmc','')) + monkeypatch.setattr(net,'_seed_for',lambda *a:None) + monkeypatch.setattr(net,'_jtbl_asm',lambda *a:[]) + monkeypatch.setattr('decompnet.seeds.generate_from_asm',lambda *a,**kw:source) + monkeypatch.setattr('decompnet.app.return_repair_autopilot.run',lambda *a:False) + def variants(*a): + assert events and events[0]=='compile' + events.append('variants');return [] + monkeypatch.setattr('decompnet.app.loop_storage_shapes.variants',variants) + def compile(*a): + events.append('compile');return SimpleNamespace(ok=True,obj=b'object') + monkeypatch.setattr(net,'_compile',compile) + candidate=net._target_obj(fn,proj) + def evaluate(*a): + assert _search_evaluation.get() + return candidate,exact,[] + monkeypatch.setattr(net,'_evaluate',evaluate) + monkeypatch.setattr(net,'_record',lambda *a,**kw:records.append(kw['matched'])) + monkeypatch.setattr(net,'_function',lambda *a:pytest.fail('Function ID refresh must not synchronize the project')) + agent,_=net.local_agent('autopilot') + result=net._autopilot_one(agent,proj,fn['id']) + assert records and all(value is exact for value in records) + assert (result=='match') is exact + assert ('variants' in events) is not exact + assert draft_reports.read(net,fn['id'])['complete'] + assert not net.store.one('SELECT 1 FROM claims WHERE function_id=?',fn['id']) + + +@pytest.mark.parametrize('stop',[False,True]) +def test_all_machine_drafts_get_a_turn_before_saved_repairs(tmp_path,monkeypatch,stop): + net=RomNetwork(tmp_path/'app.db',tmp_path);proj=tiny_game(net) + ids=[row['id'] for row in net.store.all('SELECT id FROM functions')] + with net.store.tx() as db:db.execute("UPDATE functions SET best_source='int f(void){return 1;}'") + monkeypatch.setattr(net.twins,'full_pass',lambda *a,**kw:SimpleNamespace(matched=0)) + state=dict(state='running',tried=0,matched=0,near=0,twins=0,stop=threading.Event(),_foreground=threading.Event()) + state['_foreground'].set();events=[] + def draft(agent,project,fid): + assert _draft_pipeline.get() + events.append(('draft',fid)) + if stop:state['stop'].set() + return 'far' + def repair(agent,project,fid): + assert len([kind for kind,_ in events if kind=='draft'])==len(ids) + events.append(('repair',fid));return 'match' + monkeypatch.setattr(net,'_autopilot_repair_one',repair) + net._autopilot_work(proj['slug'],ids,state,(1,1),draft) + if stop: + assert events==[('draft',ids[0])] and state['state']=='stopped' + else: + assert state['tried']==len(ids) and state['repair_done']==len(ids) and state['matched']==len(ids) + assert state['state']=='done' + + +def test_claim_cleanup_is_coalesced_but_selected_expiry_is_immediate(tmp_path,monkeypatch): + net=RomNetwork(tmp_path/'app.db',tmp_path);tiny_game(net) + ids=[row['id'] for row in net.store.all('SELECT id FROM functions')] + agent,_=net.local_agent('autopilot') + count=[];original=net._expire_claims + monkeypatch.setattr(net,'_expire_claims',lambda *a,**kw:(count.append(1),original(*a,**kw))) + now=[0.];monkeypatch.setattr(autopilot_claims.time,'monotonic',lambda:now[0]) + with autopilot_claims.scope(autopilot_claims.Batch()): + identities=autopilot_claims.identities(net,net.store) + for fid in ids: + with net.store.tx() as db:autopilot_claims.expire(net,db,fid,identities) + assert len(count)==1 + with net.store.tx() as db: + db.execute('INSERT INTO claims VALUES(?,?,?,?)',(ids[0],agent.id,0,0)) + autopilot_claims.expire(net,db,ids[0],identities) + assert not db.execute('SELECT 1 FROM claims WHERE function_id=?',(ids[0],)).fetchone() + assert len(count)==2 + with net.store.tx() as db: + db.execute('INSERT INTO claims VALUES(?,?,?,?)',(ids[0],agent.id,0,10**12)) + autopilot_claims.expire(net,db,ids[0],identities) + assert db.execute('SELECT 1 FROM claims WHERE function_id=?',(ids[0],)).fetchone() + assert len(count)==2 + now[0]=1 + with net.store.tx() as db:autopilot_claims.expire(net,db,ids[1],identities) + assert len(count)==3 + + +def test_repair_phase_rechecks_live_claims_and_saved_file_revision(network,monkeypatch): # noqa: F811 + from decompnet.network import NetworkError + net,proj,fn=network;agent,_=net.local_agent('autopilot') + other,_=net.local_agent('other-agent') + with net.store.tx() as db: + db.execute('INSERT INTO claims VALUES(?,?,?,?)',(fn['id'],other.id,0,10**12)) + monkeypatch.setattr('decompnet.app.return_repair_autopilot.run',lambda *a:pytest.fail('Busy function must be skipped')) + assert net._autopilot_repair_one(agent,proj,fn['id'])=='skip' + with net.store.tx() as db:db.execute('DELETE FROM claims WHERE function_id=?',(fn['id'],)) + monkeypatch.setattr(net.progress,'sync',lambda *a,**kw:pytest.fail('Repair must not synchronize the whole project')) + def changed(*args): + net.progress.revisions[proj['slug']]=net.progress.revisions.get(proj['slug'],0)+1 + net.progress.check_result() + monkeypatch.setattr('decompnet.app.return_repair_autopilot.run',changed) + with pytest.raises(NetworkError,match='Progress changed'): + net._autopilot_repair_one(agent,proj,fn['id']) + assert not net.store.one('SELECT 1 FROM claims WHERE function_id=?',fn['id']) + + +def test_pass_identity_reads_are_shared_but_new_identities_refresh(tmp_path,monkeypatch): + net=RomNetwork(tmp_path/'app.db',tmp_path);tiny_game(net) + times=[0.];calls=[] + monkeypatch.setattr(autopilot_claims.time,'monotonic',lambda:times[0]) + monkeypatch.setattr(net,'_machine_agent_ids',lambda:calls.append(1) or {1}) + with autopilot_claims.scope(autopilot_claims.Batch()): + for _ in range(12):assert autopilot_claims.identities(net,net.store)['machine_ids']=={1} + assert len(calls)==1 + times[0]=1 + autopilot_claims.identities(net,net.store) + assert len(calls)==2 + + +def test_stopping_in_repair_phase_keeps_draft_progress_and_stops_new_repairs(tmp_path,monkeypatch): + net=RomNetwork(tmp_path/'app.db',tmp_path);proj=tiny_game(net) + ids=[row['id'] for row in net.store.all('SELECT id FROM functions')] + with net.store.tx() as db:db.execute("UPDATE functions SET best_source='int f(void){return 1;}'") + monkeypatch.setattr(net.twins,'full_pass',lambda *a,**kw:SimpleNamespace(matched=0)) + state=dict(state='running',tried=0,matched=0,near=0,twins=0,stop=threading.Event(),_foreground=threading.Event()) + state['_foreground'].set();calls=[] + def repair(*args): + calls.append(1);state['stop'].set();return 'match' + monkeypatch.setattr(net,'_autopilot_repair_one',repair) + net._autopilot_work(proj['slug'],ids,state,(1,1),lambda *a:'far') + assert state['state']=='stopped' and state['tried']==len(ids) and state['repair_done']==1 + assert state['repair_matched']==1 and calls==[1] + assert net.autopilot_status(proj['slug'])['repair_done']==1