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.
This commit is contained in:
@@ -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)."""
|
||||
|
||||
@@ -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"}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
41
tests/test_str_subclass_copy.py
Normal file
41
tests/test_str_subclass_copy.py
Normal file
@@ -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
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user