File size: 14,125 Bytes
0e0e858
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
257
258
259
260
261
262
263
264
265
266
267
268
269
"""Exercise real fold classes and the real combiner without importing the head.

Controlled base replies expose arbitration policy, not specialist panel scores.
"""
import importlib.util
import os
from pathlib import Path
import re
import sys
from types import SimpleNamespace, ModuleType
import unittest
from unittest.mock import Mock, patch

ROOT = Path(__file__).resolve().parents[2]
ADMITTED = ROOT / "root/fable-content/oracle-m-series-2026-08-15/self_loop/admitted"
sys.path.insert(0, str(ADMITTED))
from runtime_refusal_guard import terminal_refusal
sys.path.pop(0)


def load_file(name, path):
    spec = importlib.util.spec_from_file_location(name, path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


COMBO = load_file("test_real_combo", ROOT / "root/specialists/_gate/combo_runtime_v1.py")


def fold(number, parent_number, reply):
    parent = ModuleType(f"oracle_release_runtime_w{parent_number}")
    class Base:
        def chat(self, text, session_id="default"):
            return reply
    setattr(parent, f"OracleReleaseRuntimeW{parent_number}", Base)
    # Optional runtime imports must neither search for stores nor alter loaded folds.
    modules = {parent.__name__: parent, "oracle_release_runtime_w562": None,
               "reach_router_v1": None, "knowledge_composer_v1": None,
               "reach_router_v2": None, "reach_router_v3": None,
               "oracle_release_runtime_w420": ModuleType("oracle_release_runtime_w420")}
    modules[parent.__name__] = parent
    with patch.dict(sys.modules, modules):
        module = load_file(f"test_w{number}", ADMITTED / f"oracle_release_runtime_w{number}.py")
    return module, getattr(module, f"OracleReleaseRuntimeW{number}")()


def router():
    answer = dict(subject_qid=42, property=61, direction="fwd", answer="Ada", route="agent", pattern="who", raw=[1])
    return SimpleNamespace(answer=Mock(return_value=answer), label=lambda q: "Engine",
                           _load=lambda: {"plabel": {61: "inventor"}}, AGENT=re.compile(r".*"))


class Organ:
    def __init__(self, sid, respond):
        self.id, self.respond, self.ctx = sid, respond, re.compile(".*")

    def reply(self, text, session_id="default"):
        response = self.respond(text)
        if response is None:
            return None
        return dict(id=self.id, response=response, kind="compute", status="answered", declined=False)


def family(*organs):
    # Real _ask_all and _dependence, avoiding store/module loading only.
    fam = COMBO.Family.__new__(COMBO.Family)
    fam.organs, fam.order = list(organs), [o.id for o in organs]
    return fam


ORDINARY = dict(status="withheld", path="unverified:no_record", response="No record.")
TERMINAL = [dict(status="withheld", path="proved_check:disagree>specialist:x", response="Different answers."),
            dict(status="withheld", path="specialist:x", response="Different answers.",
                 kernel_check=dict(comparison="disagreement", terminal=True)),
            dict(status="withheld", path="composed>ambiguous_candidates", response="Ambiguous.",
                 refusal=dict(reason="ambiguous_candidates", terminal=True))]


class TerminalGuards(unittest.TestCase):
    def test_coverage_folds_preserve_terminal_receipts_without_calling_fallback(self):
        for number, parent in ((564,563),(565,564),(566,565)):
            for reply in TERMINAL:
                with self.subTest(number=number, reply=reply):
                    mod, runtime = fold(number, parent, reply)
                    route = router()
                    setattr(mod, {564:"_RR",565:"_RR2",566:"_RR3"}[number], route)
                    mod._composed_reason = Mock(side_effect=AssertionError("must not run"))
                    mod._family = Mock(side_effect=AssertionError("must not run"))
                    self.assertIs(runtime.chat("Who invented the Engine?"), reply)
                    route.answer.assert_not_called()

    def test_inner_composed_and_owner_methods_preserve_contradiction(self):
        for number, parent, methods in ((554,551,("_stars","_owner")),
                                        (562,560,("_composed",)),(563,429,("_owner_words",))):
            for reply in TERMINAL:
                with self.subTest(number=number, reply=reply):
                    mod, runtime = fold(number, parent, reply)
                    mod._load = Mock(side_effect=AssertionError("must not run"))
                    for method in methods:
                        self.assertIs(getattr(runtime, method)("What is 20?", "test", reply), reply)
                    mod._load.assert_not_called()

    def test_passage_fold_preserves_terminal_receipt(self):
        # w434's actual parent is discovered from source, avoiding giant head imports.
        source = (ADMITTED / "oracle_release_runtime_w434.py").read_text()
        parent = int(re.search(r"from oracle_release_runtime_w(\d+) import",source).group(1))
        for reply in TERMINAL:
            _, runtime = fold(434, parent, reply)
            runtime._r434_passage = Mock(side_effect=AssertionError("must not run"))
            self.assertIs(runtime.chat("Passage: A is B. Question: Is A B?"), reply)
            runtime._r434_passage.assert_not_called()

    def test_no_record_and_nonterminal_kernel_checks_remain_eligible(self):
        for number, parent in ((564,563),(565,564),(566,565)):
            reply = dict(ORDINARY, kernel_check=dict(comparison="unsupported", terminal=False),
                         proved={"session":"old"},value="old value",kind="old kind")
            mod, runtime = fold(number, parent, reply)
            route = router()
            setattr(mod, {564:"_RR",565:"_RR2",566:"_RR3"}[number], route)
            mod._composed_reason = lambda text: None
            mod._family = lambda: (family(),COMBO)
            result = runtime.chat("Who invented the Engine?")
            self.assertEqual(result["status"], "answered")
            self.assertIn("Ada",result["response"])
            for stale in ("proved","kernel_check","value","kind"):
                self.assertNotIn(stale,result)
            self.assertEqual(reply["status"], "withheld")

    def test_path_tokens_are_not_substrings(self):
        self.assertFalse(terminal_refusal(dict(ORDINARY,path="unverified:validity_record_absent")))
        self.assertTrue(terminal_refusal(dict(ORDINARY,path="network>validity>receipt")))


class ComposedAdmission(unittest.TestCase):
    def run_composed(self, organs, question="Convert Celsius 20 to kelvin?", reply=ORDINARY):
        mod, runtime = fold(565,564,reply)
        route = router()
        mod._RR2 = route
        mod._family = lambda: (family(*organs),COMBO)
        return runtime.chat(question), route

    def test_unique_dependent_compute_retains_coverage(self):
        organ = Organ("kelvin",lambda q: "Kelvin: %.2f" % (float(COMBO.NUM.search(q).group())+273.15))
        for reply in (ORDINARY, dict(status="clarification",path="act:clarify|vessel:parse",response="I didn't fully parse that")):
            result, route = self.run_composed([organ],reply=reply)
            self.assertEqual(result["status"],"answered")
            self.assertEqual(result["response"],"Kelvin: 293.15 [kelvin]")
            self.assertEqual(result["provenance"]["dependent_givens"],1)
            route.answer.assert_not_called()

    def test_conflicting_candidates_are_order_independent_terminal_refusal(self):
        a,b = Organ("A",lambda q:"1"), Organ("B",lambda q:"2")
        first,route = self.run_composed([a,b])
        second,_ = self.run_composed([b,a])
        self.assertEqual(first,second)
        self.assertEqual(first["status"],"withheld")
        self.assertEqual(first["refusal"]["candidates"],["A","B"])
        self.assertTrue(terminal_refusal(first))
        route.answer.assert_not_called()
        mod,runtime = fold(566,565,first)
        mod._RR3 = router()
        self.assertIs(runtime.chat("Who invented the Engine?"),first)
        mod._RR3.answer.assert_not_called()

    def test_equal_answers_do_not_establish_unique_reading(self):
        result,_ = self.run_composed([Organ("A",lambda q:"10"),Organ("B",lambda q:"10")])
        self.assertEqual(result["refusal"]["reason"],"ambiguous_candidates")

    def test_ignored_given_cannot_be_hidden_by_relation_fallback(self):
        result,route = self.run_composed([Organ("A",lambda q:"42")])
        self.assertEqual(result["refusal"]["reason"],"input_dependence_failed")
        route.answer.assert_not_called()

    def test_constant_result_equal_to_perturbed_input_is_not_dependence(self):
        result,route = self.run_composed([Organ("A",lambda q:"Result: 2 m.")],
                                       question="For 1 m, what is the result?")
        self.assertEqual(result["refusal"]["reason"],"input_dependence_failed")
        route.answer.assert_not_called()
        result,_ = self.run_composed([Organ("A",lambda q:"Result: 2 m.")],
                                    question="For 2 m, what is the result?")
        self.assertEqual(result["refusal"]["reason"],"input_dependence_failed")

    def test_missing_counterfactual_is_inconclusive(self):
        result,route = self.run_composed([Organ("A",lambda q:"Result: 2 m." if "1 m" in q else None)],
                                       question="For 1 m, what is the result?")
        self.assertEqual(result["refusal"]["reason"],"input_dependence_failed")
        route.answer.assert_not_called()

    def test_refused_counterfactual_is_inconclusive(self):
        class RefusingOrgan(Organ):
            def reply(self, text, session_id="default"):
                if "1 m" in text:
                    return super().reply(text,session_id)
                return dict(id=self.id,kind="out_of_domain",status="withheld",declined=True,response="Outside domain.")
        result,route = self.run_composed([RefusingOrgan("A",lambda q:"Result: 2 m.")],
                                       question="For 1 m, what is the result?")
        self.assertEqual(result["refusal"]["reason"],"input_dependence_failed")
        route.answer.assert_not_called()

    def test_numeric_formatting_or_changed_unit_is_not_output_dependence(self):
        for altered in ("Result: 2.0 m.", "Result: 3 kg."):
            result,_ = self.run_composed([Organ("A",lambda q:"Result: 2 m." if "1 m" in q else altered)],
                                        question="For 1 m, what is the result?")
            self.assertEqual(result["refusal"]["reason"],"input_dependence_failed")

    def test_identity_computation_may_equal_each_given(self):
        result,_ = self.run_composed([Organ("A",lambda q:"Result: %s m." % COMBO.NUM.search(q).group())],
                                    question="For 1 m, what is the result?")
        self.assertEqual(result["status"],"answered")
        self.assertEqual(result["response"],"Result: 1 m. [A]")

    def test_every_given_must_move_the_answer(self):
        result,route = self.run_composed([Organ("A",lambda q:str(float(COMBO.NUM.search(q).group())*10))],
                                       question="Calculate area for length 3 and width 4?")
        self.assertEqual(result["refusal"]["reason"],"input_dependence_failed")
        route.answer.assert_not_called()

    def test_seventh_given_is_not_silently_omitted(self):
        def sum_first_six(question):
            return str(sum(float(m.group()) for m in list(COMBO.NUM.finditer(question))[:6]))
        result,route = self.run_composed([Organ("A",sum_first_six)],
                                       question="Compute with 1, 2, 3, 4, 5, 6 and 7?")
        self.assertEqual(result["refusal"]["reason"],"input_dependence_failed")
        route.answer.assert_not_called()

    def test_failed_candidate_validation_stands_but_unavailable_family_is_a_gap(self):
        mod,runtime = fold(565,564,ORDINARY)
        route = router()
        mod._RR2 = route
        fam = family(Organ("A",lambda q:"42"))
        fam.organs[0].reply = Mock(side_effect=[dict(id="A", response="42", kind="compute", status="answered", declined=False),
                                               RuntimeError("probe failed")])
        mod._family = lambda: (fam,COMBO)
        result = runtime.chat("Compute 20?")
        self.assertEqual(result["refusal"]["reason"],"candidate_check_failed")
        route.answer.assert_not_called()
        mod._family = Mock(side_effect=FileNotFoundError("no family installed"))
        self.assertEqual(runtime.chat("Who invented the Engine?")["status"],"answered")
        route.answer.assert_called_once()

    def test_no_composed_candidate_allows_ordinary_relation_gain(self):
        result,route = self.run_composed([])
        self.assertEqual(result["status"],"answered")
        route.answer.assert_called_once()


class RealComposedFolders(unittest.TestCase):
    def test_original_coverage_examples_and_absolute_zero(self):
        # Source/program/spec files only; no head, databases, panels or downloads.
        mod, runtime = fold(565,564,ORDINARY)
        with patch.dict(os.environ, {"ORACLE7_ROOT": str(ROOT / "root")}):
            cases = [("What is the temperature in K for temperature 20 C?", "293.15 K", "cmp3-l10"),
                     ("What is the animal for year 2024?", "dragon", "cmp3-k6"),
                     ("What is the weekday for day of the year 100?", "Thursday", "cmp3-l7")]
            for question, expected, sid in cases:
                with self.subTest(question=question):
                    result = runtime.chat(question)
                    self.assertEqual(result["status"],"answered")
                    self.assertIn(expected.lower(),result["response"].lower())
                    self.assertEqual(result["provenance"]["specialist"],sid)
            result = runtime.chat("What is the temperature in K for temperature -300 C?")
            self.assertEqual(result["status"],"withheld")
            self.assertEqual(result["refusal"]["reason"],"out_of_domain")


if __name__ == "__main__":
    unittest.main()