From fcf9b0fa559f2a1fbbbdd068abaafc2952a8a94f Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:14:41 -0800 Subject: [PATCH] fix: str subclasses with extra constructor fields survive copy and pickle FooteredReply was one of six str subclasses whose __new__ needs more than the text. Python's default copy/pickle rebuild calls cls.__new__(cls, text), so copy.deepcopy of any payload holding one raised TypeError. The gateway deep-copies every published event payload, which is how a footered reply lost its message.complete (#156709, #156824) and how an active-session refusal lost it before (a5d3c25664, which fixed only that one class). Give each remaining class a __getnewargs_ex__ returning its real constructor arguments (TimelineNotification, _ConsentRefusal, _Miss, _ProbeFailure, BacktrackResend), and replace the per-class test with one AST invariant over the whole tree, so a new subclass of this shape fails CI instead of a live turn. --- agent/prepared_compaction.py | 3 ++ hermes_cli/cli_backtrack.py | 3 ++ hermes_cli/plugins_cmd_install.py | 5 +++ persistence/sqlite/_state/repair.py | 3 ++ tests/gateway/test_runtime_footer_copy.py | 34 ------------------- tests/test_str_subclass_copy.py | 41 +++++++++++++++++++++++ tools/process_registry_notifications.py | 3 ++ 7 files changed, 58 insertions(+), 34 deletions(-) delete mode 100644 tests/gateway/test_runtime_footer_copy.py create mode 100644 tests/test_str_subclass_copy.py diff --git a/agent/prepared_compaction.py b/agent/prepared_compaction.py index f6695a99b3..4b212b07d4 100644 --- a/agent/prepared_compaction.py +++ b/agent/prepared_compaction.py @@ -91,6 +91,9 @@ class _Miss(str): miss.code = code return miss + def __getnewargs_ex__(self): # copy/pickle rebuild via __new__, which needs the code + return (self.code, str(self)), {} + def _record(event: str, **dims: Any) -> None: """Count one event in opt-in shared metrics (a no-op when off; never raises).""" diff --git a/hermes_cli/cli_backtrack.py b/hermes_cli/cli_backtrack.py index 1ad8f55d0d..7cccbbbf3c 100644 --- a/hermes_cli/cli_backtrack.py +++ b/hermes_cli/cli_backtrack.py @@ -33,6 +33,9 @@ class BacktrackResend(str): obj.ordinal, obj.expected, obj.session_id, obj.number = ordinal, expected, session_id, number return obj + def __getnewargs_ex__(self): # copy/pickle rebuild via __new__, whose fields are keyword-only + return (str(self),), {k: getattr(self, k) for k in self.__slots__} + class CLIBacktrackMixin: # browse: {"entries": [(ordinal, text)] newest first, "selected", "turns", "_scroll_offset", "_reveal"} diff --git a/hermes_cli/plugins_cmd_install.py b/hermes_cli/plugins_cmd_install.py index cfe451b126..bcbf343b04 100644 --- a/hermes_cli/plugins_cmd_install.py +++ b/hermes_cli/plugins_cmd_install.py @@ -60,11 +60,16 @@ class _ConsentRefusal(str): """A refusal reason (user-facing text) carrying its closed extension-install ``failure_class``, so publication classifies the refusal without matching the copy.""" + failure_class: str + def __new__(cls, text: str, failure_class: str) -> _ConsentRefusal: refusal = super().__new__(cls, text) refusal.failure_class = failure_class return refusal + def __getnewargs_ex__(self): # copy/pickle rebuild via __new__, which needs the class + return (str(self), self.failure_class), {} + def _install_plugin_python_deps( manifest: dict, target: Path, console, *, assume_yes: bool = False diff --git a/persistence/sqlite/_state/repair.py b/persistence/sqlite/_state/repair.py index 6f54ba6360..351ad9c530 100644 --- a/persistence/sqlite/_state/repair.py +++ b/persistence/sqlite/_state/repair.py @@ -776,6 +776,9 @@ class _ProbeFailure(str): reason.sqlite_errorcode = getattr(exc, "sqlite_errorcode", 0) return reason + def __getnewargs_ex__(self): # copy/pickle rebuild via __new__; only the code survives the exception + return (str(self), sqlite3.Error()), {} + def _is_temporary_file_failure(failure) -> bool: return (getattr(failure, "sqlite_errorcode", 0) & 0xFF) in _TEMPORARY_FILE_FAILURE_CODES or is_disk_full_error(failure) diff --git a/tests/gateway/test_runtime_footer_copy.py b/tests/gateway/test_runtime_footer_copy.py deleted file mode 100644 index b381d7569d..0000000000 --- a/tests/gateway/test_runtime_footer_copy.py +++ /dev/null @@ -1,34 +0,0 @@ -"""``FooteredReply`` is a str subclass whose ``__new__`` needs a footer, so the default -copy/pickle reconstruction (``cls.__new__(cls)``) raised TypeError. The gateway deepcopies -every event payload in ``gateway.session_events.publish``, which turned that into a failed -``message.complete`` publication and a viewer stuck on "working".""" -import pickle -from copy import copy, deepcopy - -from gateway.runtime_footer import FooteredReply - -FOOTER = "gpt-5.4 · 68% · ~/projects/hermes" - - -def _reply(): - return FooteredReply("Here it is", FOOTER) - - -def test_deepcopy_of_a_payload_holding_the_reply_keeps_the_footer(): - reply = _reply() - frame = deepcopy({"text": reply, "content": reply}) - assert frame["text"] == f"Here it is\n\n{FOOTER}" - assert frame["text"].runtime_footer == FOOTER - - -def test_copy_returns_the_immutable_reply_itself(): - reply = _reply() - assert copy(reply) is reply - assert deepcopy(reply) is reply - - -def test_pickle_roundtrip_keeps_the_footer_once(): - reply = pickle.loads(pickle.dumps(_reply())) - assert isinstance(reply, FooteredReply) - assert str(reply) == f"Here it is\n\n{FOOTER}" - assert reply.runtime_footer == FOOTER diff --git a/tests/test_str_subclass_copy.py b/tests/test_str_subclass_copy.py new file mode 100644 index 0000000000..9cdbfa61c3 --- /dev/null +++ b/tests/test_str_subclass_copy.py @@ -0,0 +1,41 @@ +"""A ``str`` subclass whose ``__new__`` needs more than the text cannot be rebuilt by the default +copy/pickle path (``cls.__new__(cls, text)``): ``copy.deepcopy`` of any payload holding one raises +``TypeError``. The gateway deep-copies every published event payload, so a footered reply lost +its ``message.complete`` (#156709) the same way an active-session refusal did before it.""" +import ast +import copy +import pickle +from pathlib import Path + +from gateway.runtime_footer import FooteredReply + +REPO = Path(__file__).resolve().parents[1] +_SKIP = {"tests", ".venv", "node_modules", "apps", "web", "website", ".worktrees", "evals"} +_HOOKS = {"__getnewargs__", "__getnewargs_ex__", "__reduce__", "__reduce_ex__"} + + +def _needs_extra_args(fn: ast.FunctionDef) -> bool: + a = fn.args + positional = len(a.posonlyargs) + len(a.args) - len(a.defaults) - 2 # cls + text + return positional > 0 or any(d is None for d in a.kw_defaults) + + +def test_every_str_subclass_with_a_wider_new_defines_its_copy_args(): + offenders = [] + for path in REPO.rglob("*.py"): + if _SKIP & set(path.relative_to(REPO).parts): + continue + for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): + if not (isinstance(node, ast.ClassDef) and any(getattr(b, "id", None) == "str" for b in node.bases)): + continue + methods = {f.name: f for f in node.body if isinstance(f, ast.FunctionDef)} + if "__new__" in methods and _needs_extra_args(methods["__new__"]) and not _HOOKS & set(methods): + offenders.append(f"{path.relative_to(REPO)}::{node.name}") + assert offenders == [], offenders + + +def test_footered_reply_survives_deepcopy_and_pickle_with_its_footer(): + reply = FooteredReply("Here it is", "gpt-5.4 · 68% · ~/projects/hermes") + for clone in (copy.deepcopy({"response": reply})["response"], pickle.loads(pickle.dumps(reply))): + assert str(clone) == "Here it is\n\ngpt-5.4 · 68% · ~/projects/hermes" + assert clone.runtime_footer == reply.runtime_footer diff --git a/tools/process_registry_notifications.py b/tools/process_registry_notifications.py index 69f97c3abc..0a8be12dd4 100644 --- a/tools/process_registry_notifications.py +++ b/tools/process_registry_notifications.py @@ -508,6 +508,9 @@ class TimelineNotification(str): instance.notification_category = notification_category return instance + def __getnewargs_ex__(self): # copy/pickle rebuild via __new__, which needs every field + return (str(self), self.display_text, self.display_kind, self.notification_category), {} + @classmethod def for_delegation(cls, text: str, event: dict) -> "TimelineNotification": from agent.notification_presentation import diagnostic_process_event