Spaces:
Running
Running
File size: 10,825 Bytes
dcf4a90 | 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 | from __future__ import annotations
import json
import tempfile
import threading
import unittest
import urllib.request
from pathlib import Path
from continual_ai import ContinualAgent
from continual_ai.http_api import create_server
from continual_ai.plasticity_adapter import suggested_target
from continual_ai.schemas import ProductError, derive_descriptor, validate_descriptor
A = {"workspace": "alpha"}
B = {"workspace": "alpha-related"}
C = {"workspace": "omega"}
class RegistryDescriptorTests(unittest.TestCase):
def setUp(self) -> None:
self.tmp = tempfile.TemporaryDirectory()
self.state = Path(self.tmp.name) / "state"
def tearDown(self) -> None:
self.tmp.cleanup()
def test_explicit_and_derived_descriptors(self) -> None:
with ContinualAgent.open(self.state, consolidate_every=0) as agent:
explicit = agent.register_context(A, [0, 0, 0, 0, 0, 0])
self.assertTrue(explicit["explicit"])
self.assertEqual(explicit["descriptor"], [0, 0, 0, 0, 0, 0])
derived = agent.register_context(B)
self.assertFalse(derived["explicit"])
self.assertEqual(derived["descriptor"], list(derive_descriptor(derived["canonical"])))
self.assertEqual(len(derived["descriptor"]), 6)
def test_descriptor_conflict_and_validation(self) -> None:
with ContinualAgent.open(self.state, consolidate_every=0) as agent:
agent.register_context(A, [0, 0, 0, 0, 0, 0])
with self.assertRaises(ProductError):
agent.register_context(A, [1, 1, 1, 1, 1, 1])
with self.assertRaises(ProductError):
agent.register_context(C, [0, 1])
with self.assertRaises(ProductError):
validate_descriptor([0, 1, 2, 0, 1, 0])
def test_registry_persists_descriptors(self) -> None:
with ContinualAgent.open(self.state, consolidate_every=0) as agent:
agent.register_context(A, [0, 0, 0, 0, 0, 1])
with ContinualAgent.open(self.state, consolidate_every=0) as reopened:
rec = reopened.contexts.lookup(A)
assert rec is not None
self.assertEqual(list(rec.descriptor or []), [0, 0, 0, 0, 0, 1])
class KernelConfigureTests(unittest.TestCase):
def setUp(self) -> None:
self.tmp = tempfile.TemporaryDirectory()
self.state = Path(self.tmp.name) / "state"
def tearDown(self) -> None:
self.tmp.cleanup()
def test_configure_pristine_and_reopen(self) -> None:
with ContinualAgent.open(self.state, consolidate_every=0, plasticity_enabled=True) as agent:
agent.register_context(A, [0, 0, 0, 0, 0, 0])
result = agent.configure_descriptors(blend=1.0)
self.assertTrue(result["configured"])
self.assertEqual(result["blend"], 1.0)
self.assertEqual(len(result["descriptors"] or []), 8)
kernel = agent.kernel_status()
self.assertFalse(kernel["locked"])
with ContinualAgent.open(self.state, consolidate_every=0, plasticity_enabled=True) as reopened:
kernel = reopened.kernel_status()
self.assertEqual(kernel["descriptors"][0], [0, 0, 0, 0, 0, 0])
self.assertEqual(kernel["descriptor_blend"], 1.0)
def test_configure_validation(self) -> None:
with ContinualAgent.open(self.state, consolidate_every=0, plasticity_enabled=True) as agent:
with self.assertRaises(ProductError):
agent.configure_descriptors(blend=9.0)
with self.assertRaises(ProductError):
agent._ensure_plasticity().configure_descriptors([[0, 0, 0, 0, 0, 0]])
def test_kernel_locks_after_feedback(self) -> None:
with ContinualAgent.open(self.state, consolidate_every=0, plasticity_enabled=True) as agent:
agent.configure_descriptors()
episode = agent.start_episode(context=A)
prediction = agent.predict(episode["episode_id"], "lock-probe")
agent.provide_feedback(prediction["event_id"], prediction["suggested_target"])
with self.assertRaises(ProductError):
agent.configure_descriptors()
def test_episodic_fast_reset(self) -> None:
# Fast adaptation must not accumulate across episodes: closing an
# episode discards the transient adapter while the trace persists.
with ContinualAgent.open(self.state, consolidate_every=0, plasticity_enabled=True) as agent:
for _ in range(30):
episode = agent.start_episode(context=A)
prediction = agent.predict(episode["episode_id"], "drift-input")
agent.provide_feedback(prediction["event_id"], 0)
agent.close_episode(episode["episode_id"])
core = agent._ensure_plasticity()._core
self.assertEqual(float(abs(core.fast_context_token_bank).sum()), 0.0)
self.assertGreater(core.trace_size(), 0)
class KernelCalibrateTests(unittest.TestCase):
def setUp(self) -> None:
self.tmp = tempfile.TemporaryDirectory()
self.state = Path(self.tmp.name) / "state"
def tearDown(self) -> None:
self.tmp.cleanup()
def test_calibrate_empty_trace(self) -> None:
with ContinualAgent.open(self.state, consolidate_every=0, plasticity_enabled=True) as agent:
agent.configure_descriptors()
with self.assertRaises(ProductError):
agent.calibrate_descriptors()
def test_calibrate_shadow_in_safe_mode(self) -> None:
with ContinualAgent.open(self.state, consolidate_every=0, plasticity_enabled=True) as agent:
agent.configure_descriptors()
episode = agent.start_episode(context=A)
prediction = agent.predict(episode["episode_id"], "shadow-input")
agent.provide_feedback(prediction["event_id"], 1)
agent.close_episode(episode["episode_id"])
before = agent.kernel_status()["desc_weights"]
report = agent.calibrate_descriptors()
self.assertEqual(report["status"], "shadow")
self.assertFalse(report["committed"])
self.assertEqual(agent.kernel_status()["desc_weights"], before)
def test_propose_budget_validation(self) -> None:
with ContinualAgent.open(self.state, consolidate_every=0, plasticity_enabled=True) as agent:
with self.assertRaises(ProductError):
agent.propose_candidate(budget=0)
with self.assertRaises(ProductError):
agent.propose_candidate(budget=100000)
class KernelTransferTests(unittest.TestCase):
def setUp(self) -> None:
self.tmp = tempfile.TemporaryDirectory()
self.state = Path(self.tmp.name) / "state"
def tearDown(self) -> None:
self.tmp.cleanup()
def test_related_transfer_end_to_end(self) -> None:
signals = ["alpha-signal-one", "alpha-signal-two"]
targets_a = {signal: suggested_target(signal) for signal in signals}
targets_c = {signal: (target + 2) % 4 for signal, target in targets_a.items()}
with ContinualAgent.open(self.state, consolidate_every=0,
plasticity_enabled=True, plasticity_safe_mode=False) as agent:
agent.register_context(A, [0, 0, 0, 0, 0, 0])
agent.register_context(B, [0, 0, 0, 0, 0, 1])
agent.register_context(C, [1, 1, 1, 1, 1, 1])
agent.configure_descriptors(blend=1.0)
for _ in range(32):
for signal in signals:
for context, targets in ((A, targets_a), (C, targets_c)):
episode = agent.start_episode(context=context)
prediction = agent.predict(episode["episode_id"], signal)
agent.provide_feedback(prediction["event_id"], targets[signal])
agent.close_episode(episode["episode_id"])
proposal = agent.propose_candidate(budget=256)
self.assertEqual(proposal["status"], "candidate_accepted")
agent.promote(proposal["proposal_id"])
for signal in signals:
self.assertEqual(agent.probe(signal, context=A)["prediction"], targets_a[signal])
self.assertEqual(agent.probe(signal, context=C)["prediction"], targets_c[signal])
self.assertEqual(agent.probe(signal, context=B)["prediction"], targets_a[signal])
agent.checkpoint()
with ContinualAgent.open(self.state, consolidate_every=0,
plasticity_enabled=True, plasticity_safe_mode=False) as reopened:
for signal in signals:
self.assertEqual(reopened.probe(signal, context=B)["prediction"], targets_a[signal])
class KernelApiTests(unittest.TestCase):
def setUp(self) -> None:
self.tmp = tempfile.TemporaryDirectory()
self.state = Path(self.tmp.name) / "state"
def tearDown(self) -> None:
self.tmp.cleanup()
def _post(self, base: str, route: str, payload: dict) -> dict:
data = json.dumps(payload).encode("utf-8")
request = urllib.request.Request(base + route, data=data,
headers={"Content-Type": "application/json"}, method="POST")
with urllib.request.urlopen(request) as response:
return json.loads(response.read().decode("utf-8"))
def test_kernel_endpoints(self) -> None:
with ContinualAgent.open(self.state, consolidate_every=0, plasticity_enabled=True) as agent:
server = create_server(agent, host="127.0.0.1", port=0)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
base = f"http://127.0.0.1:{server.server_port}"
registered = self._post(base, "/v1/contexts/register",
{"context": A, "descriptor": [0, 0, 0, 0, 0, 0]})
self.assertTrue(registered["explicit"])
with self.assertRaises(Exception):
self._post(base, "/v1/descriptors/configure", {"blend": 1.0})
configured = self._post(base, "/v1/descriptors/configure",
{"confirm": True, "blend": 1.0})
self.assertTrue(configured["configured"])
with urllib.request.urlopen(base + "/v1/kernel") as response:
kernel = json.loads(response.read().decode("utf-8"))
self.assertEqual(len(kernel["descriptors"]), 8)
finally:
server.shutdown()
server.server_close()
thread.join(timeout=5)
if __name__ == "__main__":
unittest.main()
|