Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187"""Spawning a child asks endpoints that never answer once, together.
A bare model the parent's provider does not list is looked up on every otherprofile, and a generic profile asks its endpoint's `/models`. An endpoint thataccepts connections and never answers costs one fetch timeout: asked one afteranother, three of them held a spawn for three timeouts, and two spawns thatarrived together each opened their own connection and waited their owntimeout. The parent's own profile, when its list must be fetched, is askedwith them, so a slow parent endpoint does not put its wait ahead of theirs; aparent list at hand answers alone. The wait is the daemon's, so this runsthrough the real daemon."""
import jsonimport socketimport threadingimport timeimport unittest
from harness import Albedo, Provider, exclusive, operation_id, text
STALLED = 3# A list never fetched is waited on for 8 s (robot-docs/models.md). Asked# together, the stalled endpoints are reached within moments of each other;# asked in sequence, each one 8 s after the last. The spawn's wall time also# holds the child's creation, which stretches on a starved machine, so it is# only bounded below two sequential waits.WINDOW_SECONDS = 4CEILING_SECONDS = 16
class Listing(Provider): """A provider whose /models lists `ids` after `delay` seconds, counting asks."""
def __init__(self, ids): super().__init__( lambda _request: text("ok"), catalog={"data": [{"id": i} for i in ids]} ) self.delay = 0 self.asked = 0 self.answered_at = None
def _get(owner, self): owner.asked += 1 time.sleep(owner.delay) owner.answered_at = time.monotonic() super()._get(self)
class StalledEndpointsTests(unittest.TestCase): def setUp(self): self.provider = Provider(lambda _request: text("ok")) self.addCleanup(self.provider.close) self.held = [] self.accepted = [] route = self.provider.route self.shared = f"shared-{route}" self.parent = Listing([f"fixture-alpha-{route}", self.shared]) self.addCleanup(self.parent.close) profiles = { f"alpha-{route}": self.profile( self.parent.url + "/v1", f"fixture-alpha-{route}" ), f"beta-{route}": self.profile( self.provider.url + "/beta/v1", f"fixture-beta-{route}" ), } for number in range(STALLED): profiles[f"stalled{number}-{self.provider.route}"] = self.profile( self.stall(), f"fixture-stalled{number}-{self.provider.route}" ) self.alpha = f"alpha-{self.provider.route}" self.beta = f"beta-{self.provider.route}" self.model = f"fixture-beta-{self.provider.route}" self.app = Albedo(self.provider, providers=profiles).__enter__() self.addCleanup(self.app.__exit__, None, None, None)
def profile(self, url, model): return { "extension": "openai", "baseUrl": url, "apiKey": "key", "model": model, "protocol": "chat_completions", }
def stall(self): """An endpoint url whose server accepts connections and never answers.""" server = socket.create_server(("127.0.0.1", 0)) connections = [] accepted = []
def hold(): while True: try: connections.append(server.accept()[0]) accepted.append(time.monotonic()) except OSError: return
threading.Thread(target=hold, daemon=True).start() self.held.append(connections) self.accepted.append(accepted) self.addCleanup(lambda: [c.close() for c in connections]) self.addCleanup(server.close) return f"http://127.0.0.1:{server.getsockname()[1]}/v1"
def spawn(self, parent, name, model=None): session = operation_id() body = { "kind": "child", "parent_id": parent, "address": name, "name": name, "initial_input_id": operation_id(), "task": "scan", "model": model or self.model, } with self.app.api( f"/sessions/{session}", body, method="PUT", headers={"If-None-Match": "*"} ) as response: return json.load(response)
def asked_together(self): """When the stalled endpoints were first reached, after checking they were reached within one window of each other.""" self.assertEqual([len(c) for c in self.held], [1] * STALLED) first = [times[0] for times in self.accepted] self.assertLess(max(first) - min(first), WINDOW_SECONDS) return first
def test_stalled_endpoints_are_asked_together_not_in_sequence(self): parent = self.app.session() began = time.monotonic() made = self.spawn(parent, "scout") elapsed = time.monotonic() - began self.assertEqual(made["provider_profile"], self.beta) self.asked_together() self.assertLess(elapsed, CEILING_SECONDS)
# exclusive: another test's spawn on the shared daemon asks this parent's # endpoint before its delay is set, so it answers at once @exclusive def test_a_slow_parent_endpoint_is_asked_with_the_stalled_ones(self): parent = self.app.session() self.parent.delay = 3 began = time.monotonic() made = self.spawn(parent, "scout") elapsed = time.monotonic() - began self.assertEqual(made["provider_profile"], self.beta) self.assertEqual(self.parent.asked, 1) # The stalled endpoints were reached while the parent's was still # answering, not after it. self.assertLess(max(self.asked_together()), self.parent.answered_at) self.assertLess(elapsed, CEILING_SECONDS)
# exclusive: on the shared daemon, other tests' spawns ask every saved # profile, these stalled ones included @exclusive def test_a_parent_list_at_hand_asks_no_other_endpoint(self): parent = self.app.session() with self.app.api(f"/models?provider_profile={self.alpha}") as response: listed = [item["id"] for item in json.load(response)["items"]] self.assertIn(self.shared, listed) made = self.spawn(parent, "scout", model=self.shared) self.assertEqual(made["provider_profile"], self.alpha) self.assertEqual(self.parent.asked, 1) self.assertEqual([len(c) for c in self.held], [0] * STALLED)
def test_spawns_that_arrive_together_share_one_connection_per_endpoint(self): parent = self.app.session() made = [] threads = [ threading.Thread(target=lambda n=n: made.append(self.spawn(parent, n))) for n in ("scout-1", "scout-2") ] for thread in threads: thread.start() for thread in threads: thread.join() self.assertEqual(len(made), 2) self.assertEqual([len(c) for c in self.held], [1] * STALLED)
if __name__ == "__main__": unittest.main()