Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion packages/syft-bg/src/syft_bg/api/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -538,7 +538,9 @@ def set_policies(
)
except (ApiNotFoundError, ValueError) as e:
return ApiResult(success=False, error=str(e))
return ApiResult.from_api(name, obj)
result = ApiResult.from_api(name, obj)
result.state_cleared = reset_state
return result


def run_policy(
Expand Down
12 changes: 12 additions & 0 deletions packages/syft-bg/src/syft_bg/api/results.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,8 @@ class ApiResult(BaseModel):
file_paths: list[str] = Field(default_factory=list)
peers: list[str] = Field(default_factory=list)
policies: list[str] = Field(default_factory=list) # e.g. ["input", "output"]
args: list[str] = Field(default_factory=list) # e.g. ["a: int = 1"]
state_cleared: bool = False # set_policies() cleared the api's state
error: str | None = None

@classmethod
Expand All @@ -306,6 +308,7 @@ def from_api(cls, name: str, obj: ApiDefinition) -> ApiResult:
file_paths=obj.file_paths,
peers=obj.peers,
policies=policies,
args=[a.describe() for a in obj.args],
)

def __repr__(self) -> str:
Expand All @@ -318,14 +321,23 @@ def __repr__(self) -> str:
lines.append(f" - {s}")
if self.file_paths:
lines.append(f" file_paths: {', '.join(self.file_paths)}")
if self.args:
lines.append(" args:")
for a in self.args:
lines.append(f" - {a}")
if self.peers:
lines.append(f" peers: {', '.join(self.peers)}")
else:
lines.append(" peers: (any)")
if self.policies:
lines.append(f" policies: {', '.join(self.policies)}")
if self.state_cleared:
lines.append(" state: cleared (pass reset_state=False to keep it)")
else:
lines.append("ApiResult: FAILED")
if self.error:
lines.append(f" error: {self.error}")
return "\n".join(lines)

def __str__(self) -> str:
return self.__repr__()
5 changes: 5 additions & 0 deletions packages/syft-enclave/src/syft_enclaves/enclave_job_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,11 @@ def update_read_permissions(
self._save_own_approval(approval)
return approved

def _log_release_hint(self, log_file: str) -> str:
"""The data owners release a log by requesting it, see ``request_log``."""
method = "request_stderr" if log_file == "stderr.txt" else "request_stdout"
return f"The data owners can release it with {method}."

def request_log(
self,
log_file: str,
Expand Down
18 changes: 18 additions & 0 deletions packages/syft-enclave/tests/test_read_permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -956,6 +956,24 @@ def test_one_owner_requesting_log_shares_nothing():
assert not has_file(ds, "stderr.txt")


def test_unshared_log_points_to_log_requests():
enclave, do1, do2, ds = run_crash_sharing_nothing()

job = ds.jobs["j"]
not_shared_message = (
"stderr.txt is not shared with you. "
"The data owners can release it with request_stderr."
)
assert str(job.stderr) == not_shared_message
assert not_shared_message in job.stderr._repr_html_()
assert str(job.stdout) == (
"stdout.txt is not shared with you. "
"The data owners can release it with request_stdout."
)
# The enclave ran the job, so it has the log.
assert "ValueError" in str(enclave.jobs["j"].stderr)


def test_log_request_defaults_to_data_owners():
enclave, do1, do2, ds = run_crash_sharing_nothing()
for do in (do1, do2):
Expand Down
21 changes: 21 additions & 0 deletions packages/syft-job/src/syft_job/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,27 @@ def _log_path(self, log_file: str) -> Path:
"""Where the viewers read ``log_file`` ("stdout.txt" or "stderr.txt")."""
return self.job_review_path / log_file

def _missing_log_message(self, log_file: str) -> str:
"""What to tell a reader who has no ``log_file`` of this finished job.

The datasite owner keeps every log the job wrote. Anyone else reads a
log only once it is shared with them.
"""
if self.current_user_email == self.datasite_owner_email:
return f"No {Path(log_file).stem} file found"
if self.policy_error:
# The policy may have refused the call before it ran, so the log
# may not exist.
return (
f"{log_file} is not shared with you: the data owner's policy "
"refused the call. The reason is in job.policy_error."
)
return f"{log_file} is not shared with you. {self._log_release_hint(log_file)}"

def _log_release_hint(self, log_file: str) -> str:
"""Who can share ``log_file`` with a reader who does not have it."""
return "The data owner can share it with share_job_results."

@property
def files(self) -> List[Path]:
"""Get list of relevant files across both inbox and review."""
Expand Down
27 changes: 24 additions & 3 deletions packages/syft-job/src/syft_job/job_repr.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import json
import re
from html import escape
from typing import TYPE_CHECKING, List
Expand Down Expand Up @@ -66,7 +67,7 @@ def __str__(self) -> str:
stderr_file = self.job_info._log_path("stderr.txt")

if not stderr_file.exists():
return "No stderr file found"
return self.job_info._missing_log_message("stderr.txt")

try:
with open(stderr_file, "r") as f:
Expand Down Expand Up @@ -98,7 +99,7 @@ def _repr_html_(self) -> str:
stderr_file = self.job_info._log_path("stderr.txt")

if not stderr_file.exists():
error_msg = "No stderr file found"
error_msg = escape(self.job_info._missing_log_message("stderr.txt"))
else:
try:
with open(stderr_file, "r") as f:
Expand Down Expand Up @@ -431,6 +432,8 @@ def job_info_repr_html(job: "JobInfo") -> str:
except Exception:
pass

params_section = _params_html(job)

status_emoji_map = {
"received": "📨",
"pending": "📥",
Expand Down Expand Up @@ -741,7 +744,7 @@ def job_info_repr_html(job: "JobInfo") -> str:
<div class="syftjob-single-section">
<h4>📜 Script</h4>
<div class="syftjob-single-script">{script_content}</div>
</div>{code_section}{policy_section}{outputs_section}
</div>{code_section}{params_section}{policy_section}{outputs_section}
</div>
</div>
"""
Expand All @@ -758,6 +761,24 @@ def _detail_html(label: str, value: str) -> str:
</div>"""


def _params_html(job: "JobInfo") -> str:
"""A section with code/params.json, the arguments the job runs with."""
try:
params = (job.code_dir / "params.json").read_text()
except (OSError, ValueError):
return ""
try:
params = json.dumps(json.loads(params), indent=2, ensure_ascii=False)
except ValueError:
pass # not JSON: show it as it is
return f"""
<div class="syftjob-single-section">
<h4>Parameters</h4>
<div class="syftjob-single-filename">code/params.json</div>
<div class="syftjob-single-code">{escape(params)}</div>
</div>"""


def _policy_html(job: "JobInfo") -> tuple[str, str]:
"""Detail rows (api, policy error) and a section with the policies' code."""
details = ""
Expand Down
5 changes: 3 additions & 2 deletions packages/syft-job/src/syft_job/job_stdout.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import html
import re
from html import escape
from typing import TYPE_CHECKING

if TYPE_CHECKING:
Expand Down Expand Up @@ -75,7 +76,7 @@ def __str__(self) -> str:
stdout_file = self.job_info._log_path("stdout.txt")

if not stdout_file.exists():
return "No stdout file found"
return self.job_info._missing_log_message("stdout.txt")

try:
with open(stdout_file, "r") as f:
Expand Down Expand Up @@ -108,7 +109,7 @@ def _repr_html_(self) -> str:
stdout_file = self.job_info._log_path("stdout.txt")

if not stdout_file.exists():
error_msg = "No stdout file found"
error_msg = escape(self.job_info._missing_log_message("stdout.txt"))
else:
try:
with open(stdout_file, "r") as f:
Expand Down
36 changes: 36 additions & 0 deletions packages/syft-job/tests/test_policies.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Api calls (requests), and the input and output policies run around them."""

import json
from html import escape
from pathlib import Path

import pytest
Expand Down Expand Up @@ -290,6 +291,26 @@ def test_timed_out_api_call_shares_nothing(env):
assert not env.reads(DS_EMAIL, "call.job", "returncode.txt")


def test_unshared_log_says_not_shared(env):
"""A reader without a log is told it is not shared, not that none exists."""
job = env.call("echo private; exit 3")
assert not env.reads(DS_EMAIL, "call.job", "stderr.txt")
# The DS and the DO share one SyftBox here: the DS would not have the logs.
for log_file in ("stdout.txt", "stderr.txt"):
(job.job_review_path / log_file).unlink()

not_shared_message = (
"stderr.txt is not shared with you. "
"The data owner can share it with share_job_results."
)
ds_job = _ds_job(env)
assert str(ds_job.stderr) == not_shared_message
assert not_shared_message in ds_job.stderr._repr_html_()
assert str(ds_job.stdout).startswith("stdout.txt is not shared with you.")
# The data owner keeps every log, so a missing one was never written.
assert str(job.stderr) == "No stderr file found"


def test_output_policy_with_bad_read_permissions_denies(env):
env.apis.output_code = _read_permissions_policy(["not", "a", "dict"])

Expand Down Expand Up @@ -346,6 +367,21 @@ def test_api_call_ignores_share_flags(env):
assert job.outputs_withheld


def test_job_view_shows_params_escaped(env):
(env.apis.files_dir / "run.sh").write_text("echo hi\n")
params = {"code/params.json": b'{"word": "<b>privacy</b>", "n": 3}'}
env.ds_client.submit_api_request(DO_EMAIL, "call.job", API_NAME, params)
env.ds_client.submit_bash_job(DO_EMAIL, "echo hi", "plain.job")

html = env.do_job("call.job")._repr_html_()

assert "<h4>Parameters</h4>" in html
pretty_params = '{\n "word": "<b>privacy</b>",\n "n": 3\n}'
assert escape(pretty_params) in html and "<b>privacy</b>" not in html
# A job without code/params.json has no such section.
assert "<h4>Parameters</h4>" not in env.do_job("plain.job")._repr_html_()


def test_request_becomes_approved_job_with_api_code(env):
job = env.call("cp code/params.json code/outputs/params.json")

Expand Down
15 changes: 13 additions & 2 deletions packages/syft-rds/src/syft_rds/apis/repr.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,13 @@ def _args_html(api: Api) -> str:
)


def _policy_kinds(api: Api) -> str:
"""The policies the api has, e.g. "input, output", or "-"."""
definition = api.definition
kinds = [k for k in ("input", "output") if getattr(definition, f"{k}_policy")]
return ", ".join(kinds) or "-"


def _row_html(index: int, api: Api) -> str:
call = escape(api.call_signature)
code = escape(api.python_file or "-")
Expand All @@ -67,6 +74,7 @@ def _row_html(index: int, api: Api) -> str:
f'<td class="syftapi-td syftapi-name">{escape(api.name)}</td>'
f'<td class="syftapi-td">{escape(api.datasite)}</td>'
f'<td class="syftapi-td">{_args_html(api)}</td>'
f'<td class="syftapi-td">{escape(_policy_kinds(api))}</td>'
f'<td class="syftapi-td syftapi-code">{code}</td>'
f'<td class="syftapi-td syftapi-code">{call}</td>'
"</tr>"
Expand All @@ -76,7 +84,7 @@ def _row_html(index: int, api: Api) -> str:
def api_collection_repr_html(apis: Sequence[Api]) -> str:
if not apis:
return _EMPTY_HTML
headers = ["#", "Name", "Datasite", "Args", "Code", "Call"]
headers = ["#", "Name", "Datasite", "Args", "Policies", "Code", "Call"]
head = "".join(f'<th class="syftapi-th">{h}</th>' for h in headers)
rows = "".join(_row_html(i, api) for i, api in enumerate(apis))
return f"""{_STYLE}
Expand All @@ -97,7 +105,10 @@ def api_collection_repr_str(apis: Sequence[Api]) -> str:
lines = [f"Apis ({len(apis)}):"]
for i, api in enumerate(apis):
call = api.call_signature
lines.append(f" [{i}] {api.name} (from {api.datasite}) -> {call}")
policies = _policy_kinds(api)
lines.append(
f" [{i}] {api.name} (from {api.datasite}) -> {call} | policies: {policies}"
)
return "\n".join(lines)


Expand Down
12 changes: 11 additions & 1 deletion packages/syft-rds/src/syft_rds/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,16 @@ def _peer_schema_lookup(
return lambda email: peer_store.protocol_schema(email, protocol_name)


def _print_call_result(job: Any) -> None:
"""Report how the job of a blocking api call ended, and why a policy stopped it."""
print(f"Job '{job.name}' finished with status: {job.status}")
if job.policy_error:
print(f" The data owner's policy refused the call: {job.policy_error}")
elif job.status == "done" and job.outputs_withheld:
print(" The data owner's output policy held the outputs back.")
print(" The data owner can still share them with you later.")


class SyftRDSClient(BaseModel):
# Holds live service objects (sync engine + RDS-owned managers), not
# serializable data, so arbitrary types are allowed.
Expand Down Expand Up @@ -550,7 +560,7 @@ def _wait_for_call(self, job_name: str, poll_interval: float = 2.0) -> Any:
self.sync_engine.sync()
job = _named(self.job_client.jobs, job_name)
if job is not None and job.status in FINISHED_JOB_STATUSES:
print(f"Job '{job_name}' finished with status: {job.status}")
_print_call_result(job)
return job
request = _named(self.job_client.requests, job_name)
if request is not None and request.status == "rejected":
Expand Down
Loading
Loading