Skip to content

Commit 0a5d306

Browse files
atlaieclaude
andcommitted
feat: clearer messages when an api call is refused or held back
- output_paths points to job.policy_error when a policy refused the call, and says when the output policy held the outputs back - a blocking api call prints why it ended (_print_call_result) - the api table has a Policies column - ApiResult shows the api's args and when set_policies cleared its state; print(result) shows the same text as repr - the job view shows code/params.json in a Parameters section Messages and displays only; no behaviour changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 1613a71 commit 0a5d306

9 files changed

Lines changed: 233 additions & 11 deletions

File tree

‎packages/syft-bg/src/syft_bg/api/api.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -512,7 +512,9 @@ def set_policies(
512512
)
513513
except (ApiNotFoundError, ValueError) as e:
514514
return ApiResult(success=False, error=str(e))
515-
return ApiResult.from_api(name, obj)
515+
result = ApiResult.from_api(name, obj)
516+
result.state_cleared = reset_state
517+
return result
516518

517519

518520
def run_policy(

‎packages/syft-bg/src/syft_bg/api/results.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,8 @@ class ApiResult(BaseModel):
294294
file_paths: list[str] = Field(default_factory=list)
295295
peers: list[str] = Field(default_factory=list)
296296
policies: list[str] = Field(default_factory=list) # e.g. ["input", "output"]
297+
args: list[str] = Field(default_factory=list) # e.g. ["a: int = 1"]
298+
state_cleared: bool = False # set_policies() cleared the api's state
297299
error: str | None = None
298300

299301
@classmethod
@@ -306,6 +308,7 @@ def from_api(cls, name: str, obj: ApiDefinition) -> ApiResult:
306308
file_paths=obj.file_paths,
307309
peers=obj.peers,
308310
policies=policies,
311+
args=[a.describe() for a in obj.args],
309312
)
310313

311314
def __repr__(self) -> str:
@@ -318,14 +321,23 @@ def __repr__(self) -> str:
318321
lines.append(f" - {s}")
319322
if self.file_paths:
320323
lines.append(f" file_paths: {', '.join(self.file_paths)}")
324+
if self.args:
325+
lines.append(" args:")
326+
for a in self.args:
327+
lines.append(f" - {a}")
321328
if self.peers:
322329
lines.append(f" peers: {', '.join(self.peers)}")
323330
else:
324331
lines.append(" peers: (any)")
325332
if self.policies:
326333
lines.append(f" policies: {', '.join(self.policies)}")
334+
if self.state_cleared:
335+
lines.append(" state: cleared (pass reset_state=False to keep it)")
327336
else:
328337
lines.append("ApiResult: FAILED")
329338
if self.error:
330339
lines.append(f" error: {self.error}")
331340
return "\n".join(lines)
341+
342+
def __str__(self) -> str:
343+
return self.__repr__()

‎packages/syft-job/src/syft_job/job.py‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -280,10 +280,13 @@ def _list_output_files() -> List[Path]:
280280
if status == JobStatus.FAILED:
281281
partial = _list_output_files()
282282
print(f"❌ Job '{self.name}' failed (status: {self.status}).")
283-
print(
284-
f" Returning {len(partial)} partial output file(s). "
285-
"Check stderr for details: job.stderr"
286-
)
283+
policy_error = self.policy_error
284+
if policy_error:
285+
print(f" The data owner's policy refused the call: {policy_error}")
286+
hint = "The reason is in job.policy_error."
287+
else:
288+
hint = "Check stderr for details: job.stderr"
289+
print(f" Returning {len(partial)} partial output file(s). {hint}")
287290
return partial
288291

289292
if status != JobStatus.DONE:
@@ -294,7 +297,11 @@ def _list_output_files() -> List[Path]:
294297
output_files = _list_output_files()
295298
if not output_files:
296299
print(f"⚠️ Job '{self.name}' is done but no output files were found.")
297-
print(" The job script may not have written to the outputs/ folder.")
300+
if self.outputs_withheld:
301+
print(" The data owner's output policy held the outputs back.")
302+
print(" The data owner can still share them with you later.")
303+
else:
304+
print(" The job script may not have written to the outputs/ folder.")
298305
return []
299306

300307
return output_files

‎packages/syft-job/src/syft_job/job_repr.py‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
import json
34
import re
45
from html import escape
56
from typing import TYPE_CHECKING, List
@@ -428,6 +429,8 @@ def job_info_repr_html(job: "JobInfo") -> str:
428429
except Exception:
429430
pass
430431

432+
params_section = _params_html(job)
433+
431434
status_emoji_map = {
432435
"received": "📨",
433436
"pending": "📥",
@@ -743,7 +746,7 @@ def job_info_repr_html(job: "JobInfo") -> str:
743746
<div class="syftjob-single-section">
744747
<h4>📜 Script</h4>
745748
<div class="syftjob-single-script">{script_content}</div>
746-
</div>{code_section}{policy_section}{outputs_section}
749+
</div>{code_section}{params_section}{policy_section}{outputs_section}
747750
</div>
748751
</div>
749752
"""
@@ -757,6 +760,24 @@ def _detail_html(label: str, value: str) -> str:
757760
</div>"""
758761

759762

763+
def _params_html(job: "JobInfo") -> str:
764+
"""A section with code/params.json, the arguments the job runs with."""
765+
try:
766+
params = (job.code_dir / "params.json").read_text()
767+
except (OSError, ValueError):
768+
return ""
769+
try:
770+
params = json.dumps(json.loads(params), indent=2, ensure_ascii=False)
771+
except ValueError:
772+
pass # not JSON: show it as it is
773+
return f"""
774+
<div class="syftjob-single-section">
775+
<h4>Parameters</h4>
776+
<div class="syftjob-single-filename">code/params.json</div>
777+
<div class="syftjob-single-code">{escape(params)}</div>
778+
</div>"""
779+
780+
760781
def _policy_html(job: "JobInfo") -> tuple[str, str]:
761782
"""Detail rows (api, policy error) and a section with the policies' code."""
762783
details = ""

‎packages/syft-job/tests/test_policies.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Api calls (requests), and the input and output policies run around them."""
22

33
import json
4+
from html import escape
45
from pathlib import Path
56

67
import pytest
@@ -253,6 +254,21 @@ def test_empty_recipients_hold_outputs_back(env):
253254
assert not job.outputs_withheld
254255

255256

257+
def test_job_view_shows_params_escaped(env):
258+
(env.apis.files_dir / "run.sh").write_text("echo hi\n")
259+
params = {"code/params.json": b'{"word": "<b>privacy</b>", "n": 3}'}
260+
env.ds_client.submit_api_request(DO_EMAIL, "call.job", API_NAME, params)
261+
env.ds_client.submit_bash_job(DO_EMAIL, "echo hi", "plain.job")
262+
263+
html = env.do_job("call.job")._repr_html_()
264+
265+
assert "<h4>Parameters</h4>" in html
266+
pretty = '{\n "word": "<b>privacy</b>",\n "n": 3\n}'
267+
assert escape(pretty) in html and "<b>privacy</b>" not in html
268+
# A job without code/params.json has no such section.
269+
assert "<h4>Parameters</h4>" not in env.do_job("plain.job")._repr_html_()
270+
271+
256272
def test_request_becomes_approved_job_with_api_code(env):
257273
job = env.call("cp code/params.json code/outputs/params.json")
258274

‎packages/syft-rds/src/syft_rds/apis/repr.py‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,13 @@ def _args_html(api: Api) -> str:
5858
)
5959

6060

61+
def _policy_kinds(api: Api) -> str:
62+
"""The policies the api has, e.g. "input, output", or "-"."""
63+
definition = api.definition
64+
kinds = [k for k in ("input", "output") if getattr(definition, f"{k}_policy")]
65+
return ", ".join(kinds) or "-"
66+
67+
6168
def _row_html(index: int, api: Api) -> str:
6269
call = escape(api.call_signature)
6370
code = escape(api.python_file or "-")
@@ -67,6 +74,7 @@ def _row_html(index: int, api: Api) -> str:
6774
f'<td class="syftapi-td syftapi-name">{escape(api.name)}</td>'
6875
f'<td class="syftapi-td">{escape(api.datasite)}</td>'
6976
f'<td class="syftapi-td">{_args_html(api)}</td>'
77+
f'<td class="syftapi-td">{escape(_policy_kinds(api))}</td>'
7078
f'<td class="syftapi-td syftapi-code">{code}</td>'
7179
f'<td class="syftapi-td syftapi-code">{call}</td>'
7280
"</tr>"
@@ -76,7 +84,7 @@ def _row_html(index: int, api: Api) -> str:
7684
def api_collection_repr_html(apis: Sequence[Api]) -> str:
7785
if not apis:
7886
return _EMPTY_HTML
79-
headers = ["#", "Name", "Datasite", "Args", "Code", "Call"]
87+
headers = ["#", "Name", "Datasite", "Args", "Policies", "Code", "Call"]
8088
head = "".join(f'<th class="syftapi-th">{h}</th>' for h in headers)
8189
rows = "".join(_row_html(i, api) for i, api in enumerate(apis))
8290
return f"""{_STYLE}
@@ -97,7 +105,10 @@ def api_collection_repr_str(apis: Sequence[Api]) -> str:
97105
lines = [f"Apis ({len(apis)}):"]
98106
for i, api in enumerate(apis):
99107
call = api.call_signature
100-
lines.append(f" [{i}] {api.name} (from {api.datasite}) -> {call}")
108+
policies = _policy_kinds(api)
109+
lines.append(
110+
f" [{i}] {api.name} (from {api.datasite}) -> {call} | policies: {policies}"
111+
)
101112
return "\n".join(lines)
102113

103114

‎packages/syft-rds/src/syft_rds/client.py‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,16 @@ def _print_skipped_jobs(skipped: list[tuple[str, str, str]]) -> None:
109109
print(" Pass ignore_peer_version=True to run them anyway.")
110110

111111

112+
def _print_call_result(job: Any) -> None:
113+
"""Report how the job of a blocking api call ended, and why a policy stopped it."""
114+
print(f"Job '{job.name}' finished with status: {job.status}")
115+
if job.policy_error:
116+
print(f" The data owner's policy refused the call: {job.policy_error}")
117+
elif job.status == "done" and job.outputs_withheld:
118+
print(" The data owner's output policy held the outputs back.")
119+
print(" The data owner can still share them with you later.")
120+
121+
112122
class SyftRDSClient(BaseModel):
113123
# Holds live service objects (sync engine + RDS-owned managers), not
114124
# serializable data, so arbitrary types are allowed.
@@ -502,7 +512,7 @@ def _wait_for_call(self, job_name: str, poll_interval: float = 2.0) -> Any:
502512
self.sync_engine.sync()
503513
job = _named(self.job_client.jobs, job_name)
504514
if job is not None and job.status in FINISHED_JOB_STATUSES:
505-
print(f"Job '{job_name}' finished with status: {job.status}")
515+
_print_call_result(job)
506516
return job
507517
request = _named(self.job_client.requests, job_name)
508518
if request is not None and request.status == "rejected":

‎packages/syft-rds/tests/test_api_policies.py‎

Lines changed: 101 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@
1111
from syft_bg.approve.handlers.job import ApprovedJobHandler
1212
from syft_bg.common.config import get_default_paths
1313
from syft_rds import SyftRDSClient
14+
from syft_rds.apis import Api, ApiDefinition, FileEntry
15+
from syft_rds.apis.repr import api_collection_repr_html, api_collection_repr_str
16+
from syft_rds.client import _print_call_result
1417

1518
ADDER_CODE = """import json
1619
with open("params.json") as f:
@@ -37,6 +40,12 @@
3740
raise ValueError("Sum too large to share")
3841
"""
3942

43+
# Shares the outputs with no one.
44+
HOLD_BACK_POLICY = """import os
45+
from pathlib import Path
46+
Path(os.environ["SYFT_POLICY_RECIPIENTS_PATH"]).write_text("[]")
47+
"""
48+
4049

4150
@contextmanager
4251
def _temp_config_paths():
@@ -92,7 +101,7 @@ def _ds_job(ds_manager, name: str):
92101
return next(j for j in ds_manager.jobs if j.name == name)
93102

94103

95-
def test_api_policies_allow_block_and_show():
104+
def test_api_policies_allow_block_and_show(capsys):
96105
ds_manager, do_manager = SyftRDSClient.pair_with_mock_drive_service_connection(
97106
use_in_memory_cache=False,
98107
sync_automatically=False,
@@ -109,6 +118,11 @@ def test_api_policies_allow_block_and_show():
109118

110119
do_manager.sync()
111120
ds_manager.sync()
121+
# The api table says which policies an api has.
122+
assert "client.api.adder(a, b) | policies: input, output" in str(ds_manager.api)
123+
table = ds_manager.api._repr_html_()
124+
assert '<th class="syftapi-th">Policies</th>' in table
125+
assert '<td class="syftapi-td">input, output</td>' in table
112126
api = ds_manager.api.adder
113127
assert "Rate limit reached" in repr(api)
114128
assert "Sum too large to share" in api._repr_html_()
@@ -126,14 +140,34 @@ def test_api_policies_allow_block_and_show():
126140
blocked = _ds_job(ds_manager, large.name)
127141
assert blocked.status == "failed"
128142
assert blocked.policy_error == "ValueError: Sum too large to share"
143+
capsys.readouterr()
129144
assert blocked.output_paths == []
145+
# The DS is sent to the policy's reason, not to a stderr they don't get.
146+
out = capsys.readouterr().out
147+
assert (
148+
"The data owner's policy refused the call: "
149+
"ValueError: Sum too large to share" in out
150+
)
151+
assert "job.policy_error" in out and "job.stderr" not in out
152+
_print_call_result(blocked)
153+
assert capsys.readouterr().out == (
154+
f"Job '{large.name}' finished with status: failed\n"
155+
" The data owner's policy refused the call: "
156+
"ValueError: Sum too large to share\n"
157+
)
130158

131159
# The rate limit of one call is used up.
132160
second = api(1, b=2, block=False)
133161
_run_calls(do_manager, paths.config)
134162
limited = _ds_job(ds_manager, second.name)
135163
assert limited.status == "failed"
136164
assert limited.policy_error == "ValueError: Rate limit reached: 1 call"
165+
capsys.readouterr()
166+
_print_call_result(limited)
167+
assert (
168+
"refused the call: ValueError: Rate limit reached: 1 call"
169+
in capsys.readouterr().out
170+
)
137171

138172
# The DO's view of a call shows the api and its policies.
139173
do_job = next(j for j in do_manager.jobs if j.name == large.name)
@@ -142,3 +176,69 @@ def test_api_policies_allow_block_and_show():
142176
assert "adder" in html and "Input policy" in html and "Output policy" in html
143177
original = next(j for j in do_manager.jobs if j.name == job.name)
144178
assert original.status == "pending"
179+
180+
181+
def test_held_back_outputs_point_to_the_policy(capsys):
182+
ds_manager, do_manager = SyftRDSClient.pair_with_mock_drive_service_connection(
183+
use_in_memory_cache=False,
184+
sync_automatically=False,
185+
)
186+
job = _submit_adder_job(ds_manager, do_manager, {"a": 1, "b": 2})
187+
188+
with _temp_config_paths() as (paths, tmp):
189+
result = create_api_from_job(
190+
job, output_policy=_write(tmp / "hold_back.py", HOLD_BACK_POLICY)
191+
)
192+
assert result.success
193+
do_manager.sync()
194+
ds_manager.sync()
195+
call = ds_manager.api.adder(1, b=2, block=False)
196+
_run_calls(do_manager, paths.config)
197+
held = _ds_job(ds_manager, call.name)
198+
199+
assert held.status == "done" and held.outputs_withheld
200+
capsys.readouterr()
201+
assert held.output_paths == []
202+
# The DS is told the policy held the outputs back, not that the script
203+
# wrote none.
204+
out = capsys.readouterr().out
205+
assert "The data owner's output policy held the outputs back." in out
206+
assert "The data owner can still share them with you later." in out
207+
assert "may not have written" not in out
208+
_print_call_result(held)
209+
assert capsys.readouterr().out == (
210+
f"Job '{call.name}' finished with status: done\n"
211+
" The data owner's output policy held the outputs back.\n"
212+
" The data owner can still share them with you later.\n"
213+
)
214+
215+
216+
def _policy_entry(kind: str) -> list[FileEntry]:
217+
return [FileEntry(relative_path=f"policies/{kind}/run.sh", hash="sha256:0")]
218+
219+
220+
def test_api_table_shows_policies(tmp_path):
221+
definitions = {
222+
"plain": ApiDefinition(),
223+
"checked": ApiDefinition(input_policy=_policy_entry("input")),
224+
"filtered": ApiDefinition(output_policy=_policy_entry("output")),
225+
"both": ApiDefinition(
226+
input_policy=_policy_entry("input"),
227+
output_policy=_policy_entry("output"),
228+
),
229+
}
230+
apis = [
231+
Api(name, "do@test.org", tmp_path, definition, client=None)
232+
for name, definition in definitions.items()
233+
]
234+
235+
lines = api_collection_repr_str(apis).splitlines()[1:]
236+
assert [line.split(" | ")[1] for line in lines] == [
237+
"policies: -",
238+
"policies: input",
239+
"policies: output",
240+
"policies: input, output",
241+
]
242+
html = api_collection_repr_html(apis)
243+
for policies in ("-", "input", "output", "input, output"):
244+
assert f'<td class="syftapi-td">{policies}</td>' in html

0 commit comments

Comments
 (0)