ctxblame 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ctxblame/__init__.py +1 -0
- ctxblame/ablate.py +468 -0
- ctxblame/blame.py +1262 -0
- ctxblame/cli.py +68 -0
- ctxblame/formats.py +142 -0
- ctxblame/match.py +240 -0
- ctxblame/pricing.py +123 -0
- ctxblame/proxy.py +205 -0
- ctxblame/replay.py +457 -0
- ctxblame/sse.py +241 -0
- ctxblame/trace.py +139 -0
- ctxblame-0.2.0.dist-info/METADATA +224 -0
- ctxblame-0.2.0.dist-info/RECORD +16 -0
- ctxblame-0.2.0.dist-info/WHEEL +4 -0
- ctxblame-0.2.0.dist-info/entry_points.txt +3 -0
- ctxblame-0.2.0.dist-info/licenses/LICENSE +21 -0
ctxblame/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""ctxblame: git blame for LLM agent decisions (Phase 0 spike)."""
|
ctxblame/ablate.py
ADDED
|
@@ -0,0 +1,468 @@
|
|
|
1
|
+
"""Remove pieces of a recorded request while keeping it a valid request.
|
|
2
|
+
|
|
3
|
+
Removable units:
|
|
4
|
+
system / system[i] the system prompt, or one block of it (Anthropic)
|
|
5
|
+
msg[i] one message (OpenAI system messages are messages too)
|
|
6
|
+
pair:<id> a tool call together with its result
|
|
7
|
+
tool:<name> a tool definition
|
|
8
|
+
thinking:msg[i] the reasoning of one assistant message (thinking blocks,
|
|
9
|
+
or OpenAI-format ``reasoning_content``); ``thinking`` = all
|
|
10
|
+
plus exact text spans (``remove_text``) and a random same-size span of
|
|
11
|
+
whole sentences/lines (``remove_random_span``) as a control.
|
|
12
|
+
|
|
13
|
+
Removing reasoning also gives the tool calls of those messages fresh ids
|
|
14
|
+
(and their results). Some providers (seen with DeepSeek) keep earlier
|
|
15
|
+
reasoning server-side and silently restore it when they see their own call
|
|
16
|
+
ids, so without this the "removed" reasoning still reaches the model. With
|
|
17
|
+
fresh ids such a provider refuses the request instead, which is honest.
|
|
18
|
+
|
|
19
|
+
Rule: a tool call and its result are never separated. Removing either one
|
|
20
|
+
(directly or by removing the message holding it) removes both. Messages left
|
|
21
|
+
empty are dropped and neighbours with the same role are merged, so the
|
|
22
|
+
request stays valid.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import copy
|
|
28
|
+
import json
|
|
29
|
+
import random
|
|
30
|
+
import re
|
|
31
|
+
from dataclasses import dataclass
|
|
32
|
+
|
|
33
|
+
from .formats import ANTHROPIC
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class AblationError(ValueError):
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class Unit:
|
|
42
|
+
id: str
|
|
43
|
+
kind: str
|
|
44
|
+
label: str
|
|
45
|
+
chars: int
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# ------------------------------------------------------------------ helpers
|
|
49
|
+
|
|
50
|
+
def _short(s: str, n: int = 70) -> str:
|
|
51
|
+
s = re.sub(r"\s+", " ", s).strip()
|
|
52
|
+
return s if len(s) <= n else s[: n - 1] + "…"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _text_of(content) -> str:
|
|
56
|
+
if isinstance(content, str):
|
|
57
|
+
return content
|
|
58
|
+
out = []
|
|
59
|
+
for b in content or []:
|
|
60
|
+
if isinstance(b, dict):
|
|
61
|
+
if "text" in b:
|
|
62
|
+
out.append(b["text"])
|
|
63
|
+
elif b.get("type") == "tool_result":
|
|
64
|
+
out.append(_text_of(b.get("content")))
|
|
65
|
+
elif b.get("type") == "tool_use":
|
|
66
|
+
out.append(str(b.get("input")))
|
|
67
|
+
return " ".join(out)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _tool_ids(fmt: str, msg: dict) -> set[str]:
|
|
71
|
+
ids: set[str] = set()
|
|
72
|
+
if fmt == ANTHROPIC:
|
|
73
|
+
for b in msg.get("content") if isinstance(msg.get("content"), list) else []:
|
|
74
|
+
if b.get("type") in ("tool_use", "server_tool_use"):
|
|
75
|
+
ids.add(b["id"])
|
|
76
|
+
elif b.get("type") == "tool_result":
|
|
77
|
+
ids.add(b["tool_use_id"])
|
|
78
|
+
else:
|
|
79
|
+
for c in msg.get("tool_calls") or []:
|
|
80
|
+
ids.add(c["id"])
|
|
81
|
+
if msg.get("role") == "tool":
|
|
82
|
+
ids.add(msg["tool_call_id"])
|
|
83
|
+
return ids
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# ------------------------------------------------------------------ listing
|
|
87
|
+
|
|
88
|
+
def list_units(fmt: str, body: dict) -> list[Unit]:
|
|
89
|
+
units: list[Unit] = []
|
|
90
|
+
if fmt == ANTHROPIC and body.get("system"):
|
|
91
|
+
sysv = body["system"]
|
|
92
|
+
if isinstance(sysv, str):
|
|
93
|
+
units.append(Unit("system", "system", _short(sysv), len(sysv)))
|
|
94
|
+
else:
|
|
95
|
+
for i, b in enumerate(sysv):
|
|
96
|
+
units.append(Unit(f"system[{i}]", "system", _short(b.get("text", "")), len(b.get("text", ""))))
|
|
97
|
+
pairs: dict[str, Unit] = {}
|
|
98
|
+
for i, m in enumerate(body.get("messages") or []):
|
|
99
|
+
text = _text_of(m.get("content"))
|
|
100
|
+
if not text and m.get("tool_calls"): # OpenAI: show what the turn called
|
|
101
|
+
text = " ".join(f"{(c.get('function') or {}).get('name')}"
|
|
102
|
+
f"({(c.get('function') or {}).get('arguments')})" for c in m["tool_calls"])
|
|
103
|
+
units.append(Unit(f"msg[{i}]", m.get("role", "?"), _short(text), len(text)))
|
|
104
|
+
if fmt == ANTHROPIC:
|
|
105
|
+
for b in m.get("content") if isinstance(m.get("content"), list) else []:
|
|
106
|
+
if b.get("type") == "tool_use":
|
|
107
|
+
pairs[b["id"]] = Unit(f"pair:{b['id']}", "tool pair",
|
|
108
|
+
_short(f"{b['name']}({b.get('input')})"), 0)
|
|
109
|
+
elif b.get("type") == "tool_result" and b["tool_use_id"] in pairs:
|
|
110
|
+
pairs[b["tool_use_id"]].chars = len(_text_of(b.get("content")))
|
|
111
|
+
else:
|
|
112
|
+
for c in m.get("tool_calls") or []:
|
|
113
|
+
fn = c.get("function") or {}
|
|
114
|
+
pairs[c["id"]] = Unit(f"pair:{c['id']}", "tool pair",
|
|
115
|
+
_short(f"{fn.get('name')}({fn.get('arguments')})"), 0)
|
|
116
|
+
if m.get("role") == "tool" and m.get("tool_call_id") in pairs:
|
|
117
|
+
pairs[m["tool_call_id"]].chars = len(_text_of(m.get("content")))
|
|
118
|
+
units.extend(pairs.values())
|
|
119
|
+
thinking = [(i, _thinking_text(fmt, m)) for i, m in enumerate(body.get("messages") or [])]
|
|
120
|
+
thinking = [(i, s) for i, s in thinking if s]
|
|
121
|
+
if thinking:
|
|
122
|
+
units.append(Unit("thinking", "thinking", f"all reasoning ({len(thinking)} messages)",
|
|
123
|
+
sum(len(s) for _, s in thinking)))
|
|
124
|
+
units += [Unit(f"thinking:msg[{i}]", "thinking", _short(s), len(s)) for i, s in thinking]
|
|
125
|
+
for t in body.get("tools") or []:
|
|
126
|
+
name = t.get("name") or (t.get("function") or {}).get("name")
|
|
127
|
+
units.append(Unit(f"tool:{name}", "tool def", _short(_tool_description(t)), len(json.dumps(t))))
|
|
128
|
+
return units
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _tool_description(t: dict) -> str:
|
|
132
|
+
return str(t.get("description") or (t.get("function") or {}).get("description") or "")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _thinking_text(fmt: str, m: dict) -> str:
|
|
136
|
+
if m.get("role") != "assistant":
|
|
137
|
+
return ""
|
|
138
|
+
if fmt == ANTHROPIC:
|
|
139
|
+
c = m.get("content")
|
|
140
|
+
return "\n".join(b.get("thinking", "") for b in c if isinstance(b, dict) and b.get("type") == "thinking") \
|
|
141
|
+
if isinstance(c, list) else ""
|
|
142
|
+
return m.get("reasoning_content") or ""
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _drop_thinking(fmt: str, m: dict) -> dict:
|
|
146
|
+
if fmt == ANTHROPIC:
|
|
147
|
+
c = m.get("content")
|
|
148
|
+
if isinstance(c, list):
|
|
149
|
+
m = {**m, "content": [b for b in c if b.get("type") not in ("thinking", "redacted_thinking")]}
|
|
150
|
+
return m
|
|
151
|
+
return {k: v for k, v in m.items() if k != "reasoning_content"}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
# ------------------------------------------------------------------ removal
|
|
155
|
+
|
|
156
|
+
_UNIT = re.compile(r"^(system|system\[(\d+)\]|msg\[(\d+)\]|pair:(.+)|tool:(.+)|thinking(?::msg\[(\d+)\])?)$")
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def remove_units(fmt: str, body: dict, unit_ids: list[str]) -> dict:
|
|
160
|
+
b = copy.deepcopy(body)
|
|
161
|
+
msgs = b.get("messages") or []
|
|
162
|
+
drop_msgs: set[int] = set()
|
|
163
|
+
tool_ids: set[str] = set()
|
|
164
|
+
drop_tools: set[str] = set()
|
|
165
|
+
drop_thinking: set[int] = set()
|
|
166
|
+
for uid in unit_ids:
|
|
167
|
+
m = _UNIT.match(uid)
|
|
168
|
+
if not m:
|
|
169
|
+
raise AblationError(f"unknown unit {uid!r}")
|
|
170
|
+
if uid == "system":
|
|
171
|
+
if "system" not in b:
|
|
172
|
+
raise AblationError("request has no top-level system prompt")
|
|
173
|
+
del b["system"]
|
|
174
|
+
elif m.group(2) is not None:
|
|
175
|
+
i = int(m.group(2))
|
|
176
|
+
if not isinstance(b.get("system"), list) or i >= len(b["system"]):
|
|
177
|
+
raise AblationError(f"no {uid}")
|
|
178
|
+
b["system"][i] = None
|
|
179
|
+
elif m.group(3) is not None:
|
|
180
|
+
i = int(m.group(3))
|
|
181
|
+
if i >= len(msgs):
|
|
182
|
+
raise AblationError(f"no {uid}")
|
|
183
|
+
drop_msgs.add(i)
|
|
184
|
+
tool_ids |= _tool_ids(fmt, msgs[i])
|
|
185
|
+
elif uid.startswith("thinking"):
|
|
186
|
+
if m.group(6) is None:
|
|
187
|
+
drop_thinking |= {i for i, x in enumerate(msgs) if _thinking_text(fmt, x)}
|
|
188
|
+
else:
|
|
189
|
+
i = int(m.group(6))
|
|
190
|
+
if i >= len(msgs) or not _thinking_text(fmt, msgs[i]):
|
|
191
|
+
raise AblationError(f"msg[{i}] has no reasoning to remove")
|
|
192
|
+
drop_thinking.add(i)
|
|
193
|
+
elif m.group(4) is not None:
|
|
194
|
+
if not any(m.group(4) in _tool_ids(fmt, x) for x in msgs):
|
|
195
|
+
raise AblationError(f"no tool call with id {m.group(4)!r}")
|
|
196
|
+
tool_ids.add(m.group(4))
|
|
197
|
+
else:
|
|
198
|
+
drop_tools.add(m.group(5))
|
|
199
|
+
if isinstance(b.get("system"), list):
|
|
200
|
+
b["system"] = [x for x in b["system"] if x is not None]
|
|
201
|
+
if not b["system"]:
|
|
202
|
+
del b["system"]
|
|
203
|
+
if drop_tools:
|
|
204
|
+
names = lambda t: t.get("name") or (t.get("function") or {}).get("name") # noqa: E731
|
|
205
|
+
missing = drop_tools - {names(t) for t in b.get("tools") or []}
|
|
206
|
+
if missing:
|
|
207
|
+
raise AblationError(f"no tool definition named {sorted(missing)}")
|
|
208
|
+
b["tools"] = [t for t in b["tools"] if names(t) not in drop_tools]
|
|
209
|
+
if not b["tools"]:
|
|
210
|
+
del b["tools"]
|
|
211
|
+
|
|
212
|
+
kept = [_drop_thinking(fmt, m) if i in drop_thinking else m
|
|
213
|
+
for i, m in enumerate(msgs) if i not in drop_msgs]
|
|
214
|
+
renames = {cid: f"{'toolu' if fmt == ANTHROPIC else 'call'}_ctxb{n:04d}"
|
|
215
|
+
for n, cid in enumerate(sorted({c for i in drop_thinking if i not in drop_msgs
|
|
216
|
+
for c in _tool_ids(fmt, msgs[i])} - tool_ids))}
|
|
217
|
+
if renames:
|
|
218
|
+
kept = [_rename_ids(fmt, m, renames) for m in kept]
|
|
219
|
+
kept = _strip_tool_ids(fmt, kept, tool_ids)
|
|
220
|
+
b["messages"] = _merge_same_role(fmt, kept)
|
|
221
|
+
problems = validate(fmt, b)
|
|
222
|
+
if problems:
|
|
223
|
+
raise AblationError("ablation left an invalid request: " + "; ".join(problems))
|
|
224
|
+
return b
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _rename_ids(fmt: str, m: dict, renames: dict[str, str]) -> dict:
|
|
228
|
+
if fmt == ANTHROPIC:
|
|
229
|
+
c = m.get("content")
|
|
230
|
+
if not isinstance(c, list):
|
|
231
|
+
return m
|
|
232
|
+
out = []
|
|
233
|
+
for b in c:
|
|
234
|
+
if b.get("type") in ("tool_use", "server_tool_use") and b.get("id") in renames:
|
|
235
|
+
b = {**b, "id": renames[b["id"]]}
|
|
236
|
+
elif b.get("type") == "tool_result" and b.get("tool_use_id") in renames:
|
|
237
|
+
b = {**b, "tool_use_id": renames[b["tool_use_id"]]}
|
|
238
|
+
out.append(b)
|
|
239
|
+
return {**m, "content": out}
|
|
240
|
+
m = dict(m)
|
|
241
|
+
if m.get("tool_calls"):
|
|
242
|
+
m["tool_calls"] = [{**c, "id": renames.get(c["id"], c["id"])} for c in m["tool_calls"]]
|
|
243
|
+
if m.get("tool_call_id") in renames:
|
|
244
|
+
m["tool_call_id"] = renames[m["tool_call_id"]]
|
|
245
|
+
return m
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _strip_tool_ids(fmt: str, msgs: list[dict], ids: set[str]) -> list[dict]:
|
|
249
|
+
out = []
|
|
250
|
+
for m in msgs:
|
|
251
|
+
if fmt == ANTHROPIC:
|
|
252
|
+
c = m.get("content")
|
|
253
|
+
if isinstance(c, list):
|
|
254
|
+
c = [x for x in c if not (
|
|
255
|
+
(x.get("type") in ("tool_use", "server_tool_use") and x.get("id") in ids)
|
|
256
|
+
or (x.get("type") == "tool_result" and x.get("tool_use_id") in ids))]
|
|
257
|
+
if not c or all(x.get("type") in ("thinking", "redacted_thinking") for x in c):
|
|
258
|
+
continue
|
|
259
|
+
m = {**m, "content": c}
|
|
260
|
+
else:
|
|
261
|
+
if m.get("role") == "tool" and m.get("tool_call_id") in ids:
|
|
262
|
+
continue
|
|
263
|
+
if m.get("tool_calls"):
|
|
264
|
+
calls = [c for c in m["tool_calls"] if c["id"] not in ids]
|
|
265
|
+
if len(calls) != len(m["tool_calls"]):
|
|
266
|
+
m = dict(m)
|
|
267
|
+
if calls:
|
|
268
|
+
m["tool_calls"] = calls
|
|
269
|
+
else:
|
|
270
|
+
del m["tool_calls"]
|
|
271
|
+
if not m.get("content"):
|
|
272
|
+
continue
|
|
273
|
+
out.append(m)
|
|
274
|
+
return out
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _as_blocks(content) -> list:
|
|
278
|
+
return [{"type": "text", "text": content}] if isinstance(content, str) else list(content)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _merge_same_role(fmt: str, msgs: list[dict]) -> list[dict]:
|
|
282
|
+
out: list[dict] = []
|
|
283
|
+
for m in msgs:
|
|
284
|
+
prev = out[-1] if out else None
|
|
285
|
+
if prev is None or prev.get("role") != m.get("role") or m.get("role") not in ("user", "assistant"):
|
|
286
|
+
out.append(m)
|
|
287
|
+
continue
|
|
288
|
+
if fmt == ANTHROPIC:
|
|
289
|
+
blocks = _as_blocks(prev["content"]) + _as_blocks(m["content"])
|
|
290
|
+
if m["role"] == "user": # tool_result blocks must come first
|
|
291
|
+
blocks.sort(key=lambda x: x.get("type") != "tool_result")
|
|
292
|
+
out[-1] = {**prev, "content": blocks}
|
|
293
|
+
else:
|
|
294
|
+
if prev.get("tool_calls") and m["role"] == "assistant":
|
|
295
|
+
out.append(m) # keep call/result adjacency rather than merge
|
|
296
|
+
continue
|
|
297
|
+
merged = dict(prev)
|
|
298
|
+
a, c = prev.get("content"), m.get("content")
|
|
299
|
+
if isinstance(a, list) or isinstance(c, list):
|
|
300
|
+
merged["content"] = _as_blocks(a or "") + _as_blocks(c or "")
|
|
301
|
+
else:
|
|
302
|
+
merged["content"] = "\n\n".join(x for x in (a, c) if x)
|
|
303
|
+
if m.get("tool_calls"):
|
|
304
|
+
merged["tool_calls"] = m["tool_calls"]
|
|
305
|
+
out[-1] = merged
|
|
306
|
+
return out
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def validate(fmt: str, body: dict) -> list[str]:
|
|
310
|
+
msgs = body.get("messages") or []
|
|
311
|
+
problems = []
|
|
312
|
+
if not msgs:
|
|
313
|
+
return ["no messages left"]
|
|
314
|
+
if fmt == ANTHROPIC:
|
|
315
|
+
if msgs[0].get("role") != "user":
|
|
316
|
+
problems.append("first message is not from the user")
|
|
317
|
+
for i, m in enumerate(msgs):
|
|
318
|
+
if m.get("role") != "assistant" or not isinstance(m.get("content"), list):
|
|
319
|
+
continue
|
|
320
|
+
calls = {b["id"] for b in m["content"] if b.get("type") == "tool_use"}
|
|
321
|
+
if not calls:
|
|
322
|
+
continue
|
|
323
|
+
nxt = msgs[i + 1] if i + 1 < len(msgs) else None
|
|
324
|
+
got = set()
|
|
325
|
+
if nxt and isinstance(nxt.get("content"), list):
|
|
326
|
+
got = {b["tool_use_id"] for b in nxt["content"] if b.get("type") == "tool_result"}
|
|
327
|
+
if calls - got:
|
|
328
|
+
problems.append(f"msg[{i}] tool calls without results: {sorted(calls - got)}")
|
|
329
|
+
else:
|
|
330
|
+
open_calls: set[str] = set()
|
|
331
|
+
for i, m in enumerate(msgs):
|
|
332
|
+
if m.get("role") == "tool":
|
|
333
|
+
if m.get("tool_call_id") not in open_calls:
|
|
334
|
+
problems.append(f"msg[{i}] result for unknown call {m.get('tool_call_id')}")
|
|
335
|
+
open_calls.discard(m.get("tool_call_id"))
|
|
336
|
+
else:
|
|
337
|
+
if open_calls:
|
|
338
|
+
problems.append(f"calls without results before msg[{i}]: {sorted(open_calls)}")
|
|
339
|
+
open_calls = set()
|
|
340
|
+
open_calls |= {c["id"] for c in m.get("tool_calls") or []}
|
|
341
|
+
if open_calls:
|
|
342
|
+
problems.append(f"calls without results: {sorted(open_calls)}")
|
|
343
|
+
return problems
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
# --------------------------------------------------------------------- text
|
|
347
|
+
|
|
348
|
+
def text_fields(fmt: str, body: dict) -> list[tuple[tuple, str]]:
|
|
349
|
+
"""Every editable text span as (path, text)."""
|
|
350
|
+
out: list[tuple[tuple, str]] = []
|
|
351
|
+
if fmt == ANTHROPIC:
|
|
352
|
+
s = body.get("system")
|
|
353
|
+
if isinstance(s, str):
|
|
354
|
+
out.append((("system",), s))
|
|
355
|
+
elif isinstance(s, list):
|
|
356
|
+
out += [(("system", i, "text"), b["text"]) for i, b in enumerate(s) if "text" in b]
|
|
357
|
+
for i, m in enumerate(body.get("messages") or []):
|
|
358
|
+
c = m.get("content")
|
|
359
|
+
if isinstance(c, str):
|
|
360
|
+
out.append((("messages", i, "content"), c))
|
|
361
|
+
elif isinstance(c, list):
|
|
362
|
+
for j, b in enumerate(c):
|
|
363
|
+
if b.get("type") == "text":
|
|
364
|
+
out.append((("messages", i, "content", j, "text"), b["text"]))
|
|
365
|
+
elif b.get("type") == "tool_result":
|
|
366
|
+
rc = b.get("content")
|
|
367
|
+
if isinstance(rc, str):
|
|
368
|
+
out.append((("messages", i, "content", j, "content"), rc))
|
|
369
|
+
elif isinstance(rc, list):
|
|
370
|
+
out += [(("messages", i, "content", j, "content", k, "text"), x["text"])
|
|
371
|
+
for k, x in enumerate(rc) if x.get("type") == "text"]
|
|
372
|
+
for i, t in enumerate(body.get("tools") or []): # tool and parameter descriptions
|
|
373
|
+
out += _descriptions(t, ("tools", i))
|
|
374
|
+
return out
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def _descriptions(o, path: tuple) -> list[tuple[tuple, str]]:
|
|
378
|
+
out: list[tuple[tuple, str]] = []
|
|
379
|
+
if isinstance(o, dict):
|
|
380
|
+
for k, v in o.items():
|
|
381
|
+
if k == "description" and isinstance(v, str):
|
|
382
|
+
out.append((path + (k,), v))
|
|
383
|
+
elif isinstance(v, (dict, list)):
|
|
384
|
+
out += _descriptions(v, path + (k,))
|
|
385
|
+
elif isinstance(o, list):
|
|
386
|
+
for j, v in enumerate(o):
|
|
387
|
+
out += _descriptions(v, path + (j,))
|
|
388
|
+
return out
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _set(body: dict, path: tuple, value: str) -> None:
|
|
392
|
+
o = body
|
|
393
|
+
for p in path[:-1]:
|
|
394
|
+
o = o[p]
|
|
395
|
+
o[path[-1]] = value
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def _cut(s: str, start: int, end: int) -> str:
|
|
399
|
+
"""Remove s[start:end] and tidy the seam (no double space, no empty line)."""
|
|
400
|
+
left, right = s[:start], s[end:]
|
|
401
|
+
if left.endswith((" ", "\t")) and right.startswith((" ", "\t", "\n")):
|
|
402
|
+
left = left.rstrip(" \t")
|
|
403
|
+
elif (left == "" or left.endswith("\n")) and right.startswith((" ", "\t")):
|
|
404
|
+
right = right.lstrip(" \t")
|
|
405
|
+
if (left == "" or left.endswith("\n")) and right.startswith("\n"):
|
|
406
|
+
right = right[1:]
|
|
407
|
+
return left + right
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def remove_text(fmt: str, body: dict, text: str) -> dict:
|
|
411
|
+
b = copy.deepcopy(body)
|
|
412
|
+
found = 0
|
|
413
|
+
for path, s in text_fields(fmt, b):
|
|
414
|
+
while text in s:
|
|
415
|
+
i = s.index(text)
|
|
416
|
+
s = _cut(s, i, i + len(text))
|
|
417
|
+
found += 1
|
|
418
|
+
_set(b, path, s)
|
|
419
|
+
if not found:
|
|
420
|
+
raise AblationError(f"text not found in request: {_short(text)!r}")
|
|
421
|
+
return b
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
_SEG = re.compile(r"[^\n]*?(?:[.!?](?=\s)|\n|$)\s*")
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _segments(s: str) -> list[tuple[int, int]]:
|
|
428
|
+
"""Sentence/line spans (start, end), covering s."""
|
|
429
|
+
segs, pos = [], 0
|
|
430
|
+
for m in _SEG.finditer(s):
|
|
431
|
+
if m.end() > pos:
|
|
432
|
+
segs.append((m.start(), m.end()))
|
|
433
|
+
pos = m.end()
|
|
434
|
+
if m.end() >= len(s):
|
|
435
|
+
break
|
|
436
|
+
return segs
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def remove_random_span(fmt: str, body: dict, size: int, rng: random.Random,
|
|
440
|
+
protect: list[str] = (), tolerance: float = 0.5) -> tuple[dict, str]:
|
|
441
|
+
"""Remove a random run of whole sentences/lines about ``size`` chars long
|
|
442
|
+
(within ``tolerance``), never touching any ``protect`` text."""
|
|
443
|
+
candidates = []
|
|
444
|
+
for fi, (path, s) in enumerate(text_fields(fmt, body)):
|
|
445
|
+
blocked = [(m.start(), m.end()) for p in protect if p for m in re.finditer(re.escape(p), s)]
|
|
446
|
+
segs = _segments(s)
|
|
447
|
+
for a in range(len(segs)):
|
|
448
|
+
for z in range(a, len(segs)):
|
|
449
|
+
st, en = segs[a][0], segs[z][1]
|
|
450
|
+
n = len(s[st:en].strip())
|
|
451
|
+
if n > size * (1 + tolerance):
|
|
452
|
+
break
|
|
453
|
+
if n >= size * (1 - tolerance) and not any(st < be and bs < en for bs, be in blocked):
|
|
454
|
+
candidates.append((abs(n - size), fi, path, st, en))
|
|
455
|
+
if not candidates:
|
|
456
|
+
raise AblationError(f"no removable span of ~{size} chars outside the protected text")
|
|
457
|
+
# uniform over spans within 30% of the size, so controls spread over the
|
|
458
|
+
# whole context; fall back to the closest sizes if none is that close
|
|
459
|
+
pool = [c for c in candidates if c[0] <= size * 0.3]
|
|
460
|
+
if not pool:
|
|
461
|
+
best = min(c[0] for c in candidates)
|
|
462
|
+
pool = [c for c in candidates if c[0] <= best + max(10, size * 0.2)]
|
|
463
|
+
_, _, path, st, en = rng.choice(pool)
|
|
464
|
+
b = copy.deepcopy(body)
|
|
465
|
+
s = dict(text_fields(fmt, b))[path]
|
|
466
|
+
removed = s[st:en]
|
|
467
|
+
_set(b, path, _cut(s, st, en))
|
|
468
|
+
return b, removed
|