sayfirst-conformance 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,50 @@
1
+ Metadata-Version: 2.5
2
+ Name: sayfirst-conformance
3
+ Version: 0.3.0
4
+ Summary: Contract conformance replay for control-plane servers
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/conformance/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` server conformance
21
+
22
+ This control-plane distribution exposes only the `sayfirst-conformance`
23
+ command and depends only on the public contract distribution. It replays the
24
+ authoritative server conformance scenarios:
25
+
26
+ ```console
27
+ sayfirst-conformance replay --socket allow=/run/conformance/allow.sock
28
+ ```
29
+
30
+ Complete runs exit 0 as `proven`, disagreements exit 1 as `failed`, invalid
31
+ invocations exit 2, and incomplete runs exit 3 as `unknown`. A run is complete
32
+ when every server-bound scenario has a `--socket` and is replayed; one declared
33
+ with `--expected-absent SCENARIO=REASON` leaves the run incomplete, and one
34
+ named by neither fails it. The contract distribution's README shows a run that
35
+ names all of them, and what each daemon must be arranged to do.
36
+
37
+ The `sayfirst-cli` distribution, the `sayfirst_cli` import package and the
38
+ `sayfirst` console script are the product command-line interface's, and are
39
+ not published from this repository (the operator's decision of 2026-09-05).
40
+
41
+ What this repository publishes beside the daemon is the operator surface that
42
+ inspects it, from `packages/cli`: the distribution `sayfirstd`, the import
43
+ package `sayfirstd` and the console script `sayfirstd`. The constitution names
44
+ one command with subcommands and one console script can point at one module, so
45
+ that surface re-exports replay as `sayfirstd conformance replay` by handing the
46
+ operation to the contract distribution that implements it — with the options,
47
+ the whole-run verdict and the exit statuses of this command. This distribution
48
+ claims neither set of names; it exposes `sayfirst-conformance` and nothing else,
49
+ so a deployment that wants the replayer alone installs one wheel and no operator
50
+ surface at all — one command, and it is the replayer's (article 14).
@@ -0,0 +1,32 @@
1
+ <!-- SPDX-License-Identifier: Apache-2.0 -->
2
+ # `sayfirst` server conformance
3
+
4
+ This control-plane distribution exposes only the `sayfirst-conformance`
5
+ command and depends only on the public contract distribution. It replays the
6
+ authoritative server conformance scenarios:
7
+
8
+ ```console
9
+ sayfirst-conformance replay --socket allow=/run/conformance/allow.sock
10
+ ```
11
+
12
+ Complete runs exit 0 as `proven`, disagreements exit 1 as `failed`, invalid
13
+ invocations exit 2, and incomplete runs exit 3 as `unknown`. A run is complete
14
+ when every server-bound scenario has a `--socket` and is replayed; one declared
15
+ with `--expected-absent SCENARIO=REASON` leaves the run incomplete, and one
16
+ named by neither fails it. The contract distribution's README shows a run that
17
+ names all of them, and what each daemon must be arranged to do.
18
+
19
+ The `sayfirst-cli` distribution, the `sayfirst_cli` import package and the
20
+ `sayfirst` console script are the product command-line interface's, and are
21
+ not published from this repository (the operator's decision of 2026-09-05).
22
+
23
+ What this repository publishes beside the daemon is the operator surface that
24
+ inspects it, from `packages/cli`: the distribution `sayfirstd`, the import
25
+ package `sayfirstd` and the console script `sayfirstd`. The constitution names
26
+ one command with subcommands and one console script can point at one module, so
27
+ that surface re-exports replay as `sayfirstd conformance replay` by handing the
28
+ operation to the contract distribution that implements it — with the options,
29
+ the whole-run verdict and the exit statuses of this command. This distribution
30
+ claims neither set of names; it exposes `sayfirst-conformance` and nothing else,
31
+ so a deployment that wants the replayer alone installs one wheel and no operator
32
+ surface at all — one command, and it is the replayer's (article 14).
@@ -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,49 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ [project]
3
+ name = "sayfirst-conformance"
4
+ version = "0.3.0"
5
+ description = "Contract conformance replay for control-plane servers"
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/conformance/README.md"
29
+ Changelog = "https://github.com/fredaime/sayfirst-control-plane/blob/main/CHANGELOG.md"
30
+
31
+ [project.scripts]
32
+ sayfirst-conformance = "sayfirst_conformance.main:main"
33
+
34
+ [build-system]
35
+ requires = ["hatchling==1.32.0"]
36
+ build-backend = "hatchling.build"
37
+
38
+ [tool.uv.sources]
39
+ sayfirst-contract = { workspace = true }
40
+
41
+ [tool.hatch.build.targets.wheel]
42
+ packages = ["src/sayfirst_conformance"]
43
+
44
+ [tool.hatch.build.targets.sdist.force-include]
45
+ "../../LICENSE" = "LICENSE"
46
+ "../../NOTICE" = "NOTICE"
47
+
48
+ [tool.hatch.build.targets.wheel.hooks.custom]
49
+ path = "hatch_build.py"
@@ -0,0 +1,2 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """The server conformance command distributed by the control-plane repository."""
@@ -0,0 +1,106 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Command-line entry point for contract conformance replay."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import os
8
+ import sys
9
+ from collections.abc import Mapping, Sequence
10
+ from pathlib import Path
11
+ from typing import TextIO
12
+
13
+ from sayfirst_contract.binding.http_unix_socket.replay import SocketHarness
14
+ from sayfirst_contract.golden import load_scenarios
15
+ from sayfirst_contract.replay import Report, Side, replay
16
+
17
+
18
+ def _assignments(values: Sequence[str], label: str) -> Mapping[str, str]:
19
+ result: dict[str, str] = {}
20
+ for value in values:
21
+ name, separator, assigned = value.partition("=")
22
+ if not separator or not name or not assigned:
23
+ raise ValueError(f"{label} must be SCENARIO=VALUE: {value!r}")
24
+ if name in result:
25
+ raise ValueError(f"{label} repeats scenario {name!r}")
26
+ result[name] = assigned
27
+ return result
28
+
29
+
30
+ def render(report: Report, stream: TextIO) -> None:
31
+ """Write one stable line per scenario and the whole-run result."""
32
+ for item in report.scenarios:
33
+ bound = str(item.bound_to_side).lower()
34
+ # Article 2: a line whose verdict rests on no comparison prints no count.
35
+ assertions = "-" if item.assertion_count is None else str(item.assertion_count)
36
+ stream.write(
37
+ f"{item.name}\t{item.verdict.value}\t{item.detail}"
38
+ f"\tbound={bound}\tassertions={assertions}\n"
39
+ )
40
+ if report.succeeded():
41
+ stream.write(f"run\tproven\t{len(report.proven())} scenarios proven\n")
42
+ else:
43
+ stream.write(f"run\t{report.verdict.value}\t{report.failure_reason()}\n")
44
+
45
+
46
+ def _parser() -> argparse.ArgumentParser:
47
+ parser = argparse.ArgumentParser(prog="sayfirst-conformance")
48
+ commands = parser.add_subparsers(dest="command", required=True)
49
+ replay_parser = commands.add_parser("replay")
50
+ replay_parser.add_argument(
51
+ "--socket",
52
+ action="append",
53
+ default=[],
54
+ metavar="SCENARIO=PATH",
55
+ help="socket of a daemon arranged for one scenario; repeat for each scenario",
56
+ )
57
+ replay_parser.add_argument(
58
+ "--expected-absent",
59
+ action="append",
60
+ default=[],
61
+ metavar="SCENARIO=REASON",
62
+ help="name an unavailable scenario and why it is unavailable",
63
+ )
64
+ replay_parser.add_argument("--expected-uid", type=int, default=os.geteuid())
65
+ replay_parser.add_argument("--timeout", type=float, default=5.0)
66
+ replay_parser.add_argument("--deadline-wait-seconds", type=float, default=61.0)
67
+ return parser
68
+
69
+
70
+ def main(arguments: Sequence[str] | None = None, *, stdout: TextIO | None = None) -> int:
71
+ """Run the requested command and return its process exit code."""
72
+ output = stdout or sys.stdout
73
+ namespace = _parser().parse_args(arguments)
74
+ try:
75
+ sockets = {
76
+ name: Path(path) for name, path in _assignments(namespace.socket, "--socket").items()
77
+ }
78
+ expected_absent = _assignments(namespace.expected_absent, "--expected-absent")
79
+ scenarios = load_scenarios()
80
+ server_names = {name for name, scenario in scenarios.items() if scenario.binds_server()}
81
+ if unexpected := set(sockets) - server_names:
82
+ raise ValueError(f"--socket names non-server scenarios: {sorted(unexpected)!r}")
83
+ if overlap := set(sockets) & set(expected_absent):
84
+ raise ValueError(
85
+ f"scenarios cannot have both a socket and expected absence: {sorted(overlap)!r}"
86
+ )
87
+ report = replay(
88
+ scenarios,
89
+ SocketHarness(
90
+ sockets,
91
+ expected_uid=namespace.expected_uid,
92
+ timeout=namespace.timeout,
93
+ deadline_wait_seconds=namespace.deadline_wait_seconds,
94
+ ),
95
+ Side.SERVER,
96
+ expected_absent=expected_absent,
97
+ )
98
+ except ValueError as exc:
99
+ output.write(f"run\tunknown\tinvalid invocation: {exc}\n")
100
+ return 2
101
+ render(report, output)
102
+ return {"proven": 0, "failed": 1, "unknown": 3}[report.verdict.value]
103
+
104
+
105
+ if __name__ == "__main__":
106
+ raise SystemExit(main())
@@ -0,0 +1,374 @@
1
+ # SPDX-License-Identifier: Apache-2.0 OR MIT-0
2
+ from __future__ import annotations
3
+
4
+ import copy
5
+ import os
6
+ import socket
7
+ import threading
8
+ from contextlib import ExitStack
9
+ from datetime import UTC, datetime, timedelta
10
+ from io import StringIO
11
+ from pathlib import Path
12
+
13
+ import pytest
14
+ import sayfirst_contract.binding.http_unix_socket.client as client_transport
15
+ import sayfirst_contract.binding.http_unix_socket.replay as replay_transport
16
+ from sayfirst_conformance.main import main
17
+ from sayfirst_contract.artifacts import load_json
18
+ from sayfirst_contract.binding.http_unix_socket.addresses import scenario_address
19
+ from sayfirst_contract.binding.http_unix_socket.client import (
20
+ SocketClient,
21
+ UnsupportedPlatform,
22
+ )
23
+ from sayfirst_contract.binding.http_unix_socket.replay import SocketHarness
24
+ from sayfirst_contract.client import Answered, CouldNotAsk, Refused
25
+ from sayfirst_contract.generation import CONTRACT_GENERATION, NegotiatedClient
26
+ from sayfirst_contract.golden import load_scenarios, schema_examples
27
+ from sayfirst_contract.problems import ProblemCode, problem_retryable
28
+ from sayfirst_contract.replay import RunVerdict, Side, Verdict, replay
29
+ from sayfirst_contract_stub.stub import Stub
30
+ from sayfirst_contract_stub.stub_http import serve
31
+
32
+
33
+ def _serve_scenarios(root: Path, names: tuple[str, ...]):
34
+ stack = ExitStack()
35
+ now = {name: datetime(2026, 9, 4, tzinfo=UTC) for name in names}
36
+ sockets = {}
37
+ stubs = {}
38
+ for name in names:
39
+ stub = Stub(name, clock=lambda name=name: now[name])
40
+ stubs[name] = stub
41
+ sockets[name] = stack.enter_context(serve(stub, scenario_address(root, name)))
42
+ return stack, now, sockets, stubs
43
+
44
+
45
+ def test_every_server_scenario_is_replayed_over_a_real_socket(tmp_path: Path) -> None:
46
+ """Article 13: the acceptance runner proves every server-bound shipped fixture."""
47
+ scenarios = load_scenarios()
48
+ names = tuple(name for name, item in scenarios.items() if item.binds_server())
49
+ stack, now, sockets, stubs = _serve_scenarios(tmp_path, names)
50
+ with stack:
51
+ harness = SocketHarness(
52
+ sockets,
53
+ expected_uid=os.geteuid(),
54
+ pass_deadline=lambda scenario: now.__setitem__(
55
+ scenario.name, now[scenario.name] + timedelta(seconds=61)
56
+ ),
57
+ change_policy=lambda scenario, policy: stubs[scenario.name].change_policy(),
58
+ )
59
+ report = replay(scenarios, harness, Side.SERVER)
60
+
61
+ assert report.succeeded()
62
+ assert {item.name for item in report.proven()} == set(names)
63
+ assert all(
64
+ item.verdict is Verdict.NOT_APPLICABLE
65
+ for item in report.scenarios
66
+ if item.name not in names
67
+ )
68
+
69
+
70
+ def test_a_socket_observation_that_disagrees_is_failed(tmp_path: Path) -> None:
71
+ """Article 13: a server disagreement is a failed scenario, never a proof."""
72
+ socket_path = tmp_path / "allow.sock"
73
+ with serve(Stub("deny"), socket_path):
74
+ report = replay(
75
+ {"allow": load_scenarios()["allow"]},
76
+ SocketHarness({"allow": socket_path}),
77
+ Side.SERVER,
78
+ )
79
+ item = report.scenarios[0]
80
+ assert item.verdict is Verdict.FAILED
81
+ assert item.detail == (
82
+ "outcome: expected 'allow', observed 'deny'; "
83
+ "reason: expected 'policy_allows', observed 'policy_denies'; "
84
+ "grant: expected 'present', observed 'absent'"
85
+ )
86
+ assert not report.succeeded()
87
+
88
+
89
+ def test_the_command_reports_every_scenario_and_its_reason(tmp_path: Path) -> None:
90
+ """Article 13: command output distinguishes proof, expected absence, and binding."""
91
+ stack, _, sockets, _ = _serve_scenarios(tmp_path, ("allow",))
92
+ missing = {
93
+ name: "requires a separately configured daemon"
94
+ for name, scenario in load_scenarios().items()
95
+ if scenario.binds_server() and name != "allow"
96
+ }
97
+ output = StringIO()
98
+ arguments = [
99
+ "replay",
100
+ "--socket",
101
+ f"allow={sockets['allow']}",
102
+ *(
103
+ item
104
+ for name, reason in missing.items()
105
+ for item in ("--expected-absent", f"{name}={reason}")
106
+ ),
107
+ ]
108
+ with stack:
109
+ exit_code = main(arguments, stdout=output)
110
+
111
+ rendered = output.getvalue()
112
+ assert exit_code == 3
113
+ assert "allow\tproven\tmatched expected members\tbound=true\tassertions=3" in rendered
114
+ for name, reason in missing.items():
115
+ assert f"{name}\tnot-applicable\t{reason}\tbound=true" in rendered
116
+ assert "unknown_outcome\tnot-applicable\tbinds client, not server\tbound=false" in rendered
117
+ assert "unreachable\tnot-applicable\tbinds client, not server\tbound=false" in rendered
118
+ assert "run\tunknown\t10 server-bound scenarios were not replayed" in rendered
119
+
120
+
121
+ def test_the_command_fails_when_every_scenario_is_expected_absent() -> None:
122
+ """Article 13: explicit absences do not turn a vacuous run green."""
123
+ scenarios = load_scenarios()
124
+ arguments = ["replay"]
125
+ for name, scenario in scenarios.items():
126
+ if scenario.binds_server():
127
+ arguments.extend(("--expected-absent", f"{name}=skeleton block not present"))
128
+ output = StringIO()
129
+ assert main(arguments, stdout=output) == 3
130
+ assert "run\tunknown\t11 server-bound scenarios were not replayed" in output.getvalue()
131
+
132
+
133
+ def test_the_command_returns_zero_for_a_complete_live_run(tmp_path: Path, monkeypatch) -> None: # type: ignore[no-untyped-def]
134
+ """Article 13: exit zero is proven against every shipped server fixture."""
135
+ scenarios = load_scenarios()
136
+ names = tuple(name for name, scenario in scenarios.items() if scenario.binds_server())
137
+ stack, now, sockets, stubs = _serve_scenarios(tmp_path, names)
138
+
139
+ def pass_deadline(seconds: float) -> None:
140
+ assert seconds == 61.0
141
+ for name in now:
142
+ now[name] += timedelta(seconds=seconds)
143
+
144
+ monkeypatch.setattr(replay_transport.time, "sleep", pass_deadline)
145
+ # Block 2.3's version-change fixture needs the daemon's policy replaced
146
+ # mid-scenario. The command knows socket paths and nothing else, so against
147
+ # a real daemon that replacement is the operator's act; here the fake's is
148
+ # performed the same way the deadline above is passed.
149
+ monkeypatch.setattr(
150
+ replay_transport._SocketSession,
151
+ "change_policy",
152
+ lambda self, policy: stubs[self.scenario.name].change_policy(),
153
+ )
154
+ arguments = ["replay"]
155
+ for name, socket_path in sockets.items():
156
+ arguments.extend(("--socket", f"{name}={socket_path}"))
157
+ output = StringIO()
158
+ with stack:
159
+ exit_code = main(arguments, stdout=output)
160
+
161
+ assert exit_code == 0
162
+ assert "run\tproven\t11 scenarios proven" in output.getvalue()
163
+
164
+
165
+ def test_the_command_returns_one_for_a_live_disagreement(tmp_path: Path) -> None:
166
+ """Article 13: exit one identifies an observed fixture disagreement."""
167
+ socket_path = tmp_path / "allow.sock"
168
+ arguments = ["replay", "--socket", f"allow={socket_path}"]
169
+ for name, scenario in load_scenarios().items():
170
+ if scenario.binds_server() and name != "allow":
171
+ arguments.extend(("--expected-absent", f"{name}=not arranged for this test"))
172
+ output = StringIO()
173
+ with serve(Stub("deny"), socket_path):
174
+ exit_code = main(arguments, stdout=output)
175
+
176
+ assert exit_code == 1
177
+ assert "allow\tfailed\t" in output.getvalue()
178
+ assert "run\tfailed\t1 scenario failed" in output.getvalue()
179
+
180
+
181
+ def test_the_socket_client_refuses_an_unexpected_listener(tmp_path: Path) -> None:
182
+ """Article 6: replay sends nothing through a listener with the wrong uid."""
183
+ socket_path = tmp_path / "impostor.sock"
184
+ listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
185
+ listener.bind(str(socket_path))
186
+ listener.listen()
187
+ received: list[bytes] = []
188
+
189
+ def receive() -> None:
190
+ peer, _ = listener.accept()
191
+ with peer:
192
+ peer.settimeout(1)
193
+ received.append(peer.recv(1))
194
+
195
+ thread = threading.Thread(target=receive)
196
+ thread.start()
197
+ result = SocketClient(socket_path, expected_uid=os.geteuid() + 1).read_status()
198
+ thread.join(timeout=2)
199
+ listener.close()
200
+
201
+ assert not thread.is_alive()
202
+ assert received == [b""]
203
+ assert isinstance(result, CouldNotAsk)
204
+ assert result.problem.code is ProblemCode.IMPOSTOR
205
+
206
+
207
+ def test_the_socket_client_routes_drift_with_the_published_binding(monkeypatch) -> None: # type: ignore[no-untyped-def]
208
+ """Article 13: replay gets its method and path from the shipped OpenAPI document."""
209
+ binding = copy.deepcopy(load_json("binding", "http-unix-socket", "openapi.json"))
210
+ binding["paths"]["/decisions-v2"] = binding["paths"].pop("/decisions")
211
+ monkeypatch.setattr(client_transport, "load_json", lambda *path: binding)
212
+ client_transport._published_operations.cache_clear()
213
+
214
+ class RecordingClient(SocketClient):
215
+ def __init__(self, *args, **kwargs): # type: ignore[no-untyped-def]
216
+ super().__init__(*args, **kwargs)
217
+ self.calls = []
218
+
219
+ def _read(self, method, target, document, reader, **selection): # type: ignore[no-untyped-def]
220
+ self.calls.append((method, target))
221
+ return None
222
+
223
+ try:
224
+ client = RecordingClient(Path("unused"), expected_uid=os.geteuid())
225
+ client.ask_decision(load_scenarios()["allow"].ask)
226
+ assert client.calls == [("POST", "/decisions-v2")]
227
+ finally:
228
+ client_transport._published_operations.cache_clear()
229
+
230
+
231
+ @pytest.mark.parametrize(
232
+ ("status", "example"), ((200, "decision-result"), (500, "problem-document"))
233
+ )
234
+ def test_every_response_must_echo_the_pinned_generation(status: int, example: str) -> None:
235
+ """Article 13: a response from another generation is distinctly refused."""
236
+ response_document = dict(schema_examples()[example])
237
+ response_document["contract_generation"] = 42
238
+
239
+ class WrongGenerationClient(SocketClient):
240
+ def _request(self, method, target, document=None, **selection): # type: ignore[no-untyped-def]
241
+ return status, response_document
242
+
243
+ result = WrongGenerationClient(Path("unused"), expected_uid=os.geteuid()).ask_decision(
244
+ load_scenarios()["allow"].ask
245
+ )
246
+ assert isinstance(result, CouldNotAsk)
247
+ assert result.problem.code is ProblemCode.GENERATION_UNSUPPORTED
248
+
249
+
250
+ def test_a_newer_server_that_supports_the_client_generation_is_accepted() -> None:
251
+ """Article 13: status negotiates support, not equal pinned generations."""
252
+ status_document = dict(schema_examples()["status-result"])
253
+ status_document.update(contract_generation=2, supported_generations=[1, 2])
254
+ decision_document = dict(schema_examples()["decision-result"])
255
+
256
+ class AheadServerClient(SocketClient):
257
+ def __init__(self) -> None:
258
+ super().__init__(Path("unused"), expected_uid=os.geteuid())
259
+ self.calls = []
260
+
261
+ def _request(self, method, target, document=None, **selection): # type: ignore[no-untyped-def]
262
+ self.calls.append((method, target, document))
263
+ if target == "/status":
264
+ return 200, status_document
265
+ assert document["contract_generation"] == CONTRACT_GENERATION
266
+ return 200, decision_document
267
+
268
+ transport = AheadServerClient()
269
+ client = NegotiatedClient(transport)
270
+ status = client.read_status()
271
+ result = client.ask_decision(load_scenarios()["allow"].ask)
272
+
273
+ assert isinstance(status, Answered)
274
+ assert status.value.contract_generation == 2
275
+ assert status.value.supported_generations == (1, 2)
276
+ assert isinstance(result, Answered)
277
+ assert [target for _, target, _ in transport.calls] == ["/status", "/decisions"]
278
+
279
+
280
+ def test_a_generation_refusal_keeps_the_servers_pinned_generation() -> None:
281
+ """Article 13: a generation refusal preserves the server's problem document."""
282
+ problem_document = dict(schema_examples()["problem-document"])
283
+ problem_document.update(
284
+ contract_generation=2,
285
+ code="generation_unsupported",
286
+ message="client generation is outside this server's window",
287
+ retryable=False,
288
+ member="contract_generation",
289
+ )
290
+
291
+ class RefusingServerClient(SocketClient):
292
+ def _request(self, method, target, document=None, **selection): # type: ignore[no-untyped-def]
293
+ return 400, problem_document
294
+
295
+ result = RefusingServerClient(Path("unused"), expected_uid=os.geteuid()).ask_decision(
296
+ load_scenarios()["allow"].ask
297
+ )
298
+ assert isinstance(result, Refused)
299
+ assert result.problem.contract_generation == 2
300
+ assert result.problem.message == "client generation is outside this server's window"
301
+ assert result.problem.retryable is False
302
+ assert result.problem.member == "contract_generation"
303
+
304
+
305
+ def test_answer_unreadable_uses_registry_retryability() -> None:
306
+ """Article 2: replay does not invent certainty for client-side problems."""
307
+ unreadable = dict(schema_examples()["decision-result"])
308
+ del unreadable["decision_ref"]
309
+
310
+ class UnreadableClient(SocketClient):
311
+ def _request(self, method, target, document=None, **selection): # type: ignore[no-untyped-def]
312
+ return 200, unreadable
313
+
314
+ result = UnreadableClient(Path("unused"), expected_uid=os.geteuid()).ask_decision(
315
+ load_scenarios()["allow"].ask
316
+ )
317
+ assert isinstance(result, CouldNotAsk)
318
+ assert result.problem.code is ProblemCode.ANSWER_UNREADABLE
319
+ assert result.problem.retryable is problem_retryable(ProblemCode.ANSWER_UNREADABLE)
320
+ registry = load_json("domain", "problem-codes.json")["codes"]
321
+ assert registry[ProblemCode.ANSWER_UNREADABLE.value]["origin"] == "client"
322
+
323
+
324
+ def test_unsupported_peer_credentials_are_not_applicable(tmp_path: Path, monkeypatch) -> None: # type: ignore[no-untyped-def]
325
+ """Article 6: an unsupported identity adapter is not a transport outage."""
326
+ socket_path = tmp_path / "unsupported.sock"
327
+ with serve(Stub("allow"), socket_path):
328
+ monkeypatch.setattr(
329
+ client_transport,
330
+ "_peer_uid",
331
+ lambda peer: (_ for _ in ()).throw(
332
+ UnsupportedPlatform("peer identity is unsupported on this platform")
333
+ ),
334
+ )
335
+ report = replay(
336
+ {"allow": load_scenarios()["allow"]},
337
+ SocketHarness({"allow": socket_path}),
338
+ Side.SERVER,
339
+ )
340
+ assert report.scenarios[0].verdict is Verdict.NOT_APPLICABLE
341
+ assert report.scenarios[0].detail == "peer identity is unsupported on this platform"
342
+ assert report.verdict is RunVerdict.UNKNOWN
343
+
344
+
345
+ def test_the_command_refuses_a_socket_mapping_that_cannot_be_used() -> None:
346
+ """Article 13: a misspelled or client-only mapping is not silently ignored."""
347
+ output = StringIO()
348
+ exit_code = main(
349
+ ["replay", "--socket", "unknown_outcome=/tmp/unused.sock"],
350
+ stdout=output,
351
+ )
352
+ assert exit_code == 2
353
+ assert "run\tunknown\t" in output.getvalue()
354
+ assert "non-server scenarios" in output.getvalue()
355
+
356
+
357
+ def test_a_run_that_compared_nothing_prints_no_assertion_count() -> None:
358
+ """Article 2: a run in which nothing was replayed prints no healthy-looking number.
359
+
360
+ `assertions=` was added so a reader could see non-vacuity without parsing the
361
+ English detail. Filled from the fixture it was the one machine-readable field that
362
+ read the same whether six daemons agreed or none was ever contacted; a line whose
363
+ verdict rests on no comparison now says so.
364
+ """
365
+ scenarios = load_scenarios()
366
+ arguments = ["replay"]
367
+ for name, scenario in scenarios.items():
368
+ if scenario.binds_server():
369
+ arguments.extend(("--expected-absent", f"{name}=block not landed"))
370
+ output = StringIO()
371
+ assert main(arguments, stdout=output) == 3
372
+ lines = [line for line in output.getvalue().splitlines() if not line.startswith("run\t")]
373
+ assert len(lines) == len(scenarios)
374
+ assert all(line.endswith("\tassertions=-") for line in lines), lines