diff --git a/scripts/auto-reply-worker.py b/scripts/auto-reply-worker.py index 2f86925f..13d7144c 100755 --- a/scripts/auto-reply-worker.py +++ b/scripts/auto-reply-worker.py @@ -403,8 +403,9 @@ def kakao_image_kind(message_type: object) -> int | None: "directed_at_self", } ) -MEDIA_UNAVAILABLE_CLARIFICATION = "사진이 안 열리네 다시 보내봐" +MEDIA_UNAVAILABLE_CLARIFICATION = "사진 내용을 확인하지 못했어. 필요한 부분은 글로 알려줘" MEDIA_UNAVAILABLE_CLARIFICATION_REASON = "media_unavailable_clarification" +IMAGE_INPUT_UNAVAILABLE = b"image_input_unavailable" REPLY_LAUGHTER_POLICY_REASON = "reply_laughter_policy_violation" AI_TELL_PROBE = "그래? 어떤 부분이 AI처럼 느껴졌는데" # Trailing laughter, jamo runs and punctuation are ignored when a rule checks the @@ -2038,6 +2039,62 @@ def _finish_model_call_success(lease_token: str, *, model: str | None = None) -> connection.close() +def _release_unsent_model_call(lease_token: str, model: str | None = None) -> bool: + """Release a lease whose request was never sent, keeping prior failures.""" + connection: sqlite3.Connection | None = None + transaction_started = False + try: + connection = _model_circuit_connection() + connection.execute("BEGIN IMMEDIATE") + transaction_started = True + key = _model_circuit_key(model) + row = connection.execute( + """ + SELECT state, failure_class, consecutive_failures, + open_until, lease_token + FROM model_circuit_breaker WHERE model_key = ? + """, + (key,), + ).fetchone() + current = time.time() + if ( + row is None + or not _valid_model_circuit_row(row, current) + or str(row["state"]) != "in_flight" + or str(row["lease_token"]) != lease_token + ): + connection.commit() + transaction_started = False + return False + if int(row["consecutive_failures"]) == 0: + changed = connection.execute( + """ + DELETE FROM model_circuit_breaker + WHERE model_key = ? AND state = 'in_flight' AND lease_token = ? + """, + (key, lease_token), + ).rowcount + else: + changed = connection.execute( + """ + UPDATE model_circuit_breaker + SET state = 'open', open_until = ?, lease_token = NULL, updated_at = ? + WHERE model_key = ? AND state = 'in_flight' AND lease_token = ? + """, + (current, current, key, lease_token), + ).rowcount + connection.commit() + transaction_started = False + return changed == 1 + except (OSError, PermissionError, sqlite3.Error, ValueError): + if transaction_started and connection is not None: + _rollback_queue_transaction(connection) + return False + finally: + if connection is not None: + connection.close() + + def _bounded_error_scalars(value: object, *, depth: int = 0) -> list[str]: if depth > 3: return [] @@ -6409,11 +6466,7 @@ def reject(reason: str) -> bool: return reject("empty") if len(text) > 220: return reject("too_long") - if ( - _is_context_pointer(inbound) - and _contextual_clarification_reply(inbound, recent_conversation) - and _is_contextless_confusion_reply(text) - ): + if _is_contextless_confusion_reply(text): return reject("contextless_confusion") if not _outbound_reaction_allows( text, inbound, laughter_allowed=laughter_allowed, awe_allowed=awe_allowed @@ -6722,7 +6775,7 @@ def _is_contextless_confusion_reply(reply: str) -> bool: return bool( re.fullmatch( r"(?:무슨|뭔)(?:말|뜻|소리)인지모르겠(?:네요|어요|네|어)?|" - r"(?:잘)?이해가(?:잘)?안되(?:네요|어요|네|어)?", + r"(?:잘)?이해가(?:잘)?안(?:되(?:네요|어요|네|어|요)?|돼(?:네요|요|네)?)", compact, ) ) @@ -6767,41 +6820,26 @@ def _contextual_clarification_reply( ending = "얘기예요?" if _recipient_requires_honorific(recipient, register) else "얘기야?" return f"아까 “{topic}” {ending}" + +def _missing_context_clarification_reply( + *, + recipient: str | None = None, + register: str | None = None, +) -> str: + # Not phrased as a question: the pre-send policy recheck rejects a + # question reply to a non-question turn such as "???". + if _recipient_requires_honorific(recipient, register): + return "어떤 얘기인지 조금만 더 말씀해 주세요" + return "어떤 얘기인지 조금만 더 말해줘" + + def _photo_fallback_reply( - inbound: str, recent_conversation: list[dict] | None = None + *, recipient: str | None = None, register: str | None = None ) -> str: - honorific = False - for row in recent_conversation or []: - if not isinstance(row, dict) or _is_self_chat_row(row): - continue - if str(row.get("author_nickname") or "") == "현준": - honorific = True - break - informal = ( - "화면이 좀 깨지네", - "화질이 별로네", - "이거 잘 안 보이네", - "구도가 이상하네", - "색감이 별로네", - ) - formal = ( - "화면이 좀 깨지네요", - "화질이 별로네요", - "잘 안 보이네요", - "구도가 이상하네요", - "색감이 별로네요", - ) - pool = formal if honorific else informal - recent_self = [ - " ".join(str(row.get("message") or "").split()) - for row in (recent_conversation or []) - if isinstance(row, dict) and _is_self_chat_row(row) - ][-6:] - used = set(recent_self) - unused = [line for line in pool if line not in used] - seed = abs(hash(" ".join(recent_self[-2:] + [str(inbound or "")]))) - chosen = (unused or list(pool))[seed % len(unused or pool)] - return chosen + """Admit that the photo was not inspected instead of inventing a remark.""" + if _recipient_requires_honorific(recipient, register): + return "사진 내용을 확인하지 못했어요. 필요한 부분은 글로 알려주세요" + return MEDIA_UNAVAILABLE_CLARIFICATION def _reply_ending(text: str) -> str: @@ -6834,7 +6872,8 @@ def _lenient_policy_draft(drafts: list[str], inbound: str) -> str | None: Operator rule: an authorized sender is never skipped, so a draft that the full policy refused may still go out when it clears the light rules — not empty, not longer than 220 characters, not a verbatim copy of the inbound - message. Every relaxation stays visible through the policy_rejections list. + message, not a generic confusion line. Every relaxation stays visible + through the policy_rejections list. """ normalized_inbound = " ".join(str(inbound or "").split()) for item in drafts: @@ -6843,6 +6882,8 @@ def _lenient_policy_draft(drafts: list[str], inbound: str) -> str | None: continue if normalized_inbound and text == normalized_inbound: continue + if _is_contextless_confusion_reply(text): + continue return text return None @@ -6917,10 +6958,14 @@ def select_ranked_reply( inbound ) fallback_text = "" + has_contextless_confusion = False for item in [preferred, *drafts]: text = " ".join(str(item or "").split()) if _outbound_youtube_title_label(text, inbound): text = _rewrite_youtube_title_label(text) + if _is_contextless_confusion_reply(text): + has_contextless_confusion = True + continue if text: fallback_text = text break @@ -6931,7 +6976,7 @@ def select_ranked_reply( register=register, ) if contextual_clarification and ( - not fallback_text or _is_contextless_confusion_reply(fallback_text) + not fallback_text or has_contextless_confusion ): return { "reply": contextual_clarification, @@ -6941,6 +6986,27 @@ def select_ranked_reply( "fallback": "contextual_clarification", "policy_rejections": policy_rejections, } + if has_contextless_confusion: + # Every other draft was refused by the full policy too, so none of + # them may stand in for the confusion line that was dropped. + if str(event.get("attachment") or "") == "image": + clarification = _photo_fallback_reply( + recipient=recipient, register=register + ) + fallback = "photo_passthrough" + else: + clarification = _missing_context_clarification_reply( + recipient=recipient, register=register + ) + fallback = "missing_context_clarification" + return { + "reply": clarification, + "drafts": [clarification], + "scores": [], + "winner_index": 0, + "fallback": fallback, + "policy_rejections": policy_rejections, + } if inbound_is_question and str(event.get("attachment") or "") != "image": fallback_text = fallback_text or _unknown_detail_reply( inbound, recent_conversation @@ -6955,7 +7021,7 @@ def select_ranked_reply( } if str(event.get("attachment") or "") == "image": fallback_text = fallback_text or _photo_fallback_reply( - inbound, recent_conversation + recipient=recipient, register=register ) return { "reply": fallback_text, @@ -11594,6 +11660,10 @@ def _model_fallback_chain( keeps a fallback that answered from being reported as circuit_unavailable and deferred anyway. Returns None when no candidate could run, and never raises: one broken candidate is skipped instead of ending the turn (2026-09-15). + + A candidate that sent nothing because no image loaded also ends the chain, + with its lease still open: every later candidate would get the same missing + images, and the caller releases that lease without charging a failure. """ for candidate in _reply_fallback_candidates(): @@ -11623,7 +11693,7 @@ def _model_fallback_chain( flush=True, ) continue - if returncode != 0: + if returncode != 0 and stderr_bytes != IMAGE_INPUT_UNAVAILABLE: failure_class, retry_after = _classify_model_failure( returncode, stdout_bytes, @@ -11696,6 +11766,7 @@ def _run_opencodex_generation_unleased( prompt_bytes: bytes, *, image_paths: list[Path] | None = None, + images_required: bool = True, timeout: float = 30.0, base_url: str = "http://127.0.0.1:11234/v1", ) -> tuple[int, bytes, bytes]: @@ -11777,10 +11848,14 @@ def _run_opencodex_generation_unleased( ) if len(user_parts) > 1: payload["messages"][1]["content"] = user_parts - elif image_paths: - # Every image failed to load. Sending the text alone would answer a - # question about a photo without the photo, so say so in the prompt - # instead of pretending the message had no attachment. + elif images_required: + # Every image of a photo turn failed to load. A text-only request + # lets the model answer about a photo it never saw, whatever the + # prompt says. + return 1, b"", IMAGE_INPUT_UNAVAILABLE + else: + # The images were only earlier context for a text turn, so answer + # the text and tell the model the photos could not be read. payload["messages"][1]["content"] = ( user_content + "\n\n[첨부한 사진을 읽지 못했습니다. 사진 내용을 모르는 상태이므로," @@ -11837,6 +11912,7 @@ def _run_opencodex_generation( prompt_bytes: bytes, *, image_paths: list[Path] | None = None, + images_required: bool = True, timeout: float = 30.0, base_url: str = "http://127.0.0.1:11234/v1", ) -> tuple[int, bytes, bytes]: @@ -11848,6 +11924,7 @@ def _run_opencodex_generation( system_prompt, prompt_bytes, image_paths=image_paths, + images_required=images_required, timeout=timeout, base_url=base_url, ) @@ -11858,6 +11935,7 @@ def _run_opencodex_generation( system_prompt, prompt_bytes, image_paths=image_paths, + images_required=images_required, timeout=timeout, base_url=base_url, ) @@ -11873,6 +11951,7 @@ def _run_generation_candidate( env: dict[str, str], model_stdin_bytes: bytes | None, image_paths: list[Path] | None, + images_required: bool = True, timeout: float, ) -> tuple[int, bytes, bytes]: if not _product_local_model_allowed(model): @@ -11885,6 +11964,7 @@ def _run_generation_candidate( system_prompt, prompt_bytes, image_paths=image_paths, + images_required=images_required, timeout=timeout, ) return _run_bounded_process( @@ -12379,6 +12459,7 @@ def run_fallback_candidate(candidate: str) -> tuple[int, bytes, bytes]: env=env, model_stdin_bytes=model_stdin_bytes, image_paths=normalized_image_paths, + images_required=attachment == "image", timeout=_model_generation_timeout(candidate, deadline=generation_deadline), ) @@ -12531,9 +12612,10 @@ def continue_on_fallback( env=env, model_stdin_bytes=model_stdin_bytes, image_paths=normalized_image_paths, + images_required=attachment == "image", timeout=_model_generation_timeout(active_model, deadline=generation_deadline), ) - if returncode != 0: + if returncode != 0 and stderr_bytes != IMAGE_INPUT_UNAVAILABLE: err_str = stderr_bytes.decode("utf-8", "replace").casefold() failure_class, _ = _classify_model_failure( returncode, @@ -12641,6 +12723,12 @@ def continue_on_fallback( continue_on_fallback( winner, "opencode_go_quota_fallback", first_class, first_retry ) + if returncode != 0 and stderr_bytes == IMAGE_INPUT_UNAVAILABLE: + # No request was sent, by the primary or by the fallback adopted above, + # so that model is not at fault, and another one would get the same + # missing images. + _release_unsent_model_call(lease_token, active_model) + return with_prompt_receipt({**empty, "reason": "image_unavailable"}) held = turn_hold() if held: @@ -14130,7 +14218,10 @@ def analyze_media_unavailable_clarification(event: dict) -> dict: "decision": "reply", "reason": MEDIA_UNAVAILABLE_CLARIFICATION_REASON, "category": "social", - "reply": _photo_fallback_reply(inbound_text, recent_conversation), + "reply": _photo_fallback_reply( + recipient=_event_author_nickname(event), + register=str((recipient_style_profile or {}).get("register") or "") or None, + ), "context": context, "styles": styles, "prior_decisions": prior_decisions, @@ -14525,6 +14616,21 @@ def analyze_event(event: dict) -> dict: "prompt_evidence_ids": model.get("prompt_evidence_ids"), "generation_seconds": model.get("generation_seconds"), } + if attachment == "image" and str(model.get("reason") or "") == "image_unavailable": + # No image could be shown to the model, so no request was sent. + # An authorized sender still gets an answer, one that admits it. + provenance["model_invoked"] = False + result.update( + decision="reply", + reason=MEDIA_UNAVAILABLE_CLARIFICATION_REASON, + category="social", + reply=_photo_fallback_reply( + recipient=_event_author_nickname(event), + register=str((recipient_style_profile or {}).get("register") or "") + or None, + ), + ) + return result if not model.get("should_reply"): failure_class = str(model.get("model_failure_class") or "") retry_at = model.get("model_defer_until") @@ -15713,8 +15819,10 @@ def _analyze_and_schedule_reply( analysis["reason"] = str(analysis.get("reason") or "photo_reply") analysis["category"] = "reaction" analysis["reply"] = str(analysis.get("reply") or "").strip() or _photo_fallback_reply( - str(event.get("message") or ""), - _event_recent_conversation(event), + recipient=_event_author_nickname(event), + register=str( + (analysis.get("recipient_style_profile") or {}).get("register") or "" + ) or None, ) else: # The model remained unavailable through this message's learned diff --git a/tests/test_auto_reply_cli_runtime.py b/tests/test_auto_reply_cli_runtime.py index b04ccc59..82536d4e 100644 --- a/tests/test_auto_reply_cli_runtime.py +++ b/tests/test_auto_reply_cli_runtime.py @@ -1397,22 +1397,27 @@ def test_reaction_register_blocks_unprompted_laughter(self): "style:youtube_reaction_register:v1", ) - def test_photo_fallback_varies_and_media_placeholder_is_not_echo(self): - module = self._load_auto_reply_module("auto_reply_photo_fallback_vary_test") + def test_photo_fallback_admits_it_did_not_see_the_photo(self): + module = self._load_auto_reply_module("auto_reply_photo_fallback_truthful_test") self.assertTrue(module._inbound_is_media_placeholder("사진")) self.assertFalse(module._outbound_echoes_inbound("화면이 좀 깨지네", "사진")) - self.assertTrue( - module._policy_valid_draft("화면이 좀 깨지네", "사진", [], []) - ) - recent = [{"is_self": True, "message": "화면이 좀 깨지네"}] - first = module._photo_fallback_reply("사진", recent) - self.assertNotEqual(first, "이거 뭐야") - self.assertNotIn(first, {"화면이 좀 깨지네"}) - second = module._photo_fallback_reply( - "사진", - recent + [{"is_self": True, "message": first}], - ) - self.assertNotEqual(second, first) + for recipient, expected in ( + ("MOM", "사진 내용을 확인하지 못했어. 필요한 부분은 글로 알려줘"), + ("현준", "사진 내용을 확인하지 못했어요. 필요한 부분은 글로 알려주세요"), + ): + with self.subTest(recipient=recipient): + result = module.select_ranked_reply( + "사진", + "", + [], + {"author_nickname": recipient, "attachment": "image"}, + [{"is_self": True, "message": "화면이 좀 깨지네"}], + ) + self.assertEqual(result["fallback"], "photo_passthrough") + self.assertEqual(result["reply"], expected) + self.assertTrue( + module._policy_valid_draft(expected, "사진", [], recipient=recipient) + ) def test_unsolicited_plan_is_rejected(self): module = self._load_auto_reply_module("auto_reply_unsolicited_plan_test") self.assertTrue( @@ -1946,6 +1951,92 @@ def test_punctuation_followup_uses_recent_topic_instead_of_generic_confusion(sel self.assertEqual(unknown["fallback"], "question_unknown") self.assertEqual(unknown["reply"], "몇 명인진 안 나와서 모르겠네") + def test_generic_confusion_reply_is_never_sent(self): + module = self._load_auto_reply_module("auto_reply_ungrounded_confusion_test") + confusion = ["무슨 말인지 모르겠네요", "무슨 말인지 모르겠어요"] + for inbound in ("그래서?", "???", "아 그렇구나"): + with self.subTest(inbound=inbound): + result = module.select_ranked_reply( + inbound, confusion[0], confusion[1:], {"author_nickname": "MOM"}, [] + ) + self.assertEqual(result["fallback"], "missing_context_clarification") + self.assertEqual(result["reply"], "어떤 얘기인지 조금만 더 말해줘") + self.assertTrue( + module._policy_valid_draft(result["reply"], inbound, [], recipient="MOM") + ) + honorific = module.select_ranked_reply( + "그래서?", confusion[0], confusion[1:], {"author_nickname": "현준"}, [] + ) + self.assertEqual(honorific["reply"], "어떤 얘기인지 조금만 더 말씀해 주세요") + self.assertTrue( + module._policy_valid_draft(honorific["reply"], "그래서?", [], recipient="현준") + ) + + self.assertIsNone(module._lenient_policy_draft([confusion[0]], "아 그렇구나")) + + def test_every_spelling_of_not_understanding_is_a_confusion_reply(self): + module = self._load_auto_reply_module("auto_reply_confusion_spelling_test") + spellings = ( + "이해가 안 되네요", + "이해가 안 되어요", + "이해가 안 돼", + "이해가 안 돼요", + "이해가 잘 안 돼", + "잘 이해가 안 돼요", + "이해가 안 되요", + "이해가 안 돼네", + "이해가 안 돼네요", + ) + for confusion in spellings: + with self.subTest(confusion=confusion): + self.assertFalse( + module._policy_valid_draft(confusion, "아 그렇구나", [], recipient="MOM") + ) + self.assertIsNone(module._lenient_policy_draft([confusion], "아 그렇구나")) + result = module.select_ranked_reply( + "아 그렇구나", confusion, [], {"author_nickname": "MOM"}, [] + ) + self.assertEqual(result["reply"], "어떤 얘기인지 조금만 더 말해줘") + self.assertTrue( + module._policy_valid_draft("이해가 안 돼서 다시 물어봤어", "아 그렇구나", [], recipient="MOM") + ) + + def test_removed_confusion_draft_never_promotes_a_rejected_draft(self): + module = self._load_auto_reply_module("auto_reply_confusion_no_promotion_test") + cases = ( + ("아 그렇군요", "무슨 말인지 모르겠어요", "그치 뭐함?", "현준", "", + "어떤 얘기인지 조금만 더 말씀해 주세요"), + ("아 그렇구나", "무슨 말인지 모르겠어", "너는 뭐 먹었어?", "MOM", "", + "어떤 얘기인지 조금만 더 말해줘"), + ("아 그렇구나", "무슨 말인지 모르겠네요", "ㅋㅋㅋㅋ", "MOM", "", + "어떤 얘기인지 조금만 더 말해줘"), + ("사진", "무슨 말인지 모르겠어", "이거 어디야?", "MOM", "image", + "사진 내용을 확인하지 못했어. 필요한 부분은 글로 알려줘"), + ("사진", "무슨 말인지 모르겠어요", "이거 어디야?", "현준", "image", + "사진 내용을 확인하지 못했어요. 필요한 부분은 글로 알려주세요"), + ) + for inbound, confusion, rejected, recipient, attachment, expected in cases: + with self.subTest(inbound=inbound, rejected=rejected, recipient=recipient): + self.assertFalse( + module._policy_valid_draft(rejected, inbound, [], recipient=recipient) + ) + result = module.select_ranked_reply( + inbound, + confusion, + [rejected], + {"author_nickname": recipient, "attachment": attachment}, + [], + ) + self.assertEqual(result["reply"], expected) + self.assertNotEqual(result["fallback"], "lenient_policy") + reasons = [] + self.assertTrue( + module._policy_valid_draft( + result["reply"], inbound, [], recipient=recipient, reasons_out=reasons + ), + reasons, + ) + def test_punctuation_followup_can_clarify_the_last_self_reply(self): module = self._load_auto_reply_module("auto_reply_self_context_pointer_test") recent = [ @@ -15375,8 +15466,10 @@ def record(decision): (row["scheduled_delay_seconds"], row["error_class"]), (5.0, None) ) # The reply prompt forbids stock photo acks such as 사진이 안 열리네. - self.assertTrue(row["reply"].strip()) self.assertNotIn("사진이 안 열리네", row["reply"]) + self.assertEqual( + row["reply"], "사진 내용을 확인하지 못했어. 필요한 부분은 글로 알려줘" + ) self.assertEqual(recorded["style_policy_version"], module.STYLE_POLICY_VERSION) self.assertIn("db:42:920", recorded["evidence_ids"]) self.assertFalse(recorded["provenance"]["model_invoked"]) @@ -15717,6 +15810,362 @@ def test_generate_reply_passes_ordered_multi_image_flags(self): self.assertTrue(result["should_reply"]) self.assertEqual(result["evidence_ids"], [evidence_id]) + def test_generate_reply_sends_no_request_when_no_image_loads(self): + with tempfile.TemporaryDirectory(dir=Path.home()) as temporary: + root = Path(temporary) + module, _runner = self._load_trusted_codex_module( + "auto_reply_unloadable_image_test", root + ) + with self._owned_image_bundle(module, count=2, message_type=27) as media: + evidence_id = f"media:{media['manifest']['bundle_sha256']}" + response = { + "should_reply": True, + "reply": "화질이 별로네", + "category": "social", + "reason": "useful_image_response", + "evidence_ids": [evidence_id], + } + image_model = module._generation_reply_model(True) + earlier = time.time() - 3600.0 + prior = module._acquire_model_call_slot(now=earlier, model=image_model) + module._finish_model_call_failure( + prior["lease_token"], "runner_failed", now=earlier, model=image_model + ) + for path in media["paths"]: + path.chmod(0o000) + try: + with ( + self._fake_mlx_gateway( + module, + json.dumps(response, ensure_ascii=False), + model_id=module.QWEN38_27B_MODEL_ID, + ) as gateway, + mock.patch.object( + module, "privacy_attestation_current", return_value=True + ), + mock.patch.object(module, "runner_is_trusted", return_value=True), + mock.patch.object(module, "_run_bounded_process") as process_runner, + ): + result = module.generate_reply( + "이 사진 어때?", + [], + [], + [], + [], + attachment="image", + image_path=media["paths"][0], + image_marker=media["marker"], + image_paths=media["paths"], + media_evidence_id=evidence_id, + ) + connection = module._model_circuit_connection() + try: + failures = connection.execute( + "SELECT consecutive_failures FROM model_circuit_breaker" + " WHERE model_key = ?", + (module._model_circuit_key(image_model),), + ).fetchone() + finally: + connection.close() + circuit = module._acquire_model_call_slot(model=image_model) + finally: + for path in media["paths"]: + path.chmod(0o600) + + self.assertEqual(gateway["payloads"], []) + gateway["external_urlopen"].assert_not_called() + process_runner.assert_not_called() + self.assertFalse(result["should_reply"]) + self.assertEqual(result["reply"], "") + self.assertEqual(result["reason"], "image_unavailable") + self.assertEqual(failures[0], 1) + self.assertTrue(circuit["allowed"], circuit) + for fallback in module._reply_fallback_candidates(): + self.assertEqual(self._model_failures(module, fallback), 0, fallback) + + def _analyze_with_mlx_gateway( + self, module, event, response, *, before_generate, recovered_media=None + ): + """Run analyze_event against the fake local gateway; return what it sent. + + ``recovered_media`` maps a log id to the paths the local media download + would return. No real download or screen capture runs. + """ + real_generate_reply = module.generate_reply + + def generate(*args, **kwargs): + before_generate() + return real_generate_reply(*args, **kwargs) + + with ( + mock.patch.dict( + os.environ, + { + module.DB_MODE_ENV: "database_authoritative", + "OPENKAKAO_ALLOW_IMAGE_ANALYSIS": "1", + }, + clear=False, + ), + mock.patch.object(module, "_reply_turn_hold_reason", return_value=None), + mock.patch.object(module, "privacy_attestation_current", return_value=True), + mock.patch.object(module, "runner_is_trusted", return_value=True), + mock.patch.object(module, "fetch_link_previews", return_value=[]), + mock.patch.object( + module, + "run_context_reply_bundle", + return_value={ + "context": [], + "styles": [], + "prior_decisions": [], + "style_profile": None, + "recipient_style_profile": None, + "response_time": self._timing_stats(module), + }, + ), + self._fake_mlx_gateway( + module, + json.dumps(response, ensure_ascii=False), + model_id=module.QWEN38_27B_MODEL_ID, + ) as gateway, + mock.patch.object(module, "_run_bounded_process") as process_runner, + mock.patch.object(module, "BIN", Path(os.devnull) / "openkakao-cli"), + mock.patch.object( + module, + "_recover_local_media_bundle", + side_effect=lambda media_event: (recovered_media or {}).get( + media_event["log_id"] + ), + ), + mock.patch.object(module, "capture_visible_image", return_value=None), + mock.patch.object(module, "generate_reply", side_effect=generate), + ): + result = module.analyze_event(event) + gateway["external_urlopen"].assert_not_called() + process_runner.assert_not_called() + return result, gateway["payloads"] + + def _assert_presend_accepts(self, module, event, reply): + reasons = [] + self.assertTrue( + module._policy_valid_draft( + reply, + event["message"], + module._event_recent_conversation(event), + recipient=module._event_author_nickname(event), + reasons_out=reasons, + ), + reasons, + ) + + @staticmethod + def _model_failures(module, model): + connection = module._model_circuit_connection() + try: + row = connection.execute( + "SELECT consecutive_failures FROM model_circuit_breaker WHERE model_key = ?", + (module._model_circuit_key(model),), + ).fetchone() + finally: + connection.close() + return 0 if row is None else int(row[0]) + + def test_photo_turn_with_no_loadable_image_replies_honestly_without_a_request(self): + with tempfile.TemporaryDirectory(dir=Path.home()) as temporary: + module, _runner = self._load_trusted_codex_module( + "auto_reply_unloadable_image_turn_test", Path(temporary) + ) + with self._owned_image_bundle(module, count=2, message_type=27) as media: + event = self._burst_event( + module, + 902, + "[사진]", + int(time.time()), + message_type=27, + attachment=True, + ) + event.update(media["event_fields"]) + response = { + "should_reply": True, + "reply": "화질이 별로네", + "category": "social", + "reason": "useful_image_response", + "evidence_ids": [f"media:{media['manifest']['bundle_sha256']}"], + } + + def make_images_unreadable(): + for path in media["paths"]: + path.chmod(0o000) + + try: + result, payloads = self._analyze_with_mlx_gateway( + module, event, response, before_generate=make_images_unreadable + ) + finally: + for path in media["paths"]: + if path.exists(): + path.chmod(0o600) + + self.assertEqual(payloads, []) + self.assertEqual(result["decision"], "reply") + self.assertEqual( + result["reply"], "사진 내용을 확인하지 못했어. 필요한 부분은 글로 알려줘" + ) + self._assert_presend_accepts(module, event, result["reply"]) + + def test_cooldown_fallback_with_no_loadable_image_is_not_charged_a_failure(self): + with tempfile.TemporaryDirectory(dir=Path.home()) as temporary: + module, _runner = self._load_trusted_codex_module( + "auto_reply_unloadable_image_fallback_test", Path(temporary) + ) + image_model = module._generation_reply_model(True) + vision_fallback = image_model.removeprefix("mlx/") + self.assertNotEqual(vision_fallback, image_model) + fallbacks = module._operator_state_root() / module.REPLY_MODEL_FALLBACKS_NAME + fallbacks.parent.mkdir(parents=True, exist_ok=True) + fallbacks.write_text( + json.dumps({"schema_version": 1, "models": [vision_fallback]}), + encoding="utf-8", + ) + self.assertEqual(module._reply_fallback_candidates(), [vision_fallback]) + cooling = module._acquire_model_call_slot(model=image_model) + module._finish_model_call_failure( + cooling["lease_token"], "runner_failed", model=image_model + ) + self.assertFalse(module._acquire_model_call_slot(model=image_model)["allowed"]) + with self._owned_image_bundle(module, count=2, message_type=27) as media: + event = self._burst_event( + module, + 903, + "[사진]", + int(time.time()), + message_type=27, + attachment=True, + ) + event.update(media["event_fields"]) + response = { + "should_reply": True, + "reply": "화질이 별로네", + "category": "social", + "reason": "useful_image_response", + "evidence_ids": [f"media:{media['manifest']['bundle_sha256']}"], + } + + def make_images_unreadable(): + for path in media["paths"]: + path.chmod(0o000) + + try: + result, payloads = self._analyze_with_mlx_gateway( + module, event, response, before_generate=make_images_unreadable + ) + finally: + for path in media["paths"]: + if path.exists(): + path.chmod(0o600) + + self.assertEqual(payloads, []) + self.assertEqual(self._model_failures(module, vision_fallback), 0) + self.assertTrue(module._acquire_model_call_slot(model=vision_fallback)["allowed"]) + self.assertEqual(self._model_failures(module, image_model), 1) + self.assertEqual((result["decision"], result["reason"]), + ("reply", module.MEDIA_UNAVAILABLE_CLARIFICATION_REASON)) + self.assertEqual( + result["reply"], "사진 내용을 확인하지 못했어. 필요한 부분은 글로 알려줘" + ) + self._assert_presend_accepts(module, event, result["reply"]) + + def test_text_turn_whose_recent_photos_do_not_load_is_still_answered(self): + with tempfile.TemporaryDirectory(dir=Path.home()) as temporary: + module, _runner = self._load_trusted_codex_module( + "auto_reply_text_turn_unloadable_photo_test", Path(temporary) + ) + now = int(time.time()) + with self._owned_image_bundle(module, count=1, message_type=2) as media: + photo = self._burst_event( + module, 904, "사진", now - 30, message_type=2, attachment=True + ) + event = self._burst_event( + module, + 905, + "이거 어디서 샀어?", + now, + recent=[self._recent_row(photo)], + ) + self.assertEqual( + [row["log_id"] for row in module._same_author_recent_photo_events(event)], + [904], + ) + response = { + "should_reply": True, + "reply": "다이소에서 샀어", + "category": "social", + "reason": "answer", + "evidence_ids": [], + } + + def make_images_unreadable(): + for path in media["paths"]: + path.chmod(0o000) + + try: + result, payloads = self._analyze_with_mlx_gateway( + module, + event, + response, + before_generate=make_images_unreadable, + recovered_media={904: list(media["paths"])}, + ) + finally: + for path in media["paths"]: + if path.exists(): + path.chmod(0o600) + + self.assertEqual( + (result["decision"], result["reply"]), ("reply", "다이소에서 샀어") + ) + self.assertEqual(len(payloads), 1) + content = payloads[0]["messages"][1]["content"] + self.assertIsInstance(content, str) + self.assertIn("사진을 읽지 못했습니다", content) + + def test_text_turn_never_gets_the_photo_apology_for_context_photos(self): + with tempfile.TemporaryDirectory(dir=Path.home()) as temporary: + module, _runner = self._load_trusted_codex_module( + "auto_reply_text_turn_photo_cap_test", Path(temporary) + ) + now = int(time.time()) + count = module.MAX_IMAGE_INPUTS + 1 + with self._owned_image_bundle(module, count=count, message_type=27) as media: + photo = self._burst_event( + module, 906, "사진", now - 30, message_type=27, attachment=True + ) + event = self._burst_event( + module, + 907, + "이거 어디서 샀어?", + now, + recent=[self._recent_row(photo)], + ) + response = { + "should_reply": True, + "reply": "다이소에서 샀어", + "category": "social", + "reason": "answer", + "evidence_ids": [], + } + result, payloads = self._analyze_with_mlx_gateway( + module, + event, + response, + before_generate=lambda: None, + recovered_media={906: list(media["paths"])}, + ) + + self.assertEqual(payloads, []) + self.assertEqual(result["reason"], "image_unavailable") + self.assertNotEqual(result["decision"], "reply") + self.assertEqual(result["reply"], "") + def test_gjc_generate_reply_sends_prompt_on_stdin_with_at_images(self): with tempfile.TemporaryDirectory(dir=Path.home()) as temporary: root = Path(temporary) @@ -19986,7 +20435,7 @@ def fake_http(url, deadline): self.assertIn("football tactics board", preview["text"]) self.assertTrue(module._inbound_asks_question("리드미 요약해줘")) - def test_unreadable_image_is_named_and_never_answered_blind(self): + def test_unreadable_image_is_never_answered_blind(self): """A photo the worker cannot read must not be dropped in silence. The old code swallowed the read error, so a question about a photo was @@ -20022,13 +20471,8 @@ def fake_urlopen(request, timeout=None): image_paths=[missing], timeout=5.0, ) - self.assertEqual(code, 0) - content = captured["body"]["messages"][1]["content"] - # The text is still sent, but with an explicit note that the photo was - # not readable, so the model cannot guess at a picture it never saw. - self.assertIsInstance(content, str) - self.assertIn("사진을 읽지 못했습니다", content) - self.assertIn("추측하지 말고", content) + self.assertEqual((code, _stderr), (1, b"image_input_unavailable")) + self.assertNotIn("body", captured) def test_readable_image_is_still_attached_as_a_data_url(self): """The failure path must not disturb the working path.""" diff --git a/tests/test_auto_reply_turn_holds.py b/tests/test_auto_reply_turn_holds.py index 7d871d0c..466b68f6 100644 --- a/tests/test_auto_reply_turn_holds.py +++ b/tests/test_auto_reply_turn_holds.py @@ -944,6 +944,7 @@ def fake_generation_candidate( env, model_stdin_bytes, image_paths, + images_required, timeout, ): captured["model"] = model