"""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) == []