Spaces:
Running
Running
File size: 9,809 Bytes
a656c82 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 | """Arithmetic the agent does not have to do in its head, and the fence.
THE GAP. read_result let Turing SEE its twenty guides. It still could not
average them β no tool computes a mean, a threshold count or a spread. So
the model does it mentally and writes the answer down as a finding, and
mental arithmetic over twenty rows is wrong often enough to matter. It is
wrong *invisibly*: a guessed number and a computed one read identically.
WHY THIS IS NOT A SHELL. The audit that asked for this said plainly that
Turing should not be given one β a bioinformatics agent with arbitrary
execution on the server is a different product with a different threat
model, and the value here was never "run anything", it was "do this sum
correctly". So the fence is structural rather than a denylist:
Β· no Attribute node at all. Every published escape of this shape goes
through an attribute (`().__class__.__bases__`, `x.__globals__`,
`"".join.__self__`). Removing the node removes the route, instead of
blocking today's spellings of it.
Β· no builtins, and only the dozen callables bound by name.
Β· nothing that can MAKE a large iterable: no range, no `**`. The only
data in scope is what this run's own tools returned, so an expression
is bounded by the data rather than by a timeout we would have to
enforce by killing a thread we cannot kill.
Β· a node budget, so a pathological nest is refused before it runs.
The escape suite at the bottom is the real test of all that.
"""
import pytest
from dee.core import analysis as A, orchestrator as O
GUIDES = [{"rank": i + 1,
"on_target_score": round(0.95 - i * 0.04, 3),
"gc_pct": 45 + i * 2,
"notes": ""} for i in range(20)]
SCOPE = {"guides": GUIDES}
def _val(expr, scope=None):
return A.evaluate(expr, scope if scope is not None else SCOPE)[0]
# ββ the arithmetic it was built for βββββββββββββββββββββββββββββββββββ
def test_the_mean_it_used_to_do_in_its_head():
assert _val("round(mean([g['on_target_score'] for g in guides[:5]]), 3)") == 0.87
def test_counting_rows_past_a_threshold():
assert _val("len([g for g in guides if g['gc_pct'] > 60])") == 12
def test_a_percentage_without_a_division_mistake():
assert _val("pct(len([g for g in guides if g['on_target_score'] > 0.8]), "
"len(guides))") == 20.0
def test_spread_and_extremes():
assert _val("max(g['gc_pct'] for g in guides) - "
"min(g['gc_pct'] for g in guides)") == 38
assert _val("round(stdev([g['gc_pct'] for g in guides]), 2)") == 11.83
def test_ranking_without_a_lambda():
"""sorted_by exists so the evaluator never has to allow Lambda."""
assert _val("[g['rank'] for g in sorted_by(guides, 'gc_pct', True)[:3]]") \
== [20, 19, 18]
def test_a_missing_column_sorts_last_rather_than_raising():
"""A heterogeneous table is a data fact, not a user error."""
rows = [{"a": 2}, {"b": 1}, {"a": 1}]
assert _val("[r['a'] for r in sorted_by(rows, 'a')[:2]]", {"rows": rows}) == [1, 2]
def test_empty_input_gives_nothing_rather_than_a_crash():
assert _val("mean([])", {"rows": []}) is None
assert _val("stdev([1])", {"rows": []}) is None
assert _val("pct(1, 0)", {"rows": []}) is None
# ββ what comes back is bounded ββββββββββββββββββββββββββββββββββββββββ
def test_a_huge_result_is_cut_and_says_so():
"""An expression returning the whole table is a mistake, not an
analysis β read_result is how you read rows."""
rows = [{"i": i} for i in range(500)]
out = _val("[r['i'] for r in rows]", {"rows": rows})
assert len(out) == A.MAX_RESULT_ITEMS + 1
assert "more" in str(out[-1])
def test_the_scope_is_reported_back():
_, names = A.evaluate("len(guides)", SCOPE)
assert names == ["guides"], "the agent is not told what it may refer to"
# ββ refusals a model can act on βββββββββββββββββββββββββββββββββββββββ
def test_an_unknown_name_lists_what_is_in_scope():
"""The same shelf philosophy read_result uses: the useful answer to
'no such name' is the list of real ones."""
with pytest.raises(A.AnalysisError) as exc:
A.evaluate("len(primers)", SCOPE)
assert "guides" in str(exc.value) and "mean" in str(exc.value)
def test_attribute_access_names_the_alternative():
with pytest.raises(A.AnalysisError) as exc:
A.evaluate("guides.sort()", SCOPE)
assert "sorted_by" in str(exc.value)
def test_a_bad_column_points_at_read_result():
with pytest.raises(A.AnalysisError) as exc:
A.evaluate("[g['nope'] for g in guides]", SCOPE)
assert "read_result" in str(exc.value)
def test_statements_are_refused():
for bad in ("x = 1", "import os", "for g in guides: pass"):
with pytest.raises(A.AnalysisError):
A.evaluate(bad, SCOPE)
def test_an_empty_or_oversized_expression_is_refused():
with pytest.raises(A.AnalysisError):
A.evaluate(" ", SCOPE)
with pytest.raises(A.AnalysisError):
A.evaluate("len(guides) + " * 2000 + "1", SCOPE)
def test_a_pathological_nest_is_refused_before_it_runs():
expr = "len(" * 150 + "guides" + ")" * 150
with pytest.raises(A.AnalysisError) as exc:
A.evaluate(expr, SCOPE)
assert "complex" in str(exc.value) or "node" in str(exc.value).lower()
# ββ the fence βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ESCAPES = [
"().__class__.__bases__[0].__subclasses__()",
"[].__class__.__mro__[1].__subclasses__()",
"().__getattribute__('__class__')",
"guides.__class__",
"getattr(guides, '__class__')",
"__import__('os').system('id')",
"open('/etc/passwd').read()",
"eval('1+1')",
"exec('x=1')",
"compile('1','x','eval')",
"globals()",
"locals()",
"vars()",
"dir()",
"breakpoint()",
"(lambda: 1)()",
"f'{guides}'",
"(y := 5)",
]
@pytest.mark.parametrize("attack", ESCAPES)
def test_it_does_not_escape(attack):
"""Each of these is refused with a message, not a traceback: a raw
exception leaking out is itself a finding about what ran."""
with pytest.raises(A.AnalysisError):
A.evaluate(attack, SCOPE)
RESOURCE = ["10**10**10", "[0]*10**9", "'a'*10**9",
"[x for x in range(10**9)]", "2**2**30"]
@pytest.mark.parametrize("attack", RESOURCE)
def test_it_cannot_allocate_its_way_out(attack):
"""There is no range and no '**', and the only iterables in scope are
the run's own tables β so the bound is the data, not a timeout."""
with pytest.raises(A.AnalysisError):
A.evaluate(attack, SCOPE)
def test_the_node_allowlist_fails_closed():
"""An allow-list, so a Python release that adds a node kind refuses it
rather than quietly permitting it."""
assert A.ast.Attribute not in A._ALLOWED_NODES
assert A.ast.Pow not in A._ALLOWED_NODES
assert A.ast.Lambda not in A._ALLOWED_NODES
assert A.ast.Import not in A._ALLOWED_NODES
# ββ wired into the run ββββββββββββββββββββββββββββββββββββββββββββββββ
def _run():
run = O.Run(run_id="r", owner="u", anonymous=False)
run.events.append({"kind": "tool_result", "id": "c1",
"name": "design_crispr_guides", "ok": True,
"ui": {"panel": {"guides": GUIDES},
"payload": {"guides": GUIDES}}})
return run
def test_the_scope_is_this_runs_own_tables_under_both_names():
scope = O._analysis_scope(_run())
assert scope["guides"] == GUIDES
assert scope["design_crispr_guides"] == GUIDES, (
"the agent has seen the tool name too and either is reasonable to type"
)
def test_it_computes_over_the_very_rows_read_result_shows():
"""Not a second computation that could disagree with the screen."""
run = _run()
assert O._analyze(run, {"expression": "len(guides)"})["value"] == 20
assert O._read_result(run, {"tool": "design_crispr_guides"})["n_rows"] == 20
def test_a_refusal_comes_back_as_a_readable_result_not_an_exception():
out = O._analyze(_run(), {"expression": "guides.__class__"})
assert not out["ok"] and "attribute" in out["error"].lower()
assert out["in_scope"]
def test_the_tool_is_offered_only_once_there_is_a_table():
empty = O.Run(run_id="e", owner="u", anonymous=False)
names = lambda r: [s["function"]["name"] for s in O.active_tool_specs(r)]
assert "analyze" not in names(empty)
assert "analyze" in names(_run())
def test_the_activity_line_shows_the_answer():
""""Computed something" is noise in a transcript; the number is the
whole point of the step."""
run = _run()
O._run_one_tool(run, "analyze", "call_a",
{"expression": "len(guides)", "label": "guides designed"})
ev = [e for e in run.events
if e.get("id") == "call_a" and e["kind"] == "tool_result"][0]
assert ev["summary"] == "guides designed: 20"
assert ev["ui"] is None
def test_re_computing_is_not_metered_as_work():
run = _run()
before = run.tools_run
O._run_one_tool(run, "analyze", "call_a", {"expression": "len(guides)"})
assert run.tools_run == before
def test_it_is_registered_and_categorised():
from dee.core import capabilities
assert "analyze" in [s["function"]["name"] for s in O.TOOL_SPECS]
assert capabilities.uncategorised(O.TOOL_SPECS) == []
|