b24api 2.6.2__tar.gz → 2.7.0__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 (179) hide show
  1. b24api-2.7.0/PKG-INFO +1329 -0
  2. b24api-2.7.0/README.md +1296 -0
  3. {b24api-2.6.2 → b24api-2.7.0}/b24api/__init__.py +2 -2
  4. b24api-2.7.0/b24api/_sources.py +243 -0
  5. b24api-2.7.0/b24api/_webhook.py +307 -0
  6. {b24api-2.6.2 → b24api-2.7.0}/b24api/batch/correlation.py +36 -2
  7. b24api-2.7.0/b24api/batch/engine.py +1125 -0
  8. {b24api-2.6.2 → b24api-2.7.0}/b24api/batch/logical.py +120 -118
  9. {b24api-2.6.2 → b24api-2.7.0}/b24api/batch/outcome.py +16 -2
  10. {b24api-2.6.2 → b24api-2.7.0}/b24api/batch/stream.py +170 -22
  11. b24api-2.7.0/b24api/batch/v3.py +372 -0
  12. b24api-2.7.0/b24api/cli.py +500 -0
  13. {b24api-2.6.2 → b24api-2.7.0}/b24api/cli_contract.py +24 -15
  14. {b24api-2.6.2 → b24api-2.7.0}/b24api/client.py +95 -42
  15. {b24api-2.6.2 → b24api-2.7.0}/b24api/completion/closure.py +3 -0
  16. {b24api-2.6.2 → b24api-2.7.0}/b24api/completion/fast_recorder.py +33 -13
  17. {b24api-2.6.2 → b24api-2.7.0}/b24api/completion/gate.py +40 -6
  18. {b24api-2.6.2 → b24api-2.7.0}/b24api/completion/operation_stream.py +93 -18
  19. b24api-2.7.0/b24api/completion/page_failure.py +70 -0
  20. {b24api-2.6.2 → b24api-2.7.0}/b24api/completion/recorder.py +31 -12
  21. {b24api-2.6.2 → b24api-2.7.0}/b24api/completion/reference_recorder.py +42 -39
  22. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/__init__.py +2 -1
  23. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/completion.py +2 -0
  24. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/dispatch.py +24 -2
  25. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/error_base.py +17 -1
  26. b24api-2.7.0/b24api/contracts/json.py +284 -0
  27. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/keyset_execution.py +7 -8
  28. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/policy.py +41 -90
  29. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/positional.py +9 -5
  30. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/reference.py +4 -3
  31. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/report.py +18 -2
  32. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/request.py +113 -22
  33. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/traversal.py +22 -7
  34. b24api-2.7.0/b24api/contracts/wire.py +155 -0
  35. b24api-2.7.0/b24api/encoding.py +106 -0
  36. {b24api-2.6.2 → b24api-2.7.0}/b24api/errors.py +113 -1
  37. {b24api-2.6.2 → b24api-2.7.0}/b24api/execution/__init__.py +0 -2
  38. {b24api-2.6.2 → b24api-2.7.0}/b24api/execution/boundary.py +43 -1
  39. b24api-2.7.0/b24api/execution/cleanup.py +101 -0
  40. b24api-2.7.0/b24api/execution/context.py +1100 -0
  41. b24api-2.7.0/b24api/execution/executor.py +1584 -0
  42. b24api-2.7.0/b24api/execution/facts.py +337 -0
  43. {b24api-2.6.2 → b24api-2.7.0}/b24api/execution/failure.py +89 -23
  44. b24api-2.7.0/b24api/execution/lifecycle.py +1219 -0
  45. b24api-2.7.0/b24api/execution/rate.py +632 -0
  46. {b24api-2.6.2 → b24api-2.7.0}/b24api/execution/snapshot.py +6 -0
  47. b24api-2.7.0/b24api/execution/throttle.py +211 -0
  48. {b24api-2.6.2 → b24api-2.7.0}/b24api/migration.py +2 -2
  49. {b24api-2.6.2 → b24api-2.7.0}/b24api/redaction.py +1 -8
  50. {b24api-2.6.2 → b24api-2.7.0}/b24api/references/binding.py +3 -2
  51. {b24api-2.6.2 → b24api-2.7.0}/b24api/references/budget_view.py +30 -6
  52. {b24api-2.6.2 → b24api-2.7.0}/b24api/references/compatibility.py +23 -8
  53. {b24api-2.6.2 → b24api-2.7.0}/b24api/references/counted_io.py +103 -42
  54. b24api-2.7.0/b24api/references/dispatch.py +1718 -0
  55. b24api-2.7.0/b24api/references/dispatch_plan.py +48 -0
  56. {b24api-2.6.2 → b24api-2.7.0}/b24api/references/facade.py +33 -47
  57. {b24api-2.6.2 → b24api-2.7.0}/b24api/references/fanout.py +29 -8
  58. {b24api-2.6.2 → b24api-2.7.0}/b24api/references/keyset_run.py +35 -25
  59. {b24api-2.6.2 → b24api-2.7.0}/b24api/references/outcome.py +2 -2
  60. {b24api-2.6.2 → b24api-2.7.0}/b24api/references/program.py +2 -2
  61. {b24api-2.6.2 → b24api-2.7.0}/b24api/references/run.py +5 -1
  62. {b24api-2.6.2 → b24api-2.7.0}/b24api/references/scheduler.py +418 -219
  63. {b24api-2.6.2 → b24api-2.7.0}/b24api/references/sources.py +2 -2
  64. {b24api-2.6.2 → b24api-2.7.0}/b24api/references/stream.py +28 -9
  65. {b24api-2.6.2 → b24api-2.7.0}/b24api/references/support.py +52 -34
  66. {b24api-2.6.2 → b24api-2.7.0}/b24api/references/wave_engine.py +84 -37
  67. {b24api-2.6.2 → b24api-2.7.0}/b24api/settings.py +64 -21
  68. {b24api-2.6.2 → b24api-2.7.0}/b24api/testing/__init__.py +1 -1
  69. {b24api-2.6.2 → b24api-2.7.0}/b24api/testing/scripted.py +51 -9
  70. {b24api-2.6.2 → b24api-2.7.0}/b24api/testing/transport.py +124 -26
  71. {b24api-2.6.2 → b24api-2.7.0}/b24api/transport/base.py +18 -3
  72. {b24api-2.6.2 → b24api-2.7.0}/b24api/transport/decoding.py +86 -42
  73. b24api-2.7.0/b24api/transport/httpx.py +450 -0
  74. {b24api-2.6.2 → b24api-2.7.0}/b24api/transport/log_records.py +15 -12
  75. {b24api-2.6.2 → b24api-2.7.0}/b24api/transport/logging_shield.py +73 -47
  76. {b24api-2.6.2 → b24api-2.7.0}/b24api/transport/protocol.py +95 -34
  77. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/continuation.py +20 -4
  78. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/control_preflight.py +2 -0
  79. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/counted.py +38 -18
  80. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/counted_batch.py +70 -74
  81. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/counted_io.py +83 -26
  82. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/counted_rules.py +60 -47
  83. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/cursor.py +9 -3
  84. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/cursor_domain.py +1 -1
  85. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/driver.py +150 -89
  86. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/facade.py +29 -31
  87. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/facade_support.py +44 -2
  88. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/identity.py +35 -21
  89. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/identity_ledger.py +9 -2
  90. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/inclusive_window.py +5 -3
  91. b24api-2.7.0/b24api/traversal/keyset_auto.py +289 -0
  92. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/keyset_capability.py +79 -20
  93. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/keyset_context.py +34 -8
  94. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/keyset_eligibility.py +39 -41
  95. b24api-2.7.0/b24api/traversal/keyset_engine.py +95 -0
  96. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/keyset_fast_plan.py +4 -13
  97. b24api-2.7.0/b24api/traversal/keyset_fast_stream.py +169 -0
  98. b24api-2.7.0/b24api/traversal/keyset_geometry.py +530 -0
  99. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/keyset_ordered_admission.py +6 -5
  100. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/keyset_page_validation.py +50 -27
  101. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/keyset_plan.py +111 -45
  102. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/keyset_reporting.py +7 -1
  103. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/keyset_runtime.py +11 -11
  104. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/keyset_step.py +40 -2
  105. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/keyset_transaction_contract.py +1 -0
  106. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/keyset_transactions.py +158 -84
  107. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/keyset_verifier.py +24 -20
  108. b24api-2.7.0/b24api/traversal/keyset_waves.py +303 -0
  109. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/offset_rules.py +43 -14
  110. b24api-2.7.0/b24api/traversal/page_adaptation.py +132 -0
  111. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/plans.py +34 -8
  112. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/sequential.py +54 -15
  113. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/strategy_context.py +22 -3
  114. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/stream.py +16 -2
  115. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/values.py +85 -41
  116. b24api-2.7.0/b24api.egg-info/PKG-INFO +1329 -0
  117. {b24api-2.6.2 → b24api-2.7.0}/b24api.egg-info/SOURCES.txt +4 -0
  118. {b24api-2.6.2 → b24api-2.7.0}/b24api.egg-info/requires.txt +1 -0
  119. {b24api-2.6.2 → b24api-2.7.0}/pyproject.toml +14 -3
  120. b24api-2.6.2/PKG-INFO +0 -837
  121. b24api-2.6.2/README.md +0 -806
  122. b24api-2.6.2/b24api/_sources.py +0 -172
  123. b24api-2.6.2/b24api/batch/engine.py +0 -701
  124. b24api-2.6.2/b24api/batch/v3.py +0 -343
  125. b24api-2.6.2/b24api/cli.py +0 -260
  126. b24api-2.6.2/b24api/contracts/json.py +0 -140
  127. b24api-2.6.2/b24api/contracts/wire.py +0 -85
  128. b24api-2.6.2/b24api/encoding.py +0 -40
  129. b24api-2.6.2/b24api/execution/cleanup.py +0 -47
  130. b24api-2.6.2/b24api/execution/context.py +0 -415
  131. b24api-2.6.2/b24api/execution/executor.py +0 -963
  132. b24api-2.6.2/b24api/execution/lifecycle.py +0 -400
  133. b24api-2.6.2/b24api/execution/rate.py +0 -341
  134. b24api-2.6.2/b24api/execution/throttle.py +0 -107
  135. b24api-2.6.2/b24api/references/dispatch.py +0 -938
  136. b24api-2.6.2/b24api/references/dispatch_plan.py +0 -26
  137. b24api-2.6.2/b24api/transport/httpx.py +0 -398
  138. b24api-2.6.2/b24api/traversal/keyset_auto.py +0 -227
  139. b24api-2.6.2/b24api/traversal/keyset_engine.py +0 -62
  140. b24api-2.6.2/b24api/traversal/keyset_fast_stream.py +0 -179
  141. b24api-2.6.2/b24api/traversal/keyset_geometry.py +0 -313
  142. b24api-2.6.2/b24api/traversal/page_adaptation.py +0 -91
  143. b24api-2.6.2/b24api.egg-info/PKG-INFO +0 -837
  144. {b24api-2.6.2 → b24api-2.7.0}/LICENSE +0 -0
  145. {b24api-2.6.2 → b24api-2.7.0}/MANIFEST.in +0 -0
  146. {b24api-2.6.2 → b24api-2.7.0}/b24api/_client_traversal.py +0 -0
  147. {b24api-2.6.2 → b24api-2.7.0}/b24api/_diagnostics.py +0 -0
  148. {b24api-2.6.2 → b24api-2.7.0}/b24api/_error_types.py +0 -0
  149. {b24api-2.6.2 → b24api-2.7.0}/b24api/batch/__init__.py +0 -0
  150. {b24api-2.6.2 → b24api-2.7.0}/b24api/batch/facade.py +0 -0
  151. {b24api-2.6.2 → b24api-2.7.0}/b24api/completion/__init__.py +0 -0
  152. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/bounded_range.py +0 -0
  153. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/command.py +0 -0
  154. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/continuation.py +0 -0
  155. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/evidence.py +0 -0
  156. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/identity_store.py +0 -0
  157. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/keyset_capability.py +0 -0
  158. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/page.py +0 -0
  159. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/page_stop.py +0 -0
  160. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/reference_source.py +0 -0
  161. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/request_summary.py +0 -0
  162. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/response.py +0 -0
  163. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/stream.py +0 -0
  164. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/v3_codes.py +0 -0
  165. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/violation.py +0 -0
  166. {b24api-2.6.2 → b24api-2.7.0}/b24api/contracts/wire_body.py +0 -0
  167. {b24api-2.6.2 → b24api-2.7.0}/b24api/py.typed +0 -0
  168. {b24api-2.6.2 → b24api-2.7.0}/b24api/references/__init__.py +0 -0
  169. {b24api-2.6.2 → b24api-2.7.0}/b24api/testing/_isolation.py +0 -0
  170. {b24api-2.6.2 → b24api-2.7.0}/b24api/transport/__init__.py +0 -0
  171. {b24api-2.6.2 → b24api-2.7.0}/b24api/transport/disposition.py +0 -0
  172. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/__init__.py +0 -0
  173. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/keyset.py +0 -0
  174. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/keyset_observation.py +0 -0
  175. {b24api-2.6.2 → b24api-2.7.0}/b24api/traversal/sparse.py +0 -0
  176. {b24api-2.6.2 → b24api-2.7.0}/b24api.egg-info/dependency_links.txt +0 -0
  177. {b24api-2.6.2 → b24api-2.7.0}/b24api.egg-info/entry_points.txt +0 -0
  178. {b24api-2.6.2 → b24api-2.7.0}/b24api.egg-info/top_level.txt +0 -0
  179. {b24api-2.6.2 → b24api-2.7.0}/setup.cfg +0 -0
b24api-2.7.0/PKG-INFO ADDED
@@ -0,0 +1,1329 @@
1
+ Metadata-Version: 2.4
2
+ Name: b24api
3
+ Version: 2.7.0
4
+ Summary: Bitrix24 API
5
+ Author-email: Shkarupa Alex <shkarupa.alex@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/shkarupa-alex/b24api
8
+ Project-URL: Repository, https://github.com/shkarupa-alex/b24api
9
+ Project-URL: Issues, https://github.com/shkarupa-alex/b24api/issues
10
+ Keywords: bitrix24,rest,api,client,async,httpx,batch,pagination
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Framework :: AsyncIO
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Internet :: WWW/HTTP
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.12
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: httpx[http2]<0.29,>=0.28.1
27
+ Requires-Dist: h2<4.5,>=4.3.0
28
+ Requires-Dist: hpack<4.3,>=4.1.0
29
+ Requires-Dist: h11>=0.16
30
+ Requires-Dist: pydantic>=2.12.0
31
+ Requires-Dist: pydantic-settings>=2.10.1
32
+ Dynamic: license-file
33
+
34
+ # b24api 2.x
35
+
36
+ `b24api` is a thin asynchronous Bitrix24 REST client for Python 3.12+. It knows how to send
37
+ requests, split logical batches, traverse lists, retry safely, preserve caller correlation and
38
+ close resources. It does not contain a Tasks, CRM or IM method catalog and does not impose
39
+ application storage rules.
40
+
41
+ ## Install and configure
42
+
43
+ ```console
44
+ uv sync --frozen
45
+ export BITRIX24_API_WEBHOOK_URL='https://portal.example/rest/.../'
46
+ ```
47
+
48
+ Keep the webhook out of source, logs and command arguments. Reuse one client for a related unit of work
49
+ so its HTTP/2 connection pool and rate state are reused. The URL has the form
50
+ `https://<portal>/rest/<user>/<token>/`, with a numeric user and a token of letters, digits, `_` and
51
+ `-`. `http` is accepted. Letter case is normalized only in the scheme and host, which are lowered: the
52
+ path keeps its case, so the token is sent as written and `/REST/` is refused. A default port is dropped
53
+ and any other kept, `.` and `..` segments are resolved, a missing trailing slash is added, and leading
54
+ and trailing control characters U+0000–U+001F and spaces are dropped. A host of non-ASCII letters
55
+ is IDNA-encoded, an empty userinfo (`https://@portal/...`, `https://:@portal/...`) is dropped, and a
56
+ host with a trailing dot is accepted as written; see
57
+ [the webhook URL rule](https://github.com/shkarupa-alex/b24api/blob/master/docs/migration.md#transport-hygiene-webhook-urls-unsendable-requests-error-chains)
58
+ for all of it. Any other form is refused, one with a user name or password, a query, a fragment, a
59
+ percent-encoded path, or a surrounding DEL (U+007F) or non-ASCII space (a no-break space, for example)
60
+ included, since the token is its only credential and is registered for redaction as it is sent.
61
+
62
+ `Settings` reads only the process environment. It never reads a `.env` file, so a library call
63
+ cannot pick up a credential from whatever directory the process runs in; the `b24api` CLI is the only
64
+ reader of `.env` (see [CLI](#cli)). `Settings` cannot be pickled, because it holds the webhook
65
+ credential: build it in each process from the environment.
66
+
67
+ `Settings` reads two limits as well. `BITRIX24_API_HTTP_TIMEOUT` bounds each attempt of the client's own
68
+ HTTPX transport in seconds (30 by default, finite): connecting, TLS included, waiting for a pooled
69
+ connection, writing the request and each read of the answer; a transport you inject keeps its own
70
+ timeouts. `BITRIX24_API_MAX_CONCURRENT_REQUESTS` is how many requests one client
71
+ keeps in flight at once, all its calls, streams and retries together (10 by default). An operation's own
72
+ limits only narrow it, and which of them apply depends on the dispatch. A `DirectDispatch` sends at most
73
+ the smallest of its `concurrency`, `ExecutionPolicy.max_direct_concurrency`,
74
+ `ExecutionPolicy.max_active_references` and the client limit at once, so
75
+ `DirectDispatch(concurrency=40)` alone still runs 10 requests at a time. A `BatchDispatch` bounds
76
+ physical batches, not requests: it keeps at most the smallest of its `concurrency`,
77
+ `max_active_references` and the client limit in flight, and `max_direct_concurrency` does not limit it.
78
+ When a REST 3.0 envelope of `SAFE` commands may have run without an answer, its unresolved commands are
79
+ sent again alone, one at a time, within the slot of that envelope's batch. `fan_out()` and
80
+ `fan_out_outcomes()` divide `max_buffered_rows` among the results they may have in flight at once: the
81
+ requests of a `DirectDispatch`, or `batch_size` commands per physical batch of a `BatchDispatch`, at most
82
+ `max_active_references`. That share is what a command reserves before it is sent. A longer result takes
83
+ the rest from the free rows, first in line for the rows that come back, while the commands already reserved
84
+ or the consumer may still free all it lacks; a result longer than the budget, or one whose missing rows are
85
+ held by other results waiting to grow, ends with `ResultTooLargeError` (see Resource boundaries). A `BatchDispatch`
86
+ share never drops below a full 50-row portal page while
87
+ the budget holds one per command of a batch: fewer commands are counted, and the row budget holds back
88
+ the commands beyond them, which coalesce into fewer, fuller batches: a batch whose commands fit only
89
+ once a batch in flight lands waits for it (`coalesce_wait=0` sends it at once, in more requests). Of the
90
+ default 2,500 rows that gives:
91
+
92
+ | Dispatch | Share (rows) | In flight at once |
93
+ | --- | --- | --- |
94
+ | `DirectDispatch()` | 250 | 10 requests |
95
+ | `BatchDispatch()` | 50 | 1 batch of 50 |
96
+ | `BatchDispatch(batch_size=1, concurrency=8)` | 312 | 8 batches of 1 |
97
+ | `BatchDispatch(batch_size=5, concurrency=4)` | 125 | 4 batches of 5 |
98
+ | `BatchDispatch(concurrency=2)` | 50 | 1 batch of 50 |
99
+ | `BatchDispatch(batch_size=20, concurrency=4)` | 50 | 2 batches of 20 |
100
+
101
+ Raise `max_buffered_rows` or narrow the dispatch for longer results. Raise the client limit only as far
102
+ as the portal's rate limits allow. `Bitrix24.from_webhook()` takes both limits
103
+ as arguments:
104
+
105
+ <!-- tested: tests/settings_test.py::test_effective_concurrency_is_the_smallest_of_the_client_and_operation_limits -->
106
+ ```python
107
+ import os
108
+
109
+ from b24api import Bitrix24, Request
110
+
111
+ async with Bitrix24.from_webhook(os.environ["BITRIX24_API_WEBHOOK_URL"], max_concurrent_requests=20) as client:
112
+ users = await client.call(Request.bare("user.get", {"ID": 1}))
113
+ ```
114
+
115
+ ## Quickstart
116
+
117
+ <!-- tested: tests/readme_test.py::test_quickstart_runs_exactly_against_a_scripted_portal -->
118
+ ```python
119
+ import os
120
+
121
+ from b24api import Bitrix24, Request
122
+
123
+ async with Bitrix24.from_webhook(os.environ["BITRIX24_API_WEBHOOK_URL"]) as client:
124
+ deals = client.iter_list(Request.bare("crm.deal.list", {"select": ["ID", "TITLE"]}))
125
+ async for deal in deals:
126
+ print(deal["ID"], deal["TITLE"])
127
+ print(deals.report.state)
128
+ ```
129
+
130
+ Four things are at work:
131
+
132
+ - **The client.** `Bitrix24.from_webhook()` checks the URL and owns the connection pool it opens;
133
+ `async with` closes it. `Bitrix24()` reads the same URL from the environment.
134
+ - **The request.** `Request.bare()` names a REST method and its parameters and sends them to the
135
+ classic `/rest/` endpoint. The route is always explicit: `Request.v3()` targets the V3 API.
136
+ - **`iter_list()`.** It walks the list page by page, following the server's `next`, and stops at
137
+ the page that has none.
138
+ - **The report.** `deals.report` says how the traversal ended. `completed` means every page was
139
+ read; a traversal that stops early or fails records why.
140
+
141
+ A single call returns the decoded `result`:
142
+
143
+ <!-- tested: tests/readme_test.py::test_quickstart_runs_exactly_against_a_scripted_portal -->
144
+ ```python
145
+ users = await client.call(Request.bare("user.get", {"ID": 1}))
146
+ ```
147
+
148
+ The client owns the transport it creates. An injected transport remains caller-owned. `aclose()` is
149
+ idempotent and closes active streams before the owned transport. A closed client raises
150
+ `ClientClosedError` (from `b24api.errors`) for every call awaited and every stream created after
151
+ `aclose()` (the method that creates the stream raises it), and for the calls still waiting for a permit
152
+ when it closed. It is a `TransportError` of phase `not_dispatched`, so the attempt it stopped was not
153
+ sent, and it is never retried. It is a `RuntimeError` as well. The phase covers only that attempt: a
154
+ `SAFE` request that waited for the permit of a retry may already have run on an earlier attempt. To
155
+ prove that no row is missing or repeated, give the traversal an identity (see
156
+ [Choosing a list operation](#choosing-a-list-operation)).
157
+
158
+ ## Direct calls
159
+
160
+ Use `call()` for detached decoded JSON and `call_response()` when you also need the immutable
161
+ response envelope: `result`, `total`, `next`, timing and bounded diagnostic evidence.
162
+
163
+ Use `call_bytes()` when a successful method response is a file rather than a Bitrix JSON envelope.
164
+ The operation is explicit and never hides malformed JSON by falling back to bytes.
165
+
166
+ <!-- tested: tests/client_findings_3_test.py::test_binary_call_returns_every_success_byte_without_json_sniffing -->
167
+ ```python
168
+ from b24api import RouteKind
169
+ archive = await client.call_bytes(Request("example.export.download", replay_safety=ReplaySafety.SAFE, route=RouteKind.BARE))
170
+ payload = archive.body
171
+ ```
172
+
173
+ `archive.filename` is the name decoded from `Content-Disposition` (`filename*` takes precedence
174
+ over `filename`), or `None`; `archive.evidence.filename_status` records whether that header was
175
+ absent, parsed or malformed. The name is caller-facing metadata, not a safe path: it is never
176
+ normalized, truncated or reduced to a basename, and it stays out of the representation and
177
+ diagnostics. Sanitize it before using it on a filesystem.
178
+
179
+ A few actions refuse a POST or read a raw body instead of parameters. `BodyEncoding.QUERY_STRING` sends a
180
+ request's parameters in the URL's query, in the PHP encoding of form bodies. Without `content` it is a GET:
181
+ `crm.site.fileuploader.preview`, `crm.site.fileuploader.download`, `call.Track.download` and
182
+ `crm.timeline.ai.mergefields` accept nothing else. With `content=RawContent(data, content_type)` it is a
183
+ POST of those bytes as they are, under the declared content type, as `crm.site.fileuploader.upload` reads a
184
+ chunk. The query is part of the URL, which the portal's web server and any proxy may log: send nothing
185
+ secret in it. The client's own HTTPX log records keep the path and drop the query.
186
+
187
+ <!-- tested: tests/query_string_request_test.py::test_raw_content_is_posted_byte_for_byte_with_its_type_and_the_parameters_in_the_query -->
188
+ ```python
189
+ from b24api import ReplaySafety, Request
190
+ from b24api.contracts import BodyEncoding, RawContent, RequestHeaders
191
+
192
+ preview = await client.call_bytes(
193
+ Request.bare("crm.site.fileuploader.preview", {"fileId": 7}, ReplaySafety.SAFE, encoding=BodyEncoding.QUERY_STRING)
194
+ )
195
+ chunk = b"the first bytes of the file"
196
+ uploaded = await client.call(
197
+ Request.bare(
198
+ "crm.site.fileuploader.upload",
199
+ replay_safety=ReplaySafety.UNSAFE,
200
+ encoding=BodyEncoding.QUERY_STRING,
201
+ headers=RequestHeaders({"X-Upload-Content-Name": "chunk.bin"}),
202
+ content=RawContent(chunk, "application/octet-stream"),
203
+ )
204
+ )
205
+ ```
206
+
207
+ <!-- tested: tests/client_v2_test.py::test_call_and_call_response_have_stable_detached_types -->
208
+ ```python
209
+ from b24api import RouteKind
210
+ from b24api import ReplaySafety
211
+
212
+ request = Request("example.item.get", {"id": 7}, ReplaySafety.SAFE, route=RouteKind.BARE)
213
+ decoded = await client.call(request)
214
+ response = await client.call_response(request)
215
+ ```
216
+
217
+ ### Replay safety
218
+
219
+ `Request.replay_safety` describes what the client may do when a connection fails after the request
220
+ may already have reached Bitrix:
221
+
222
+ | Value | Meaning | After possible dispatch |
223
+ |---|---|---|
224
+ | `SAFE` | Repeating the request cannot create a second business effect. Typical reads and explicitly idempotent operations belong here. | Automatic retry is allowed within policy budgets. |
225
+ | `UNSAFE` | Repeating the request is known to risk a duplicate effect, for example creating an entity without an idempotency key. | No automatic replay; the caller receives an ambiguous-execution error and reconciles state. It is retried only when the failure proves it did not run. |
226
+ | `UNKNOWN` | The caller has not established whether replay is safe. This is the default. | Same conservative behavior as `UNSAFE`, while diagnostics preserve that safety was unknown rather than known unsafe. |
227
+
228
+ A failure that proves the request did not run is retried whatever its safety: a transport failure
229
+ before dispatch, or a refusal listed in `AmbiguityPolicy`, which by default is a 423, 425 or 429 whose
230
+ body is a gateway's page (`refusal_http_statuses`: not JSON, or JSON without a top-level `error` and
231
+ without a repeated top-level member) or a `QUERY_LIMIT_EXCEEDED` / `OPERATION_TIME_LIMIT` /
232
+ REST 3.0 `BITRIX_REST_V3_EXCEPTION_RATELIMITEXCEPTION` refusal (`refusal_api_codes`). A code or
233
+ status added only to `RetryPolicy` is retried for `SAFE` work alone. An answer that proves nothing
234
+ leaves `UNSAFE` and `UNKNOWN` work ambiguous, and `call()` raises `AmbiguousExecutionError` with that
235
+ answer's failure as its cause: an ambiguous status (408 or any 5xx by default, `ambiguous_unstructured_statuses`),
236
+ structured or not, unless its code is a listed refusal; a 2xx body that cannot be decoded, has no `result`, or
237
+ contradicts itself (both a `result` and an `error`, or a repeated member name where the answer is decided).
238
+ Any other structured error or status outside 2xx is the request's answer and is raised as it is. A request
239
+ that HTTPX could not build was never sent: it fails at once with a `TransportError` of phase `not_dispatched`,
240
+ never as ambiguous, and is not counted as a physical request. An exception from an injected client's event hook, auth flow, transport or response
241
+ stream may follow dispatch. An HTTPX request error (`httpx.RequestError`, such as a connection or read
242
+ error) follows the same phase rule as one from the network. A builtin `TimeoutError` counts as the
243
+ attempt's deadline passing after possible dispatch: `SAFE` work is retried, `UNSAFE` and `UNKNOWN`
244
+ work raises `AmbiguousExecutionError`. Any other `Exception` is not retried and counts as possibly
245
+ sent, with the same consequence for `UNSAFE` and `UNKNOWN` work; the failure itself is a
246
+ `TransportError` that names the exception's class and any HTTP status the client received
247
+ (`error.http_status`), without the exception, which would carry the webhook URL, on its chain. A
248
+ cancellation is re-raised with the same arguments, without the HTTPX frames it was raised in, and an
249
+ exception that is not an `Exception` (`KeyboardInterrupt`) passes through as it is but without those
250
+ frames, which hold the request, and without its chain (`__cause__` and `__context__` are cleared), which
251
+ may be an HTTPX exception that holds it too. A response the
252
+ transport refuses itself is reported as `ProtocolError` (a status outside 100-599) or
253
+ `ResponseTooLargeError` rather than `TransportError`.
254
+ A physical batch applies these rules to each command: after a failure, only the commands that
255
+ may run again are sent again, in a smaller batch, and an `UNSAFE` command of a batch that may have run
256
+ arrives as unknown. Replay rounds spend the same attempt and retry-time budget as the sends before
257
+ them. Method names never imply safety;
258
+ mark a request `SAFE` only when the operation's semantics justify it.
259
+
260
+ Use `ExecutionPolicy` to narrow attempts or resource budgets for one operation:
261
+
262
+ <!-- tested: tests/execution_test.py::test_ambiguous_dispatch_never_retries_unproven_request -->
263
+ ```python
264
+ from b24api import ExecutionPolicy
265
+
266
+ one_attempt = ExecutionPolicy(max_attempts_per_request=1)
267
+ result = await client.call(request, policy=one_attempt)
268
+ ```
269
+
270
+ A `policy=` argument replaces the client's default policy, `ExecutionPolicy()`, wholesale; fields are
271
+ never merged. `Settings` puts nothing in the policy, so a `policy=` keeps the configured attempt timeout
272
+ and concurrency. To change one field of a policy, derive it with `dataclasses.replace`:
273
+
274
+ <!-- tested: tests/settings_test.py::test_a_per_call_policy_replaces_the_client_default_without_merging -->
275
+ ```python
276
+ import dataclasses
277
+
278
+ from b24api import ExecutionPolicy
279
+
280
+ one_attempt = dataclasses.replace(ExecutionPolicy(max_requests=500), max_attempts_per_request=1)
281
+ result = await client.call(request, policy=one_attempt)
282
+ ```
283
+
284
+ `max_retry_elapsed_per_request` (120 s by default) is each request's retry window. It opens when the
285
+ request's first send gets a permit from the client's shared limiter, so waiting in that queue spends
286
+ only the operation's `max_elapsed` (900 s by default; lower it to bound the queue, at the cost of first
287
+ sends that a long queue leaves only a sliver of it, and a known pause that outlasts it fails at once).
288
+ Every send, retry wait and later permit wait then comes out of the window. Each attempt is also bounded
289
+ by its transport's timeout (`Settings.http_timeout` for the client's own transport), so an attempt that
290
+ hangs leaves the rest of the window to its retries; one that times out before anything was sent
291
+ (connecting, the TLS handshake, waiting for a pooled connection) is retried whatever its safety.
292
+
293
+ The portal's load limits slow down what they limit, for every request of the client. A request-rate
294
+ refusal (`QUERY_LIMIT_EXCEEDED`, the REST 3.0 rate limit, or a 429) holds the whole portal for the
295
+ server's hint (`Retry-After` or `X-Bitrix-RateLimit-Reset`). Without one, it paces the portal: the
296
+ portal limits a webhook by its request rate, so requests that waited out a pause together would be
297
+ refused together again. The client's sends then leave one gap apart, those waiting for a connection
298
+ slot included. The gap starts at the retry backoff's initial delay (0.5 s by default) and grows by its
299
+ factor, up to its maximum delay, with each refusal of a request sent after it last grew. Each answer to
300
+ a request sent after that quickens the pace a step (a 32nd of the initial delay's rate), and past 16
301
+ times that rate the client sends at full speed again; an answer about the load (a 429, a 503 or a
302
+ limit's code) does not. A batch is one request, and its answer is about the load if any of its
303
+ commands' entries carries a limit's code. Only answers quicken it, not time: a client that
304
+ went idle keeps its gap until its next requests are answered. The pace holds every kind of work alike,
305
+ so batches keep their share of the sends it lets through. So 300 reads from 10 tasks or from 300, against a
306
+ limit of 2 requests a second, all succeed in about the time the limit allows, with some 20 sends
307
+ refused. An `OPERATION_TIME_LIMIT` holds its method
308
+ alone: for the hint, else until the method's operating time resets, as its latest answer said
309
+ (`time.operating_reset_at`, of a classic batch command too), else for the backoff. A hint on any
310
+ other answer than a 429, a 503 or a load limit's code holds nothing. A retry waits the longer of its
311
+ own exponential backoff and those holds, so a hint of zero or a past date never cancels the backoff. A
312
+ hint given as a date is measured against the response's `Date`, so a local clock running ahead cannot
313
+ shorten it, unless that `Date` is more than a minute behind the local clock (a stale answer or a server
314
+ clock set back), when the local clock measures it: a dated hint never waits more than a minute longer
315
+ than the local clock says, and never more than an hour.
316
+
317
+ A retry of an `UNSAFE` or `UNKNOWN` request is sent only while the window it would have left is at
318
+ least as long as it waited (as planned, or longer when the wait overran); a `SAFE` retry is sent with
319
+ whatever window is left. When the hold alone outlasts what the window allows, the request ends with the
320
+ server's refusal, its code and evidence (`ApiResponseError` with `normalized_code`
321
+ `operation_time_limit` or `query_limit_exceeded`, or the 429 or 503 itself), proven not run where the
322
+ refusal proves it: under the default 120 s window, a `Retry-After` of 60 s or more ends an `UNSAFE` or
323
+ `UNKNOWN` request so even when its first send took no time. When the backoff makes the wait too long,
324
+ it ends with `BudgetExceededError`, whose cause is that refusal. The same holds for the replay rounds
325
+ of a classic batch and the replays of a REST 3.0 envelope: a command its own entry or element answered
326
+ keeps that answer; one whose batch was refused as a whole ends with that refusal when its own hold
327
+ alone outlasts the window, or with `BudgetExceededError` caused by it. Each command is weighed against
328
+ its own method's hold, as known when its round is planned. The rounds share the batch's attempts, so a
329
+ round waits for the longest hold among its commands when each of them can wait that long, and sends them
330
+ all; when an `UNSAFE` or `UNKNOWN` command cannot (the wait must leave it as much window again), the
331
+ round waits for the longest hold those commands can afford, sends every command held no longer, and the
332
+ `SAFE` commands held longer go together in the next round;
333
+ one still waiting when `max_attempts_per_request` is spent is not sent again. A hold that appears during a round's wait stops the whole round at its permit when it
334
+ outlasts the window. The first send of a `batch()` or `batch_outcomes()` chunk weighs its commands the
335
+ same way, by how much longer their methods are held than the portal: the least held go at once, a
336
+ command held longer goes in a later envelope once its hold ends, and only one whose hold outlasts what
337
+ the operation has left is not sent and ends with `BudgetExceededError`. A chunk whose every command can
338
+ go at once, or none can, and every chunk of a fail-fast `batch()`, which is never split, waits within
339
+ `max_elapsed` as a lone request does, and so do traversal pages and `fan_out()` waves. By default
340
+ `SAFE` requests are also retried after an unstructured 408, 500, 502, 503 or 504
341
+ (`RetryPolicy.transient_http_statuses`).
342
+
343
+ ### Error codes
344
+
345
+ Every error of `b24api.errors` survives `pickle` and `copy` with its message and attributes, so it can
346
+ cross a process pool or a task queue. The exception is an error that holds a caller's correlation:
347
+ `BatchFailed` and `ReferenceFailed` keep their outcomes, each with its correlation, so `pickle` fails on
348
+ them when the correlation cannot be pickled, and `copy.deepcopy()` when it cannot be deep-copied, with
349
+ the error the correlation raises (`TypeError` for a lock, for example); `copy.copy()` still works. A structured refusal raises `ApiResponseError`. Its
350
+ message, `wire_code`, `normalized_code`, `code` (lower case) and `to_safe_dict()` name the server's
351
+ code, so failures can be told apart:
352
+
353
+ ```text
354
+ API error [BITRIX_REST_V3_EXCEPTION_ACCESSDENIEDEXCEPTION]: Access denied
355
+ API error [NOTE_EMPTY_UPDATE]: Nothing to update
356
+ ```
357
+
358
+ A REST 3.0 `error.code` is shown verbatim whenever it is a snake-case identifier: upper case, such
359
+ as `BITRIX_REST_V3_EXCEPTION_INVALIDSELECTEXCEPTION` or `FEATURE_NOT_AVAILABLE_ON_CURRENT_PLAN`, or
360
+ lower case of letters only, such as `invalid_select_field`; the server's set is open, so no list is
361
+ kept. Error texts, classic
362
+ `{"error": ...}` codes and response previews keep the conservative redaction, so a long run of
363
+ letters and digits there still renders as `[REDACTED]`. A code that equals or contains your
364
+ webhook token or a credential of the request, in any letter case, is always `[REDACTED]`; one that
365
+ names a field of your request is shown as its `field#N` alias, or as `[REDACTED]` when only its
366
+ letter case differs.
367
+
368
+ Recognizing a code does not make it retryable. By default only the REST 3.0 load limits are retried,
369
+ after the server's `Retry-After`:
370
+
371
+ | Code | Status | Retried |
372
+ |---|---|---|
373
+ | `BITRIX_REST_V3_EXCEPTION_RATELIMITEXCEPTION` | 429 | Any direct request: the limiter refuses before the method runs. In a REST 3.0 batch envelope only `SAFE` commands: the limiter counts each command, so its refusal of the envelope may follow commands that ran. |
374
+ | `BITRIX_REST_V3_EXCEPTION_LIMITER_QUERYTIMELIMITEXCEPTION` | 503 | `SAFE` requests only: the method may have run. |
375
+
376
+ Every other REST 3.0 code is not retried. Outside an ambiguous status (408 or any 5xx by default,
377
+ `ambiguous_unstructured_statuses`) it is the request's answer and is raised at once as `ApiResponseError`,
378
+ a 429 that a module declares for a longer-lived state (`LANDING_AI_SITE_MODERATION_BLOCK_LIMIT`)
379
+ included. At an ambiguous status (`LANDING_AI_MODULE_UNAVAILABLE` with 503) it proves nothing about
380
+ whether the method ran: `SAFE` work raises the `ApiResponseError`, `UNSAFE` and `UNKNOWN` work raise
381
+ `AmbiguousExecutionError` caused by it. List more codes in
382
+ `RetryPolicy.transient_api_codes` (and in `AmbiguityPolicy.refusal_api_codes` when the code proves the
383
+ method did not run). The request faults `BITRIX_REST_V3_EXCEPTION_VALIDATION_REQUESTVALIDATIONEXCEPTION` and
384
+ `BITRIX_REST_V3_EXCEPTION_METHODNOTFOUNDEXCEPTION` in a REST 3.0 error envelope are never retried,
385
+ even when listed.
386
+
387
+ ## Logical batch and correlation
388
+
389
+ `batch()` accepts an arbitrary-length synchronous or asynchronous command source. It consumes the
390
+ source incrementally and splits it into physical Bitrix batches of at most 50 commands; the full
391
+ input is never materialized.
392
+
393
+ `Command.correlation` is arbitrary caller-owned state. It is retained by reference, returned with
394
+ the outcome, never serialized to Bitrix and never included in safe diagnostics. This is useful for
395
+ matching a result to the object, file, chat or database row that produced its request.
396
+
397
+ <!-- tested: tests/client_v2_test.py::test_logical_batch_is_unbounded_ordered_and_correlation_is_strictly_off_wire -->
398
+ ```python
399
+ from b24api import RouteKind
400
+ from b24api.contracts import Command, CommandSuccess
401
+
402
+ commands = (
403
+ Command(
404
+ Request("example.item.get", {"id": item_id}, ReplaySafety.SAFE, route=RouteKind.BARE),
405
+ correlation=item_id,
406
+ )
407
+ for item_id in source_ids
408
+ )
409
+
410
+ async with client.batch(commands, batch_size=25) as stream:
411
+ async for outcome in stream:
412
+ assert isinstance(outcome, CommandSuccess)
413
+ consume(outcome.correlation, outcome.result)
414
+ ```
415
+
416
+ `batch()` is fail-fast. `batch_outcomes()` continues where safe and yields one of
417
+ `CommandSuccess`, `CommandFailure`, `CommandNotExecuted` or `CommandOutcomeUnknown` in input order.
418
+ It does not continue past its budgets: once `max_requests` refuses a send, it yields the outcomes of
419
+ the commands it has already read, those never sent as `CommandFailure` with `BudgetExceededError`,
420
+ then raises `BudgetExceededError`, reads no further input and closes the source, as when
421
+ `max_elapsed` runs out. Its report is `incomplete` and records the `budget_exhausted` violation.
422
+ `fan_out_outcomes()` and the reference traversals end the same way.
423
+
424
+ <!-- tested: tests/client_v2_test.py::test_batch_outcomes_retains_typed_failure_without_halting_later_commands -->
425
+ ```python
426
+ from b24api.contracts import CommandFailure, CommandNotExecuted, CommandOutcomeUnknown
427
+
428
+ async with client.batch_outcomes(commands) as stream:
429
+ async for outcome in stream:
430
+ match outcome:
431
+ case CommandSuccess() as success:
432
+ consume(success.correlation, success.result)
433
+ case CommandFailure() | CommandNotExecuted() | CommandOutcomeUnknown():
434
+ handle(outcome)
435
+ ```
436
+
437
+ Commands whose request uses `RouteKind.API_V3` travel in native REST 3.0 batch envelopes: one JSON
438
+ array of at most 50 commands, never mixed with classic commands and grouped into contiguous runs of
439
+ one replay safety (`UNSAFE` and `UNKNOWN` share a run). Envelopes go out in input order: a classic
440
+ command between two v3 commands travels in its own envelope between theirs. The one exception is a
441
+ command whose method is held longer than the rest of its envelope's: it goes in a later envelope, after
442
+ the chunk's other envelopes (see the load limits above). Outcomes come back in input order either way.
443
+ The transport must
444
+ advertise JSON-array bodies, as `HttpxTransport` does; otherwise such a command fails with
445
+ `CapabilityError` before any request. Each array element is checked against its own request's
446
+ embedded-error contract, so one failed command neither fails nor resends its successful neighbours.
447
+ An element of a request with no `result_error` contract is its result, whatever it holds: the client
448
+ cannot tell an error element from data without one, so such a command is a `CommandSuccess`.
449
+
450
+ <!-- tested: tests/v3_batch_test.py::test_a21_wire_four_safe_v3_reads_travel_in_one_envelope_in_input_order -->
451
+ ```python
452
+ from b24api import RouteKind
453
+ from b24api.contracts import Command
454
+
455
+ v3_commands = (
456
+ Command(Request("example.item.get", {"id": item_id}, ReplaySafety.SAFE, route=RouteKind.API_V3), item_id)
457
+ for item_id in source_ids
458
+ )
459
+ async with client.batch_outcomes(v3_commands) as stream:
460
+ async for outcome in stream:
461
+ handle(outcome)
462
+ ```
463
+
464
+ REST 3.0 does not roll a batch back. An envelope refused for its credentials (a 401) is answered whole:
465
+ each command is a `CommandFailure` with that error and is not sent alone, as in a classic batch. Any other
466
+ error on a REST 3.0 envelope, structured, unreadable or contradictory, may come from the command that
467
+ aborted it after earlier ones ran, unless it is a gateway's page (not JSON, or JSON without a top-level `error`
468
+ and without a repeated top-level member) at a listed refusal status, which proves the envelope was refused. A classic
469
+ envelope answered with an ambiguous status (408 or a 5xx) that is not a listed refusal leaves each of its commands unknown, as a REST 3.0 one does. When a whole envelope fails after it may have
470
+ run, `SAFE` commands of a transient failure get one envelope retry within their attempt budget, and commands
471
+ still unresolved are sent individually (`RetryPolicy.isolate_safe_batch_abort`, enabled by default)
472
+ under the same attempt lineage. That isolation waits and is admitted as a retry is (backoff, throttle
473
+ hint, attempts, retry window, deadline), then sends one command at a time, so it stays within the
474
+ dispatch's concurrency; `UNSAFE` and `UNKNOWN` commands arrive
475
+ as `CommandOutcomeUnknown` without a resend. The report counts `ambiguous_physical_attempts` and
476
+ `batch_isolation_requests`. Fail-fast `batch()` finishes resolving the envelope it already sent and
477
+ then raises without reading further input. A batch stream that ends before it delivered every outcome
478
+ (cancelled mid-envelope, say) tells the admitted commands it never delivered apart in its report:
479
+ `undelivered_possibly_run` counts those a send may have run (in flight, or sent without an answer),
480
+ `undelivered_not_sent` those never sent; the rest were answered.
481
+
482
+ A classic (non-REST 3.0) batch sends each command as a PHP query string, which cannot carry every
483
+ JSON value with the meaning a direct call gives it. A command is sent in a classic batch only when its
484
+ query string means what its JSON would mean; otherwise it fails alone with `CapabilityError` before any
485
+ request (as a `CommandFailure` in `batch_outcomes()` and `fan_out_outcomes()`), and the message says
486
+ which value is the problem. These values are refused:
487
+
488
+ - `None` (a direct call sends `null`, which a filter or update reads as "empty"; the query string drops
489
+ the key, which changes what the command selects or writes);
490
+ - an empty array or object, which the query string drops the same way;
491
+ - an empty key, a key holding `[`, `]` or NUL, and a top-level key holding `.` or a space, which PHP
492
+ renames;
493
+ - text holding a reference pattern (`$result[`, `$result_error[`, `$result_total[`, `$result_next[` or
494
+ `$result_time[`, in any letter case), which the batch handler replaces inside any value.
495
+
496
+ Send such a command directly (`client.call()`, or `fan_out()` with `DirectDispatch`), or by REST 3.0. A
497
+ `bool` is sent as `1` or `0`, as PHP's `http_build_query` writes it. `Request.classic_batch_obstacle`
498
+ names what would keep a request out of classic batch, or is `None`.
499
+
500
+ For independently dispatchable commands, use `fan_out()` or `fan_out_outcomes()` with
501
+ `DirectDispatch` or `BatchDispatch`. Delivery order is explicitly `READY` or `INPUT`.
502
+
503
+ ## Choosing a list operation
504
+
505
+ The unsuffixed operation is the basic strategy with the fewest endpoint assumptions. Faster or
506
+ more specialized mechanics have explicit names and explicit preconditions.
507
+
508
+ | Operation | Use it when | Network mechanics | Completion proof |
509
+ |---|---|---|---|
510
+ | `iter_list` | The method supports ordinary offset pagination. | Sequential requests follow server `next` (the next offset). Ordinary counted Bitrix list endpoints do server-side COUNT for `total` plus LIMIT/OFFSET page retrieval. | The last page carries no `next`; a reported `total` must match the rows read; add identity for duplicate detection. |
511
+ | `iter_list_counted` | The first response provides an exact filtered `total` and stable offset pages. | Head page is direct; all known tail offsets are grouped into physical Bitrix batches. | Exact total, ranges and identities. |
512
+ | `iter_list_keyset` | The method may omit `total`, but reliably supports ordering and filtering by a unique integer identity. | Auto by default: it plans first, then selects boundary-only, sequential, range, or partitioned execution; runtime sends no diagnostic canaries. | Caller-asserted keyset contract, strict monotonic identity, active bound validation, and terminal empty confirmation. |
513
+ | `iter_list_cursor` | Each next request depends on a cursor from the previous response. | Sequential dependent cursor requests. | Strict unique monotonic cursor and empty terminal page. |
514
+ | `iter_list_continuation` | The next request is described by values on the current page, such as a response cursor object or a pair of controls. | Sequential requests; a pure caller rule returns the next values of declared controls or ends the source. | Rule-declared end; undeclared updates and repeated control vectors fail closed. |
515
+ | `iter_list_window` | A newest-first list resumes from an inclusive timestamp boundary and may also return pinned rows. | Sequential requests carrying the oldest paging timestamp of the previous page. | Strict boundary progress, overlap delivered once, and a response flag that closes the source. |
516
+ | `iter_cursors` | One or many parent-bound cursor traversals need correlation and shared batching. | Lazy per-parent drivers share the reference batch queue; each binding may have `start_cursor`. | Isolated strict cursor progress and terminal event per binding. |
517
+ | `iter_references` | The same list method must run for many parent parameter sets, such as comments per owner or messages per chat. | Bindings are scheduled with direct or physical-batch dispatch; each binding has its own traversal state. | Per-binding rows, completion/failure and caller correlation. |
518
+ | `iter_reference_sources` | Parents need different methods or traversals in one operation. | Each source brings its own request and traversal; compatible pages of all sources share one batch queue. | Per-source rows, terminal event and correlation. |
519
+
520
+ `page_size` is a local decoded-page cap. It is sent to Bitrix only when you provide the endpoint's
521
+ exact `limit_path`; the client never guesses method-specific parameter names.
522
+
523
+ ### List traversal comparison
524
+
525
+ ![List traversal comparison](https://raw.githubusercontent.com/shkarupa-alex/b24api/master/list-traversal-comparison.svg)
526
+
527
+ The animation replays traces executed against a scripted portal with 1,000 dense IDs at 50 rows
528
+ per page. `iter_list` sends 20 pages and stops at the one without `next` (20 HTTP). `iter_list_counted` sends
529
+ the head and one batch of 19 pages (2 HTTP). `iter_list_keyset` in auto mode selects range
530
+ execution: it reads both ends of the range in one batch, the 19 ranges between them in a second, and
531
+ confirms the end with one call for `ID > 1000` (3 HTTP). A `BoundedIdentityRange` with a qualified
532
+ upper ID needs no confirmation: sequential execution stops when it receives that ID. On a real portal
533
+ auto chooses from the observed geometry, so the plan and its request count can differ; the report's
534
+ `keyset_selection` says which plan ran.
535
+
536
+ ### Sequential offset
537
+
538
+ This is the canonical default. It follows the `next` returned by the server and ends at the first
539
+ page without one. For ordinary counted Bitrix list endpoints, `next` is an offset for the next
540
+ LIMIT/OFFSET page, not a keyset cursor. Producing `total` involves a separate server-side count
541
+ query in addition to retrieving the page. These database operations are performed inside the same
542
+ REST request: the client does not issue an additional HTTP call just for the count. This distinction
543
+ matters for performance: not making a separate HTTP count call does **not** mean avoiding server-side
544
+ COUNT work. `iter_list` does not suppress that work; a returned `total` never ends this strategy,
545
+ but it is checked against the rows read at the end (below). Exact database implementation is
546
+ endpoint-specific.
547
+
548
+ Nothing is requested past the last page. Many endpoints cannot answer such a request with an empty
549
+ page: `crm.lead.list`, `crm.deal.list`, `crm.activity.list` and `tasks.task.list` round `start` down to
550
+ a multiple of 50 and answer a `start` at or past the end with their last page again, and
551
+ `department.get` ignores `start` and always returns everything without `next`. The page without
552
+ `next` is therefore the end on every Bitrix list endpoint. A Bitrix list `total` counts the filter's
553
+ rows, so when the traversal started at the first page, a `total` reported by the last page (or, if
554
+ it has none, by the latest page that had one) must equal the number of rows read; otherwise the traversal raises `IncompleteTraversalError` caused by a
555
+ `PaginationError` with the `total_drift` page rejection, and the report is `incomplete`, never
556
+ `completed`. An endpoint whose `total` is not an exact count of its rows can declare that with
557
+ `ConsistencyPolicy(total_semantics=TotalSemantics.ADVISORY)`: a mismatch is then the
558
+ `advisory_total_mismatch` warning. `TotalSemantics.GLOBAL` declares a `total` that counts every row of
559
+ the endpoint rather than the filter's, so it is never compared with the rows read.
560
+
561
+ <!-- tested: tests/client_v2_test.py::test_iter_list_is_sequential_mechanics_only_and_report_is_post_cleanup -->
562
+ ```python
563
+ from b24api import RouteKind
564
+ from b24api import IdentityCoercion, IdentitySpec, ResultSelector
565
+
566
+ identity = IdentitySpec(
567
+ item_path=("ID",),
568
+ filter_key="ID",
569
+ order_key="ID",
570
+ coercion=IdentityCoercion.DECIMAL_STRING_INTEGER,
571
+ )
572
+
573
+ stream = client.iter_list(
574
+ Request("example.item.list", replay_safety=ReplaySafety.SAFE, route=RouteKind.BARE),
575
+ selector=ResultSelector(("items",)),
576
+ identity=identity,
577
+ )
578
+ async with stream:
579
+ async for item in stream:
580
+ consume(item)
581
+ ```
582
+
583
+ Without `identity`, successful exhaustion is reported as `MECHANICS_ONLY`: pagination completed,
584
+ but the client cannot prove that the portal did not duplicate or substitute rows.
585
+
586
+ A page identical to an earlier page fails the traversal: rows alone cannot tell such a page from a
587
+ portal that ignored `start` and returned the same page again, and a changed `next` or `total` cannot
588
+ either, because an endpoint that ignores `start` can still compute them from it. A narrow `select`
589
+ whose rows repeat by content, such as `{"select": ["STAGE_ID"]}`, therefore needs a unique field in
590
+ the rows: add `ID` to the `select` and declare it as `identity`.
591
+
592
+ A row whose identity is missing or does not match its coercion raises `IdentityContractError`, a
593
+ `PaginationError`, as the cause of `IncompleteTraversalError` on every traversal; it names the path,
594
+ the coercion, the observed JSON type and the row offset, never the value. The offset counts rows of
595
+ the traversal; a fast keyset counts them within the lane that read the page. Identities and cursors
596
+ are read before a `page_adapter` runs, so an adapter never sees a row that breaks them.
597
+ `DECIMAL_STRING_INTEGER` accepts an integer or the canonical decimal string of one: ASCII digits
598
+ without a leading zero, with a minus only before a non-zero value (`"0"`, `"12"`, `"-7"`). `"012"`,
599
+ `" 12"`, `"1_2"` and `"+12"` are refused, so two different wire values never become one identity.
600
+
601
+ `OffsetContinuation.SERVER_NEXT` is the default. An endpoint that honors `start` exactly but sends no
602
+ `next` declares `OffsetContinuation.OBSERVED_COUNT`: the next offset is the current one plus the rows
603
+ read, and an empty page ends the traversal. Such an endpoint has no Bitrix list envelope, so its
604
+ `total` is not read unless the caller qualifies it (`EXACT_QUALIFIED`, or an `ADVISORY` comparison);
605
+ the same holds for `FIXED_STEP`. An empty page that still carries `next` is refused only where `next`
606
+ is followed, under `SERVER_NEXT`; cursor, continuation and window traversals, an observed count and a
607
+ fixed step do not read it. `ConsistencyPolicy(confirmation_policy=EMPTY_AFTER_BOUNDARY)`
608
+ asks for such an empty page, so it is refused with `CapabilityError` before any request under
609
+ `SERVER_NEXT`, whose end is the page without `next`.
610
+ `TotalTermination.EXACT_QUALIFIED` requires every page to carry the same exact `total` and the rows
611
+ to reach it; under `OBSERVED_COUNT` or `FIXED_STEP` the page that reaches it ends the traversal
612
+ without an empty confirmation. A first page with no rows, no `next` and no usable `total` (missing,
613
+ `null` or `-1`, as `user.get` answers a filter that matches nothing) completes as an observed empty
614
+ source, as it does for `iter_list_counted` below.
615
+
616
+ An endpoint that honors `start` only at a fixed server window and signals its end only with a
617
+ shorter page (no usable `total`, no `next`) can declare that stop rule with
618
+ `OffsetSpec(short_page_termination=ShortPageTermination.DECLARED_TERMINAL)`; its successful
619
+ exhaustion is always `MECHANICS_ONLY`. See
620
+ [Declared short-page closure](https://github.com/shkarupa-alex/b24api/blob/master/docs/recipes.md#declared-short-page-closure).
621
+
622
+ Mapping-backed collections are explicit as well. `MAPPING_VALUES` yields values from a selected
623
+ mapping in insertion order; `MAPPING_VALUES_OR_EMPTY` additionally accepts only an empty terminal
624
+ sequence and records that degradation in the operation report.
625
+
626
+ <!-- tested: tests/client_findings_3_test.py::test_shape_rejection_is_retained_as_zero_admission_page_evidence -->
627
+ ```python
628
+ from b24api import RouteKind
629
+ from b24api.contracts import ResultCollectionShape
630
+
631
+ stream = client.iter_list(
632
+ Request("example.dictionary.list", replay_safety=ReplaySafety.SAFE, route=RouteKind.BARE),
633
+ selector=ResultSelector(("items",)),
634
+ collection_shape=ResultCollectionShape.MAPPING_VALUES,
635
+ )
636
+ async with stream:
637
+ async for value in stream:
638
+ consume(value)
639
+ ```
640
+
641
+ ### Counted, physically batched tail
642
+
643
+ The first direct page must contain an exact filtered `total` and, when more rows exist, `next`.
644
+ The client derives all remaining offsets from the observed head width and sends tail pages through
645
+ bounded physical batches. A tail page whose rows do not fit what `max_buffered_rows` leaves it is
646
+ dropped: the pages before it are yielded, and the traversal raises `IncompleteTraversalError` caused
647
+ by `ResultTooLargeError`.
648
+
649
+ <!-- tested: tests/client_v2_test.py::test_counted_traversal_preserves_frozen_request_shape_and_exact_identity -->
650
+ ```python
651
+ from b24api import RouteKind
652
+ stream = client.iter_list_counted(
653
+ Request("example.item.list", replay_safety=ReplaySafety.SAFE, route=RouteKind.BARE),
654
+ selector=ResultSelector(("items",)),
655
+ identity=identity,
656
+ page_size=50,
657
+ batch_size=50,
658
+ )
659
+ ```
660
+
661
+ Use it only when `total` is exact for the supplied filter and offset pages are stable. Any missing
662
+ range, overlap, duplicate identity or total contradiction, a head without `next` short of its `total`
663
+ included, raises `IncompleteTraversalError`. As in `iter_list`, every other failure (an API error, a
664
+ missing `total`, a result of the wrong shape, a spent budget) is raised as it is, and the report says
665
+ `failed` (`incomplete` for a budget). The exact `total` is known from the head, so a range the page,
666
+ request, row-buffer or in-memory identity budget cannot hold is refused right there with
667
+ `BudgetExceededError`, before any row is yielded; the head is traced as rejected with the
668
+ `budget_exhausted` page rejection.
669
+
670
+ A filtered call that matches nothing may omit `total` entirely, as `user.get` does with
671
+ `result: []`. A first page with no rows, no `next` and no usable `total` (missing, `null`, or the
672
+ `-1` unknown sentinel) therefore completes as an observed empty source after that one request: the
673
+ report is `completed` and `exhausted`, but its assurance is `mechanics_only` (`identity_exact` with an
674
+ identity), never a count-matched claim, and no total is invented. A first page that reports
675
+ `total: 0` keeps the count-matched result. Rows without a usable total, a remaining `next`, a fixed
676
+ step, or a `ConsistencyPolicy` whose `confirmation_policy` is `QUALIFIED_TOTAL` (from
677
+ `b24api.contracts.policy.ConfirmationPolicy`) stay strict and raise `CapabilityError`; a positive
678
+ total with no rows raises `IncompleteTraversalError`.
679
+
680
+ Physical batching reduces HTTP exchanges, but does not suppress server-side COUNT in ordinary
681
+ counted list subrequests. Each command still performs its own offset page retrieval and associated
682
+ total calculation on the server. Do not confuse batching these commands with a no-count traversal.
683
+
684
+ ### No-count keyset
685
+
686
+ Keyset traversal uses automatic execution by default. Omitting `execution` is equivalent to
687
+ `AutoKeysetExecution(StableIntegerKeysetContract())`: the client captures both ordered boundaries,
688
+ then selects boundary-only, sequential, range, or partitioned execution from the observed geometry
689
+ and available policy capacity. Planning completes before any row is emitted, so partial consumption
690
+ still pays that barrier cost. A sequential selection made by auto is a cost decision; a failed or
691
+ contradictory fast plan is never silently restarted as sequential.
692
+
693
+ By using the default, the caller asserts that the endpoint has a stable, unique integer key, honors
694
+ strict numeric bounds and ordering, and satisfies empty-confirmation completion. Concurrent mutation
695
+ outside the captured middle is handled by the finishing sweep; mutation inside it is outside this
696
+ assertion. Pass `SequentialKeysetExecution()` explicitly when an endpoint cannot satisfy the fast
697
+ contract or when the previous request-by-request behavior is required.
698
+
699
+ Static incompatibility with the auto contract raises `CapabilityError` from the
700
+ `iter_list_keyset(...)` call before iteration begins. A portal that accepts but contradicts the
701
+ declared controls fails before emission with `IncompleteTraversalError`; auto never restarts that
702
+ operation silently. Reference traversal can opt into the same selection for each binding; see
703
+ [Keyset references](#keyset-references). The
704
+ terminal report carries a compact `keyset_selection` (`requested_kind`, `selected_kind`, `reason`)
705
+ for every keyset traversal. A `page_stop` callback needs the ordered page stream, so auto reports
706
+ `AUTO`, `SEQUENTIAL`, `PAGE_STOP`; an explicit `SequentialKeysetExecution()` reports
707
+ `EXPLICIT_SEQUENTIAL`. Fast execution sends classic batch commands, so for a request that classic batch
708
+ cannot carry (see [Logical batch and correlation](#logical-batch-and-correlation)) auto reports `AUTO`,
709
+ `SEQUENTIAL`, `BATCH_UNREPRESENTABLE` and sends its pages directly, while an explicit fast execution
710
+ raises `CapabilityError` before any request. A fast or automatic reference binding fails with that
711
+ error before its first request: under `BatchDispatch` its sequential pages would travel in classic
712
+ batch too, so such a binding needs `SequentialKeysetExecution()` under `DirectDispatch`. The detailed `keyset_execution` report is present only when the fast path ran.
713
+
714
+ Use `await client.verify_keyset_capability(...)` as a development/CI/staging guard on a stable
715
+ representative fixture. It performs five strict-bound checks and returns only a `VERIFIED` report;
716
+ unsupported and inconclusive verdicts raise `KeysetCapabilityError`. The ordinary
717
+ `iter_list_keyset()` remains a separate caller-asserted operation with zero verifier canaries and
718
+ may emit a partial prefix before a late endpoint contradiction is detected.
719
+ Keep the guard beside the traversal, for example under
720
+ `if os.environ.get("ENV") != "PROD":`; set `ENV=PROD` only after qualifying the exact portal,
721
+ credentials, method, request/filter, identity, ordering representation, and page cap.
722
+
723
+ Every list operation also accepts an immutable `PageAdapter` strategy. The adapter synchronously
724
+ maps selected frozen items using sibling result metadata while preserving cardinality, order and
725
+ configured identities. The identity adapter is the default and preserves existing JSON output.
726
+
727
+ An advisory `total` may only raise an automatic cost estimate and never proves completion. Reports
728
+ record the selected strategy and reason: unbounded auto continuation has the same
729
+ `ordered_prefix_only` assurance as sequential traversal, while bounded plans additionally report
730
+ `caller_asserted_bounds`. Runtime traversal does not perform verifier canaries.
731
+
732
+ <!-- tested: tests/keyset_fast_test.py::test_omitted_execution_defaults_to_auto -->
733
+ ```python
734
+ import os
735
+
736
+ from b24api import KeysetSpec, ParameterPath, ReplaySafety, Request, ResultSelector, RouteKind
737
+
738
+ request = Request("example.item.list", replay_safety=ReplaySafety.SAFE, route=RouteKind.BARE)
739
+ selector = ResultSelector(("items",))
740
+ keyset = KeysetSpec(
741
+ filter_path=ParameterPath(("filter",)),
742
+ order_path=ParameterPath(("order",)),
743
+ )
744
+
745
+ if os.environ.get("ENV") != "PROD":
746
+ # Accepting an ID filter does not prove strict bounds or ordering.
747
+ await client.verify_keyset_capability(
748
+ request,
749
+ selector=selector,
750
+ identity=identity,
751
+ page_size=50,
752
+ keyset=keyset,
753
+ )
754
+
755
+ stream = client.iter_list_keyset(
756
+ request,
757
+ selector=selector,
758
+ identity=identity,
759
+ page_size=50,
760
+ keyset=keyset,
761
+ )
762
+ ```
763
+
764
+ ### Dependent cursor
765
+
766
+ Use a cursor when the next boundary is returned or derived from the previous page, as with many
767
+ message-list methods.
768
+
769
+ <!-- tested: tests/client_v2_test.py::test_keyset_and_cursor_are_explicit_strict_alternatives -->
770
+ ```python
771
+ from b24api import RouteKind
772
+ from b24api import CursorSpec, ParameterPath
773
+
774
+ stream = client.iter_list_cursor(
775
+ Request("example.message.list", replay_safety=ReplaySafety.SAFE, route=RouteKind.BARE),
776
+ selector=ResultSelector(("items",)),
777
+ cursor=CursorSpec(
778
+ parameter_path=ParameterPath(("LAST_ID",)),
779
+ item_path=("ID",),
780
+ coercion=IdentityCoercion.DECIMAL_STRING_INTEGER,
781
+ direction="ascending",
782
+ take="last",
783
+ ),
784
+ )
785
+ ```
786
+
787
+ Cursor values must be unique and strictly monotonic. If an endpoint exposes only a non-unique
788
+ boundary, use an application-owned direct-call workflow or supply a unique tie-breaker.
789
+
790
+ Some message endpoints move the boundary toward older rows but return each page oldest-first.
791
+ Declare that page order separately with `page_order="ascending"` beside `direction="descending"` and
792
+ `take="first"`: rows must be strictly ordered inside the page and every value must lie beyond the
793
+ previous boundary. `continuation=ResponseFlagTerminal(ResultSelector(("hasNextPage",)))` closes the
794
+ traversal on a `False` flag, even on a non-empty page, instead of requesting an empty confirmation
795
+ page; a missing or non-boolean flag fails closed. An explicit global ascending or descending
796
+ `ConsistencyPolicy` order contradicting a reversed page order is refused before any request.
797
+
798
+ The cursor and the row identity are independent. Without `identity` the cursor value is the identity.
799
+ An `identity` on another field, or on the cursor field with another coercion, only has to be unique:
800
+ the cursor alone carries the order, so the identity's values may come in any order unless the
801
+ consistency policy declares an order. An explicit `ConsistencyPolicy(order_semantics=...)` then
802
+ applies to that identity, independently of the cursor's direction, and a page breaking it fails.
803
+
804
+ ### Response-driven continuation
805
+
806
+ When the next request is fully described by the current page, `iter_list_continuation()` keeps the
807
+ request transaction, identity checks and terminal evidence in the client and asks a pure rule only
808
+ for the next control values. `ResponseCursorRule` carries a response cursor, whole and unchanged
809
+ (an object cursor keeps every field and its full precision), while a boolean response flag says more
810
+ pages exist:
811
+
812
+ <!-- tested: tests/continuation_test.py::test_a22_a_response_object_cursor_is_carried_whole_and_rule_ends_nonempty_page -->
813
+ ```python
814
+ from b24api import ParameterPath, ResultSelector, RouteKind
815
+ from b24api.contracts import ContinuationTraversal, ResponseCursorRule, ResponseFlagTerminal
816
+
817
+ cursor_control = ParameterPath(("cursor",))
818
+ stream = client.iter_list_continuation(
819
+ Request("example.event.list", replay_safety=ReplaySafety.SAFE, route=RouteKind.BARE),
820
+ traversal=ContinuationTraversal(
821
+ selector=ResultSelector(("items",)),
822
+ identity=identity,
823
+ controls=(cursor_control,),
824
+ rule=ResponseCursorRule(
825
+ cursor_selector=ResultSelector(("cursor",)),
826
+ parameter_path=cursor_control,
827
+ terminal=ResponseFlagTerminal(ResultSelector(("hasMore",))),
828
+ ),
829
+ ),
830
+ )
831
+ async with stream:
832
+ async for item in stream:
833
+ consume(item)
834
+ ```
835
+
836
+ A custom rule implements `evaluate(page)` and returns `ContinueWith(updates)` for exactly the
837
+ declared controls, or `EndOfSource()`. Rows of the page that ends the source are still delivered,
838
+ and the report closes with `rule_declared_end`. The client rejects updates to undeclared controls,
839
+ control vectors over 64 KiB and a repeated control vector with `ContinuationError`; such a failure
840
+ never reports the source as exhausted.
841
+
842
+ For newest-first lists that resume from an inclusive timestamp and may also return pinned rows,
843
+ `iter_list_window()` sends the oldest paging timestamp of each page unchanged, delivers rows
844
+ repeated by the overlap once and fails as non-progress, without another request, when the boundary
845
+ does not move. Its `page_stop` callback receives every validated page, empty closing page
846
+ included, and `PageBoundary.result` carries that page's server result for response-level fields. See
847
+ [Inclusive timestamp windows](https://github.com/shkarupa-alex/b24api/blob/master/docs/recipes.md#inclusive-timestamp-windows).
848
+
849
+ For multiple parent-bound cursor chains, `iter_cursors()` keeps cursor progress and correlation
850
+ isolated per binding while ready pages share the physical batch queue.
851
+
852
+ ![Cursor batching across independent chats](https://raw.githubusercontent.com/shkarupa-alex/b24api/master/cursor-batching.svg)
853
+
854
+ See [architecture](https://github.com/shkarupa-alex/b24api/blob/master/docs/architecture.md), [migration](https://github.com/shkarupa-alex/b24api/blob/master/docs/migration.md),
855
+ [performance](https://github.com/shkarupa-alex/b24api/blob/master/docs/performance.md), and [endpoint recipes](https://github.com/shkarupa-alex/b24api/blob/master/docs/recipes.md) for the complete
856
+ contracts and selection guidance.
857
+
858
+ ### One list method across many parent entities
859
+
860
+ `Binding` applies exact parameter updates to a base request and carries parent correlation. The
861
+ client remains unaware of entity types: a binding can represent a deal, lead, chat or any other
862
+ caller-defined parent.
863
+
864
+ ![Reference batching across leads and deals](https://raw.githubusercontent.com/shkarupa-alex/b24api/master/references-batching.svg)
865
+
866
+ <!-- tested: tests/client_v2_test.py::test_bound_references_apply_nested_updates_off_wire_and_emit_exact_completion -->
867
+ ```python
868
+ from b24api import RouteKind
869
+ from b24api import BatchDispatch, Binding, ParameterPath, ParameterUpdate, SequentialTraversal
870
+ from b24api.contracts import ReferenceComplete, ReferenceItem
871
+
872
+ bindings = (
873
+ Binding(
874
+ summary=f"owner {parent_id}",
875
+ updates=(ParameterUpdate(ParameterPath(("filter", "OWNER_ID")), parent_id),),
876
+ correlation=parent_id,
877
+ )
878
+ for parent_id in parent_ids
879
+ )
880
+
881
+ stream = client.iter_references(
882
+ Request("example.comment.list", replay_safety=ReplaySafety.SAFE, route=RouteKind.BARE),
883
+ bindings,
884
+ traversal=SequentialTraversal(selector=ResultSelector(("items",)), identity=identity),
885
+ dispatch=BatchDispatch(batch_size=25, concurrency=2),
886
+ )
887
+ async with stream:
888
+ async for event in stream:
889
+ if isinstance(event, ReferenceItem):
890
+ consume(event.correlation, event.item)
891
+ elif isinstance(event, ReferenceComplete):
892
+ record_completion(event.correlation, event.row_count)
893
+ ```
894
+
895
+ With `KeysetTraversal`, a binding may also set simple constant fields directly inside the keyset
896
+ filter, such as `filter[=ownerId]`, while each binding keeps its own cursor; see
897
+ [Keyset references with per-owner filters](https://github.com/shkarupa-alex/b24api/blob/master/docs/recipes.md#keyset-references-with-per-owner-filters).
898
+
899
+ For messages across chats, use the same `iter_references()` shape: each binding updates the chat
900
+ parameter and carries the chat correlation; choose `CursorTraversal` when the message endpoint is
901
+ cursor-based. Identity tracking and completion remain scoped to each binding, so equal child IDs
902
+ under different parents are not conflated.
903
+
904
+ <!-- tested: tests/client_v2_test.py::test_bound_references_apply_nested_updates_off_wire_and_emit_exact_completion -->
905
+ ```python
906
+ from b24api import RouteKind
907
+ from b24api import (
908
+ Binding,
909
+ CursorSpec,
910
+ CursorTraversal,
911
+ DirectDispatch,
912
+ IdentityCoercion,
913
+ ParameterPath,
914
+ ParameterUpdate,
915
+ ResultSelector,
916
+ )
917
+
918
+ chat_bindings = (
919
+ Binding(
920
+ summary=f"chat {chat_id}",
921
+ updates=(ParameterUpdate(ParameterPath(("DIALOG_ID",)), chat_id),),
922
+ correlation={"chat_id": chat_id},
923
+ )
924
+ for chat_id in chat_ids
925
+ )
926
+
927
+ messages = client.iter_references(
928
+ Request("example.message.list", replay_safety=ReplaySafety.SAFE, route=RouteKind.BARE),
929
+ chat_bindings,
930
+ traversal=CursorTraversal(
931
+ selector=ResultSelector(("items",)),
932
+ cursor=CursorSpec(
933
+ parameter_path=ParameterPath(("LAST_ID",)),
934
+ item_path=("ID",),
935
+ coercion=IdentityCoercion.DECIMAL_STRING_INTEGER,
936
+ direction="ascending",
937
+ take="last",
938
+ ),
939
+ ),
940
+ dispatch=DirectDispatch(concurrency=4),
941
+ )
942
+ ```
943
+
944
+ `iter_reference_outcomes()` additionally yields correlated `ReferenceFailure`,
945
+ `ReferenceNotExecuted` and `ReferenceOutcomeUnknown`. A malformed source object that is not a
946
+ `Binding` has no valid caller correlation, so it terminates the source with `InputSourceError`
947
+ rather than fabricating a reference outcome. Already accepted bindings retain their real outcomes.
948
+
949
+ With `DeliveryOrder.INPUT` the bindings are delivered in source order, and each still reads its pages
950
+ ahead while earlier bindings are being consumed, holding their rows within
951
+ `ExecutionPolicy.max_buffered_rows`, so physical batches stay well filled. They fill less than under
952
+ `READY`, whose consumer takes pages as they come: a sequential traversal of many bindings with several
953
+ pages each may send up to four or five times `READY`'s requests with the default pool, and up to twice
954
+ with a larger one; a counted traversal sends at most about twice as many, and often fewer. A binding
955
+ with a `page_stop` fetches its next page only once the consumer has received the page and the callback
956
+ has returned, so its pages travel in small batches.
957
+
958
+ ### Keyset references
959
+
960
+ `KeysetTraversal` bindings run sequentially by default (`SequentialKeysetExecution()`), unlike
961
+ `iter_list_keyset()`, whose default is automatic. Pass `AutoKeysetExecution`, `RangeKeysetExecution`
962
+ or `PartitionedKeysetExecution` as the traversal's `execution` to opt in. A binding with automatic,
963
+ range or partitioned execution runs its own planning barrier and selection; its waves and its final
964
+ confirmation pages travel through the shared batch queue beside other bindings' pages, so a cohort
965
+ of small parents shares physical batches instead of confirming each parent with a direct request.
966
+ Its `ReferenceComplete` carries the binding's `keyset_selection` and, when the fast path ran, its
967
+ `keyset_execution`. From its first request to its terminal event the binding holds a share of
968
+ `ExecutionPolicy.max_buffered_rows` and plans every wave within it; once a sequential or
969
+ boundary-only plan is chosen, the binding keeps only the rows that plan can still hold and returns
970
+ the rest to the bindings waiting for a share. Under `INPUT` delivery row capacity is granted in
971
+ binding order: while a binding waits for its share, no later binding is granted a share or reserves
972
+ an ordinary page. A binding whose batch was lost in transit ends with `ReferenceOutcomeUnknown`.
973
+ Requests, pages, attempts and elapsed time stay on the one operation budget. An automatic binding
974
+ whose planning floor exceeds the whole row budget waits to run alone with all of it (under `INPUT`
975
+ delivery, once it is the next binding to deliver); a binding that cannot obtain its floor while no
976
+ other binding can release rows fails with `BudgetExceededError`, and waiting for a share never
977
+ outlasts `max_elapsed`.
978
+
979
+ Fast and automatic keyset references need `BatchDispatch` with a `batch_size` of at least 2: every
980
+ wave travels in one shared physical batch, and the first holds both boundary probes. With a
981
+ `page_stop`, automatic execution runs sequentially and reports `PAGE_STOP`; an explicit fast mode with
982
+ a `page_stop`, and either fast mode without one under `DirectDispatch` or `batch_size=1`, is refused
983
+ before any request. A `KeysetSpec.boundary` remains unavailable in references.
984
+
985
+ ### Counted references
986
+
987
+ `CountedTraversal` bindings read their head page and every known tail offset through the shared
988
+ batch queue, so one physical batch can carry pages of several bindings and the HTTP count drops
989
+ accordingly; each subrequest still performs its own server-side COUNT. Pages are committed in
990
+ offset order per binding. Counted references need `BatchDispatch` and do not accept a `page_stop`.
991
+
992
+ ### Different methods in one operation
993
+
994
+ `iter_reference_sources()` accepts a lazy source of `ReferenceSource` values, each with its own
995
+ request template, traversal, binding and optional `page_stop`. All sources share one dispatcher,
996
+ row pool, `ExecutionPolicy` and terminal report, so compatible pages of different methods coalesce
997
+ into the same physical batch, and late sources start as capacity frees up rather than after earlier
998
+ sources finish. Identities and page state belong to each source: equal child IDs under different
999
+ sources are never conflated.
1000
+
1001
+ <!-- tested: tests/reference_sources_test.py::test_a28_different_templates_share_the_dispatcher_and_keep_separate_state -->
1002
+ ```python
1003
+ from b24api import Binding, ParameterPath, ParameterUpdate, RouteKind, SequentialTraversal
1004
+ from b24api.contracts import ReferenceItem, ReferenceSource
1005
+
1006
+
1007
+ def owned(method, owner_id):
1008
+ return ReferenceSource(
1009
+ Request(method, replay_safety=ReplaySafety.SAFE, route=RouteKind.BARE),
1010
+ SequentialTraversal(selector=ResultSelector(("items",)), identity=identity),
1011
+ Binding(
1012
+ summary=f"{method} for owner {owner_id}",
1013
+ updates=(ParameterUpdate(ParameterPath(("filter", "OWNER_ID")), owner_id),),
1014
+ correlation=(method, owner_id),
1015
+ ),
1016
+ )
1017
+
1018
+
1019
+ sources = (
1020
+ owned(method, owner_id)
1021
+ for owner_id in parent_ids
1022
+ for method in ("example.comment.list", "example.activity.list")
1023
+ )
1024
+ stream = client.iter_reference_sources(sources)
1025
+ async with stream:
1026
+ async for event in stream:
1027
+ if isinstance(event, ReferenceItem):
1028
+ consume(event.correlation, event.item)
1029
+ ```
1030
+
1031
+ `iter_reference_source_outcomes()` additionally yields correlated failures. A valid source the
1032
+ operation cannot run, such as a counted source under `DirectDispatch`, becomes a correlated
1033
+ `ReferenceNotExecuted` before any request while the other sources continue.
1034
+
1035
+ ## Streams, partial results and reports
1036
+
1037
+ Every multi-item operation returns an `OperationStream`. Prefer `async with`: a plain `break` does
1038
+ not close an arbitrary async iterator. After cleanup, `stream.report` permanently exposes one
1039
+ immutable `OperationReport`; before termination it is `None`.
1040
+
1041
+ <!-- tested: tests/client_v2_test.py::test_partial_helper_closes_without_claiming_completion -->
1042
+ ```python
1043
+ first = await client.iter_list(request).first()
1044
+ page = await client.iter_list(request).collect(limit=100)
1045
+
1046
+ assert first.report.partial
1047
+ assert page.report.partial
1048
+ ```
1049
+
1050
+ Helpers do not pull an extra row just to prove exhaustion. Reaching a requested limit is therefore
1051
+ `EARLY_CLOSED`, never a false `COMPLETED`. When the stream fails, the error a helper raises carries the
1052
+ items it read before the failure as `partial_values`. A client serves the event loop it was first used
1053
+ in. A call, a stream's first read or the client's close from another loop raises `RuntimeError` before it
1054
+ reads a source or sends a request, and the client stays open: create one client per event loop, and close it there. A started stream stays the
1055
+ client's until it ends, so a stream the application drops is still closed with its client. Cancellation and cleanup preserve the primary exception
1056
+ and publish the same final report where the Python exception type permits it.
1057
+
1058
+ ## Resource boundaries
1059
+
1060
+ `ExecutionPolicy` bounds requests, pages, elapsed time, attempts, decompressed response bytes,
1061
+ buffered commands and rows, retained unordered identity keys, direct concurrency and active
1062
+ references. The default response ceiling is 16 MiB and is enforced while streaming, before JSON
1063
+ decoding.
1064
+
1065
+ A command's decoded rows are known only once it has run, so `max_buffered_rows` bounds what an operation
1066
+ holds rather than what it sends. `batch()` and `batch_outcomes()` share the budget among a window's
1067
+ results in input order, one row per outcome and a success's other rows while they fit; `fan_out()` and
1068
+ `fan_out_outcomes()` reserve each command an equal share among the results their dispatch may have in
1069
+ flight at once, under a `BatchDispatch` never below a 50-row page while the budget holds one per
1070
+ command of a batch (50 rows under the default `BatchDispatch`, 250 under the default `DirectDispatch`,
1071
+ see the table above). A longer result grows into free rows. While it waits for them, the rows that come
1072
+ back are its first: no other command reserves rows (under `INPUT` delivery, none but the frontier's), and
1073
+ the commands reserved before it are still sent. It waits while the rows it lacks may all come back without
1074
+ it: a command already reserved lands, or the consumer takes rows (its own earlier pages and, under `READY`
1075
+ delivery, any). Under `INPUT` delivery a result behind the frontier
1076
+ waits for the frontier to reach it: the rows the results before it hold come back by then, those waiting to
1077
+ grow as well, while rows read ahead for the results behind it come back only after it. While a result waits its decoded rows are held beside the budget, not in it:
1078
+ at most one result per command in flight, each no longer than the budget. A result longer than the whole
1079
+ budget, or one whose missing rows are held by results waiting to grow as well or, under `INPUT`, read ahead
1080
+ behind it, does not fit and is dropped at once: its command ends as a `CommandFailure` with `ResultTooLargeError`, a `BudgetExceededError` that
1081
+ says the command ran and was answered, so it is never replayed, and every other command keeps its own
1082
+ outcome. A result still waiting when `max_elapsed` runs out is dropped the same way, its command answered, and
1083
+ the operation ends with its time budget. A page's wait for row capacity before its send, while the
1084
+ consumer has not yet taken the rows other pages hold, is bounded by `max_elapsed`: when it runs out, the
1085
+ binding or `fan_out()` command fails with its waiting page unsent, with `BudgetExceededError` ("row
1086
+ buffer wait exceeded operation time budget"). A binding's wait for the consumer to take a page already
1087
+ handed to it (under `READY` delivery, or with a `page_stop`) is not bounded: it lasts as long as the
1088
+ consumer takes.
1089
+
1090
+ `max_elapsed` is checked at the operation's scheduling points: when a request, a page or a source item
1091
+ is admitted, while a send waits for its permit (a pause included), while a page waits for row capacity
1092
+ and while a source, synchronous or asynchronous, is pulled. A send in flight is cut at what is left of
1093
+ the operation or of its retry window, whichever is shorter. It does not bound the time the application
1094
+ spends while it holds control: in a `page_stop` callback, or as a consumer that is slow between pulls of
1095
+ the stream. Nothing interrupts the application when the budget runs out meanwhile; the next scheduling
1096
+ point ends the operation, even when all that is left is to read the end of the source. Once that end
1097
+ was read, a deadline that passes while the application holds control ends nothing. A deadline that ends the
1098
+ operation leaves the report `incomplete`, with `BudgetExceededError` as its terminal reason and a `budget_exhausted` violation.
1099
+ The operation's page budget (`max_pages`) ends it the same way once it refuses a page, as `max_requests`
1100
+ does once it refuses a send: the source is not read further.
1101
+ The stream raises a plain `BudgetExceededError`, except that a fail-fast stream whose stop failed a
1102
+ command or a binding raises its wrapper (`BatchFailed` or `ReferenceFailed`, whose report carries that
1103
+ reason). A stop at a source pull or at the end-of-source check fails none by itself, but `batch()` and
1104
+ `batch_outcomes()` still send the commands they read into the window before it, which the budget refuses
1105
+ in turn (each a `CommandFailure` with `BudgetExceededError`), so `batch()` then raises `BatchFailed`. So
1106
+ for a fail-fast stream it depends on where the budget stopped the stream, not on the operation (a
1107
+ tolerant stream raises the plain error): handle both, or read the report. A refusal of one request while
1108
+ time is left ends that request alone: a retry whose wait is longer than the time left, one whose own
1109
+ retry window closed first, a known pause that outlasts what it may wait, or a spent
1110
+ `max_attempts_per_request`. It ends with that refusal, `BudgetExceededError`, caused by the failure of
1111
+ the send it followed, except when that failure is the server's load refusal and its hold alone outlasts
1112
+ the window: then it ends with that load refusal itself (see the load limits above). Either way, a
1113
+ request or command that send proved not run fails with it, and one that send may have run is unknown
1114
+ (`AmbiguousExecutionError`, named after that send, with the refusal as its cause; a lone call raises the
1115
+ refusal). Nothing is recorded as the operation's refusal, and a tolerant stream
1116
+ goes on: with no other failure it ends `completed_with_failures`, with no `budget_exhausted`. Cleanup
1117
+ never ends a stream with the budget. A send cut in flight is another case: its command may have run, so
1118
+ it is unknown (`AmbiguousExecutionError`), and a fail-fast stream may end on that ambiguity instead.
1119
+
1120
+ Cleanup runs once the operation has ended, often because `max_elapsed` ran out, so it is not cut at
1121
+ the budget: each of its steps (closing the source, stopping the operation's own tasks) waits for what
1122
+ is left of `max_elapsed`, but at least 0.1 s. A source whose close ends at once (a list, a generator,
1123
+ an async generator whose `aclose()` returns) closes within that grace, and the report records the
1124
+ budget's end alone. A close that blocks longer goes on in the background: the report adds a
1125
+ `cleanup_failure` violation, and the stream still raises the error that ended it. When nothing else
1126
+ ended it, the close raises `b24api.errors.CleanupOverrunError`, a `BudgetExceededError` that refused
1127
+ no work, and the report is the one a close that raised any other error gets, with no
1128
+ `budget_exhausted`: after `break` or an early `aclose()`, `early_closed` with the terminal reason
1129
+ "stream cleanup failed"; on a stream read to its end, `failed`. Either way its `cleanup_failure`
1130
+ violation names `CleanupOverrunError`. A cancelled read, close or `async with` exit (an exit whose body a
1131
+ cancellation ended, Ctrl-C included, counts as cancelled) waits for cleanup only one second, not for
1132
+ what is left of `max_elapsed`, and one cancellation is deferred for one second in all, however many exits
1133
+ it unwinds (the stream's, then the client's), and a second cancellation
1134
+ during that second ends with it. An exit that must raise another exception in its place (the body's own, or
1135
+ a failed read or close) replays the cancellation at the task's next `await`: the replay is a new delivery,
1136
+ and each exit it then reaches waits at most one second more. Cleanup still running then
1137
+ goes on in the background, and the close raises the cancellation, which caused that overrun, with the
1138
+ overrun recorded behind it ("stream cleanup also failed (CleanupOverrunError)"); `client.aclose()` does the
1139
+ same, and so do `collect()` and `first()`, which close as an `async with` exit does. A close nobody cancelled
1140
+ waits for its cleanup, so `finally: await stream.aclose()` after a cancelled read waits for all of it: close
1141
+ with `async with stream` to keep the grace. A cancellation outranks the budget's error or a failure only when it came first: a consumer
1142
+ cancelled before the budget or a failure ended the stream receives its `CancelledError`, with a
1143
+ `cancelled` report, even when the close then overruns.
1144
+ One cancelled after them, while the cleanup waits, receives the budget's error (or the failure), with
1145
+ an `incomplete` (or `failed`) report, and the cancellation is delivered at its next `await`. A stream
1146
+ closed before its first pull closes its source the same way. A synchronous source is pulled and closed in worker threads, in
1147
+ one `contextvars.Context`; a pull the deadline cut while it still runs is waited for before the close
1148
+ runs in that context, so a pull that outlasts the grace leaves its close to the background the same way.
1149
+ An asynchronous source also runs every pull and its close in one context of its own, copied when the call
1150
+ that creates the stream is made and driven by the task that reads it, so a context variable a generator sets
1151
+ before a `yield` is still set when it resumes. A context variable the caller sets after that call (a tracing
1152
+ span around the `async for` loop, say) is not seen by the source: set it before creating the stream.
1153
+
1154
+ Every `Exception` a source raises, from a pull or from its close, is its failure: the stream raises
1155
+ `InputSourceError` (`batch()` and `fan_out()`: `BatchFailed`, whose `__cause__` is that
1156
+ `InputSourceError`) with the source's exception as its `__cause__`, whether the source is synchronous
1157
+ or asynchronous and even when that exception is a library error of its own. An item that is not what
1158
+ the family reads fails the source too, with a `TypeError` as that cause. Every family reports a
1159
+ failed close the same way. When nothing failed before it, the close is what failed: the terminal
1160
+ reason is "stream cleanup failed" and the report carries one `cleanup_failure` violation, "stream
1161
+ cleanup failed (X)", where X is `InputSourceError` or `CleanupOverrunError`. Behind an earlier failure,
1162
+ that failure stays the terminal reason and the close adds "stream cleanup also failed (X)". So does a
1163
+ close that fails behind the reader's cancellation: the reader gets its `CancelledError`, the stream is
1164
+ `cancelled` with the terminal reason "iteration cancelled", whether the cancellation landed while a
1165
+ read waited or between reads. That `CancelledError` carries the close's failure as its `__cause__`
1166
+ (`InputSourceError`, whose own `__cause__` is your source's exception) and the report as `.report`. An
1167
+ interrupt is the exception: a `KeyboardInterrupt` or `SystemExit` raised anywhere in the operation (by
1168
+ a close, a pull, or your transport inside one of the library's own tasks) is never behind anything. It
1169
+ is what the stream raises, whatever ended the stream before it (its end, a failure, the reader's
1170
+ cancellation, a timeout, a close from another task), and the report has one shape for it: `failed`
1171
+ with the terminal reason "operation interrupted", every violation recorded before it kept (an earlier
1172
+ failure's first), and one `interrupted` violation last, "operation interrupted (X)", where X is
1173
+ `KeyboardInterrupt` or `SystemExit`. The raised interrupt carries that report as `.report`, as the
1174
+ `CancelledError` does. A close that fails after an interrupt ended the stream is "stream cleanup also
1175
+ failed (X)", as behind any other end that came first.
1176
+
1177
+ A failure is an `Exception`. Any other `BaseException` that is neither an interrupt nor a cancellation is
1178
+ no failure: the library never catches it as one, never wraps it, never makes it an outcome and never ranks
1179
+ it; it propagates as Python propagates it. Raised by your source's close it replaces whatever ended the
1180
+ stream, as an exception raised in a `finally` does, and under `async with` it replaces your own exception,
1181
+ which becomes its `__context__`. The library guarantees only this, in every family: it reaches you as it
1182
+ is, whether your transport raised it in your read or between your reads (in the stream's background work),
1183
+ or your source's pull or close did; the source is closed once; nothing hangs waiting for an end it took
1184
+ the place of; and it is never lost silently: when no read got it (you closed the stream between reads, or
1185
+ the close cancelled the send or the pull that raised it), the close raises it, once. A read the close ends
1186
+ in another task raises `b24api.errors.StreamClosedError`. One delivered to a read or a close never reaches the event loop's
1187
+ exception handler and is never left in a task whose exception nobody retrieves; one the library could no
1188
+ longer deliver to a read or a close (raised by work that outlived the stream's cleanup window, a second
1189
+ one behind what the close already raises, or one a close or a read could not raise because its coroutine was
1190
+ closed while it ran the stream's end) is reported to the loop's exception handler, once, with the
1191
+ stream's report as `report`. So is one of a stream nothing ever ends (left open when `asyncio.run` shuts
1192
+ down, or dropped): as asyncio reports a task's exception nobody retrieved, it is reported once the
1193
+ stream's work is collected, on a closed loop too. What the report says about it, and how it ranks behind
1194
+ other ends, is not promised.
1195
+
1196
+ An interrupt raised while no read is waiting (by a send the stream runs between your reads, while you work
1197
+ on an item) does not wait for your next read: it leaves the event loop at once, out of `asyncio.run`, as
1198
+ asyncio raises any task's, and the operation's end follows: its work cancelled, its source closed and its
1199
+ report published, attached to the interrupt as `.report`. A read or close you start before that end is
1200
+ over runs it or waits for it, then finds the stream ended (a read raises `StopAsyncIteration`, a close
1201
+ returns); neither raises the interrupt, which the loop has. Under `asyncio.run` the interrupt stops the
1202
+ loop before the end begins, and the end is the close that `asyncio.run`'s shutdown runs as it cancels your
1203
+ tasks: the exit of an `async with stream` around your reads, or of the client's `async with`. A read or
1204
+ close cancelled while it runs the end still lets the end publish, with "stream cleanup also failed
1205
+ (CancelledError)" before the `interrupted` violation. The stream gets no end, so its source stays open and
1206
+ there is no report, only when nothing closes it: you never close the stream nor its client, or
1207
+ `asyncio.run` was already shutting down (your main coroutine had returned) when the interrupt was raised.
1208
+ The interrupt leaves `asyncio.run` in every case. An
1209
+ interrupt raised after the operation ended (by a close or a send still running past the cleanup window) is
1210
+ never dropped either: it leaves the event loop the same way, unless the stream already raised one. So does
1211
+ one that ends a close or a read whose coroutine was closed while it ran the stream's end, unless a read that
1212
+ close ended raises it. A stream
1213
+ raises one interrupt at most; a second one is reported to the loop's exception handler, like any escape the
1214
+ stream could no longer deliver, so it never stops the loop again while you unwind from the first. A library
1215
+ error carries this in its report (`error.report`), not as a note; your own exception raised inside
1216
+ `async with stream` stays what is raised and carries one note, the report's `cleanup_failure` violation
1217
+ word for word. Once the
1218
+ stream ends, its source is closed, even when the stream's own tasks outlast the cleanup window. A close from
1219
+ another task while a read is in flight is an early close: the read it ends raises `StreamClosedError`,
1220
+ which carries the report as `.report`, or the close's failure when the close failed (an interrupt
1221
+ included), which the close raises too. A reader whose own task is cancelled gets its `CancelledError`,
1222
+ unless an interrupt ends the stream within the one second its read waits for the close: then it gets the
1223
+ interrupt, which the close raises too.
1224
+ A close from another task while a failed read cleans up returns quietly; the read raises its failure. A
1225
+ close ends the stream before failures no read reached, a source's failure in the read-ahead included:
1226
+ it returns, and the report is `early_closed`. A stream its reader's cancellation ended reports
1227
+ `cancelled` with the terminal reason "iteration cancelled", whatever its source had reached.
1228
+ `report.emitted` counts the items the reader got.
1229
+
1230
+ Sequential, counted, and multi-reference exact traversal retain at most `max_identity_keys`
1231
+ observed identities per operation in memory (100,000 by default). All active reference bindings
1232
+ share that ceiling. A page that would exceed it is rejected atomically with typed budget evidence.
1233
+ Set a larger finite ceiling when the expected aggregate cardinality is known, or pass
1234
+ `identity_store=` to `iter_list`/`iter_list_counted` so a caller-owned `IdentityStore` (for example a
1235
+ SQLite table keyed by `identity_store_key(...)`) proves uniqueness while in-process identity memory
1236
+ stays bounded by one page; the client never closes that store. Repeated-page detection still keeps
1237
+ one short fingerprint per page, so raise `max_pages` deliberately for very long traversals.
1238
+ Strict keyset and cursor traversal retain only monotonic progression state when sufficient.
1239
+
1240
+ ## CLI
1241
+
1242
+ The wheel installs `b24api`. Stdout contains only result data; list rows are JSONL. Reports and safe
1243
+ errors go to stderr. Credentials come only from `Settings` and cannot be passed as CLI arguments. The
1244
+ CLI reads the environment and then a `.env` file in its working directory, if one exists; the
1245
+ environment wins.
1246
+
1247
+ <!-- tested-console: tests/cli_test.py::test_call_routes_replay_safety_and_keeps_success_data_on_stdout -->
1248
+ ```console
1249
+ b24api call profile --route bare
1250
+ b24api call example.item.get --route bare --params '{"id":7}' --raw --replay-safety safe
1251
+ b24api list example.item.list --route bare --params @params.json
1252
+ b24api list example.item.list --route bare --strategy counted --contract @counted-contract.json
1253
+ ```
1254
+
1255
+ The `--raw` CLI option selects the response envelope; it does not alter the Python API. Advanced
1256
+ list strategies use closed JSON `version: 1` contracts. The entire contract is validated before
1257
+ client construction. `--params -` and `--contract -` read stdin (not both in one run); input that is
1258
+ not UTF-8 or not valid JSON is a usage error. Output to a terminal or pipe that cannot write Unicode
1259
+ gets JSON with `\u` escapes instead of failing. Run `b24api --help` and `b24api list --help` for the compact option surface.
1260
+
1261
+ Exit codes are `0` success, `2` usage/contract error, `3` unavailable configuration, `4`
1262
+ remote/protocol/correctness/incomplete failure, `5` broken output consumer, `6` keyset bounds
1263
+ unsupported and `7` keyset verification inconclusive (both from `verify-keyset`), `130`
1264
+ cancellation (Ctrl-C), and `128 + signal` for `SIGTERM` (`143`) or `SIGHUP` (`129`). A signal ends a
1265
+ `list` as Ctrl-C does: the stream closes and its report is written to stderr.
1266
+ `5` takes priority whenever a write to stdout or stderr finds its reader gone, including a run whose
1267
+ data was delivered but whose diagnostic hit a closed stderr, and a run started with stdout or stderr
1268
+ already closed. Any other failed write, such as to a full
1269
+ disk, exits `4`.
1270
+
1271
+ ## Testing without a portal
1272
+
1273
+ `b24api.testing` holds two offline tools. `ScriptedTransport` plays a fixed table of exchanges
1274
+ (`ScriptedExchange.json()`, `.batch()` for a classic batch, `.v3_batch()` for a REST 3.0 envelope) to a
1275
+ client built on it, with no socket and no credential. A call matches an exchange only when it sends what
1276
+ the exchange names: the same method, route, replay safety, body encoding (JSON, form or query string), scoped
1277
+ headers, raw content and parameters. Parameters compare as JSON values, so the order of mapping keys does not matter for a
1278
+ match; `calls` keeps each request with its keys in the order they were sent, for a test that checks the
1279
+ sort priority of `order`. A call nothing matches fails its send, as a transport failure, and is kept in
1280
+ `unexpected`; `assert_exhausted()` reports such calls and exchanges never used. `.batch()` refuses a
1281
+ command a classic batch would refuse (see [Logical batch and correlation](#logical-batch-and-correlation)).
1282
+ `run_transport_conformance()` checks your own transport against the cases the client relies on.
1283
+
1284
+ ## Correctness boundaries
1285
+
1286
+ The client fails closed on contradictory pagination, missing counted ranges, duplicate identities,
1287
+ unsafe ambiguous replay, oversized responses and incomplete cleanup. It can prove only facts visible
1288
+ through the transport contract: continuation, totals, identity, order, budgets and lifecycle.
1289
+
1290
+ It cannot generically prove that Bitrix honored the business meaning of a filter, choose an
1291
+ application's composite storage key or reconcile an ambiguous write. Applications must validate
1292
+ expected business sets and verify writes where needed.
1293
+
1294
+ ## Performance and profiling
1295
+
1296
+ The current deterministic profile covers request counts, wall/CPU time, time to first row,
1297
+ high-water counters, retained resources and optional Memray allocations:
1298
+
1299
+ ```console
1300
+ uv run python tools/b24api_evidence/profile_runtime.py --capability-suite
1301
+ uv run python tools/b24api_evidence/profile_runtime.py --samples 7 --warmups 2
1302
+ uv run --with memray python tools/b24api_evidence/profile_runtime.py \
1303
+ --case dense-10k --plan counted_batch --samples 7 --warmups 2 \
1304
+ --memray-output /tmp/b24api.bin
1305
+ uv run --with memray memray stats /tmp/b24api.bin
1306
+ ```
1307
+
1308
+ These deterministic fixtures characterize local resources and network shape; they are not live
1309
+ portal latency admission. See [docs/performance.md](https://github.com/shkarupa-alex/b24api/blob/master/docs/performance.md) for current measurements
1310
+ and [docs/architecture.md](https://github.com/shkarupa-alex/b24api/blob/master/docs/architecture.md) for guarantees and ownership boundaries.
1311
+
1312
+ Projects moving from an earlier API surface can use [docs/migration.md](https://github.com/shkarupa-alex/b24api/blob/master/docs/migration.md).
1313
+
1314
+ ## Verification
1315
+
1316
+ ```console
1317
+ uv sync --frozen
1318
+ make qc
1319
+ git diff --check
1320
+ ```
1321
+
1322
+ `make qc` runs the lint, type and default test checks that CI blocks on. The tests run in parallel, one
1323
+ worker process per CPU: `make qc PYTEST_WORKERS=2` bounds them, `PYTEST_WORKERS=0` runs them in one
1324
+ process. It leaves out the internal benches (the pytest marker `slow`: the evidence harness contracts and
1325
+ the 50k/100k-scale runs, which take several minutes). `make bench` runs them, in one process, and so does
1326
+ the blocking CI job `slow`.
1327
+
1328
+ The wheel regression installs into an isolated environment, executes the `b24api` entry point and
1329
+ checks that tests, live/evidence tooling and credentials are excluded.