sayfirst-boundary 0.3.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.
@@ -0,0 +1,10 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ __pycache__/
3
+ *.py[cod]
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ .venv/
7
+ dist/
8
+
9
+ # The working report of a change, kept beside the tree and never published.
10
+ .sdd-quiet-gaps-report.md
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,12 @@
1
+ sayfirst control plane
2
+ Copyright 2026 Frédéric Aime
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use these files except in compliance with the License. A copy of the
6
+ License is in the LICENSE file at the root of this repository.
7
+
8
+ Distributions that incorporate this software must reproduce the attribution
9
+ notices this file carries (Apache License 2.0, section 4(d)).
10
+
11
+ The Apache License grants no rights in the names and marks of this project; see
12
+ TRADEMARKS.md.
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.5
2
+ Name: sayfirst-boundary
3
+ Version: 0.3.0
4
+ Summary: The in-process boundary that holds a grant and asks before an effect
5
+ Project-URL: Repository, https://github.com/fredaime/sayfirst-control-plane
6
+ Project-URL: Documentation, https://github.com/fredaime/sayfirst-control-plane/blob/main/packages/boundary/README.md
7
+ Project-URL: Changelog, https://github.com/fredaime/sayfirst-control-plane/blob/main/CHANGELOG.md
8
+ Author-email: fredaime <frederic.aime@gmail.com>
9
+ License-Expression: Apache-2.0
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Requires-Python: <3.15,>=3.12
16
+ Requires-Dist: sayfirst-contract==0.3.0
17
+ Description-Content-Type: text/markdown
18
+
19
+ <!-- SPDX-License-Identifier: Apache-2.0 -->
20
+ # sayfirst-boundary
21
+
22
+ The in-process boundary. A governed program opens `Boundary.request(...)` around
23
+ an effect; the decision lands before the body runs, or the body does not run.
24
+
25
+ This distribution holds no policy and decides nothing. It asks the control plane
26
+ over a socket whose peer it verified, caches an `allow` as a grant for exactly
27
+ the question it answers, and stops honouring that grant the moment any of four
28
+ things happens: the connection carrying it ends, its lifetime runs out, the
29
+ policy version it was issued under changes, or the control plane goes silent for
30
+ a lifetime. Built with `hold_grants=False`, it holds nothing and asks for every
31
+ act — what a verifier needs, whose proof is one recorded decision for each
32
+ effect, while a grant hit records none.
33
+
34
+ It publishes no exit codes. Outcomes leave as exceptions, and a caller that runs
35
+ a process decides what to exit with.
@@ -0,0 +1,17 @@
1
+ <!-- SPDX-License-Identifier: Apache-2.0 -->
2
+ # sayfirst-boundary
3
+
4
+ The in-process boundary. A governed program opens `Boundary.request(...)` around
5
+ an effect; the decision lands before the body runs, or the body does not run.
6
+
7
+ This distribution holds no policy and decides nothing. It asks the control plane
8
+ over a socket whose peer it verified, caches an `allow` as a grant for exactly
9
+ the question it answers, and stops honouring that grant the moment any of four
10
+ things happens: the connection carrying it ends, its lifetime runs out, the
11
+ policy version it was issued under changes, or the control plane goes silent for
12
+ a lifetime. Built with `hold_grants=False`, it holds nothing and asks for every
13
+ act — what a verifier needs, whose proof is one recorded decision for each
14
+ effect, while a grant hit records none.
15
+
16
+ It publishes no exit codes. Outcomes leave as exceptions, and a caller that runs
17
+ a process decides what to exit with.
@@ -0,0 +1,32 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Reproduce repository notices in the wheel."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from hatchling.builders.hooks.plugin.interface import BuildHookInterface
10
+
11
+
12
+ class CustomBuildHook(BuildHookInterface):
13
+ """Include the repository licence and notice as wheel metadata."""
14
+
15
+ def initialize(self, version: str, build_data: dict[str, Any]) -> None:
16
+ # In the workspace the notices live at the repository root and have to
17
+ # be carried in by hand. In an unpacked source distribution they
18
+ # travel beside the package, where the backend's own licence globs
19
+ # already find them, so carrying them again would add the same file
20
+ # twice.
21
+ root = Path(self.root)
22
+ if not (root / "LICENSE").is_file():
23
+ metadata_directory = (
24
+ f"{self.metadata.core.name.replace('-', '_')}-{self.metadata.version}.dist-info"
25
+ )
26
+ repository = root.parents[1]
27
+ build_data["force_include"].update(
28
+ {
29
+ str(repository / "LICENSE"): f"{metadata_directory}/licenses/LICENSE",
30
+ str(repository / "NOTICE"): f"{metadata_directory}/licenses/NOTICE",
31
+ }
32
+ )
@@ -0,0 +1,46 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ [project]
3
+ name = "sayfirst-boundary"
4
+ version = "0.3.0"
5
+ description = "The in-process boundary that holds a grant and asks before an effect"
6
+ readme = "README.md"
7
+ requires-python = ">=3.12,<3.15"
8
+ dependencies = ["sayfirst-contract==0.3.0"]
9
+ license = "Apache-2.0"
10
+
11
+ authors = [{ name = "fredaime", email = "frederic.aime@gmail.com" }]
12
+ classifiers = [
13
+ "Development Status :: 4 - Beta",
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3.12",
16
+ "Programming Language :: Python :: 3.13",
17
+ "Programming Language :: Python :: 3.14",
18
+ ]
19
+
20
+ # The public repository this distribution sends a reader to. It was created
21
+ # fresh, as article 0 asks, in the act that published it on 2026-09-17, under
22
+ # the name the operator chose. `tests/test_pointers_survive_publication.py`
23
+ # holds these URLs, so a rename lands in every project file and in the guard
24
+ # together or not at all. No licence classifier: the licence is declared as an
25
+ # expression above, and an index refuses a distribution that carries both.
26
+ [project.urls]
27
+ Repository = "https://github.com/fredaime/sayfirst-control-plane"
28
+ Documentation = "https://github.com/fredaime/sayfirst-control-plane/blob/main/packages/boundary/README.md"
29
+ Changelog = "https://github.com/fredaime/sayfirst-control-plane/blob/main/CHANGELOG.md"
30
+
31
+ [build-system]
32
+ requires = ["hatchling==1.32.0"]
33
+ build-backend = "hatchling.build"
34
+
35
+ [tool.uv.sources]
36
+ sayfirst-contract = { workspace = true }
37
+
38
+ [tool.hatch.build.targets.wheel]
39
+ packages = ["src/sayfirst_boundary"]
40
+
41
+ [tool.hatch.build.targets.sdist.force-include]
42
+ "../../LICENSE" = "LICENSE"
43
+ "../../NOTICE" = "NOTICE"
44
+
45
+ [tool.hatch.build.targets.wheel.hooks.custom]
46
+ path = "hatch_build.py"
@@ -0,0 +1,20 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """The in-process boundary: ask before the effect, or do not act."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from .boundary import Boundary, GrantHandle
7
+ from .errors import AskRefused, BoundaryError, CouldNotAsk, Denied, Suspended
8
+ from .evidence import OutcomeLog, Record
9
+
10
+ __all__ = [
11
+ "AskRefused",
12
+ "Boundary",
13
+ "BoundaryError",
14
+ "CouldNotAsk",
15
+ "Denied",
16
+ "GrantHandle",
17
+ "OutcomeLog",
18
+ "Record",
19
+ "Suspended",
20
+ ]
@@ -0,0 +1,195 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """The one shape a governed program uses, and the only way into the body.
3
+
4
+ with boundary.request(capability, arguments) as grant:
5
+ result = do_the_effect(**arguments)
6
+ grant.record_outcome(digest(result))
7
+
8
+ There is no path into that body that skips the ask, which is the whole design:
9
+ the decision is not a check the body could forget to make, it is the thing that
10
+ opens the body at all. A hit on a held grant does not ask; a miss asks; anything
11
+ other than an allow raises before the body, and `could not ask` raises too,
12
+ because the absence of a refusal is not permission (doctrine D4).
13
+
14
+ Only an allow is cached, and only an allow that arrived with a grant. The
15
+ control plane mints a grant for exactly one question, and an allow served
16
+ without one is an allow that is not to be reused.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from collections.abc import Callable, Iterator, Mapping
22
+ from contextlib import contextmanager
23
+ from dataclasses import dataclass
24
+ from datetime import UTC, datetime
25
+ from typing import Protocol
26
+
27
+ from sayfirst_contract.client import Answered, Refused
28
+ from sayfirst_contract.client import CouldNotAsk as CouldNotAskResult
29
+ from sayfirst_contract.decisions import Decision, DecisionAsk, Outcome
30
+
31
+ from .cache import GrantStore
32
+ from .digest import arguments_digest
33
+ from .errors import AskRefused, CouldNotAsk, Denied, Suspended
34
+ from .evidence import OutcomeLog
35
+ from .signals import SignalReader
36
+
37
+
38
+ class _Client(Protocol):
39
+ def hold_decision(self, ask: DecisionAsk) -> tuple[object, object]: ...
40
+
41
+
42
+ @dataclass
43
+ class GrantHandle:
44
+ """What the body may say about what it did."""
45
+
46
+ decision_ref: str
47
+ capability: str
48
+ _log: OutcomeLog
49
+ recorded: bool = False
50
+
51
+ def record_outcome(self, digest: str) -> None:
52
+ self._log.record(
53
+ capability=self.capability,
54
+ decision_ref=self.decision_ref,
55
+ outcome_digest=digest,
56
+ )
57
+ self.recorded = True
58
+
59
+
60
+ class Boundary:
61
+ """Ask the control plane before an effect, and hold what it grants."""
62
+
63
+ def __init__(
64
+ self,
65
+ *,
66
+ client: _Client,
67
+ principal_reference: str,
68
+ correlation: str | None = None,
69
+ log: OutcomeLog | None = None,
70
+ clock: Callable[[], datetime] | None = None,
71
+ hold_grants: bool = True,
72
+ ) -> None:
73
+ self._client = client
74
+ self._principal = principal_reference
75
+ # Article 10's cache: an allow minted a grant, and an identical later act
76
+ # is answered by it without a round trip. A boundary that holds none asks
77
+ # for every act instead — what a verifier needs, since its proof is one
78
+ # recorded decision for each effect it saw and a grant hit records
79
+ # nothing. Asking more often is always allowed; never asking less is the
80
+ # rule the cache itself keeps.
81
+ self._hold_grants = hold_grants
82
+ # One boundary is one execution, so a correlation set here is stamped on
83
+ # every ask this boundary puts, and the plane records it on the effect
84
+ # (`correlation_source: boundary_supplied`). It is how a later reader —
85
+ # the verifier above all — tells THIS run's records from another
86
+ # execution's of the same principal, without trusting the boundary for a
87
+ # connection identity. It is not part of a grant's key (a grant matches
88
+ # on scope, principal, capability and digest), so a constant correlation
89
+ # across a run leaves the cache exactly as it was.
90
+ self._correlation = correlation
91
+ self._clock = clock or (lambda: datetime.now(UTC))
92
+ self._store = GrantStore()
93
+ self._log = log or OutcomeLog(capacity=1024, sink=lambda record: None, clock=self._clock)
94
+
95
+ @contextmanager
96
+ def request(
97
+ self,
98
+ capability: str,
99
+ arguments: Mapping[str, object],
100
+ *,
101
+ scope: str = "local",
102
+ ) -> Iterator[GrantHandle]:
103
+ try:
104
+ digest = arguments_digest(arguments)
105
+ except (TypeError, ValueError, RecursionError) as error:
106
+ # UnicodeEncodeError is a ValueError: a path that is not UTF-8, which
107
+ # `os.fsdecode` leaves as a lone surrogate. The digest is how the
108
+ # question is put, so arguments it cannot describe are a question
109
+ # that was not asked — one of this boundary's four outcomes, and the
110
+ # body does not run.
111
+ raise CouldNotAsk(
112
+ detail=f"the effect's arguments cannot be described to the control plane: {error}",
113
+ retryable=False,
114
+ ) from error
115
+ ask = DecisionAsk(
116
+ capability=capability,
117
+ scope=scope,
118
+ arguments_digest=digest,
119
+ correlation=self._correlation,
120
+ )
121
+ now = self._clock()
122
+ held = self._store.take(ask, self._principal, now=now) if self._hold_grants else None
123
+ decision_ref = held.held().grant.decision_ref if held is not None else self._ask(ask)
124
+ handle = GrantHandle(decision_ref=decision_ref, capability=capability, _log=self._log)
125
+ try:
126
+ yield handle
127
+ finally:
128
+ if not handle.recorded:
129
+ self._log.record(
130
+ capability=capability,
131
+ decision_ref=decision_ref,
132
+ outcome_digest=None,
133
+ )
134
+
135
+ def _ask(self, ask: DecisionAsk) -> str:
136
+ """Put the question, raise anything that is not an allow, cache what is."""
137
+ result, stream = self._client.hold_decision(ask)
138
+ if isinstance(result, Refused):
139
+ raise AskRefused(
140
+ problem_code=str(result.problem.code),
141
+ detail=str(result.problem.message),
142
+ )
143
+ if isinstance(result, CouldNotAskResult):
144
+ # The contract already says whether asking again could help, so the
145
+ # boundary reports that rather than deciding for itself.
146
+ raise CouldNotAsk(
147
+ detail=str(result.problem.message),
148
+ retryable=result.problem.retryable,
149
+ )
150
+ if not isinstance(result, Answered):
151
+ raise CouldNotAsk(detail="the answer could not be read", retryable=False)
152
+ decision: Decision = result.value
153
+ if decision.outcome is Outcome.DENY:
154
+ self._close(stream)
155
+ raise Denied(
156
+ decision_ref=decision.decision_ref,
157
+ capability=decision.capability,
158
+ reason=str(decision.reason),
159
+ )
160
+ if decision.outcome is Outcome.SUSPEND:
161
+ self._close(stream)
162
+ raise Suspended(
163
+ approval_ref=str(decision.approval_ref),
164
+ decision_ref=decision.decision_ref,
165
+ capability=decision.capability,
166
+ )
167
+ if self._hold_grants and stream is not None and getattr(stream, "grant", None) is not None:
168
+ try:
169
+ reader = SignalReader(stream, clock=self._clock)
170
+ except Exception:
171
+ # The allow was answered and recorded, and this act runs on it.
172
+ # A grant that cannot be held only means the next identical act
173
+ # asks again; keeping the connection with nothing reading it
174
+ # would be the leak.
175
+ self._close(stream)
176
+ else:
177
+ self._store.put(reader)
178
+ else:
179
+ self._close(stream)
180
+ return decision.decision_ref
181
+
182
+ @staticmethod
183
+ def _close(stream: object) -> None:
184
+ closer = getattr(stream, "close", None)
185
+ if callable(closer):
186
+ closer()
187
+
188
+ def flush(self) -> None:
189
+ """Hand held records to the sink. Called by a caller, never on the hot path."""
190
+ self._log.flush()
191
+
192
+ def close(self) -> None:
193
+ """Give up every held grant and flush what is recorded."""
194
+ self._store.close()
195
+ self._log.flush()
@@ -0,0 +1,87 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """The held grants, keyed on exactly the questions they answer.
3
+
4
+ A grant's conditions ARE its key: scope, capability, principal and the pinned
5
+ arguments digest are what the control plane minted it for, and asking anything
6
+ else is asking a different question. So there is no matching to write here — the
7
+ conditions are compared as a whole, and a near miss is a miss.
8
+
9
+ `take` returns a grant that may be used, or nothing. It never returns one for
10
+ the caller to test: a store that handed out stale grants would be relying on
11
+ every caller to apply the freshness rule, which is as many chances to forget as
12
+ there are callers. An ended grant is discarded and its channel closed on the way
13
+ out, because the channel is what was holding it.
14
+
15
+ ## Why there is a lock
16
+
17
+ A boundary is used from more than one thread, and two threads missing the cache
18
+ on the same question at the same moment each come back with a grant. That is
19
+ correct: two asks, two grants, and the daemon admits both. What must not happen
20
+ is what the first version of `put` allowed — read `None`, be overtaken by the
21
+ other thread's store, then store over it: the overtaken reader was never closed,
22
+ so its channel and its thread stayed alive for the daemon's whole grant lifetime,
23
+ invisible to the store and to `close()`. The e2e case
24
+ `test_racing_puts_do_not_orphan_a_reader` forces that interleaving and is the
25
+ regression test for this lock. Nothing under the lock touches the network: a
26
+ reader's `close` is a socket close, and `ending` is arithmetic.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ from datetime import datetime
32
+ from threading import Lock
33
+
34
+ from sayfirst_contract.decisions import DecisionAsk
35
+ from sayfirst_contract.grants import GrantConditions
36
+
37
+ from .freshness import Ending, ending
38
+ from .signals import SignalReader
39
+
40
+
41
+ class GrantStore:
42
+ """Every grant this boundary holds, at most one per question."""
43
+
44
+ def __init__(self) -> None:
45
+ self._held: dict[GrantConditions, SignalReader] = {}
46
+ self._lock = Lock()
47
+
48
+ def put(self, reader: SignalReader) -> None:
49
+ """Hold this reader for its question, closing whichever one it displaces."""
50
+ conditions = reader.held().grant.conditions
51
+ with self._lock:
52
+ existing = self._held.get(conditions)
53
+ if existing is not None and existing is not reader:
54
+ existing.close()
55
+ self._held[conditions] = reader
56
+
57
+ def take(
58
+ self,
59
+ ask: DecisionAsk,
60
+ principal_reference: str,
61
+ *,
62
+ now: datetime,
63
+ ) -> SignalReader | None:
64
+ """A reader whose grant covers this ask, or nothing at all."""
65
+ key = GrantConditions(
66
+ scope=ask.scope,
67
+ capability=ask.capability,
68
+ principal_reference=principal_reference,
69
+ arguments_digest=ask.arguments_digest,
70
+ )
71
+ with self._lock:
72
+ reader = self._held.get(key)
73
+ if reader is None:
74
+ return None
75
+ if ending(reader.held(), ask, principal_reference, now=now) is Ending.LIVE:
76
+ return reader
77
+ del self._held[key]
78
+ reader.close()
79
+ return None
80
+
81
+ def close(self) -> None:
82
+ """Give up every channel, and with it every grant."""
83
+ with self._lock:
84
+ readers = tuple(self._held.values())
85
+ self._held.clear()
86
+ for reader in readers:
87
+ reader.close()