chap-analytics 0.2.4__tar.gz → 0.2.6__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 (67) hide show
  1. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/CHANGELOG.md +78 -0
  2. {chap_analytics-0.2.4/chap_analytics.egg-info → chap_analytics-0.2.6}/PKG-INFO +12 -7
  3. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/README.md +9 -4
  4. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/__init__.py +1 -1
  5. chap_analytics-0.2.6/chap_analytics/_patch.py +401 -0
  6. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/briefs.py +59 -9
  7. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/export.py +11 -8
  8. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/frames.py +69 -5
  9. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/schema.py +5 -0
  10. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/stats.py +73 -10
  11. {chap_analytics-0.2.4 → chap_analytics-0.2.6/chap_analytics.egg-info}/PKG-INFO +12 -7
  12. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics.egg-info/SOURCES.txt +4 -0
  13. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics.egg-info/requires.txt +2 -2
  14. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/pyproject.toml +3 -3
  15. chap_analytics-0.2.6/tests/test_acknowledgements.py +128 -0
  16. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/tests/test_charts_and_briefs.py +17 -0
  17. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/tests/test_handoff_and_routing.py +12 -7
  18. chap_analytics-0.2.6/tests/test_held_passes.py +90 -0
  19. chap_analytics-0.2.6/tests/test_patch_limits.py +307 -0
  20. chap_analytics-0.2.6/tests/test_recorded_decisions.py +98 -0
  21. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/tests/test_review_passes.py +78 -8
  22. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/tests/test_watch_export_models.py +15 -0
  23. chap_analytics-0.2.4/chap_analytics/_patch.py +0 -234
  24. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/LICENSE +0 -0
  25. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/MANIFEST.in +0 -0
  26. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/_report/report.css +0 -0
  27. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/_report/report.html +0 -0
  28. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/_report/report.js +0 -0
  29. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/_report/stats.js +0 -0
  30. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/_vendor/LICENSE.vega +0 -0
  31. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/_vendor/LICENSE.vega-embed +0 -0
  32. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/_vendor/LICENSE.vega-lite +0 -0
  33. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/_vendor/README.md +0 -0
  34. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/_vendor/render.js +0 -0
  35. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/_vendor/vega-embed.min.js +0 -0
  36. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/_vendor/vega-lite.min.js +0 -0
  37. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/_vendor/vega.min.js +0 -0
  38. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/charts.py +0 -0
  39. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/graph.py +0 -0
  40. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/load.py +0 -0
  41. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/models.py +0 -0
  42. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/py.typed +0 -0
  43. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/report.py +0 -0
  44. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/sample.py +0 -0
  45. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics/watch.py +0 -0
  46. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics.egg-info/dependency_links.txt +0 -0
  47. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/chap_analytics.egg-info/top_level.txt +0 -0
  48. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/examples/build_notebook.py +0 -0
  49. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/examples/chap_analytics_walkthrough.ipynb +0 -0
  50. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/examples/support_desk.py +0 -0
  51. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/setup.cfg +0 -0
  52. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/tests/conftest.py +0 -0
  53. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/tests/js_stats_runner.js +0 -0
  54. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/tests/test_differential.py +0 -0
  55. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/tests/test_example.py +0 -0
  56. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/tests/test_from_url_scheme.py +0 -0
  57. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/tests/test_graph.py +0 -0
  58. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/tests/test_identity.py +0 -0
  59. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/tests/test_notebook.py +0 -0
  60. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/tests/test_projection.py +0 -0
  61. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/tests/test_redaction_and_malformed.py +0 -0
  62. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/tests/test_refusals.py +0 -0
  63. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/tests/test_report.py +0 -0
  64. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/tests/test_sample_and_export.py +0 -0
  65. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/tests/test_stats.py +0 -0
  66. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/tests/test_successors.py +0 -0
  67. {chap_analytics-0.2.4 → chap_analytics-0.2.6}/tests/test_typescript_store.py +0 -0
@@ -4,6 +4,84 @@
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.6
8
+
9
+ Reads the logs of `chap-coordinator` 0.3.5.
10
+
11
+ ### Added
12
+
13
+ - **Time to open and time to decide.** Coordinators from 0.3.5 record
14
+ `review.acknowledge` when a reviewer opens a review. The decisions table
15
+ gains `acknowledged_at`, `time_to_open_s` and `time_to_decide_s`, and
16
+ `stats.latency` splits each pass's wait the same way, open passes
17
+ included; `open_queue` says which waiting reviews were opened. The
18
+ latency brief reports both medians, counts the waiting reviews nobody
19
+ has opened, and says to tell reviewers when a review arrives where most
20
+ of the wait comes before anyone opens the work. A log without
21
+ acknowledgements reads as before.
22
+ - **Decisions a bridge recorded.** A framework bridge records a decision a
23
+ person made outside CHAP, and from 0.3.5 the call carries
24
+ `via: "bridge-record"`. The decisions table and each pass in
25
+ `stats.latency` carry `via`; `latency_by`, `survival` and the latency
26
+ brief leave out passes a recorded decision settled, and the brief counts
27
+ them. It also points out decisions made within a second of their request,
28
+ which a bridge from before 0.3.5 records unmarked.
29
+ - **The artefact each decision was made on.** The decisions table gains
30
+ `artefact`.
31
+
32
+ ### Fixed
33
+
34
+ - **A completion after a review.** From 0.3.5 a task that has held a review
35
+ completes only through a decision, and completing it again opens a new
36
+ pass. The replay read such a completion as the end of the task, so the
37
+ decision that followed landed in the earlier pass. It now holds the
38
+ completion and opens a pass when a decision or an acknowledgement on the
39
+ task follows, or when the state shows the task under review; a log from
40
+ before 0.3.5 reads as before.
41
+ - **The successor of an escalated task.** From 0.3.5 `escalate.raise`
42
+ hands a review on with the work: the successor requires review when the
43
+ original held one. The replay now reads it so.
44
+ - **Approved evaluation cases.** `export.evaluation_cases(include_approved=True)`
45
+ gave approved tasks an empty `agent_output` and `corrected_output`. Both
46
+ now hold the artefact the settling decision approved.
47
+ - **One reviewer.** The concentration brief said reviewing was spread across
48
+ people when one reviewer decided everything on a small sample, and wrote
49
+ "1 reviewers". One reviewer is now named as the only one, and a high
50
+ share on too few decisions says the sample is too small to tell.
51
+
52
+ ## 0.2.5
53
+
54
+ Reads the review rounds of `chap-coordinator` 0.3.4.
55
+
56
+ ### Changed
57
+
58
+ - **A revised artefact is a new review pass.** A task that requires review
59
+ and is completed again after a revision now opens a new pass of the same
60
+ review, as `chap-coordinator` 0.3.4 does: the reviewers and the rule stay,
61
+ the completer leaves the reviewers, and the decisions start empty. Before,
62
+ the pass carried on with the decisions on the earlier artefact.
63
+ `n_reviews` and `review_index` count the new pass, in a chain any
64
+ coordinator wrote. In a chain written before 0.3.4, a task completed by
65
+ approvals of an earlier artefact now reads as open from the envelopes and
66
+ as completed bypassing review from state, which is what its chain shows.
67
+
68
+ ### Fixed
69
+
70
+ - **A patch that grows the document past a size or depth limit.**
71
+ `chap-analytics` applies each override's patch to rebuild the corrected
72
+ artefact. Its copy of the patch engine limited operations and values, and
73
+ nothing limited size or depth, so a few `copy` operations of the root
74
+ could grow an artefact to gigabytes, and a patch that puts one value
75
+ inside another could nest it deeper than Python can follow. It now
76
+ refuses a patch when, after any of its operations, the artefact holds
77
+ more than 64 MiB of string and key text, counted in UTF-8 bytes, or nests
78
+ deeper than 64 levels, or when its copies, and its moves to a deeper
79
+ place or onto the whole artefact, carry more than three times the value
80
+ and size limits between them. The artefact's `result` is then empty. A
81
+ coordinator refuses an override past its own `max_envelope_bytes`, 1 MiB
82
+ by default, so every override a 0.3.4 coordinator accepted is rebuilt
83
+ while that limit is at most 64 MiB.
84
+
7
85
  ## 0.2.4
8
86
 
9
87
  ### 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.6
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
@@ -29,7 +29,7 @@ License-File: LICENSE
29
29
  Requires-Dist: pandas>=2.0
30
30
  Requires-Dist: numpy>=1.23
31
31
  Provides-Extra: coordinator
32
- Requires-Dist: chap-coordinator>=0.3.0; extra == "coordinator"
32
+ Requires-Dist: chap-coordinator>=0.3.5; extra == "coordinator"
33
33
  Provides-Extra: viz
34
34
  Requires-Dist: altair>=5; extra == "viz"
35
35
  Requires-Dist: vl-convert-python>=1.0; extra == "viz"
@@ -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.5; 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"
@@ -145,7 +145,7 @@ reversed the agent's decision, or a rejection.
145
145
  | Which part of the prompt to fix | Where do the corrections land in the artefact? | Patch path frequency by task kind | Heatmap of `top_path` (the first segment of the corrected path) against kind, with the rationales behind each cell one click away |
146
146
  | Retune the routing thresholds | Does the agent's reported confidence track its outcomes? | Reliability curve, expected calibration error, Brier score | Reliability diagram with per-bin counts |
147
147
  | Promote an agent from trial to production | Is the substantive correction rate below the bar, given how many tasks have been seen? | Beta posterior probability that the true rate is under the threshold; Wald's sequential test | Posterior density against the threshold; the sequential test between its bounds |
148
- | Add reviewers, or reroute | Where do decisions wait, and for whom? | Time to decision as a Kaplan-Meier curve with open reviews censored; latency by reviewer; the open queue | Survival curve; median and 90th percentile per reviewer |
148
+ | Add reviewers, or reroute | Where do decisions wait, and for whom? | Time to decision as a Kaplan-Meier curve with open reviews censored; latency by reviewer; the open queue; where reviewers acknowledge opening a review, time to open and time to decide; decisions a framework bridge recorded from outside CHAP counted apart, and decisions too quick to have been read pointed out | Survival curve; median and 90th percentile per reviewer |
149
149
  | Rewrite an ambiguous policy | Do reviewers agree with each other on the same artefact? | Fleiss' kappa across multi-reviewer passes; pairwise Cohen's kappa; abstentions by category | Agreement matrix |
150
150
  | Clarify the task inputs | How often do agents have to ask, and does anyone answer in time? | Whispers (an agent's deadline-bound question to a person) per task, the share that lapsed unanswered, response time | Lapse rate by asker |
151
151
  | Cover the shift | Are handoffs accepted, and how fast? | Acceptance rate, response time, declines by recipient | Acceptance by recipient |
@@ -360,9 +360,14 @@ which rows are censored. It knows when a decision settled a review under
360
360
  each review rule (`any_one_approves`, `all_approve`, `quorum:N`). It keeps
361
361
  review passes apart, so a task sent back for revision is measured from each
362
362
  pass's own opening and `outcome` reads from the decision that settled the
363
- last pass. It reconstructs the corrected artefact from the patch with the
364
- coordinator's own RFC 6902 semantics. It counts the tasks the server mints
365
- on escalation and supersession, with what they inherit from the original.
363
+ last pass. It tells a decision a person sent from their own client, such as
364
+ a desk, from one a framework bridge recorded in their name, made in an
365
+ interface outside CHAP: `decisions.via` is `bridge-record` for those, and
366
+ the time-to-decision measures leave them out, since their time on the log
367
+ measures no review. It reconstructs the corrected artefact from the patch
368
+ with the coordinator's own RFC 6902 semantics. It counts the tasks the
369
+ server mints on escalation and supersession, with what they inherit from
370
+ the original.
366
371
  And it says how sure it is: `id_certain` and `assignee_certain` mark the
367
372
  rows where the chain admits more than one reading, so the population to
368
373
  draw conclusions from is a filter away.
@@ -96,7 +96,7 @@ reversed the agent's decision, or a rejection.
96
96
  | Which part of the prompt to fix | Where do the corrections land in the artefact? | Patch path frequency by task kind | Heatmap of `top_path` (the first segment of the corrected path) against kind, with the rationales behind each cell one click away |
97
97
  | Retune the routing thresholds | Does the agent's reported confidence track its outcomes? | Reliability curve, expected calibration error, Brier score | Reliability diagram with per-bin counts |
98
98
  | Promote an agent from trial to production | Is the substantive correction rate below the bar, given how many tasks have been seen? | Beta posterior probability that the true rate is under the threshold; Wald's sequential test | Posterior density against the threshold; the sequential test between its bounds |
99
- | Add reviewers, or reroute | Where do decisions wait, and for whom? | Time to decision as a Kaplan-Meier curve with open reviews censored; latency by reviewer; the open queue | Survival curve; median and 90th percentile per reviewer |
99
+ | Add reviewers, or reroute | Where do decisions wait, and for whom? | Time to decision as a Kaplan-Meier curve with open reviews censored; latency by reviewer; the open queue; where reviewers acknowledge opening a review, time to open and time to decide; decisions a framework bridge recorded from outside CHAP counted apart, and decisions too quick to have been read pointed out | Survival curve; median and 90th percentile per reviewer |
100
100
  | Rewrite an ambiguous policy | Do reviewers agree with each other on the same artefact? | Fleiss' kappa across multi-reviewer passes; pairwise Cohen's kappa; abstentions by category | Agreement matrix |
101
101
  | Clarify the task inputs | How often do agents have to ask, and does anyone answer in time? | Whispers (an agent's deadline-bound question to a person) per task, the share that lapsed unanswered, response time | Lapse rate by asker |
102
102
  | Cover the shift | Are handoffs accepted, and how fast? | Acceptance rate, response time, declines by recipient | Acceptance by recipient |
@@ -311,9 +311,14 @@ which rows are censored. It knows when a decision settled a review under
311
311
  each review rule (`any_one_approves`, `all_approve`, `quorum:N`). It keeps
312
312
  review passes apart, so a task sent back for revision is measured from each
313
313
  pass's own opening and `outcome` reads from the decision that settled the
314
- last pass. It reconstructs the corrected artefact from the patch with the
315
- coordinator's own RFC 6902 semantics. It counts the tasks the server mints
316
- on escalation and supersession, with what they inherit from the original.
314
+ last pass. It tells a decision a person sent from their own client, such as
315
+ a desk, from one a framework bridge recorded in their name, made in an
316
+ interface outside CHAP: `decisions.via` is `bridge-record` for those, and
317
+ the time-to-decision measures leave them out, since their time on the log
318
+ measures no review. It reconstructs the corrected artefact from the patch
319
+ with the coordinator's own RFC 6902 semantics. It counts the tasks the
320
+ server mints on escalation and supersession, with what they inherit from
321
+ the original.
317
322
  And it says how sure it is: `id_certain` and `assignee_certain` mark the
318
323
  rows where the chain admits more than one reading, so the population to
319
324
  draw conclusions from is a filter away.
@@ -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.6"
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