diff --git a/fastinsight/bot.py b/fastinsight/bot.py index 523435d..9447515 100644 --- a/fastinsight/bot.py +++ b/fastinsight/bot.py @@ -18,6 +18,7 @@ import threading import time from collections import OrderedDict +from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, Optional @@ -34,6 +35,8 @@ parse_feishu_message, ) from .pipeline import ( + Cancelled, + Operation, confirmation_text, paper_from_ocr, paper_from_url, @@ -49,6 +52,14 @@ LOGGER = logging.getLogger("fastinsight") +@dataclass +class ImageBatch: + id: str + operation: Operation = field(default_factory=Operation) + # The capture loop owns one job until it closes; each payload owns another. + jobs: int = 1 + + class SeenSet: def __init__(self, limit: int = SEEN_LIMIT) -> None: self.limit = limit @@ -77,7 +88,7 @@ def __init__(self) -> None: ) self.capture = CaptureStore(Path(env("FASTINSIGHT_STATE_DIR", str(ROOT))) / ".pending-capture.json") self._seen = SeenSet() - self._batch_stops: Dict[str, tuple] = {} + self._batches: Dict[str, ImageBatch] = {} self._batch_lock = threading.Lock() def start(self) -> None: @@ -161,24 +172,34 @@ def _start_image_batch(self, chat_id: str, parsed: ParsedMessage) -> None: batch_id = hashlib.sha256( f"{chat_id}:{parsed.event_id or parsed.message_id}:{command_time}".encode("utf-8") ).hexdigest() - stop = threading.Event() + batch = ImageBatch(batch_id) with self._batch_lock: - previous = self._batch_stops.get(chat_id) - self._batch_stops[chat_id] = (batch_id, stop) + previous = self._batches.get(chat_id) + if previous: + previous.operation.stop.set() + self.capture.arm( + chat_id, + chat_id=chat_id, + mode="image_batch", + batch_id=batch_id, + command_message_id=parsed.message_id, + window_start=window_start, + window_end=window_end, + ) + self._batches[chat_id] = batch if previous: - previous_stop = previous[1] - previous_stop.set() - self.capture.finish_batch(chat_id, batch_id=str(previous[0]), status="cancelled") - - self.capture.arm( - chat_id, - chat_id=chat_id, - mode="image_batch", - batch_id=batch_id, - command_message_id=parsed.message_id, - window_start=window_start, - window_end=window_end, - ) + previous.operation.cancel() + try: + self._run_image_batch(chat_id, parsed, batch, window_start, window_end) + except Cancelled: + self._finish_job(chat_id, batch) + except Exception: + self._cancel_batch(chat_id, batch) + self._finish_job(chat_id, batch) + raise + + def _run_image_batch(self, chat_id, parsed, batch, window_start, window_end): + batch.operation.checkpoint() probe = self.feishu.probe_list(chat_id) prompt = ( f"已开启 FastInsight 批量处理:将分发命令前 {CAPTURE_WINDOW_SECONDS // 60} 分钟至 " @@ -186,11 +207,12 @@ def _start_image_batch(self, chat_id: str, parsed: ParsedMessage) -> None: ) if probe.get("list_permission_denied") or probe.get("missing_scopes"): prompt += "\n\n" + timeout_hint(list(probe.get("missing_scopes") or [])) - self.feishu.send_text(chat_id, prompt) + with batch.operation.effect(): + self.feishu.send_text(chat_id, prompt) self._queue_batch_payloads( parsed, - batch_id=batch_id, + batch_id=batch.id, source="command_event", include_urls=True, ) @@ -198,11 +220,10 @@ def _start_image_batch(self, chat_id: str, parsed: ParsedMessage) -> None: target=self._image_batch_loop, kwargs={ "chat_id": chat_id, - "batch_id": batch_id, + "batch": batch, "command_message_id": parsed.message_id, "window_start": window_start, "window_end": window_end, - "stop": stop, "can_list": bool(probe.get("list_ok")), }, daemon=True, @@ -212,7 +233,7 @@ def _start_image_batch(self, chat_id: str, parsed: ParsedMessage) -> None: { "event": "image_batch_armed", "chat_id": chat_id, - "batch_id": batch_id, + "batch_id": batch.id, "window_start": window_start, "window_end": window_end, "missing_scopes": probe.get("missing_scopes") or [], @@ -223,11 +244,15 @@ def _start_image_batch(self, chat_id: str, parsed: ParsedMessage) -> None: ) def _active_image_batch(self, chat_id: str) -> str: - status = self.capture.status(chat_id) - record = status.get("record") if isinstance(status.get("record"), dict) else {} - if not status.get("armed") or record.get("mode") != "image_batch": + with self._batch_lock: + batch = self._batches.get(chat_id) + if not batch or batch.operation.stop.is_set(): + return "" + status = self.capture.status(chat_id) + record = status.get("record") if isinstance(status.get("record"), dict) else {} + if status.get("armed") and record.get("batch_id") == batch.id: + return batch.id return "" - return str(record.get("batch_id") or "") def _queue_batch_payloads( self, @@ -239,33 +264,53 @@ def _queue_batch_payloads( ) -> None: message_time = create_time_seconds(parsed.create_time) or time.time() for payload in batch_payloads(parsed, include_urls=include_urls): - claim = self.capture.claim_payload( - parsed.chat_id, - batch_id=batch_id, - payload_id=str(payload.get("payload_id") or ""), - message_id=parsed.message_id, - image_key=str(payload.get("image_key") or ""), - message_time=message_time, - ) - if not claim.get("claimed"): - continue - payload["message_id"] = parsed.message_id - payload["source"] = source - payload["sender_id"] = parsed.sender_id - payload["batch_id"] = batch_id - self._process_async(parsed.chat_id, payload, batch_id=batch_id) + with self._batch_lock: + batch = self._batches.get(parsed.chat_id) + if not batch or batch.id != batch_id or batch.operation.stop.is_set(): + return + claim = self.capture.claim_payload( + parsed.chat_id, + batch_id=batch_id, + payload_id=str(payload.get("payload_id") or ""), + message_id=parsed.message_id, + image_key=str(payload.get("image_key") or ""), + message_time=message_time, + ) + if not claim.get("claimed"): + continue + payload["message_id"] = parsed.message_id + payload["source"] = source + payload["sender_id"] = parsed.sender_id + payload["batch_id"] = batch_id + batch.jobs += 1 + try: + self._process_async(parsed.chat_id, payload, batch=batch) + except Exception: + batch.jobs -= 1 + raise def _image_batch_loop( self, *, chat_id: str, - batch_id: str, + batch: ImageBatch, command_message_id: str, window_start: float, window_end: float, - stop: threading.Event, can_list: bool, ) -> None: + try: + self._poll_image_batch( + chat_id=chat_id, batch=batch, command_message_id=command_message_id, + window_start=window_start, window_end=window_end, can_list=can_list, + ) + except Cancelled: + pass + finally: + self._finish_job(chat_id, batch) + + def _poll_image_batch(self, *, chat_id, batch, command_message_id, window_start, window_end, can_list): + stop = batch.operation.stop while not stop.is_set() and time.time() <= window_end: if can_list: try: @@ -286,7 +331,7 @@ def _image_batch_loop( continue self._queue_batch_payloads( parsed, - batch_id=batch_id, + batch_id=batch.id, source="feishu_list", ) except Exception as error: # noqa: BLE001 @@ -297,57 +342,72 @@ def _image_batch_loop( if stop.is_set(): return - result = self.capture.finish_batch(chat_id, batch_id=batch_id, status="completed") with self._batch_lock: - current = self._batch_stops.get(chat_id) - if current and current[0] == batch_id: - self._batch_stops.pop(chat_id, None) + if self._batches.get(chat_id) is not batch or stop.is_set(): + return + result = self.capture.finish_batch(chat_id, batch_id=batch.id, status="completed") count = int(result.get("processed_count") or 0) - self.feishu.send_text( - chat_id, - f"图片处理时间窗已结束,本批次共登记 {count} 个处理项;时间窗外的新消息不再处理。", - ) + with batch.operation.effect(): + self.feishu.send_text( + chat_id, + f"图片处理时间窗已结束,本批次共登记 {count} 个处理项;时间窗外的新消息不再处理。", + ) def _cancel_image_batch(self, chat_id: str) -> None: with self._batch_lock: - current = self._batch_stops.pop(chat_id, None) - if not current: - return - batch_id, stop = current - stop.set() - self.capture.finish_batch(chat_id, batch_id=str(batch_id), status="cancelled") + current = self._batches.get(chat_id) + if current: + self._cancel_batch(chat_id, current) + + def _cancel_batch(self, chat_id: str, batch: ImageBatch) -> None: + with self._batch_lock: + batch.operation.stop.set() + if self._batches.get(chat_id) is batch: + self.capture.finish_batch(chat_id, batch_id=batch.id, status="cancelled") + self._batches.pop(chat_id, None) + batch.operation.cancel() + + def _finish_job(self, chat_id: str, batch: ImageBatch) -> None: + with self._batch_lock: + batch.jobs -= 1 + if batch.jobs == 0 and self._batches.get(chat_id) is batch: + self._batches.pop(chat_id, None) def _process_async( self, chat_id: str, payload: Dict[str, Any], *, - batch_id: str = "", + batch: ImageBatch, ) -> None: threading.Thread( target=self._process, - args=(chat_id, payload, batch_id), + args=(chat_id, payload, batch), daemon=True, ).start() - def _process(self, chat_id: str, payload: Dict[str, Any], batch_id: str = "") -> None: + def _process(self, chat_id: str, payload: Dict[str, Any], batch: ImageBatch) -> None: print(json.dumps({"event": "captured", "chat_id": chat_id, "payload": _public_payload(payload)}, ensure_ascii=False), flush=True) try: - self.feishu.send_text(chat_id, WORKING_TEXT) - except Exception as error: # noqa: BLE001 - LOGGER.warning("working notify failed: %s", error) - try: + with batch.operation.effect(): + try: + self.feishu.send_text(chat_id, WORKING_TEXT) + except Exception as error: # noqa: BLE001 + LOGGER.warning("working notify failed: %s", error) + batch.operation.checkpoint() if payload.get("kind") == "image": payload["image_path"] = self.feishu.download_image( str(payload.get("message_id") or ""), str(payload.get("image_key") or ""), ) + batch.operation.checkpoint() paper = self._payload_to_paper(chat_id, payload) if paper is None: return - result = process_paper(paper) + result = process_paper(paper, operation=batch.operation) text = confirmation_text(result) - self.feishu.send_text(chat_id, text) + with batch.operation.effect(): + self.feishu.send_text(chat_id, text) print( json.dumps( { @@ -360,13 +420,18 @@ def _process(self, chat_id: str, payload: Dict[str, Any], batch_id: str = "") -> ), flush=True, ) + except Cancelled: + LOGGER.info("batch payload cancelled: %s", batch.id) except Exception as error: # noqa: BLE001 LOGGER.exception("pipeline failed: %s", error) try: - self.feishu.send_text(chat_id, f"FastInsight 处理失败:{error}") + with batch.operation.effect(): + self.feishu.send_text(chat_id, f"FastInsight 处理失败:{error}") except Exception: pass print(json.dumps({"event": "failed", "chat_id": chat_id, "error": str(error)}, ensure_ascii=False), flush=True) + finally: + self._finish_job(chat_id, batch) def _payload_to_paper( self, diff --git a/fastinsight/pipeline.py b/fastinsight/pipeline.py index 3757b89..b12e3ae 100644 --- a/fastinsight/pipeline.py +++ b/fastinsight/pipeline.py @@ -26,6 +26,7 @@ sys.path.insert(0, str(SCRIPTS)) from auto_pipeline import enrich_paper, process as run_auto_pipeline # noqa: E402 +from operation import Operation, Cancelled # noqa: E402 def _looks_like_user_title(text: str) -> bool: @@ -285,14 +286,18 @@ def generate_trend(paper: Dict[str, Any]) -> str: ) -def process_paper(paper: Dict[str, Any]) -> Dict[str, Any]: +def process_paper(paper: Dict[str, Any], *, operation: Optional[Operation] = None) -> Dict[str, Any]: + operation = operation or Operation() + operation.checkpoint() paper = dict(paper) if not str(paper.get("title") or "").strip() and str(paper.get("url") or "").strip(): paper["title"] = paper["url"] # Skill order: identify → verify/enrich → LLM trend → classify → FastResearch. paper = enrich_paper(paper) + operation.checkpoint() trend = generate_trend(paper) - result = run_auto_pipeline(paper, trend_text=trend, skip_verify=True) + operation.checkpoint() + result = run_auto_pipeline(paper, trend_text=trend, skip_verify=True, operation=operation) result["trend_text"] = trend return result diff --git a/scripts/auto_pipeline.py b/scripts/auto_pipeline.py index 16bc524..d1feaf0 100644 --- a/scripts/auto_pipeline.py +++ b/scripts/auto_pipeline.py @@ -23,6 +23,7 @@ from text_clip import compose_research_summary, prefer_abstract from service_auth import service_configuration, service_token from publish_receipt import validate_publish_receipt +from operation import Operation ROSTER_DEFAULT = ROOT.parent / "assets" / "colleagues.yaml" @@ -197,8 +198,10 @@ def enrich_paper(paper): return _apply_verification(paper, verified) -def process(paper, *, roster_path=None, endpoint=None, ingest_key=None, trend_text=None, skip_verify=False): +def process(paper, *, roster_path=None, endpoint=None, ingest_key=None, trend_text=None, skip_verify=False, operation=None): """Verify, enrich, route, and publish one paper. Returns an audit object.""" + operation = operation or Operation() + operation.checkpoint() paper = _normalize_paper(paper) endpoint = endpoint or os.environ.get("FASTRESEARCH_URL", "http://127.0.0.1:8787") ingest_key = ingest_key if ingest_key is not None else os.environ.get("FASTINSIGHT_INGEST_KEY", "") @@ -206,6 +209,7 @@ def process(paper, *, roster_path=None, endpoint=None, ingest_key=None, trend_te roster_path = str(roster_path or os.environ.get("FASTINSIGHT_ROSTER", ROSTER_DEFAULT)) if not skip_verify: paper = enrich_paper(paper) + operation.checkpoint() with tempfile.TemporaryDirectory(prefix="fastinsight-") as temp_dir: temp = Path(temp_dir) paper_path = temp / "paper.json" @@ -235,6 +239,7 @@ def process(paper, *, roster_path=None, endpoint=None, ingest_key=None, trend_te if not trends and trends_path.exists(): trends = json.loads(trends_path.read_text(encoding="utf-8")) route, route_code = _run_json([sys.executable, str(ROOT / "route_paper.py"), "--paper", str(paper_path), "--roster", roster_path, "--trends", str(trends_path), "--dry-run"]) + operation.checkpoint() if route_code != 0 or not isinstance(route, dict): raise RuntimeError( "route_paper refused to render an incomplete card: " @@ -257,18 +262,19 @@ def process(paper, *, roster_path=None, endpoint=None, ingest_key=None, trend_te errors.append(f"{person}: FastCAS 服务投递需要名册中的 receiver_ref") continue try: - delivered.append( - _publish( - endpoint, - ingest_key, - person, - paper, - trends, - direction, - cas_config=cas_config, - receiver_ref=receiver_ref, + with operation.effect(): + delivered.append( + _publish( + endpoint, + ingest_key, + person, + paper, + trends, + direction, + cas_config=cas_config, + receiver_ref=receiver_ref, + ) ) - ) except (urllib.error.URLError, urllib.error.HTTPError, OSError, ValueError) as exc: errors.append(f"{person}: {exc}") return {"paper": paper, "route": route, "route_code": route_code, "delivered": delivered, "errors": errors} diff --git a/scripts/operation.py b/scripts/operation.py new file mode 100644 index 0000000..c580291 --- /dev/null +++ b/scripts/operation.py @@ -0,0 +1,29 @@ +"""Cooperative work cancellation and admission of irreversible effects.""" +import threading +from contextlib import contextmanager + + +class Cancelled(RuntimeError): + pass + + +class Operation: + def __init__(self): + self.stop = threading.Event() + self._effects = threading.Lock() + + def checkpoint(self): + if self.stop.is_set(): + raise Cancelled("Operation cancelled") + + @contextmanager + def effect(self): + with self._effects: + self.checkpoint() + yield + + def cancel(self): + self.stop.set() + # Drain effects already admitted before acknowledging cancellation. + with self._effects: + pass diff --git a/tests/http_world.py b/tests/http_world.py index 7d29b03..4d55828 100644 --- a/tests/http_world.py +++ b/tests/http_world.py @@ -19,9 +19,19 @@ def __init__(self): self.receipts = {} self.published = [] self.requests = [] + self.notifications = [] self.model_entered = threading.Event() self.model_release = threading.Event() self.model_release.set() + self.verification_entered = threading.Event() + self.verification_release = threading.Event() + self.verification_release.set() + self.image_entered = threading.Event() + self.image_release = threading.Event() + self.image_release.set() + self.publish_entered = threading.Event() + self.publish_release = threading.Event() + self.publish_release.set() world = self class Handler(BaseHTTPRequestHandler): @@ -40,15 +50,40 @@ def respond(self): body = self.rfile.read(int(self.headers.get("Content-Length", "0"))) world.requests.append(target) status, content_type = 200, "application/json" - if path.endswith("/chat/completions"): + if path == "/open-apis/auth/v3/tenant_access_token/internal": + value = {"code": 0, "tenant_access_token": "fixture-token", "expire": 7200} + elif path == "/open-apis/im/v1/messages": + if self.command == "POST": + world.notifications.append(json.loads(json.loads(body)["content"])["text"]) + value = {"code": 0, "data": {"items": [], "has_more": False, "message_id": "om_fixture"}} + elif "/resources/" in path: + world.image_entered.set() + if not world.image_release.wait(10): + self.send_error(500) + return + data = b"\x89PNG\r\n\x1a\nfixture" + self.send_response(200) + self.send_header("Content-Type", "image/png") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + return + elif path.endswith("/chat/completions"): world.model_entered.set() if not world.model_release.wait(10): status, value = 500, {"error": "fixture model was not released"} else: - value = {"choices": [{"message": {"content": "A fixture trend summary."}}]} + messages = json.loads(body).get("messages", []) + vision = any(isinstance(item.get("content"), list) for item in messages) + content = json.dumps({"title": "Known firmware paper", "url": "https://doi.org/10.1000/known"}) if vision else "A fixture trend summary." + value = {"choices": [{"message": {"content": content}}]} elif path == "/api/insight/publish": payload = json.loads(body) world.published.append(payload) + world.publish_entered.set() + if not world.publish_release.wait(10): + self.send_error(500) + return value = world.receipts.get(payload.get("person"), { "ok": True, "deliveredTo": [payload.get("person", "A")], }) @@ -62,6 +97,10 @@ def respond(self): '' '') elif "api.crossref.org" in target: + world.verification_entered.set() + if not world.verification_release.wait(10): + self.send_error(500) + return value = {"message": {"items": []}} elif "api.openalex.org" in target: value = {"results": []} @@ -109,6 +148,9 @@ def __enter__(self): def __exit__(self, *args): self.model_release.set() + self.verification_release.set() + self.image_release.set() + self.publish_release.set() self.server.shutdown() self.thread.join() self.server.server_close() diff --git a/tests/test_bot_lifecycle.py b/tests/test_bot_lifecycle.py new file mode 100644 index 0000000..e07b07c --- /dev/null +++ b/tests/test_bot_lifecycle.py @@ -0,0 +1,163 @@ +import json +import sys +import threading +import time +import unittest +from contextlib import contextmanager +from unittest.mock import patch + +import lark_oapi as lark + +from fastinsight.bot import FastInsightBot +from tests.http_world import HTTPWorld + + +def event(identifier, text="", *, image=False, timestamp=None): + return {"header": {"event_id": identifier}, "event": { + "sender": {"sender_type": "user", "sender_id": {"open_id": "ou_person"}}, + "message": {"message_id": identifier, "chat_id": "oc_fixture", + "create_time": str(int((timestamp or time.time()) * 1000)), + "message_type": "image" if image else "text", + "content": json.dumps({"image_key": identifier} if image else {"text": text})}, + }} + + +@contextmanager +def bot_world(): + with HTTPWorld() as world: + builder = lark.Client.builder + # The SDK itself stays real; select its public local-server domain boundary. + with patch.object(lark.Client, "builder", side_effect=lambda: builder().domain(world.origin)): + bot = FastInsightBot() + existing_threads = set(threading.enumerate()) + try: + yield bot, world + finally: + world.model_release.set() + world.verification_release.set() + world.image_release.set() + world.publish_release.set() + bot.handle_event(event("cleanup", "@fastinsight cancel")) + for thread in set(threading.enumerate()) - existing_threads: + thread.join(5) + if thread.is_alive(): + raise AssertionError(f"Scenario-owned thread did not finish: {thread.name}") + + +def wait_until(predicate): + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + if predicate(): + return + time.sleep(0.01) + raise AssertionError("Expected lifecycle transition did not complete") + + +class BotLifecycleScenarios(unittest.TestCase): + def test_cancel_during_identification_verification_or_trend_prevents_publication(self): + for stage in ("image", "verification", "model"): + with self.subTest(stage=stage): + with bot_world() as (bot, world): + getattr(world, stage + "_release").clear() + bot.handle_event(event("start", "@fastinsight")) + if stage == "image": + bot.handle_event(event("payload", image=True)) + else: + bot.handle_event(event("payload", "https://doi.org/10.1000/known firmware")) + self.assertTrue(getattr(world, stage + "_entered").wait(5)) + bot.handle_event(event("cancel", "@fastinsight cancel")) + self.assertFalse(bot.capture.status("oc_fixture")["armed"]) + getattr(world, stage + "_release").set() + self.assertEqual(world.published, []) + + def test_cancel_drains_admitted_publish_and_prevents_the_next_recipient(self): + with bot_world() as (bot, world): + world.publish_release.clear() + bot.handle_event(event("start", "@fastinsight")) + bot.handle_event(event("payload", "https://doi.org/10.1000/known firmware")) + self.assertTrue(world.publish_entered.wait(5)) + cancelled = threading.Event() + def cancel(): + bot.handle_event(event("cancel", "@fastinsight cancel")) + cancelled.set() + thread = threading.Thread(target=cancel) + thread.start() + try: + self.assertFalse(cancelled.wait(0.1), "Cancellation acknowledged an in-flight publication") + finally: + world.publish_release.set() + thread.join(5) + self.assertTrue(cancelled.is_set()) + self.assertEqual([item["person"] for item in world.published], ["A"]) + + def test_window_completion_keeps_registered_work_cancellable(self): + for cancel_after_window in (False, True): + with self.subTest(cancel=cancel_after_window), bot_world() as (bot, world): + original_time = time.time + offset = [0] + with patch("time.time", side_effect=lambda: original_time() + offset[0]): + world.model_release.clear() + bot.handle_event(event("start", "@fastinsight")) + bot.handle_event(event("payload", "https://doi.org/10.1000/known firmware")) + self.assertTrue(world.model_entered.wait(5)) + offset[0] = 61 + wait_until(lambda: bot.capture.status("oc_fixture")["record"].get("status") == "completed" + and len(world.notifications) >= 3) + if cancel_after_window: + bot.handle_event(event("cancel", "@fastinsight cancel")) + world.model_release.set() + if not cancel_after_window: + wait_until(lambda: len(world.published) == 2) + self.assertEqual(len(world.published), 0 if cancel_after_window else 2) + + def test_cancel_interleaved_with_arm_leaves_no_orphan_capture(self): + with bot_world() as (bot, world): + entered, release, cancelled = threading.Event(), threading.Event(), threading.Event() + observed = {"active": True, "thread": None, "blocked": False} + def filesystem_boundary(name, arguments): + if (observed["active"] and name == "os.mkdir" + and threading.get_ident() == observed["thread"] + and str(arguments[0]) == str(world.root) and not observed["blocked"]): + observed["blocked"] = True + entered.set() + if not release.wait(5): + raise AssertionError("Filesystem boundary was not released") + # Python's OS audit boundary controls the actual mkdir, without replacing CaptureStore. + sys.addaudithook(filesystem_boundary) + def start(): + observed["thread"] = threading.get_ident() + bot.handle_event(event("start", "@fastinsight")) + starter = threading.Thread(target=start) + starter.start() + self.assertTrue(entered.wait(5)) + def cancel(): + bot.handle_event(event("cancel", "@fastinsight cancel")) + cancelled.set() + canceller = threading.Thread(target=cancel) + canceller.start() + try: + cancelled.wait(1) + finally: + release.set() + observed["active"] = False + starter.join(5) + canceller.join(5) + self.assertTrue(cancelled.is_set()) + self.assertFalse(bot.capture.status("oc_fixture")["armed"]) + + def test_old_worker_cannot_complete_or_publish_into_replacement_batch(self): + with bot_world() as (bot, world): + world.model_release.clear() + bot.handle_event(event("old", "@fastinsight")) + bot.handle_event(event("payload", "https://doi.org/10.1000/known firmware")) + self.assertTrue(world.model_entered.wait(5)) + bot.handle_event(event("new", "@fastinsight")) + replacement = bot.capture.status("oc_fixture")["record"]["batch_id"] + world.model_release.set() + bot.handle_event(event("new-payload", "https://doi.org/10.1000/known firmware")) + wait_until(lambda: len(world.published) >= 2) + self.assertEqual(len(world.published), 2) + state = bot.capture.status("oc_fixture") + self.assertTrue(state["armed"]) + self.assertEqual(state["record"]["batch_id"], replacement) + self.assertEqual(len(world.published), 2)