synth-code 0.0.1__py3-none-macosx_15_0_arm64.whl
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.
- synth_code/__init__.py +0 -0
- synth_code/account.py +551 -0
- synth_code/account_http.py +86 -0
- synth_code/account_refusal.py +80 -0
- synth_code/accounting.py +148 -0
- synth_code/activity_grouping.py +149 -0
- synth_code/agent_panels.py +127 -0
- synth_code/approvals.py +397 -0
- synth_code/blobs.py +31 -0
- synth_code/cli.py +734 -0
- synth_code/client.py +413 -0
- synth_code/composer_delivery.py +139 -0
- synth_code/conversation.py +949 -0
- synth_code/daemon.py +34 -0
- synth_code/edition.py +306 -0
- synth_code/enrollment.py +304 -0
- synth_code/file_edit_facts.py +10 -0
- synth_code/freeze.py +234 -0
- synth_code/grant.py +59 -0
- synth_code/history.py +140 -0
- synth_code/history_generated.py +219 -0
- synth_code/history_wire.py +166 -0
- synth_code/image_input.py +109 -0
- synth_code/image_preview.py +105 -0
- synth_code/legacy_history.py +161 -0
- synth_code/live_turns.py +171 -0
- synth_code/model_picker.py +311 -0
- synth_code/native/manifest.json +1 -0
- synth_code/native/synth-code-runtime +0 -0
- synth_code/native.py +95 -0
- synth_code/oauth.py +284 -0
- synth_code/operator.py +116 -0
- synth_code/pack_source.py +65 -0
- synth_code/panel_request.py +291 -0
- synth_code/panels.py +40 -0
- synth_code/plugin_host.py +459 -0
- synth_code/protocol.py +35 -0
- synth_code/provider.py +313 -0
- synth_code/provider_fault.py +173 -0
- synth_code/provider_frames.py +571 -0
- synth_code/recommendation.py +324 -0
- synth_code/report.py +72 -0
- synth_code/research_events.py +44 -0
- synth_code/research_trace.py +449 -0
- synth_code/rex_view.py +58 -0
- synth_code/runtime_refusal.py +108 -0
- synth_code/schema/budgets.json +17 -0
- synth_code/schema/history-v2.json +1002 -0
- synth_code/session.py +291 -0
- synth_code/shoal.py +564 -0
- synth_code/side_panel.py +309 -0
- synth_code/skills.py +269 -0
- synth_code/slash.py +425 -0
- synth_code/source_view.py +135 -0
- synth_code/starter.json +13 -0
- synth_code/stdio.py +75 -0
- synth_code/stream.py +142 -0
- synth_code/subscriptions.py +267 -0
- synth_code/synth_authority.py +362 -0
- synth_code/synth_extra.py +32 -0
- synth_code/terminal.py +817 -0
- synth_code/terminal_journal.py +284 -0
- synth_code/terminal_layout.py +643 -0
- synth_code/terminal_surfaces.py +470 -0
- synth_code/terminal_viewport.py +125 -0
- synth_code/tool_render.py +86 -0
- synth_code/transcript_frames.py +212 -0
- synth_code/transcript_placement.py +63 -0
- synth_code/transcript_rows.py +456 -0
- synth_code/transport.py +243 -0
- synth_code/v001_history.py +468 -0
- synth_code/view.py +854 -0
- synth_code/views/__init__.py +93 -0
- synth_code/views/charts.py +196 -0
- synth_code/views/curses_adapter.py +116 -0
- synth_code/views/engine.py +170 -0
- synth_code/views/model.py +226 -0
- synth_code/views/primitives.py +270 -0
- synth_code/views/tiling.py +124 -0
- synth_code-0.0.1.dist-info/METADATA +50 -0
- synth_code-0.0.1.dist-info/RECORD +110 -0
- synth_code-0.0.1.dist-info/WHEEL +5 -0
- synth_code-0.0.1.dist-info/entry_points.txt +6 -0
- synth_code-0.0.1.dist-info/licenses/temper/LICENSE-APACHE +190 -0
- synth_code-0.0.1.dist-info/licenses/temper/LICENSE-MIT +21 -0
- synth_code-0.0.1.dist-info/licenses/temper/SOURCE.json +433 -0
- synth_code-0.0.1.dist-info/top_level.txt +2 -0
- synth_code_plugins/_sdk/__init__.py +19 -0
- synth_code_plugins/_sdk/callback_wire.py +240 -0
- synth_code_plugins/_sdk/callbacks.py +317 -0
- synth_code_plugins/_sdk/compliance.py +51 -0
- synth_code_plugins/_sdk/contracts.py +236 -0
- synth_code_plugins/_sdk/discovery.py +75 -0
- synth_code_plugins/_sdk/job_binding.py +71 -0
- synth_code_plugins/_sdk/lifecycle.py +50 -0
- synth_code_plugins/_sdk/lifecycle_generated.py +15 -0
- synth_code_plugins/_sdk/manifest.py +269 -0
- synth_code_plugins/_sdk/pack.py +332 -0
- synth_code_plugins/_sdk/push.py +98 -0
- synth_code_plugins/_sdk/records.py +26 -0
- synth_code_plugins/_sdk/registry.py +491 -0
- synth_code_plugins/_sdk/schemas.py +210 -0
- synth_code_plugins/_sdk/sources.py +230 -0
- synth_code_plugins/_sdk/surfaces.py +54 -0
- synth_code_plugins/_sdk/tools.py +172 -0
- synth_code_plugins/_sdk/worker_memory.py +49 -0
- synth_code_plugins/core/SKILL.md +6 -0
- synth_code_plugins/core/__init__.py +21 -0
- synth_code_plugins/core/plugin.toml +44 -0
- synth_code_plugins/core/source.py +18 -0
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
"""Typed result frames for the fixture callback process boundary."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import cast
|
|
9
|
+
|
|
10
|
+
from .contracts import MAX_CONTEXT_CHARS, Health, Refusal, RefusalCode
|
|
11
|
+
from .surfaces import ContextSnapshot, RenderedView
|
|
12
|
+
|
|
13
|
+
__all__ = (
|
|
14
|
+
"MAX_RENDER_LINE_CHARS",
|
|
15
|
+
"MAX_RENDER_ROWS",
|
|
16
|
+
"MAX_RESULT_BYTES",
|
|
17
|
+
"CallbackRequest",
|
|
18
|
+
"CallbackWireError",
|
|
19
|
+
"decode_result",
|
|
20
|
+
"encode_result",
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
MAX_RENDER_ROWS = 256
|
|
24
|
+
MAX_RENDER_LINE_CHARS = 4096
|
|
25
|
+
MAX_RESULT_BYTES = 5 * 1024 * 1024
|
|
26
|
+
|
|
27
|
+
_VERSION = 1
|
|
28
|
+
_MAX_DIAGNOSTIC_CHARS = 4096
|
|
29
|
+
_MIN_DIAGNOSTIC_INTEGER = -(1 << 63)
|
|
30
|
+
_MAX_DIAGNOSTIC_INTEGER = (1 << 63) - 1
|
|
31
|
+
# Skip quoted strings when counting structure so valid rendered text cannot
|
|
32
|
+
# exhaust the parser budget by including JSON punctuation.
|
|
33
|
+
_STRUCTURE = re.compile(rb'\\.|["\[\]{},:]', re.DOTALL)
|
|
34
|
+
_CHILD_REFUSAL_CODES = frozenset({RefusalCode.CALLBACK_FAILED, RefusalCode.OUTPUT_INVALID})
|
|
35
|
+
|
|
36
|
+
Result = ContextSnapshot | RenderedView | Refusal
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True, slots=True)
|
|
40
|
+
class CallbackRequest:
|
|
41
|
+
request_id: str
|
|
42
|
+
plugin: str
|
|
43
|
+
subject: str
|
|
44
|
+
result_type: type[ContextSnapshot | RenderedView]
|
|
45
|
+
source_ids: tuple[str, ...]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class CallbackWireError(ValueError):
|
|
49
|
+
"""A frame exceeded a quota or violated its declared callback contract."""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def encode_result(request: CallbackRequest, result: Result) -> bytes:
|
|
53
|
+
if type(result) is Refusal:
|
|
54
|
+
if result.plugin != request.plugin or result.subject != request.subject:
|
|
55
|
+
raise CallbackWireError("refusal does not match the callback")
|
|
56
|
+
if type(result.code) is not RefusalCode or result.code not in _CHILD_REFUSAL_CODES:
|
|
57
|
+
raise CallbackWireError("callback refusal code is outside child authority")
|
|
58
|
+
kind = "refusal"
|
|
59
|
+
payload = {
|
|
60
|
+
"code": result.code.value,
|
|
61
|
+
"detail": _text(result.detail, _MAX_DIAGNOSTIC_CHARS),
|
|
62
|
+
"expected": _diagnostic(result.expected),
|
|
63
|
+
"actual": _diagnostic(result.actual),
|
|
64
|
+
}
|
|
65
|
+
elif isinstance(result, ContextSnapshot) and request.result_type is ContextSnapshot:
|
|
66
|
+
kind = "context"
|
|
67
|
+
payload = {"text": result.text, "health": result.health.value}
|
|
68
|
+
elif isinstance(result, RenderedView) and request.result_type is RenderedView:
|
|
69
|
+
kind = "render"
|
|
70
|
+
payload = {
|
|
71
|
+
"lines": result.lines,
|
|
72
|
+
"health": [(key, health.value) for key, health in result.health],
|
|
73
|
+
}
|
|
74
|
+
else:
|
|
75
|
+
raise CallbackWireError("unexpected callback result type")
|
|
76
|
+
|
|
77
|
+
try:
|
|
78
|
+
data = json.dumps(
|
|
79
|
+
{
|
|
80
|
+
"version": _VERSION,
|
|
81
|
+
"request": request.request_id,
|
|
82
|
+
"kind": kind,
|
|
83
|
+
"payload": payload,
|
|
84
|
+
},
|
|
85
|
+
ensure_ascii=False,
|
|
86
|
+
allow_nan=False,
|
|
87
|
+
separators=(",", ":"),
|
|
88
|
+
).encode("utf-8")
|
|
89
|
+
except (TypeError, ValueError, RecursionError) as error:
|
|
90
|
+
raise CallbackWireError("callback output is not JSON serializable") from error
|
|
91
|
+
if len(data) > MAX_RESULT_BYTES:
|
|
92
|
+
raise CallbackWireError("callback output exceeds its byte budget")
|
|
93
|
+
return data
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def decode_result(request: CallbackRequest, data: bytes | bytearray) -> Result:
|
|
97
|
+
if len(data) > MAX_RESULT_BYTES:
|
|
98
|
+
raise CallbackWireError("callback output exceeds its byte budget")
|
|
99
|
+
_check_structure(data, len(request.source_ids))
|
|
100
|
+
try:
|
|
101
|
+
raw: object = json.loads(
|
|
102
|
+
data.decode("utf-8"),
|
|
103
|
+
object_pairs_hook=_unique_object,
|
|
104
|
+
parse_int=_integer,
|
|
105
|
+
parse_float=_reject_number,
|
|
106
|
+
parse_constant=_reject_number,
|
|
107
|
+
)
|
|
108
|
+
except CallbackWireError:
|
|
109
|
+
raise
|
|
110
|
+
except (ValueError, RecursionError) as error:
|
|
111
|
+
raise CallbackWireError("invalid callback JSON") from error
|
|
112
|
+
|
|
113
|
+
frame = _object(raw, "version", "request", "kind", "payload")
|
|
114
|
+
if type(frame["version"]) is not int or frame["version"] != _VERSION:
|
|
115
|
+
raise CallbackWireError("unexpected callback wire version")
|
|
116
|
+
if type(frame["request"]) is not str or frame["request"] != request.request_id:
|
|
117
|
+
raise CallbackWireError("callback result does not match its request")
|
|
118
|
+
|
|
119
|
+
kind = frame["kind"]
|
|
120
|
+
if kind == "refusal":
|
|
121
|
+
return _refusal(request, frame["payload"])
|
|
122
|
+
if kind == "context" and request.result_type is ContextSnapshot:
|
|
123
|
+
payload = _object(frame["payload"], "text", "health")
|
|
124
|
+
return ContextSnapshot(
|
|
125
|
+
_text(payload["text"], MAX_CONTEXT_CHARS), _health(payload["health"])
|
|
126
|
+
)
|
|
127
|
+
if kind == "render" and request.result_type is RenderedView:
|
|
128
|
+
return _rendered_view(request, frame["payload"])
|
|
129
|
+
raise CallbackWireError("unexpected callback result kind")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _check_structure(data: bytes | bytearray, source_count: int) -> None:
|
|
133
|
+
# The deepest allowed object is an envelope containing a render payload,
|
|
134
|
+
# its health array and one [source, health] pair.
|
|
135
|
+
depth = 0
|
|
136
|
+
tokens = 0
|
|
137
|
+
in_string = False
|
|
138
|
+
max_tokens = 32 + MAX_RENDER_ROWS + 4 * source_count
|
|
139
|
+
for match in _STRUCTURE.finditer(data):
|
|
140
|
+
token = data[match.start()]
|
|
141
|
+
if token == ord('"'):
|
|
142
|
+
in_string = not in_string
|
|
143
|
+
continue
|
|
144
|
+
if in_string or token == ord("\\"):
|
|
145
|
+
continue
|
|
146
|
+
tokens += 1
|
|
147
|
+
if token in (ord("{"), ord("[")):
|
|
148
|
+
depth += 1
|
|
149
|
+
elif token in (ord("}"), ord("]")):
|
|
150
|
+
depth -= 1
|
|
151
|
+
if depth < 0 or depth > 4 or tokens > max_tokens:
|
|
152
|
+
raise CallbackWireError("callback frame exceeds its structure budget")
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _unique_object(pairs: list[tuple[str, object]]) -> dict[str, object]:
|
|
156
|
+
fields = dict(pairs)
|
|
157
|
+
if len(fields) != len(pairs):
|
|
158
|
+
raise CallbackWireError("duplicate callback field")
|
|
159
|
+
return fields
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _integer(raw: str) -> int:
|
|
163
|
+
if len(raw) > 20:
|
|
164
|
+
raise CallbackWireError("callback integer exceeds its budget")
|
|
165
|
+
value = int(raw)
|
|
166
|
+
if not _MIN_DIAGNOSTIC_INTEGER <= value <= _MAX_DIAGNOSTIC_INTEGER:
|
|
167
|
+
raise CallbackWireError("callback integer exceeds its budget")
|
|
168
|
+
return value
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _reject_number(_raw: str) -> int:
|
|
172
|
+
raise CallbackWireError("callback frame requires bounded integers")
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _object(value: object, *keys: str) -> dict[str, object]:
|
|
176
|
+
if type(value) is not dict:
|
|
177
|
+
raise CallbackWireError("callback object required")
|
|
178
|
+
fields = cast(dict[str, object], value)
|
|
179
|
+
if fields.keys() != set(keys):
|
|
180
|
+
raise CallbackWireError("unexpected callback fields")
|
|
181
|
+
return fields
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _text(value: object, maximum: int) -> str:
|
|
185
|
+
if type(value) is not str or len(value) > maximum or (value and not value.isprintable()):
|
|
186
|
+
raise CallbackWireError("callback text exceeds its type or display budget")
|
|
187
|
+
return value
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _health(value: object) -> Health:
|
|
191
|
+
try:
|
|
192
|
+
return Health(_text(value, _MAX_DIAGNOSTIC_CHARS))
|
|
193
|
+
except ValueError as error:
|
|
194
|
+
raise CallbackWireError("unknown callback health") from error
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _rendered_view(request: CallbackRequest, value: object) -> RenderedView:
|
|
198
|
+
payload = _object(value, "lines", "health")
|
|
199
|
+
lines, health = payload["lines"], payload["health"]
|
|
200
|
+
if type(lines) is not list or len(lines) > MAX_RENDER_ROWS:
|
|
201
|
+
raise CallbackWireError("callback render exceeds its row budget")
|
|
202
|
+
if type(health) is not list or len(health) != len(request.source_ids):
|
|
203
|
+
raise CallbackWireError("callback health does not match requested sources")
|
|
204
|
+
source_health: list[tuple[str, Health]] = []
|
|
205
|
+
for source_id, pair in zip(request.source_ids, health, strict=True):
|
|
206
|
+
if type(pair) is not list or len(pair) != 2 or pair[0] != source_id:
|
|
207
|
+
raise CallbackWireError("callback health does not match requested sources")
|
|
208
|
+
source_health.append((source_id, _health(pair[1])))
|
|
209
|
+
return RenderedView(
|
|
210
|
+
tuple(_text(line, MAX_RENDER_LINE_CHARS) for line in lines),
|
|
211
|
+
tuple(source_health),
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _refusal(request: CallbackRequest, value: object) -> Refusal:
|
|
216
|
+
payload = _object(value, "code", "detail", "expected", "actual")
|
|
217
|
+
try:
|
|
218
|
+
code = RefusalCode(_text(payload["code"], _MAX_DIAGNOSTIC_CHARS))
|
|
219
|
+
except ValueError as error:
|
|
220
|
+
raise CallbackWireError("unknown callback refusal code") from error
|
|
221
|
+
if code not in _CHILD_REFUSAL_CODES:
|
|
222
|
+
raise CallbackWireError("callback refusal code is outside child authority")
|
|
223
|
+
return Refusal(
|
|
224
|
+
code,
|
|
225
|
+
request.plugin,
|
|
226
|
+
request.subject,
|
|
227
|
+
_text(payload["detail"], _MAX_DIAGNOSTIC_CHARS),
|
|
228
|
+
_diagnostic(payload["expected"]),
|
|
229
|
+
_diagnostic(payload["actual"]),
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _diagnostic(value: object) -> str | int | None:
|
|
234
|
+
if value is None:
|
|
235
|
+
return None
|
|
236
|
+
if type(value) is int:
|
|
237
|
+
if not _MIN_DIAGNOSTIC_INTEGER <= value <= _MAX_DIAGNOSTIC_INTEGER:
|
|
238
|
+
raise CallbackWireError("callback integer exceeds its budget")
|
|
239
|
+
return value
|
|
240
|
+
return _text(value, _MAX_DIAGNOSTIC_CHARS)
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
"""Bounded subprocess execution for read-only fixture entrypoints."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from concurrent.futures import Future, ThreadPoolExecutor
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from multiprocessing import get_context
|
|
9
|
+
from pickle import PicklingError
|
|
10
|
+
from socket import socket, socketpair
|
|
11
|
+
from threading import Event, Lock
|
|
12
|
+
from time import monotonic
|
|
13
|
+
from typing import Generic, TypeVar, cast
|
|
14
|
+
from uuid import uuid4
|
|
15
|
+
|
|
16
|
+
from .callback_wire import (
|
|
17
|
+
MAX_RESULT_BYTES,
|
|
18
|
+
CallbackRequest,
|
|
19
|
+
CallbackWireError,
|
|
20
|
+
decode_result,
|
|
21
|
+
encode_result,
|
|
22
|
+
)
|
|
23
|
+
from .contracts import ContractError, Refusal, RefusalCode
|
|
24
|
+
from .surfaces import ContextSnapshot, RenderedView
|
|
25
|
+
from .worker_memory import MAX_WORKER_RESIDENT_BYTES, resident_bytes
|
|
26
|
+
|
|
27
|
+
T = TypeVar("T")
|
|
28
|
+
Outcome = TypeVar("Outcome", ContextSnapshot, RenderedView)
|
|
29
|
+
|
|
30
|
+
_WORKERS = 4
|
|
31
|
+
_PER_PLUGIN_WORKERS = 2
|
|
32
|
+
_MAX_CALLBACK_SECONDS = 5
|
|
33
|
+
_TERMINATION_SECONDS = 1
|
|
34
|
+
_CANCEL_CHECK_SECONDS = 0.025
|
|
35
|
+
_MP = get_context("spawn")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _run_child(
|
|
39
|
+
writer: socket,
|
|
40
|
+
callback: Callable[[], Outcome],
|
|
41
|
+
request: CallbackRequest,
|
|
42
|
+
) -> None:
|
|
43
|
+
with writer:
|
|
44
|
+
try:
|
|
45
|
+
result: ContextSnapshot | RenderedView | Refusal = callback()
|
|
46
|
+
except ContractError as error:
|
|
47
|
+
result = error.refusal
|
|
48
|
+
except Exception as error: # noqa: BLE001 - isolated plugin callback boundary
|
|
49
|
+
result = Refusal(
|
|
50
|
+
RefusalCode.CALLBACK_FAILED,
|
|
51
|
+
request.plugin,
|
|
52
|
+
request.subject,
|
|
53
|
+
f"callback raised {type(error).__name__}",
|
|
54
|
+
)
|
|
55
|
+
try:
|
|
56
|
+
encoded = encode_result(request, result)
|
|
57
|
+
except CallbackWireError as error:
|
|
58
|
+
encoded = encode_result(
|
|
59
|
+
request,
|
|
60
|
+
Refusal(
|
|
61
|
+
RefusalCode.OUTPUT_INVALID,
|
|
62
|
+
request.plugin,
|
|
63
|
+
request.subject,
|
|
64
|
+
str(error),
|
|
65
|
+
),
|
|
66
|
+
)
|
|
67
|
+
writer.sendall(encoded)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(frozen=True, slots=True)
|
|
71
|
+
class CallbackState(Generic[T]):
|
|
72
|
+
"""Latest completed output and whether a bounded refresh is running."""
|
|
73
|
+
|
|
74
|
+
latest: T | Refusal | None
|
|
75
|
+
pending: bool
|
|
76
|
+
refresh_refusal: Refusal | None = None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class _ReapFailed(RuntimeError):
|
|
80
|
+
pass
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class CallbackWorkers:
|
|
84
|
+
"""Per-registry executor with no unbounded submit queue."""
|
|
85
|
+
|
|
86
|
+
def __init__(self, timeout_s: float) -> None:
|
|
87
|
+
if not 0 < timeout_s <= _MAX_CALLBACK_SECONDS:
|
|
88
|
+
raise ValueError(f"callback timeout must be in (0, {_MAX_CALLBACK_SECONDS}] seconds")
|
|
89
|
+
self._timeout_s = timeout_s
|
|
90
|
+
self._executor = ThreadPoolExecutor(
|
|
91
|
+
max_workers=_WORKERS, thread_name_prefix="plugin-callback"
|
|
92
|
+
)
|
|
93
|
+
self._lock = Lock()
|
|
94
|
+
self._active: dict[str, int] = {}
|
|
95
|
+
self._closed = False
|
|
96
|
+
|
|
97
|
+
def submit(
|
|
98
|
+
self,
|
|
99
|
+
plugin: str,
|
|
100
|
+
subject: str,
|
|
101
|
+
callback: Callable[[], Outcome],
|
|
102
|
+
cancelled: Event,
|
|
103
|
+
*,
|
|
104
|
+
result_type: type[Outcome],
|
|
105
|
+
source_ids: tuple[str, ...] = (),
|
|
106
|
+
) -> Future[Outcome | Refusal] | Refusal:
|
|
107
|
+
with self._lock:
|
|
108
|
+
plugin_workers = self._active.get(plugin, 0)
|
|
109
|
+
if (
|
|
110
|
+
self._closed
|
|
111
|
+
or plugin_workers >= _PER_PLUGIN_WORKERS
|
|
112
|
+
or sum(self._active.values()) >= _WORKERS
|
|
113
|
+
):
|
|
114
|
+
return Refusal(
|
|
115
|
+
RefusalCode.CALLBACK_BUSY,
|
|
116
|
+
plugin,
|
|
117
|
+
subject,
|
|
118
|
+
"fixture callback capacity unavailable",
|
|
119
|
+
expected=_WORKERS,
|
|
120
|
+
)
|
|
121
|
+
self._active[plugin] = plugin_workers + 1
|
|
122
|
+
request = CallbackRequest(uuid4().hex, plugin, subject, result_type, source_ids)
|
|
123
|
+
future = self._executor.submit(self._run_guarded, request, callback, cancelled)
|
|
124
|
+
future.add_done_callback(lambda result: self._release(plugin, result.result()))
|
|
125
|
+
return future
|
|
126
|
+
|
|
127
|
+
def close(self) -> None:
|
|
128
|
+
with self._lock:
|
|
129
|
+
self._closed = True
|
|
130
|
+
self._executor.shutdown(wait=True)
|
|
131
|
+
|
|
132
|
+
def _release(self, plugin: str, outcome: object) -> None:
|
|
133
|
+
if isinstance(outcome, Refusal) and outcome.code is RefusalCode.CALLBACK_REAP_FAILED:
|
|
134
|
+
# Quarantine this capacity until registry teardown. The process may remain live.
|
|
135
|
+
return
|
|
136
|
+
with self._lock:
|
|
137
|
+
remaining = self._active[plugin] - 1
|
|
138
|
+
if remaining == 0:
|
|
139
|
+
del self._active[plugin]
|
|
140
|
+
else:
|
|
141
|
+
self._active[plugin] = remaining
|
|
142
|
+
|
|
143
|
+
def _run_guarded(
|
|
144
|
+
self,
|
|
145
|
+
request: CallbackRequest,
|
|
146
|
+
callback: Callable[[], Outcome],
|
|
147
|
+
cancelled: Event,
|
|
148
|
+
) -> Outcome | Refusal:
|
|
149
|
+
plugin, subject = request.plugin, request.subject
|
|
150
|
+
try:
|
|
151
|
+
return self._run(request, callback, cancelled)
|
|
152
|
+
except _ReapFailed as error:
|
|
153
|
+
return Refusal(RefusalCode.CALLBACK_REAP_FAILED, plugin, subject, str(error))
|
|
154
|
+
except (OSError, ValueError, IndexError) as error:
|
|
155
|
+
return Refusal(
|
|
156
|
+
RefusalCode.CALLBACK_FAILED,
|
|
157
|
+
plugin,
|
|
158
|
+
subject,
|
|
159
|
+
f"callback supervision failed: {type(error).__name__}",
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
def _run(
|
|
163
|
+
self,
|
|
164
|
+
request: CallbackRequest,
|
|
165
|
+
callback: Callable[[], Outcome],
|
|
166
|
+
cancelled: Event,
|
|
167
|
+
) -> Outcome | Refusal:
|
|
168
|
+
plugin, subject = request.plugin, request.subject
|
|
169
|
+
deadline = monotonic() + self._timeout_s
|
|
170
|
+
reader, writer = socketpair()
|
|
171
|
+
child = _MP.Process(
|
|
172
|
+
target=_run_child,
|
|
173
|
+
args=(writer, callback, request),
|
|
174
|
+
daemon=True,
|
|
175
|
+
)
|
|
176
|
+
started = False
|
|
177
|
+
try:
|
|
178
|
+
if cancelled.is_set():
|
|
179
|
+
return Refusal(
|
|
180
|
+
RefusalCode.CALLBACK_CANCELLED,
|
|
181
|
+
plugin,
|
|
182
|
+
subject,
|
|
183
|
+
"callback cancelled",
|
|
184
|
+
)
|
|
185
|
+
try:
|
|
186
|
+
child.start()
|
|
187
|
+
started = True
|
|
188
|
+
except (OSError, TypeError, AttributeError, PicklingError) as error:
|
|
189
|
+
return Refusal(
|
|
190
|
+
RefusalCode.CALLBACK_FAILED,
|
|
191
|
+
plugin,
|
|
192
|
+
subject,
|
|
193
|
+
f"callback could not start: {type(error).__name__}",
|
|
194
|
+
)
|
|
195
|
+
finally:
|
|
196
|
+
writer.close()
|
|
197
|
+
data = bytearray()
|
|
198
|
+
while not cancelled.is_set():
|
|
199
|
+
left = deadline - monotonic()
|
|
200
|
+
if left <= 0:
|
|
201
|
+
return Refusal(
|
|
202
|
+
RefusalCode.CALLBACK_TIMEOUT,
|
|
203
|
+
plugin,
|
|
204
|
+
subject,
|
|
205
|
+
"read-only callback exceeded its deadline",
|
|
206
|
+
expected=round(self._timeout_s * 1000),
|
|
207
|
+
)
|
|
208
|
+
assert child.pid is not None
|
|
209
|
+
measured = resident_bytes(child.pid)
|
|
210
|
+
if measured is None and child.is_alive():
|
|
211
|
+
return Refusal(
|
|
212
|
+
RefusalCode.CALLBACK_FAILED,
|
|
213
|
+
plugin,
|
|
214
|
+
subject,
|
|
215
|
+
"callback memory accounting unavailable",
|
|
216
|
+
)
|
|
217
|
+
if measured is not None and measured > MAX_WORKER_RESIDENT_BYTES:
|
|
218
|
+
return Refusal(
|
|
219
|
+
RefusalCode.CALLBACK_BUDGET,
|
|
220
|
+
plugin,
|
|
221
|
+
subject,
|
|
222
|
+
"callback resident memory exceeds its budget",
|
|
223
|
+
expected=MAX_WORKER_RESIDENT_BYTES,
|
|
224
|
+
actual=measured,
|
|
225
|
+
)
|
|
226
|
+
reader.settimeout(min(left, _CANCEL_CHECK_SECONDS))
|
|
227
|
+
try:
|
|
228
|
+
chunk = reader.recv(65536)
|
|
229
|
+
except TimeoutError:
|
|
230
|
+
continue
|
|
231
|
+
except OSError as error:
|
|
232
|
+
return Refusal(
|
|
233
|
+
RefusalCode.CALLBACK_FAILED,
|
|
234
|
+
plugin,
|
|
235
|
+
subject,
|
|
236
|
+
f"callback result transport failed: {type(error).__name__}",
|
|
237
|
+
)
|
|
238
|
+
if not chunk:
|
|
239
|
+
if not data:
|
|
240
|
+
return Refusal(
|
|
241
|
+
RefusalCode.CALLBACK_FAILED,
|
|
242
|
+
plugin,
|
|
243
|
+
subject,
|
|
244
|
+
"callback exited without a result",
|
|
245
|
+
)
|
|
246
|
+
try:
|
|
247
|
+
result = decode_result(request, data)
|
|
248
|
+
return cast(Outcome | Refusal, result)
|
|
249
|
+
except CallbackWireError as error:
|
|
250
|
+
return Refusal(
|
|
251
|
+
RefusalCode.OUTPUT_INVALID,
|
|
252
|
+
plugin,
|
|
253
|
+
subject,
|
|
254
|
+
str(error),
|
|
255
|
+
)
|
|
256
|
+
data.extend(chunk)
|
|
257
|
+
if len(data) > MAX_RESULT_BYTES:
|
|
258
|
+
return Refusal(
|
|
259
|
+
RefusalCode.OUTPUT_INVALID,
|
|
260
|
+
plugin,
|
|
261
|
+
subject,
|
|
262
|
+
"callback exceeded its result byte budget",
|
|
263
|
+
expected=MAX_RESULT_BYTES,
|
|
264
|
+
)
|
|
265
|
+
return Refusal(RefusalCode.CALLBACK_CANCELLED, plugin, subject, "callback cancelled")
|
|
266
|
+
finally:
|
|
267
|
+
reader.close()
|
|
268
|
+
writer.close()
|
|
269
|
+
if started:
|
|
270
|
+
if child.is_alive():
|
|
271
|
+
try:
|
|
272
|
+
child.kill()
|
|
273
|
+
except ProcessLookupError:
|
|
274
|
+
child.join(0)
|
|
275
|
+
except OSError as error:
|
|
276
|
+
raise _ReapFailed(
|
|
277
|
+
f"callback process {child.pid} could not be terminated"
|
|
278
|
+
) from error
|
|
279
|
+
child.join(_TERMINATION_SECONDS)
|
|
280
|
+
if child.is_alive():
|
|
281
|
+
raise _ReapFailed(f"callback process {child.pid} could not be reaped")
|
|
282
|
+
child.close()
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
class CallbackCache(Generic[T]):
|
|
286
|
+
"""Retain one completed revision and one in-flight request for a surface."""
|
|
287
|
+
|
|
288
|
+
def __init__(self) -> None:
|
|
289
|
+
self._key: object = None
|
|
290
|
+
self._latest: T | Refusal | None = None
|
|
291
|
+
self._future: Future[T | Refusal] | None = None
|
|
292
|
+
self._cancelled = Event()
|
|
293
|
+
|
|
294
|
+
def refresh(
|
|
295
|
+
self,
|
|
296
|
+
key: object,
|
|
297
|
+
submit: Callable[[Event], Future[T | Refusal] | Refusal],
|
|
298
|
+
) -> CallbackState[T]:
|
|
299
|
+
self.collect()
|
|
300
|
+
if self._future is None and self._key != key:
|
|
301
|
+
future = submit(self._cancelled)
|
|
302
|
+
if isinstance(future, Refusal):
|
|
303
|
+
# Capacity may become available; preserve the last real result.
|
|
304
|
+
latest = self._latest if self._latest is not None else future
|
|
305
|
+
return CallbackState(latest, pending=False, refresh_refusal=future)
|
|
306
|
+
self._key = key
|
|
307
|
+
self._future = future
|
|
308
|
+
return CallbackState(self._latest, pending=self._future is not None)
|
|
309
|
+
|
|
310
|
+
def collect(self, *, wait: bool = False) -> T | Refusal | None:
|
|
311
|
+
if self._future is not None and (wait or self._future.done()):
|
|
312
|
+
self._latest = self._future.result()
|
|
313
|
+
self._future = None
|
|
314
|
+
return self._latest
|
|
315
|
+
|
|
316
|
+
def cancel(self) -> None:
|
|
317
|
+
self._cancelled.set()
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Reusable probes for fixture-plugin rendering and fault isolation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
from .contracts import Health, Refusal, RefusalCode
|
|
9
|
+
from .registry import FixturePlugin
|
|
10
|
+
from .surfaces import RenderedView
|
|
11
|
+
|
|
12
|
+
__all__ = ("RenderWitness", "check_isolation", "check_render")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True, slots=True)
|
|
16
|
+
class RenderWitness:
|
|
17
|
+
view: str
|
|
18
|
+
lines: tuple[str, ...]
|
|
19
|
+
health: tuple[tuple[str, Health], ...]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def check_render(plugin: FixturePlugin, witness: RenderWitness) -> None:
|
|
23
|
+
"""Compare a rendered fixture against an exact transcript and health witness."""
|
|
24
|
+
output = plugin.await_render(witness.view)
|
|
25
|
+
expected = RenderedView(witness.lines, witness.health)
|
|
26
|
+
if output != expected:
|
|
27
|
+
raise AssertionError(
|
|
28
|
+
f"{plugin.manifest.id}/{witness.view}: expected {expected!r}, got {output!r}"
|
|
29
|
+
)
|
|
30
|
+
if any(not line.isprintable() for line in witness.lines if line):
|
|
31
|
+
raise AssertionError(
|
|
32
|
+
f"{plugin.manifest.id}/{witness.view}: witness contains terminal controls"
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def check_isolation(
|
|
37
|
+
poison: Callable[[], object],
|
|
38
|
+
unaffected: Callable[[], object],
|
|
39
|
+
*,
|
|
40
|
+
expected_refusal: RefusalCode = RefusalCode.CALLBACK_FAILED,
|
|
41
|
+
) -> None:
|
|
42
|
+
"""Prove a named refusal and that a separate surface retains its known-good result."""
|
|
43
|
+
before = unaffected()
|
|
44
|
+
if isinstance(before, Refusal):
|
|
45
|
+
raise AssertionError(f"baseline surface already refused: {before!r}") # noqa: TRY004
|
|
46
|
+
refusal = poison()
|
|
47
|
+
if not isinstance(refusal, Refusal) or refusal.code is not expected_refusal:
|
|
48
|
+
raise AssertionError(f"expected {expected_refusal.value}, got {refusal!r}")
|
|
49
|
+
after = unaffected()
|
|
50
|
+
if after != before:
|
|
51
|
+
raise AssertionError(f"poison affected a sibling surface: {before!r} -> {after!r}")
|