chap-analytics 0.2.4__tar.gz → 0.2.5__tar.gz

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.
Files changed (64) hide show
  1. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/CHANGELOG.md +33 -0
  2. {chap_analytics-0.2.4/chap_analytics.egg-info → chap_analytics-0.2.5}/PKG-INFO +2 -2
  3. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/__init__.py +1 -1
  4. chap_analytics-0.2.5/chap_analytics/_patch.py +401 -0
  5. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/frames.py +7 -3
  6. {chap_analytics-0.2.4 → chap_analytics-0.2.5/chap_analytics.egg-info}/PKG-INFO +2 -2
  7. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics.egg-info/SOURCES.txt +1 -0
  8. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics.egg-info/requires.txt +1 -1
  9. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/pyproject.toml +2 -2
  10. chap_analytics-0.2.5/tests/test_patch_limits.py +307 -0
  11. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/tests/test_review_passes.py +9 -8
  12. chap_analytics-0.2.4/chap_analytics/_patch.py +0 -234
  13. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/LICENSE +0 -0
  14. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/MANIFEST.in +0 -0
  15. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/README.md +0 -0
  16. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/_report/report.css +0 -0
  17. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/_report/report.html +0 -0
  18. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/_report/report.js +0 -0
  19. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/_report/stats.js +0 -0
  20. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/_vendor/LICENSE.vega +0 -0
  21. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/_vendor/LICENSE.vega-embed +0 -0
  22. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/_vendor/LICENSE.vega-lite +0 -0
  23. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/_vendor/README.md +0 -0
  24. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/_vendor/render.js +0 -0
  25. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/_vendor/vega-embed.min.js +0 -0
  26. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/_vendor/vega-lite.min.js +0 -0
  27. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/_vendor/vega.min.js +0 -0
  28. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/briefs.py +0 -0
  29. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/charts.py +0 -0
  30. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/export.py +0 -0
  31. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/graph.py +0 -0
  32. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/load.py +0 -0
  33. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/models.py +0 -0
  34. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/py.typed +0 -0
  35. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/report.py +0 -0
  36. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/sample.py +0 -0
  37. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/schema.py +0 -0
  38. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/stats.py +0 -0
  39. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics/watch.py +0 -0
  40. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics.egg-info/dependency_links.txt +0 -0
  41. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/chap_analytics.egg-info/top_level.txt +0 -0
  42. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/examples/build_notebook.py +0 -0
  43. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/examples/chap_analytics_walkthrough.ipynb +0 -0
  44. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/examples/support_desk.py +0 -0
  45. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/setup.cfg +0 -0
  46. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/tests/conftest.py +0 -0
  47. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/tests/js_stats_runner.js +0 -0
  48. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/tests/test_charts_and_briefs.py +0 -0
  49. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/tests/test_differential.py +0 -0
  50. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/tests/test_example.py +0 -0
  51. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/tests/test_from_url_scheme.py +0 -0
  52. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/tests/test_graph.py +0 -0
  53. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/tests/test_handoff_and_routing.py +0 -0
  54. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/tests/test_identity.py +0 -0
  55. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/tests/test_notebook.py +0 -0
  56. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/tests/test_projection.py +0 -0
  57. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/tests/test_redaction_and_malformed.py +0 -0
  58. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/tests/test_refusals.py +0 -0
  59. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/tests/test_report.py +0 -0
  60. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/tests/test_sample_and_export.py +0 -0
  61. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/tests/test_stats.py +0 -0
  62. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/tests/test_successors.py +0 -0
  63. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/tests/test_typescript_store.py +0 -0
  64. {chap_analytics-0.2.4 → chap_analytics-0.2.5}/tests/test_watch_export_models.py +0 -0
@@ -4,6 +4,39 @@
4
4
  so a protocol release moves the coordinator packages together and leaves this
5
5
  one where it is until the tables or the analyses change.
6
6
 
7
+ ## 0.2.5
8
+
9
+ Reads the review rounds of `chap-coordinator` 0.3.4.
10
+
11
+ ### Changed
12
+
13
+ - **A revised artefact is a new review pass.** A task that requires review
14
+ and is completed again after a revision now opens a new pass of the same
15
+ review, as `chap-coordinator` 0.3.4 does: the reviewers and the rule stay,
16
+ the completer leaves the reviewers, and the decisions start empty. Before,
17
+ the pass carried on with the decisions on the earlier artefact.
18
+ `n_reviews` and `review_index` count the new pass, in a chain any
19
+ coordinator wrote. In a chain written before 0.3.4, a task completed by
20
+ approvals of an earlier artefact now reads as open from the envelopes and
21
+ as completed bypassing review from state, which is what its chain shows.
22
+
23
+ ### Fixed
24
+
25
+ - **A patch that grows the document past a size or depth limit.**
26
+ `chap-analytics` applies each override's patch to rebuild the corrected
27
+ artefact. Its copy of the patch engine limited operations and values, and
28
+ nothing limited size or depth, so a few `copy` operations of the root
29
+ could grow an artefact to gigabytes, and a patch that puts one value
30
+ inside another could nest it deeper than Python can follow. It now
31
+ refuses a patch when, after any of its operations, the artefact holds
32
+ more than 64 MiB of string and key text, counted in UTF-8 bytes, or nests
33
+ deeper than 64 levels, or when its copies, and its moves to a deeper
34
+ place or onto the whole artefact, carry more than three times the value
35
+ and size limits between them. The artefact's `result` is then empty. A
36
+ coordinator refuses an override past its own `max_envelope_bytes`, 1 MiB
37
+ by default, so every override a 0.3.4 coordinator accepted is rebuilt
38
+ while that limit is at most 64 MiB.
39
+
7
40
  ## 0.2.4
8
41
 
9
42
  ### Fixed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: chap-analytics
3
- Version: 0.2.4
3
+ Version: 0.2.5
4
4
  Summary: The record of a collaboration between people and agents, measured and drawn: a CHAP audit chain as documented tables, statistics with their intervals, graphs, charts, briefs and a self-contained interactive report
5
5
  Author-email: Brightbeam AI <oss@brightbeam.com>
6
6
  License-Expression: Apache-2.0
@@ -41,7 +41,7 @@ Requires-Dist: nbclient>=0.9; extra == "notebook"
41
41
  Requires-Dist: ipykernel>=6; extra == "notebook"
42
42
  Provides-Extra: dev
43
43
  Requires-Dist: pytest>=8; extra == "dev"
44
- Requires-Dist: chap-coordinator>=0.3.0; extra == "dev"
44
+ Requires-Dist: chap-coordinator>=0.3.4; extra == "dev"
45
45
  Requires-Dist: nbformat>=5; extra == "dev"
46
46
  Requires-Dist: altair>=5; extra == "dev"
47
47
  Requires-Dist: networkx>=3; extra == "dev"
@@ -41,7 +41,7 @@ The layers, bottom up:
41
41
  """
42
42
  from __future__ import annotations
43
43
 
44
- __version__ = "0.2.4"
44
+ __version__ = "0.2.5"
45
45
 
46
46
  from . import briefs, charts, export, graph, models, sample, stats, watch # noqa: E402
47
47
  from .frames import Frames, frames # noqa: E402
@@ -0,0 +1,401 @@
1
+ """
2
+ RFC 6902 JSON Patch, for reconstructing the corrected artefact.
3
+
4
+ ``decide.override`` carries the patch a reviewer applied; ``review.request``
5
+ carried the artefact they applied it to. Applying the one to the other gives
6
+ the corrected artefact from envelopes alone, which is what makes the
7
+ ``result`` column available to a client that has only ``audit.read``.
8
+
9
+ This is the coordinator's own applier, copied rather than imported, because
10
+ the package runs with pandas alone and the two implementations have to agree
11
+ exactly for ``result`` to equal what the coordinator stored. The differential
12
+ suite applies every patch both ways and requires the same document. Keep this
13
+ file in step with ``chap_coordinator/patch.py``; the limits and the refused
14
+ path segments are deliberately the same.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import re
19
+ from typing import Any
20
+
21
+ __all__ = ["apply_json_patch", "PatchError"]
22
+
23
+ # Refused in every JSON Pointer segment, as the coordinator refuses them: in a
24
+ # JavaScript runtime they enable prototype pollution, and every implementation
25
+ # refuses the same patches.
26
+ _DANGEROUS_KEYS = frozenset({"__proto__", "constructor", "prototype"})
27
+
28
+ # An RFC 6901 array index: "0" or a positive integer with no leading zero.
29
+ _ARRAY_INDEX_RE = re.compile(r"^(0|[1-9][0-9]*)$")
30
+
31
+ MAX_PATCH_OPS = 1000
32
+ MAX_DOCUMENT_NODES = 100_000
33
+ # How deeply a rebuilt artefact may nest, counting it as level one, as the
34
+ # coordinators count it.
35
+ MAX_DOCUMENT_DEPTH = 64
36
+ # How much a patch's copies, and its moves to a deeper place or onto the whole
37
+ # document, may carry between them, as a multiple of the document's limits, as
38
+ # the coordinators allow.
39
+ MAX_CARRIED_TIMES = 3
40
+
41
+
42
+ class PatchError(Exception):
43
+ """A patch operation that fails to apply to this document."""
44
+
45
+
46
+ def _array_index(seg: str) -> int:
47
+ if not _ARRAY_INDEX_RE.match(seg):
48
+ raise PatchError(f"Array index expected at {seg!r}")
49
+ return int(seg)
50
+
51
+
52
+ def _unescape(token: str) -> str:
53
+ return token.replace("~1", "/").replace("~0", "~")
54
+
55
+
56
+ def _split_path(path: str) -> list[str]:
57
+ if path == "":
58
+ return []
59
+ if not isinstance(path, str) or not path.startswith("/"):
60
+ raise PatchError(f"JSON Pointer must start with '/': {path!r}")
61
+ segments = [_unescape(tok) for tok in path[1:].split("/")]
62
+ for seg in segments:
63
+ if seg in _DANGEROUS_KEYS:
64
+ raise PatchError(f"Refusing unsafe path segment {seg!r}")
65
+ return segments
66
+
67
+
68
+ def _navigate(doc: Any, parts: list[str]) -> tuple[Any, str | int]:
69
+ """The parent of the target, and the key of the target within it."""
70
+ if not parts:
71
+ raise PatchError("Cannot operate on root with this helper.")
72
+ parent = doc
73
+ for i, part in enumerate(parts[:-1]):
74
+ if isinstance(parent, list):
75
+ idx = _array_index(part)
76
+ if idx >= len(parent):
77
+ raise PatchError(f"Index out of range at /{'/'.join(parts[:i + 1])}")
78
+ parent = parent[idx]
79
+ elif isinstance(parent, dict):
80
+ if part not in parent:
81
+ raise PatchError(f"Path not found: /{'/'.join(parts[:i + 1])}")
82
+ parent = parent[part]
83
+ else:
84
+ raise PatchError(f"Cannot traverse into {type(parent).__name__} at {part!r}")
85
+ last = parts[-1]
86
+ if isinstance(parent, list):
87
+ if last == "-":
88
+ return parent, "-"
89
+ return parent, _array_index(last)
90
+ return parent, last
91
+
92
+
93
+ def _get(doc: Any, path: str) -> Any:
94
+ parts = _split_path(path)
95
+ if not parts:
96
+ return doc
97
+ parent, key = _navigate(doc, parts)
98
+ if isinstance(parent, list):
99
+ if key == "-":
100
+ raise PatchError("Cannot read '-' position.")
101
+ if not isinstance(key, int) or key < 0 or key >= len(parent):
102
+ raise PatchError(f"Index out of range: {path}")
103
+ return parent[key]
104
+ if not isinstance(parent, dict) or key not in parent:
105
+ raise PatchError(f"Path not found: {path}")
106
+ return parent[key]
107
+
108
+
109
+ def _json_equal(a: Any, b: Any) -> bool:
110
+ """JSON-type-aware deep equality for the RFC 6902 ``test`` operation.
111
+
112
+ Python's ``==`` treats ``True == 1`` and ``False == 0`` as equal because
113
+ ``bool`` is a subclass of ``int``. JSON distinguishes them: ``true`` is a
114
+ boolean, ``1`` is a number. The TypeScript reference's ``deepEqual``
115
+ handles this via ``typeof``; this function is the Python equivalent.
116
+ """
117
+ if isinstance(a, bool) != isinstance(b, bool):
118
+ return False
119
+ if a is None or b is None:
120
+ return a is b
121
+ if isinstance(a, dict):
122
+ if not isinstance(b, dict) or len(a) != len(b):
123
+ return False
124
+ return all(k in b and _json_equal(a[k], b[k]) for k in a)
125
+ if isinstance(a, list):
126
+ if not isinstance(b, list) or len(a) != len(b):
127
+ return False
128
+ return all(_json_equal(x, y) for x, y in zip(a, b))
129
+ return a == b
130
+
131
+
132
+ def _tree_copy(value: Any) -> Any:
133
+ """A copy of a JSON value that shares nothing with it, or within itself."""
134
+ if isinstance(value, dict):
135
+ return {k: _tree_copy(v) if isinstance(v, (dict, list)) else v for k, v in value.items()}
136
+ if isinstance(value, list):
137
+ return [_tree_copy(v) if isinstance(v, (dict, list)) else v for v in value]
138
+ return value
139
+
140
+
141
+ def _add(doc: Any, path: str, value: Any, size: _Size | None,
142
+ copied: bool = False, moved_from: int | None = None) -> Any:
143
+ """Put ``value``, which the document owns from here on, at ``path``.
144
+
145
+ A copied value counts towards what the patch carries. A moved value is
146
+ counted already. ``moved_from`` is the number of segments of the place it
147
+ left: only its key, a value it replaces and how deep it now reaches change
148
+ the count. A move to a deeper place, or onto the whole document, costs a
149
+ pass over the value, so it counts towards what the patch carries as well.
150
+ """
151
+ parts = _split_path(path)
152
+ if not parts:
153
+ if size is not None:
154
+ size.reset(value)
155
+ if copied or moved_from is not None:
156
+ size.carry((size.nodes, size.bytes, size.depth))
157
+ return value
158
+ parent, key = _navigate(doc, parts)
159
+ new_key = None
160
+ if isinstance(parent, list):
161
+ if key == "-":
162
+ parent.append(value)
163
+ else:
164
+ if not isinstance(key, int) or key < 0 or key > len(parent):
165
+ raise PatchError(f"Index out of range for add: {path}")
166
+ parent.insert(key, value)
167
+ elif isinstance(parent, dict):
168
+ if key in parent:
169
+ if size is not None:
170
+ size.take(parent[key], None)
171
+ else:
172
+ new_key = key
173
+ parent[key] = value
174
+ else:
175
+ raise PatchError(f"Cannot add into {type(parent).__name__}")
176
+ if size is not None:
177
+ if moved_from is None:
178
+ inserted = size.insert(value, len(parts), new_key)
179
+ if copied:
180
+ size.carry(inserted)
181
+ else:
182
+ if new_key is not None:
183
+ size.bytes += _utf8_length(new_key)
184
+ if len(parts) > moved_from:
185
+ # A move to a deeper place costs a pass over the value, for its depth.
186
+ moved = _size_of(value)
187
+ size.depth = max(size.depth, len(parts) + moved[2])
188
+ size.carry(moved)
189
+ return doc
190
+
191
+
192
+ def _remove(doc: Any, path: str, size: _Size | None, moved: bool = False) -> Any:
193
+ """Remove the value at ``path``. A moved value goes back in elsewhere, so
194
+ only its key leaves the count."""
195
+ parts = _split_path(path)
196
+ if not parts:
197
+ raise PatchError("Cannot remove root.")
198
+ parent, key = _navigate(doc, parts)
199
+ if isinstance(parent, list):
200
+ if not isinstance(key, int) or key < 0 or key >= len(parent):
201
+ raise PatchError(f"Index out of range for remove: {path}")
202
+ if size is not None and not moved:
203
+ size.take(parent[key], None)
204
+ del parent[key]
205
+ elif isinstance(parent, dict):
206
+ if key not in parent:
207
+ raise PatchError(f"Path not found for remove: {path}")
208
+ if size is not None:
209
+ if moved:
210
+ size.bytes -= _utf8_length(key)
211
+ else:
212
+ size.take(parent[key], key)
213
+ del parent[key]
214
+ else:
215
+ raise PatchError(f"Cannot remove from {type(parent).__name__}")
216
+ return doc
217
+
218
+
219
+ def _apply_one(doc: Any, op: dict, size: _Size | None = None) -> Any: # noqa: C901 - one branch per RFC 6902 operation
220
+ kind = op.get("op")
221
+ path = op.get("path", "")
222
+
223
+ if kind == "add":
224
+ if "value" not in op:
225
+ raise PatchError("'add' requires 'value'")
226
+ return _add(doc, path, _tree_copy(op["value"]), size)
227
+
228
+ if kind == "replace":
229
+ if "value" not in op:
230
+ raise PatchError("'replace' requires 'value'")
231
+ parts = _split_path(path)
232
+ value = _tree_copy(op["value"])
233
+ if not parts:
234
+ if size is not None:
235
+ size.reset(value)
236
+ return value
237
+ parent, key = _navigate(doc, parts)
238
+ if isinstance(parent, list):
239
+ if not isinstance(key, int) or key < 0 or key >= len(parent):
240
+ raise PatchError(f"Path not found for replace: {path}")
241
+ elif isinstance(parent, dict):
242
+ if key not in parent:
243
+ raise PatchError(f"Path not found for replace: {path}")
244
+ else:
245
+ raise PatchError(f"Cannot replace in {type(parent).__name__}")
246
+ if size is not None:
247
+ size.take(parent[key], None)
248
+ size.insert(value, len(parts), None)
249
+ parent[key] = value
250
+ return doc
251
+
252
+ if kind == "remove":
253
+ return _remove(doc, path, size)
254
+
255
+ if kind == "copy":
256
+ src = op.get("from")
257
+ if src is None:
258
+ raise PatchError("'copy' requires 'from'")
259
+ return _add(doc, path, _tree_copy(_get(doc, src)), size, copied=True)
260
+
261
+ if kind == "move":
262
+ src = op.get("from")
263
+ if src is None:
264
+ raise PatchError("'move' requires 'from'")
265
+ if isinstance(path, str) and path.startswith(src + "/"):
266
+ raise PatchError("'move' cannot move a location into its own child.")
267
+ value = _get(doc, src)
268
+ doc = _remove(doc, src, size, moved=True)
269
+ return _add(doc, path, value, size, moved_from=len(_split_path(src)))
270
+
271
+ if kind == "test":
272
+ if "value" not in op:
273
+ raise PatchError("'test' requires 'value'")
274
+ if not _json_equal(_get(doc, path), op["value"]):
275
+ raise PatchError(f"'test' failed at {path}")
276
+ return doc
277
+
278
+ raise PatchError(f"Unsupported op: {kind!r}")
279
+
280
+
281
+ # The cap on the string and key text a rebuilt artefact may hold, in UTF-8
282
+ # bytes. The node cap alone does not bound size: a ``copy`` of the root doubles
283
+ # the document, long strings included, so fifteen of them grow 64 KiB to about
284
+ # 2 GiB within 100,000 nodes. A coordinator refuses an override past its own
285
+ # ``max_envelope_bytes``, 1 MiB by default and 16 MiB in the code gate, so this
286
+ # reader allows 64 MiB: it rebuilds what a coordinator accepted, and stops a
287
+ # chain from anywhere else from exhausting memory.
288
+ DEFAULT_MAX_PATCHED_BYTES = 67_108_864
289
+
290
+
291
+ def _utf8_length(s: str) -> int:
292
+ # surrogatepass counts a lone surrogate as three bytes, as the TypeScript
293
+ # count does, so the two references refuse the same patches.
294
+ return len(s) if s.isascii() else len(s.encode("utf-8", "surrogatepass"))
295
+
296
+
297
+ def _size_of(value: Any) -> tuple[int, int, int]:
298
+ """A value's count of values, the UTF-8 bytes of its strings and keys, and
299
+ its depth, counting the value itself as level one, in one pass that does
300
+ not recurse."""
301
+ if not isinstance(value, (dict, list)):
302
+ return 1, _utf8_length(value) if isinstance(value, str) else 0, 1
303
+ nodes = size = depth = 0
304
+ stack = [(value, 1)]
305
+ while stack:
306
+ v, level = stack.pop()
307
+ nodes += 1
308
+ if level > depth:
309
+ depth = level
310
+ child = level + 1
311
+ # A scalar child is counted here, which saves a trip through the stack.
312
+ if isinstance(v, dict):
313
+ for k, x in v.items():
314
+ size += _utf8_length(k if isinstance(k, str) else str(k))
315
+ if isinstance(x, (dict, list)):
316
+ stack.append((x, child))
317
+ else:
318
+ nodes += 1
319
+ if child > depth:
320
+ depth = child
321
+ if isinstance(x, str):
322
+ size += _utf8_length(x)
323
+ else:
324
+ for x in v:
325
+ if isinstance(x, (dict, list)):
326
+ stack.append((x, child))
327
+ else:
328
+ nodes += 1
329
+ if child > depth:
330
+ depth = child
331
+ if isinstance(x, str):
332
+ size += _utf8_length(x)
333
+ return nodes, size, depth
334
+
335
+
336
+ class _Size:
337
+ """What the working document holds, kept in step by each operation: the
338
+ values and bytes exactly, the depth as a bound that passes the limit when
339
+ the document does, or when the document started deeper."""
340
+
341
+ __slots__ = ("nodes", "bytes", "depth", "carried_nodes", "carried_bytes")
342
+
343
+ def __init__(self, doc: Any) -> None:
344
+ self.reset(doc)
345
+ # What copies, and moves to a deeper place or onto the whole document,
346
+ # have carried.
347
+ self.carried_nodes = self.carried_bytes = 0
348
+
349
+ def reset(self, doc: Any) -> None:
350
+ self.nodes, self.bytes, self.depth = _size_of(doc)
351
+
352
+ def insert(self, value: Any, segments: int, key: str | None) -> tuple[int, int, int]:
353
+ measured = _size_of(value)
354
+ nodes, size, depth = measured
355
+ self.nodes += nodes
356
+ self.bytes += size + (0 if key is None else _utf8_length(key))
357
+ self.depth = max(self.depth, segments + depth)
358
+ return measured
359
+
360
+ def carry(self, measured: tuple[int, int, int]) -> None:
361
+ self.carried_nodes += measured[0]
362
+ self.carried_bytes += measured[1]
363
+
364
+ def take(self, value: Any, key: str | None) -> None:
365
+ nodes, size, _ = _size_of(value)
366
+ self.nodes -= nodes
367
+ self.bytes -= size + (0 if key is None else _utf8_length(key))
368
+
369
+
370
+ def apply_json_patch(doc: Any, patch: list[dict], *,
371
+ max_string_bytes: int = DEFAULT_MAX_PATCHED_BYTES) -> Any:
372
+ """Apply a patch to a copy of ``doc`` and return the result."""
373
+ if not isinstance(patch, list):
374
+ raise PatchError("A patch is a list of operations.")
375
+ if len(patch) > MAX_PATCH_OPS:
376
+ raise PatchError(f"Patch has too many operations ({len(patch)} > {MAX_PATCH_OPS})")
377
+ out = _tree_copy(doc)
378
+ # Each operation counts what it puts in and takes out, so a patch costs
379
+ # what it changes, whatever the document's size.
380
+ size = _Size(out)
381
+ for op in patch:
382
+ if not isinstance(op, dict):
383
+ raise PatchError("Each operation is an object.")
384
+ out = _apply_one(out, op, size)
385
+ if size.depth > MAX_DOCUMENT_DEPTH:
386
+ size.depth = _size_of(out)[2]
387
+ if size.nodes > MAX_DOCUMENT_NODES:
388
+ raise PatchError(f"Patched document exceeds the node limit ({MAX_DOCUMENT_NODES})")
389
+ if size.bytes > max_string_bytes:
390
+ raise PatchError(
391
+ f"Patched document exceeds the size limit ({max_string_bytes} bytes of strings and keys)"
392
+ )
393
+ if size.depth > MAX_DOCUMENT_DEPTH:
394
+ raise PatchError(f"Patched document nests deeper than {MAX_DOCUMENT_DEPTH} levels")
395
+ if (size.carried_nodes > MAX_CARRIED_TIMES * MAX_DOCUMENT_NODES
396
+ or size.carried_bytes > MAX_CARRIED_TIMES * max_string_bytes):
397
+ raise PatchError(
398
+ f"Patch copies or moves more than its limit ({MAX_CARRIED_TIMES * MAX_DOCUMENT_NODES} values"
399
+ f" or {MAX_CARRIED_TIMES * max_string_bytes} bytes of strings and keys)"
400
+ )
401
+ return out
@@ -650,13 +650,17 @@ def _replay(chain: Chain) -> _Index: # noqa: C901 - one pass, one branch per me
650
650
  t.confidence, t.confidence_reported = conf, True
651
651
  if t.review_required:
652
652
  # review/1.0 S3.1: completing a task that requires review opens
653
- # a review. The coordinator reuses an existing review rather
654
- # than replacing it, so decisions already cast stay in force;
655
- # review.request is what starts a fresh pass.
653
+ # a review. Completed again after a revision, it opens a new
654
+ # pass of the same review: the reviewers and the rule stay, and
655
+ # the decisions start empty, because a decision counts only for
656
+ # the artefact it was made on (chap-coordinator 0.3.4). The
657
+ # completer, the new artefact's author, is not a reviewer of it.
656
658
  r = t.review
657
659
  if r is None:
658
660
  r = t.open_review(ts, _implicit_reviewers(ix, actor, t.assignee),
659
661
  "any_one_approves", None)
662
+ else:
663
+ r = t.open_review(ts, [x for x in r.requested_to if x != actor], r.rule, None)
660
664
  r.artefact = p.get("output")
661
665
  t.state, t.settled_at = "review_requested", None
662
666
  else:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: chap-analytics
3
- Version: 0.2.4
3
+ Version: 0.2.5
4
4
  Summary: The record of a collaboration between people and agents, measured and drawn: a CHAP audit chain as documented tables, statistics with their intervals, graphs, charts, briefs and a self-contained interactive report
5
5
  Author-email: Brightbeam AI <oss@brightbeam.com>
6
6
  License-Expression: Apache-2.0
@@ -41,7 +41,7 @@ Requires-Dist: nbclient>=0.9; extra == "notebook"
41
41
  Requires-Dist: ipykernel>=6; extra == "notebook"
42
42
  Provides-Extra: dev
43
43
  Requires-Dist: pytest>=8; extra == "dev"
44
- Requires-Dist: chap-coordinator>=0.3.0; extra == "dev"
44
+ Requires-Dist: chap-coordinator>=0.3.4; extra == "dev"
45
45
  Requires-Dist: nbformat>=5; extra == "dev"
46
46
  Requires-Dist: altair>=5; extra == "dev"
47
47
  Requires-Dist: networkx>=3; extra == "dev"
@@ -48,6 +48,7 @@ tests/test_graph.py
48
48
  tests/test_handoff_and_routing.py
49
49
  tests/test_identity.py
50
50
  tests/test_notebook.py
51
+ tests/test_patch_limits.py
51
52
  tests/test_projection.py
52
53
  tests/test_redaction_and_malformed.py
53
54
  tests/test_refusals.py
@@ -6,7 +6,7 @@ chap-coordinator>=0.3.0
6
6
 
7
7
  [dev]
8
8
  pytest>=8
9
- chap-coordinator>=0.3.0
9
+ chap-coordinator>=0.3.4
10
10
  nbformat>=5
11
11
  altair>=5
12
12
  networkx>=3
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "chap-analytics"
7
- version = "0.2.4"
7
+ version = "0.2.5"
8
8
  description = "The record of a collaboration between people and agents, measured and drawn: a CHAP audit chain as documented tables, statistics with their intervals, graphs, charts, briefs and a self-contained interactive report"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -43,7 +43,7 @@ viz = ["altair>=5", "vl-convert-python>=1.0"]
43
43
  graph = ["networkx>=3"]
44
44
  # Regenerating examples/chap_analytics_walkthrough.ipynb with its outputs.
45
45
  notebook = ["nbformat>=5", "nbclient>=0.9", "ipykernel>=6"]
46
- dev = ["pytest>=8", "chap-coordinator>=0.3.0", "nbformat>=5", "altair>=5", "networkx>=3"]
46
+ dev = ["pytest>=8", "chap-coordinator>=0.3.4", "nbformat>=5", "altair>=5", "networkx>=3"]
47
47
 
48
48
  [project.urls]
49
49
  Homepage = "https://github.com/BrightbeamAI/chap/tree/main/packages/chap-analytics"