diff --git a/e2e/account_migration_test.py b/e2e/account_migration_test.py deleted file mode 100644 index 4f04e6012..000000000 --- a/e2e/account_migration_test.py +++ /dev/null @@ -1,309 +0,0 @@ -"""Old implicit pools survive startup without expanding future plain profiles. - -These scenarios boot real daemons from old config and credential files: account -IDs, cross-file publication, and restart behavior cannot be checked by a fresh -profile or a transport-only test. -""" - -from contextlib import closing -import json -import stat -import unittest - -from harness import Albedo, Provider, exclusive, text - - -def values(document, store): - value = document.get("accounts", {}).get(store, []) - return value if isinstance(value, list) else [value] - - -def read(app, name): - return json.loads((app.home / name).read_text()) - - -class AccountMigrationTest(unittest.TestCase): - @exclusive - def test_existing_pools_become_explicit_and_keys_are_deduplicated(self): - with closing(Provider(lambda _request: text("ok"))) as provider: - profiles = { - "fixture": { - "extension": "openai", - "baseUrl": provider.url, - "apiKey": "same-key", - "model": "fixture-model", - "protocol": "chat_completions", - }, - "same": { - "extension": "openai", - "baseUrl": provider.url, - "apiKey": "same-key", - }, - "codex": {"extension": "codex"}, - "claude": {"extension": "claude"}, - "empty": {"extension": "antigravity"}, - "pinned": {"extension": "codex", "accountId": "codex-two"}, - "explicit": {"extension": "codex", "accountIds": ["codex-two"]}, - "go-a": {"extension": "opencode-go", "apiKey": "go-a"}, - "go-b": {"extension": "opencode-go", "apiKey": "go-b"}, - "go-oauth": {"extension": "opencode-go"}, - } - - def prepare(app): - app.env.pop("OPENCODE_GO_API_KEY", None) - app.env.pop("OPENCODE_API_KEY", None) - app.store_secrets( - "accounts", - { - "openai-codex": [ - {"type": "oauth", "access": "one"}, - { - "type": "oauth", - "access": "two", - "_albedo_account_id": "codex-two", - }, - ], - "anthropic": {"type": "oauth", "access": "claude"}, - "opencode-go": [ - {"type": "oauth", "access": "go-oauth"}, - {"key": "legacy-go", "limitedUntil": 123}, - ], - }, - ) - app.store_secrets("providers", {"fixture": {"apiKey": "older-key"}}) - - with Albedo(provider, providers=profiles, prepare=prepare) as app: - config = read(app, "config.json") - creds = read(app, "creds.json") - migrated = config["providers"] - self.assertEqual(config["accountsVersion"], 2) - codex_ids = [ - account["_albedo_account_id"] - for account in values(creds, "openai-codex") - ] - self.assertEqual(migrated["codex"]["accountIds"], codex_ids) - self.assertEqual(migrated["pinned"]["accountId"], "codex-two") - self.assertEqual(migrated["explicit"]["accountIds"], ["codex-two"]) - self.assertEqual( - migrated["claude"]["accountId"], - values(creds, "anthropic")[0]["_albedo_account_id"], - ) - self.assertNotIn("accountId", migrated["empty"]) - self.assertNotIn("accountIds", migrated["empty"]) - keys = values(creds, "openai") - self.assertEqual(len(keys), 1) - self.assertEqual(keys[0]["apiKey"], "same-key") - self.assertEqual(keys[0]["label"], "fixture") - for name in ("fixture", "same"): - self.assertEqual( - migrated[name]["accountId"], keys[0]["_albedo_account_id"] - ) - self.assertNotIn(name, creds["providers"]) - self.assertNotIn("apiKey", migrated[name]) - go_accounts = values(creds, "opencode-go") - go_ids = [account["_albedo_account_id"] for account in go_accounts] - self.assertEqual(len(go_ids), 4) - for name in ("go-a", "go-b"): - own = next( - account["_albedo_account_id"] - for account in go_accounts - if account.get("apiKey") == name - ) - self.assertEqual( - migrated[name]["accountIds"], - [own] - + [account_id for account_id in go_ids if account_id != own], - ) - self.assertEqual(migrated["go-oauth"]["accountIds"], go_ids) - legacy = next( - account - for account in go_accounts - if account.get("apiKey") == "legacy-go" - ) - self.assertEqual(legacy["limitedUntil"], 123) - self.assertEqual( - stat.S_IMODE((app.home / "creds.json").stat().st_mode), 0o600 - ) - session = app.session() - app.prompt(session, "check migrated key").close() - app.idle(session) - self.assertEqual( - provider.requests[-1]["authorization"], "Bearer same-key" - ) - - @exclusive - def test_alibaba_profiles_keep_the_old_pool_at_their_own_endpoint(self): - with closing(Provider(lambda _request: text("ok"))) as provider: - profiles = { - "fixture": { - "extension": "openai", - "baseUrl": provider.url, - "apiKey": "fixture-key", - }, - "ali-a": {"extension": "alibaba", "apiKey": "ali-a", "baseUrl": ""}, - "ali-b": { - "extension": "alibaba", - "apiKey": "ali-b", - "baseUrl": provider.url, - }, - } - - def prepare(app): - app.env["ALIBABA_API_KEY"] = "environment-only-secret" - app.store_secrets( - "accounts", - { - "alibaba": { - "key": "legacy-ali", - "baseUrl": provider.url + "/legacy", - "limitedUntil": 456, - } - }, - ) - - with Albedo(provider, providers=profiles, prepare=prepare) as app: - config = read(app, "config.json") - creds = read(app, "creds.json") - self.assertNotIn("alibaba", creds["accounts"]) - self.assertNotIn( - "environment-only-secret", (app.home / "creds.json").read_text() - ) - keys = { - account["apiKey"]: account for account in values(creds, "openai") - } - self.assertEqual( - set(keys), {"fixture-key", "ali-a", "ali-b", "legacy-ali"} - ) - self.assertEqual( - keys["legacy-ali"]["endpoint"], provider.url + "/legacy" - ) - self.assertEqual(keys["legacy-ali"]["limitedUntil"], 456) - # The legacy key's endpoint is neither profile's, so it joins - # no rotation. - for name in ("ali-a", "ali-b"): - profile = config["providers"][name] - self.assertEqual(profile["extension"], "openai") - self.assertEqual(profile["protocol"], "chat_completions") - self.assertEqual( - profile["accountIds"], - [keys[name]["_albedo_account_id"], "env:ALIBABA_API_KEY"], - ) - self.assertNotIn(name, creds["providers"]) - self.assertEqual( - config["providers"]["ali-a"]["baseUrl"], keys["ali-a"]["endpoint"] - ) - self.assertEqual( - keys["ali-a"]["endpoint"], - "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1", - ) - - @exclusive - def test_restart_keeps_deliberate_plain_profiles_plain(self): - def prepare(app): - app.store_secrets( - "accounts", - { - "openai-codex": [ - {"type": "oauth", "access": "one"}, - {"type": "oauth", "access": "two"}, - ] - }, - ) - - with Albedo(prepare=prepare) as app: - - def plain(fixture): - config = read(fixture, "config.json") - config["providers"]["plain"] = {"extension": "codex"} - (fixture.home / "config.json").write_text(json.dumps(config)) - - before = read(app, "creds.json") - app.restart(prepare=plain) - self.assertEqual( - read(app, "config.json")["providers"]["plain"], {"extension": "codex"} - ) - self.assertEqual(read(app, "creds.json"), before) - app.restart() - self.assertEqual(read(app, "creds.json"), before) - self.assertEqual( - read(app, "config.json")["providers"]["plain"], {"extension": "codex"} - ) - - @exclusive - def test_handwritten_key_replaces_an_existing_pin_or_rotation_on_restart(self): - with Albedo() as app: - for field in ("accountId", "accountIds"): - - def replace_key(fixture): - config = read(fixture, "config.json") - profile = config["providers"][fixture.profile] - previous = profile["accountId"] - profile.pop("accountId") - profile[field] = previous if field == "accountId" else [previous] - profile["apiKey"] = field + "-secret" - (fixture.home / "config.json").write_text(json.dumps(config)) - - app.restart(prepare=replace_key) - profile = read(app, "config.json")["providers"][app.profile] - self.assertNotIn("accountIds", profile) - self.assertNotIn("apiKey", profile) - key = next( - account - for account in values(read(app, "creds.json"), "openai") - if account["_albedo_account_id"] == profile["accountId"] - ) - self.assertEqual(key["apiKey"], field + "-secret") - session = app.session() - app.prompt(session, "use the handwritten key").close() - app.idle(session) - self.assertEqual( - app.provider.requests[-1]["authorization"], - "Bearer " + field + "-secret", - ) - - @exclusive - def test_alibaba_environment_only_profile_keeps_its_custom_endpoint(self): - with closing(Provider(lambda _request: text("ok"))) as provider: - - def prepare(app): - app.env["ALIBABA_API_KEY"] = "environment-only-secret" - - profiles = { - "ali": { - "extension": "alibaba", - "baseUrl": provider.url, - "model": "fixture-model", - } - } - with Albedo(provider, providers=profiles, prepare=prepare) as app: - profile = read(app, "config.json")["providers"]["ali"] - self.assertEqual(profile["accountId"], "env:ALIBABA_API_KEY") - self.assertNotIn( - "environment-only-secret", (app.home / "creds.json").read_text() - ) - with app.api("/auth") as response: - accounts = json.load(response)["accounts"] - env_account = next( - account - for account in accounts - if account["id"] == "env:ALIBABA_API_KEY" - ) - self.assertEqual(env_account["endpoint"], provider.url) - session = app.session() - app.prompt(session, "use the migrated environment key").close() - app.idle(session) - self.assertEqual( - provider.requests[-1]["authorization"], - "Bearer environment-only-secret", - ) - - @exclusive - def test_unreadable_credentials_are_not_replaced_or_marked_migrated(self): - def prepare(app): - (app.home / "creds.json").write_text("not json") - - with Albedo(prepare=prepare) as app: - self.assertEqual((app.home / "creds.json").read_text(), "not json") - config = read(app, "config.json") - self.assertNotIn("accountsVersion", config) - self.assertEqual(config["providers"][app.profile]["apiKey"], "fixture-key") diff --git a/e2e/areas.toml b/e2e/areas.toml index c870d9e29..6c7363580 100644 --- a/e2e/areas.toml +++ b/e2e/areas.toml @@ -568,7 +568,6 @@ "folders_test.py", "transfer_test.py", "mcp_test.py", - "account_migration_test.py", "python_test.py", ] # Group publication and crash recovery of settings and credentials. @@ -577,7 +576,6 @@ "daemon_test.py", "credentials_test.py", "accounts_test.py", - "account_migration_test.py", ] "packages/albedo_file/src/albedo_file/revision.gleam" = [ "model_catalogs_test.py", @@ -750,7 +748,7 @@ "integration_test.py", "context_test.py", "prompt_test.py", - "key_endpoints_test.py", + "opencode_zen_test.py", "output_ceiling_test.py", "compaction_progress_test.py", "provider_protocols_test.py", @@ -771,7 +769,7 @@ "perplexity_test.py", "opencode_go_login_test.py", "bedrock_effort_catalog_test.py", - "key_endpoints_test.py", + "opencode_zen_test.py", ] "packages/albedo_env/src/albedo_env.gleam" = [ "proxy_test.py", @@ -780,7 +778,7 @@ "perplexity_test.py", "opencode_go_login_test.py", "bedrock_effort_catalog_test.py", - "key_endpoints_test.py", + "opencode_zen_test.py", ] "packages/albedo_sdk/src/albedo_sdk/credentials.gleam" = [ "credentials_test.py", @@ -831,7 +829,7 @@ "integration_test.py", "context_test.py", "prompt_test.py", - "key_endpoints_test.py", + "opencode_zen_test.py", "output_ceiling_test.py", ] "extensions/opencode_go/src/albedo_ext_opencode_go/**" = [ @@ -841,35 +839,29 @@ "extensions/perplexity/src/albedo_ext_perplexity/**" = [ "perplexity_test.py", "web_search_test.py", - "key_endpoints_test.py", ] "extensions/claude/src/albedo_ext_claude/search.gleam" = ["web_search_test.py"] "e2e/_claude_search_support.py" = ["web_search_test.py"] "e2e/fixtures/claude_search/**" = ["web_search_test.py"] "extensions/anthropic_api/src/albedo_ext_anthropic_api/**" = [ "anthropic_api_test.py", - "key_endpoints_test.py", -] -"extensions/mistral/src/albedo_ext_mistral/**" = [ - "mistral_test.py", - "key_endpoints_test.py", ] +"extensions/mistral/src/albedo_ext_mistral/**" = ["mistral_test.py"] "packages/albedo_sdk/src/albedo_sdk/auth_accounts.gleam" = [ "account_rotation_test.py", "accounts_test.py", ] "packages/albedo_sdk/src/albedo_sdk/key_accounts.gleam" = [ "anthropic_api_test.py", - "key_endpoints_test.py", + "opencode_zen_test.py", "account_rotation_test.py", "fast_mode_test.py", "perplexity_test.py", ] "packages/albedo_sdk/src/albedo_sdk/credential_store.gleam" = [ "anthropic_api_test.py", - "key_endpoints_test.py", + "opencode_zen_test.py", "account_rotation_test.py", - "account_migration_test.py", "accounts_test.py", "credentials_test.py", "mcp_oauth_test.py", @@ -900,13 +892,11 @@ ] "packages/albedo_sdk/src/albedo_sdk/account_migration.gleam" = [ "anthropic_api_test.py", - "key_endpoints_test.py", - "account_migration_test.py", + "credentials_test.py", ] # The settings store's reads, raising API and group commits. "packages/albedo_sdk/src/albedo_sdk/settings_store.gleam" = [ "settings_test.py", - "account_migration_test.py", "credentials_test.py", "mcp_oauth_test.py", "profile_rename_test.py", @@ -953,7 +943,7 @@ "integration_test.py", "context_test.py", "prompt_test.py", - "key_endpoints_test.py", + "opencode_zen_test.py", "github_copilot_test.py", "mistral_test.py", "perplexity_test.py", @@ -1116,7 +1106,7 @@ "provider_protocols_test.py", "fast_mode_test.py", "bedrock_effort_catalog_test.py", - "key_endpoints_test.py", + "opencode_zen_test.py", "accounts_test.py", ] "packages/albedo_sdk/src/albedo_sdk/history.gleam" = [ @@ -1418,7 +1408,7 @@ "context_test.py", "prompt_test.py", "output_ceiling_test.py", - "key_endpoints_test.py", + "opencode_zen_test.py", ] "e2e/provider_events.py" = [ "antigravity_test.py", @@ -1427,6 +1417,6 @@ "context_test.py", "prompt_test.py", "output_ceiling_test.py", - "key_endpoints_test.py", + "opencode_zen_test.py", ] "e2e/*.py" = [] diff --git a/e2e/key_endpoints_test.py b/e2e/key_endpoints_test.py deleted file mode 100644 index f23250a7c..000000000 --- a/e2e/key_endpoints_test.py +++ /dev/null @@ -1,190 +0,0 @@ -"""A profile's turns go to its own base url unless it names a key saved elsewhere. - -A key account owns its routing, so a key in the wrong profile's list sends that -profile's conversation to another host. Catches the two ways one got there -without anyone choosing it: startup folded every OpenCode Go and Alibaba key into -each such hand-written profile's rotation, and a plain Mistral profile took the -first saved key whatever endpoint it was saved for. - -Accounts and startup migrations are global, so every test gets its own daemon. -""" - -import json -import time -import unittest -from contextlib import ExitStack, closing - -from harness import Albedo, Provider, Reply, exclusive, operation_id, text - -# A rotation spreads sessions over its members, so each profile runs a few. -SESSIONS = 4 - - -@exclusive -class KeyEndpointTests(unittest.TestCase): - def start(self, extension, model, *, keyed=True): - """Two fake providers and one `extension` profile at each.""" - stack = ExitStack() - self.addCleanup(stack.close) - providers = { - name: stack.enter_context(closing(Provider(lambda _request: text("ok")))) - for name in ("a", "b") - } - profiles = { - name: { - "extension": extension, - "baseUrl": provider.url, - "model": model, - "protocol": "chat_completions", - **({"apiKey": f"{name}-key"} if keyed else {}), - } - for name, provider in providers.items() - } - app = stack.enter_context(Albedo(providers["a"], providers=profiles)) - return app, providers - - def turns(self, app, profile): - """Runs one turn in each of SESSIONS new sessions on `profile`.""" - app.profile = profile - for _ in range(SESSIONS): - session = app.session() - app.prompt(session, "say ok").close() - app.idle(session) - - def assert_own_endpoint(self, app, providers): - config = json.loads((app.home / "config.json").read_text())["providers"] - for name in providers: - self.assertEqual(len(config[name].get("accountIds") or [None]), 1) - for name in providers: - self.turns(app, name) - for name, provider in providers.items(): - with self.subTest(profile=name): - self.assertEqual( - {sent["authorization"] for sent in provider.requests}, - {f"Bearer {name}-key"}, - ) - self.assertEqual(len(provider.requests), SESSIONS) - - def test_zen_keeps_its_identity_on_chat_and_responses_routes(self): - # OpenCode's cost fields, which both routes carry in their own usage. - billing: dict[str, object] = {} - - def script(request: dict) -> Reply: - if request["model"].startswith("muse-spark-"): - return text( - "ok", usage={"input_tokens": 10, "output_tokens": 20, **billing} - ) - usage = {"prompt_tokens": 10, "completion_tokens": 20, **billing} - return Reply( - "text", - "ok", - events=[ - {"choices": [{"index": 0, "delta": {"content": "ok"}}]}, - { - "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}], - "usage": usage, - }, - ], - ) - - with closing(Provider(script)) as provider: - profiles = { - name: { - "extension": "opencode-zen", - "baseUrl": provider.url, - "apiKey": "zen-key", - "protocol": "chat_completions", - "model": model, - } - for name, model in ( - ("chat", "fixture-model"), - ("responses", "muse-spark-fixture"), - ) - } - with Albedo(provider, providers=profiles) as app: - for profile, path in ( - ("chat", "/chat/completions"), - ("responses", "/responses"), - ): - app.profile = profile - session = app.session() - before = len(provider.requests) - for charge, basis, usd in ( - (0, "listed", 0.00412), - (0.002, "charged", 0.002), - ): - billing["cost"] = charge - billing["opencode"] = { - "billing_source": "balance" if charge else "free", - "list_cost": 0.00412, - } - app.prompt(session, "say ok").close() - app.idle(session) - with app.api(f"/sessions/{session}?tail=0") as response: - spent = json.load(response)["usage"]["spent"] - self.assertIsNotNone(spent) - self.assertEqual(spent["basis"], basis) - self.assertAlmostEqual(spent["usd"], usd) - sent = provider.requests[before:] - self.assertEqual(len(sent), 2) - self.assertTrue( - all(record["path"].endswith(path) for record in sent) - ) - identities = [] - for record in sent: - headers = record["headers"] - self.assertEqual(headers["authorization"], "Bearer zen-key") - self.assertEqual(headers["x-opencode-client"], "cli") - self.assertTrue(headers["user-agent"].startswith("opencode/")) - identity = headers["x-opencode-session"] - self.assertTrue(identity.startswith("ses_")) - for key in ( - "x-opencode-session-id", - "x-session-affinity", - "x-session-id", - ): - self.assertEqual(headers[key], identity) - self.assertTrue(headers["x-opencode-project"]) - identities.append(identity) - self.assertEqual(identities[0], identities[1]) - - def test_anthropic_gateway_profiles_keep_their_own_endpoint_and_key(self): - self.assert_own_endpoint(*self.start("anthropic-api", "claude-fixture")) - - def test_opencode_go_profiles_keep_their_own_endpoint_and_key(self): - self.assert_own_endpoint(*self.start("opencode-go", "qwen-fixture")) - - def test_alibaba_profiles_keep_their_own_endpoint_and_key(self): - self.assert_own_endpoint(*self.start("alibaba", "fixture-model")) - - def test_a_plain_mistral_profile_skips_a_key_saved_for_another_endpoint(self): - app, providers = self.start("mistral", "mistral-fixture", keyed=False) - body = { - "provider": "mistral", - "endpoint": providers["b"].url, - "api_key": "b-key", - } - with app.api(f"/auth/keys/{operation_id()}", body, method="PUT") as response: - response.read() - app.profile = "a" - session = app.session() - app.prompt(session, "say ok").close() - deadline = time.monotonic() + 10 - while time.monotonic() < deadline: - with app.api(f"/sessions/{session}?tail=0") as response: - blocked = json.load(response)["status"]["blocking_reason"] - if blocked: - break - time.sleep(0.03) - self.assertIn("Mistral is not authenticated", blocked["detail"]) - self.assertEqual(providers["a"].requests, []) - self.assertEqual(providers["b"].requests, []) - self.turns(app, "b") - self.assertEqual( - {sent["authorization"] for sent in providers["b"].requests}, - {"Bearer b-key"}, - ) - - -if __name__ == "__main__": - unittest.main() diff --git a/e2e/opencode_zen_test.py b/e2e/opencode_zen_test.py new file mode 100644 index 000000000..0178ab1e7 --- /dev/null +++ b/e2e/opencode_zen_test.py @@ -0,0 +1,101 @@ +"""OpenCode Zen keeps one session identity and its cost basis on both routes. + +Zen keys its cached prefix by the session headers, and bills by the cost fields +in each route's own usage. The route a profile's model picks, the headers the +client adds, and the usage the session records meet only in the running daemon. +""" + +import json +import unittest +from contextlib import closing + +from harness import Albedo, Provider, Reply, text + + +class OpencodeZenTests(unittest.TestCase): + def test_zen_keeps_its_identity_on_chat_and_responses_routes(self): + # OpenCode's cost fields, which both routes carry in their own usage. + billing: dict[str, object] = {} + + def script(request: dict) -> Reply: + if request["model"].startswith("muse-spark-"): + return text( + "ok", usage={"input_tokens": 10, "output_tokens": 20, **billing} + ) + usage = {"prompt_tokens": 10, "completion_tokens": 20, **billing} + return Reply( + "text", + "ok", + events=[ + {"choices": [{"index": 0, "delta": {"content": "ok"}}]}, + { + "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}], + "usage": usage, + }, + ], + ) + + with closing(Provider(script)) as provider: + profiles = { + name: { + "extension": "opencode-zen", + "baseUrl": provider.url, + "apiKey": "zen-key", + "protocol": "chat_completions", + "model": model, + } + for name, model in ( + ("chat", "fixture-model"), + ("responses", "muse-spark-fixture"), + ) + } + with Albedo(provider, providers=profiles) as app: + for profile, path in ( + ("chat", "/chat/completions"), + ("responses", "/responses"), + ): + app.profile = profile + session = app.session() + before = len(provider.requests) + for charge, basis, usd in ( + (0, "listed", 0.00412), + (0.002, "charged", 0.002), + ): + billing["cost"] = charge + billing["opencode"] = { + "billing_source": "balance" if charge else "free", + "list_cost": 0.00412, + } + app.prompt(session, "say ok").close() + app.idle(session) + with app.api(f"/sessions/{session}?tail=0") as response: + spent = json.load(response)["usage"]["spent"] + self.assertIsNotNone(spent) + self.assertEqual(spent["basis"], basis) + self.assertAlmostEqual(spent["usd"], usd) + sent = provider.requests[before:] + self.assertEqual(len(sent), 2) + self.assertTrue( + all(record["path"].endswith(path) for record in sent) + ) + identities = [] + for record in sent: + headers = record["headers"] + self.assertEqual(headers["authorization"], "Bearer zen-key") + self.assertEqual(headers["x-opencode-client"], "cli") + self.assertTrue(headers["user-agent"].startswith("opencode/")) + identity = headers["x-opencode-session"] + self.assertTrue(identity.startswith("ses_")) + for key in ( + "x-opencode-session-id", + "x-session-affinity", + "x-session-id", + ): + self.assertEqual(headers[key], identity) + self.assertTrue(headers["x-opencode-project"]) + identities.append(identity) + self.assertEqual(identities[0], identities[1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/extensions/mistral/test/albedo_ext_mistral/accounts_test.gleam b/extensions/mistral/test/albedo_ext_mistral/accounts_test.gleam new file mode 100644 index 000000000..1c72e9543 --- /dev/null +++ b/extensions/mistral/test/albedo_ext_mistral/accounts_test.gleam @@ -0,0 +1,103 @@ +//// A plain Mistral profile, one that names no key, takes a saved key only +//// when the key was saved for its own endpoint. Taking the first saved key +//// instead sends one host's key, and the conversation, to another host. +//// Selection reads the settings files, so each test writes a scratch home. + +import albedo_env +import albedo_ext_mistral/accounts +import albedo_sdk/key_accounts +import albedo_sdk/key_environment +import gleam/dynamic.{type Dynamic} +import gleam/int +import gleam/option + +const host_a = "http://127.0.0.1:9/a" + +const host_b = "http://127.0.0.1:9/b" + +pub fn a_plain_profile_skips_a_key_saved_for_another_endpoint_test() -> Nil { + use home <- scratch + assert accounts.select(home, "a", "session-a", key_environment.empty()) + |> is_error + let assert Ok(account) = + accounts.select(home, "b", "session-b", key_environment.empty()) + assert key_accounts.key(account) == "b-key" + assert accounts.endpoint(home, "b", account) == Ok(host_b) +} + +pub fn a_key_saved_for_no_endpoint_serves_any_plain_profile_test() -> Nil { + use home <- scratch + write( + home, + "creds.json", + "{\"accounts\":{\"mistral\":[{\"_albedo_account_id\":\"any\",\"type\":\"key\",\"apiKey\":\"any-key\",\"label\":\"any\"}]}}", + ) + let assert Ok(account) = + accounts.select(home, "a", "session-c", key_environment.empty()) + assert key_accounts.key(account) == "any-key" + assert accounts.endpoint(home, "a", account) == Ok(host_a) +} + +fn is_error(result: Result(a, b)) -> Bool { + case result { + Ok(_) -> False + Error(_) -> True + } +} + +/// A home with plain Mistral profiles `a` and `b` at two hosts and one key +/// saved for `b`'s. +fn scratch(run: fn(String) -> Nil) -> Nil { + let home = + "/tmp/albedo-mistral-accounts-test-" + <> int.to_string(system_time()) + <> "-" + <> int.to_string(int.absolute_value(unique_integer())) + let _ = make_dir(home) + let saved = albedo_env.lookup("MISTRAL_API_KEY") + albedo_env.unset("MISTRAL_API_KEY") + write( + home, + "config.json", + "{\"accountsVersion\":2,\"providers\":{" + <> "\"a\":{\"extension\":\"mistral\",\"baseUrl\":\"" + <> host_a + <> "\"},\"b\":{\"extension\":\"mistral\",\"baseUrl\":\"" + <> host_b + <> "\"}}}", + ) + write( + home, + "creds.json", + "{\"accounts\":{\"mistral\":[{\"_albedo_account_id\":\"b\",\"type\":\"key\",\"apiKey\":\"b-key\",\"endpoint\":\"" + <> host_b + <> "\",\"label\":\"b\"}]}}", + ) + run(home) + case saved { + option.Some(value) -> albedo_env.set("MISTRAL_API_KEY", value) + option.None -> Nil + } + let _ = del_dir_r(home) + Nil +} + +fn write(home: String, file: String, text: String) -> Nil { + let _ = write_file(home <> "/" <> file, text) + Nil +} + +@external(erlang, "erlang", "system_time") +fn system_time() -> Int + +@external(erlang, "erlang", "unique_integer") +fn unique_integer() -> Int + +@external(erlang, "file", "make_dir") +fn make_dir(path: String) -> Dynamic + +@external(erlang, "file", "write_file") +fn write_file(path: String, text: String) -> Dynamic + +@external(erlang, "file", "del_dir_r") +fn del_dir_r(path: String) -> Dynamic diff --git a/packages/albedo_sdk/gleam.toml b/packages/albedo_sdk/gleam.toml index 8c7360a73..0470edcb4 100644 --- a/packages/albedo_sdk/gleam.toml +++ b/packages/albedo_sdk/gleam.toml @@ -37,3 +37,5 @@ albedo_web = { path = "../albedo_web" } [dev_dependencies] gleeunit = ">= 1.0.0 and < 2.0.0" +qcheck = ">= 1.0.5 and < 2.0.0" +albedo_property = { path = "../albedo_property" } diff --git a/packages/albedo_sdk/manifest.toml b/packages/albedo_sdk/manifest.toml index 1e7bd343d..0a0ebee81 100644 --- a/packages/albedo_sdk/manifest.toml +++ b/packages/albedo_sdk/manifest.toml @@ -20,6 +20,7 @@ packages = [ { name = "albedo_openai", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_bytes", "albedo_http", "albedo_json", "albedo_model", "albedo_model_stream", "albedo_sse", "gleam_json", "gleam_stdlib"], source = "local", path = "../albedo_openai" }, { name = "albedo_ports", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_clock", "albedo_protect", "gleam_erlang", "gleam_stdlib"], source = "local", path = "../albedo_ports" }, { name = "albedo_process", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_clock", "albedo_protect", "gleam_erlang", "gleam_otp", "gleam_stdlib"], source = "local", path = "../albedo_process" }, + { name = "albedo_property", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_env", "albedo_protect", "gleam_erlang", "gleam_stdlib", "qcheck"], source = "local", path = "../albedo_property" }, { name = "albedo_protect", version = "0.1.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_stdlib"], source = "local", path = "../albedo_protect" }, { name = "albedo_sqlite", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_clock", "albedo_process", "esqlite", "gleam_erlang", "gleam_otp", "gleam_stdlib", "sqlight"], source = "local", path = "../albedo_sqlite" }, { name = "albedo_sse", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_bytes", "gleam_stdlib"], source = "local", path = "../albedo_sse" }, @@ -31,13 +32,17 @@ packages = [ { name = "gleam_http", version = "4.4.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_http", source = "hex", outer_checksum = "F065CE9941A7756ABBAEAE7F9F32A96CAD29DA3311A381DB2D926EA8E8C156DC" }, { name = "gleam_json", version = "3.1.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_json", source = "hex", outer_checksum = "44FDAA8847BE8FC48CA7A1C089706BD54BADCC4C45B237A992EDDF9F2CDB2836" }, { name = "gleam_otp", version = "1.3.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_stdlib"], otp_app = "gleam_otp", source = "hex", outer_checksum = "DE4CA6850842F0266EE95317A25DD6A0A0F20CDFAB7C0ADC2E63251D7C3C72EC" }, + { name = "gleam_regexp", version = "1.1.1", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_regexp", source = "hex", outer_checksum = "9C215C6CA84A5B35BB934A9B61A9A306EC743153BE2B0425A0D032E477B062A9" }, { name = "gleam_stdlib", version = "1.0.5", build_tools = ["gleam"], requirements = [], otp_app = "gleam_stdlib", source = "hex", outer_checksum = "CEE5B6C076A85B45F60C585F4316C63EC8B7127C119D5738C3958A9C4D50404E" }, + { name = "gleam_yielder", version = "1.1.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_yielder", source = "hex", outer_checksum = "8E4E4ECFA7982859F430C57F549200C7749823C106759F4A19A78AEA6687717A" }, { name = "gleeunit", version = "1.11.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleeunit", source = "hex", outer_checksum = "EC31ABA74256AEA531EDF8169931D775BBB384FED0A8A1BDC4DD9354E3E21826" }, { name = "glisten", version = "9.0.1", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_otp", "gleam_stdlib", "logging"], otp_app = "glisten", source = "hex", outer_checksum = "7795AA50830656F3A0316A6B26595F893C83272DA901B3405E31339CAA31A10B" }, { name = "gramps", version = "6.0.1", build_tools = ["gleam"], requirements = ["gleam_crypto", "gleam_erlang", "gleam_http", "gleam_stdlib"], otp_app = "gramps", source = "hex", outer_checksum = "D55636072DEE173F6586A5679D3C02EC7A0DE3F8646B78C351B72908FF223DF7" }, { name = "hpack_erl", version = "0.3.0", build_tools = ["rebar3"], requirements = [], otp_app = "hpack", source = "hex", outer_checksum = "D6137D7079169D8C485C6962DFE261AF5B9EF60FBC557344511C1E65E3D95FB0" }, { name = "logging", version = "1.5.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "logging", source = "hex", outer_checksum = "BC5F18CE5DD9686100229FE5409BDC3DD5C46D5A7DF2F804AD2D8F0DD6C5060E" }, { name = "mist", version = "6.0.3", build_tools = ["gleam"], requirements = ["exception", "gleam_erlang", "gleam_http", "gleam_otp", "gleam_stdlib", "glisten", "gramps", "hpack_erl", "logging"], source = "local", path = "../../vendor/mist" }, + { name = "prng", version = "6.0.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "prng", source = "hex", outer_checksum = "7FE3879E13150248BD370469205ED07B9404DD90670FEBB8CD0E7643707C420E" }, + { name = "qcheck", version = "1.0.5", build_tools = ["gleam"], requirements = ["exception", "gleam_regexp", "gleam_stdlib", "gleam_yielder", "prng"], otp_app = "qcheck", source = "hex", outer_checksum = "D27C12074776EC95F082EE56E0FC74685506B6EE26176F194D10F0322A39AC11" }, { name = "sqlight", version = "1.2.0", build_tools = ["gleam"], requirements = ["esqlite", "gleam_stdlib"], otp_app = "sqlight", source = "hex", outer_checksum = "841768D0A81107EE2DB46B949354F284A68B2E8098315C28A1FE3C07D206C17A" }, { name = "yamerl", version = "0.10.0", build_tools = ["rebar3"], requirements = [], otp_app = "yamerl", source = "hex", outer_checksum = "346ADB2963F1051DC837A2364E4ACF6EB7D80097C0F53CBDC3046EC8EC4B4E6E" }, ] @@ -56,6 +61,7 @@ albedo_oauth = { path = "../albedo_oauth" } albedo_openai = { path = "../albedo_openai" } albedo_ports = { path = "../albedo_ports" } albedo_process = { path = "../albedo_process" } +albedo_property = { path = "../albedo_property" } albedo_protect = { path = "../albedo_protect" } albedo_sqlite = { path = "../albedo_sqlite" } albedo_web = { path = "../albedo_web" } @@ -67,5 +73,6 @@ gleam_otp = { version = ">= 1.3.0 and < 2.0.0" } gleam_stdlib = { version = ">= 1.0.0 and < 2.0.0" } gleeunit = { version = ">= 1.0.0 and < 2.0.0" } mist = { path = "../../vendor/mist" } +qcheck = { version = ">= 1.0.5 and < 2.0.0" } sqlight = { version = ">= 1.2.0 and < 2.0.0" } yamerl = { version = ">= 0.10.0 and < 1.0.0" } diff --git a/packages/albedo_sdk/test/albedo_sdk/account_migration_test.gleam b/packages/albedo_sdk/test/albedo_sdk/account_migration_test.gleam new file mode 100644 index 000000000..60502136f --- /dev/null +++ b/packages/albedo_sdk/test/albedo_sdk/account_migration_test.gleam @@ -0,0 +1,737 @@ +//// Startup's credential and account migration over homes written before +//// accounts existed. The defects: a secret lost or duplicated, a profile +//// bound to keys saved for another endpoint (each turn then goes to the wrong +//// host), a deliberate plain profile widened again on a later start, an +//// unreadable store overwritten, and a second start that changes what the +//// first wrote. `credentials.migrate` is the whole startup transform, file in +//// and file out, so no daemon is needed. +//// +//// The homes under `test/fixtures/accounts-v1/` hold the documents the old +//// end-to-end tests wrote. Keep them as they are while startup still reads +//// that shape. + +import albedo_env +import albedo_property +import albedo_sdk/credentials +import gleam/dict +import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode +import gleam/erlang/atom.{type Atom} +import gleam/int +import gleam/json.{type Json} +import gleam/list +import gleam/option.{type Option, None, Some} +import gleam/result +import gleam/set.{type Set} +import gleam/string +import qcheck.{type Generator} + +const fixtures = "test/fixtures/accounts-v1/" + +const fixture_url = "http://127.0.0.1:9/v1" + +const environment = [ + "ALIBABA_API_KEY", "DASHSCOPE_API_KEY", "OPENCODE_GO_API_KEY", + "OPENCODE_API_KEY", +] + +// ---- committed old homes ---------------------------------------------------- + +pub fn old_pools_become_explicit_and_keys_are_deduplicated_test() -> Nil { + use home <- fixture("pools") + let assert Ok(_) = credentials.migrate(home, "test") + let config = read(home, "config.json") + let creds = read(home, "creds.json") + let profile = fn(name) { at(config, ["providers", name]) } + assert at(config, ["accountsVersion"]) == dyn(2) + + // Rotation profiles reach the old pool, explicitly; pins stay. + let codex = ids(values(creds, "openai-codex")) + assert list.length(codex) == 2 + assert field(profile("codex"), "accountIds") == Ok(dyn(codex)) + assert field(profile("pinned"), "accountId") == Ok(dyn("codex-two")) + assert field(profile("explicit"), "accountIds") == Ok(dyn(["codex-two"])) + assert field(profile("claude"), "accountId") + == Ok(first_id(values(creds, "anthropic"))) + assert field(profile("empty"), "accountId") == Error(Nil) + assert field(profile("empty"), "accountIds") == Error(Nil) + + // Two profiles with one key share one account; the key leaves both. + let assert [key] = values(creds, "openai") + assert field(key, "apiKey") == Ok(dyn("same-key")) + assert field(key, "label") == Ok(dyn("fixture")) + list.each(["fixture", "same"], fn(name) { + assert field(profile(name), "accountId") == field(key, "_albedo_account_id") + assert field(profile(name), "apiKey") == Error(Nil) + assert field(at(creds, ["providers"]), name) == Error(Nil) + }) + + // OpenCode Go keeps its own key first, then the rest of the old pool. + let go = values(creds, "opencode-go") + let go_ids = ids(go) + assert list.length(go_ids) == 4 + list.each(["go-a", "go-b"], fn(name) { + let assert Ok(own) = + list.find(go, fn(value) { field(value, "apiKey") == Ok(dyn(name)) }) + let own = text(own, "_albedo_account_id") + assert field(profile(name), "accountIds") + == Ok(dyn([own, ..list.filter(go_ids, fn(id) { id != own })])) + }) + assert field(profile("go-oauth"), "accountIds") == Ok(dyn(go_ids)) + let assert Ok(legacy) = + list.find(go, fn(value) { field(value, "apiKey") == Ok(dyn("legacy-go")) }) + assert field(legacy, "limitedUntil") == Ok(dyn(123)) + Nil +} + +pub fn alibaba_profiles_keep_the_old_pool_at_their_own_endpoint_test() -> Nil { + use home <- fixture("alibaba") + use <- with_env("ALIBABA_API_KEY", "environment-only-secret") + let assert Ok(_) = credentials.migrate(home, "test") + let config = read(home, "config.json") + let creds = read(home, "creds.json") + assert field(at(creds, ["accounts"]), "alibaba") == Error(Nil) + assert !string.contains(raw(home, "creds.json"), "environment-only-secret") + let keys = + values(creds, "openai") + |> list.map(fn(value) { #(text(value, "apiKey"), value) }) + |> dict.from_list + assert dict.keys(keys) |> list.sort(string.compare) + == ["ali-a", "ali-b", "fixture-key", "legacy-ali"] + let assert Ok(legacy) = dict.get(keys, "legacy-ali") + assert field(legacy, "endpoint") == Ok(dyn(fixture_url <> "/legacy")) + assert field(legacy, "limitedUntil") == Ok(dyn(456)) + // The legacy key's endpoint is neither profile's, so it joins no rotation. + list.each(["ali-a", "ali-b"], fn(name) { + let profile = at(config, ["providers", name]) + let assert Ok(own) = dict.get(keys, name) + assert field(profile, "extension") == Ok(dyn("openai")) + assert field(profile, "protocol") == Ok(dyn("chat_completions")) + assert field(profile, "accountIds") + == Ok(dyn([text(own, "_albedo_account_id"), "env:ALIBABA_API_KEY"])) + assert field(at(creds, ["providers"]), name) == Error(Nil) + }) + let assert Ok(ali_a) = dict.get(keys, "ali-a") + assert field(at(config, ["providers", "ali-a"]), "baseUrl") + == field(ali_a, "endpoint") + assert field(ali_a, "endpoint") + == Ok(dyn( + "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1", + )) +} + +pub fn an_environment_only_alibaba_profile_keeps_its_endpoint_test() -> Nil { + use home <- fixture("alibaba-environment") + use <- with_env("ALIBABA_API_KEY", "environment-only-secret") + let assert Ok(_) = credentials.migrate(home, "test") + let profile = at(read(home, "config.json"), ["providers", "ali"]) + assert field(profile, "accountId") == Ok(dyn("env:ALIBABA_API_KEY")) + assert field(profile, "baseUrl") == Ok(dyn(fixture_url)) + assert !string.contains(raw(home, "creds.json"), "environment-only-secret") +} + +pub fn hand_written_key_profiles_keep_their_own_endpoint_and_key_test() -> Nil { + // Startup once folded every OpenCode Go and Alibaba key into each such + // profile's rotation, sending its turns to another profile's host. + use home <- fixture("key-endpoints") + let assert Ok(_) = credentials.migrate(home, "test") + let config = read(home, "config.json") + let creds = read(home, "creds.json") + list.each(["anthropic-api", "opencode-go", "alibaba"], fn(extension) { + let store = case extension { + "alibaba" -> "openai" + _ -> extension + } + list.each(["a", "b"], fn(name) { + let profile = at(config, ["providers", extension <> "-" <> name]) + let assert Ok(id) = field(profile, "accountId") + as { extension <> " profile " <> name <> " is bound to one account" } + assert field(profile, "accountIds") == Error(Nil) + let assert Ok(account) = + list.find(values(creds, store), fn(value) { + field(value, "_albedo_account_id") == Ok(id) + }) + assert field(account, "apiKey") == Ok(dyn(name <> "-key")) + assert field(account, "endpoint") + == Ok(dyn("http://127.0.0.1:9/" <> name)) + }) + }) +} + +pub fn a_plain_profile_written_after_migration_stays_plain_test() -> Nil { + use home <- fixture("codex-pool") + let assert Ok(_) = credentials.migrate(home, "test") + let creds = raw(home, "creds.json") + add_profile( + home, + "plain", + json.object([#("extension", json.string("codex"))]), + ) + let assert Ok(_) = credentials.migrate(home, "test") + let assert Ok(_) = credentials.migrate(home, "test") + assert at(read(home, "config.json"), ["providers", "plain"]) + == dyn(dict.from_list([#("extension", "codex")])) + assert raw(home, "creds.json") == creds +} + +pub fn a_hand_written_key_replaces_a_pin_or_rotation_test() -> Nil { + list.each(["accountId", "accountIds"], fn(binding) { + use home <- scratch + let bound = case binding { + "accountId" -> json.string("old-id") + _ -> json.array(["old-id"], json.string) + } + write( + home, + "config.json", + json.object([ + #("accountsVersion", json.int(2)), + #( + "providers", + json.object([ + #( + "fixture", + json.object([ + #("extension", json.string("openai")), + #("baseUrl", json.string(fixture_url)), + #(binding, bound), + #("apiKey", json.string(binding <> "-secret")), + ]), + ), + ]), + ), + ]), + ) + let assert Ok(_) = credentials.migrate(home, "test") + let profile = at(read(home, "config.json"), ["providers", "fixture"]) + assert field(profile, "accountIds") == Error(Nil) + assert field(profile, "apiKey") == Error(Nil) + let assert Ok(id) = field(profile, "accountId") + let assert [key] = values(read(home, "creds.json"), "openai") + assert field(key, "_albedo_account_id") == Ok(id) + assert field(key, "apiKey") == Ok(dyn(binding <> "-secret")) + }) +} + +pub fn unreadable_credentials_are_not_replaced_or_marked_migrated_test() -> Nil { + use home <- fixture("codex-pool") + write_raw(home, "creds.json", "not json") + let config = raw(home, "config.json") + let assert Error(_) = credentials.migrate(home, "test") + assert raw(home, "creds.json") == "not json" + assert raw(home, "config.json") == config +} + +// ---- generated old homes ---------------------------------------------------- + +type Home { + Home( + version: Option(Int), + profiles: List(#(String, Profile)), + accounts: List(#(String, List(Account))), + secrets: List(#(String, String)), + ) +} + +type Profile { + Profile( + extension: Option(String), + base_url: Option(String), + key: Option(String), + binding: Binding, + ) +} + +type Binding { + Plain + Pin(String) + Rotation(List(String)) + Null +} + +/// One saved account. `field` names where an old version kept its secret. +/// An account with an id has `-`, its place in its list, so ids are +/// unique and pins can name them. +type Account { + Account(id: Bool, field: String, secret: String, at: Option(String)) +} + +/// Startup turns any old home into one a second start leaves byte for byte, +/// keeps every secret the home held, binds each profile only to keys saved +/// for its own endpoint, and leaves a plain profile added later plain. +/// +/// An eunit generator, so a discovery budget is not cut at eunit's five +/// seconds. +pub fn migrating_any_old_home_is_stable_and_loses_no_secret_test_() -> #( + Atom, + Int, + fn() -> Nil, +) { + #(atom.create("timeout"), 3600, migrating_any_old_home) +} + +fn migrating_any_old_home() -> Nil { + use home_value <- albedo_property.run(150, home()) + use home <- scratch + write(home, "config.json", config_json(home_value)) + write(home, "creds.json", creds_json(home_value)) + let expected = secrets(home_value) + let assert Ok(_) = credentials.migrate(home, "test") + let config_text = raw(home, "config.json") + let creds_text = raw(home, "creds.json") + let assert Ok(_) = credentials.migrate(home, "test") + assert raw(home, "config.json") == config_text + assert raw(home, "creds.json") == creds_text + + let config = read(home, "config.json") + let creds = read(home, "creds.json") + assert at(config, ["accountsVersion"]) == dyn(2) + let kept = set.union(strings(config), strings(creds)) + assert set.difference(expected, kept) |> set.is_empty + as "a secret the old home held is gone" + + list.each(home_value.profiles, fn(entry) { + let #(name, original) = entry + case original.binding { + Plain | Null -> own_endpoint(config, creds, name) + Pin(_) | Rotation(_) -> Nil + } + }) + + list.each(["codex", "claude", "antigravity", "opencode-go"], fn(extension) { + add_profile( + home, + "later", + json.object([#("extension", json.string(extension))]), + ) + let assert Ok(_) = credentials.migrate(home, "test") + assert at(read(home, "config.json"), ["providers", "later"]) + == dyn(dict.from_list([#("extension", extension)])) + assert raw(home, "creds.json") == creds_text + }) +} + +/// Every key account a migrated profile names is saved for that profile's +/// base URL, or for none. +fn own_endpoint(config: Dynamic, creds: Dynamic, name: String) -> Nil { + let profile = at(config, ["providers", name]) + let base = case field(profile, "baseUrl") { + Ok(url) -> decode.run(url, decode.string) |> result.unwrap("") + Error(Nil) -> "" + } + let store = case field(profile, "extension") { + Ok(extension) -> decode.run(extension, decode.string) |> result.unwrap("") + Error(Nil) -> "openai" + } + case base, list.contains(["openai", "opencode-go", "anthropic-api"], store) { + "", _ | _, False -> Nil + _, True -> { + let bound = + list.append( + field(profile, "accountId") + |> result.try(fn(id) { + decode.run(id, decode.string) |> result.replace_error(Nil) + }) + |> result.map(list.wrap) + |> result.unwrap([]), + field(profile, "accountIds") + |> result.try(fn(ids) { + decode.run(ids, decode.list(decode.string)) + |> result.replace_error(Nil) + }) + |> result.unwrap([]), + ) + list.each(values(creds, store), fn(account) { + case list.contains(bound, text(account, "_albedo_account_id")) { + False -> Nil + True -> { + let endpoint = trimmed(text(account, "endpoint")) + assert endpoint == "" || endpoint == trimmed(base) + as { name <> " is bound to a key saved for " <> endpoint } + } + } + }) + } + } +} + +fn trimmed(url: String) -> String { + case string.ends_with(url, "/") { + True -> trimmed(string.drop_end(url, 1)) + False -> url + } +} + +/// The secrets an old home holds: each profile's own nonempty key, or else the +/// one creds.json keeps for it, and every saved account's. +fn secrets(home: Home) -> Set(String) { + let shadowed = dict.from_list(home.secrets) + let profiles = + list.filter_map(home.profiles, fn(entry) { + case { entry.1 }.key { + Some(key) if key != "" -> Ok(key) + _ -> dict.get(shadowed, entry.0) + } + }) + let names = list.map(home.profiles, fn(entry) { entry.0 }) + let orphans = + list.filter_map(home.secrets, fn(entry) { + case list.contains(names, entry.0) { + True -> Error(Nil) + False -> Ok(entry.1) + } + }) + let accounts = + list.flat_map(home.accounts, fn(entry) { + list.map(entry.1, fn(account) { account.secret }) + }) + set.from_list(list.flatten([profiles, orphans, accounts])) + |> set.delete("") +} + +fn home() -> Generator(Home) { + qcheck.map4( + qcheck.from_generators(qcheck.return(None), [ + qcheck.return(Some(1)), + qcheck.return(Some(2)), + ]), + qcheck.generic_list( + qcheck.tuple2(one_of(["p1", "p2", "p3", "p4"]), profile()), + qcheck.bounded_int(0, 5), + ), + qcheck.generic_list( + qcheck.tuple2( + one_of(["openai-codex", "opencode-go", "alibaba", "openai", "anthropic"]), + qcheck.generic_list(account(), qcheck.bounded_int(0, 3)), + ), + qcheck.bounded_int(0, 3), + ), + qcheck.generic_list( + qcheck.tuple2(one_of(["p1", "p2", "p5"]), secret()), + qcheck.bounded_int(0, 2), + ), + fn(version, profiles, accounts, secrets) { + Home( + version:, + profiles: dedupe(profiles), + accounts: dedupe(accounts), + secrets: dedupe(secrets), + ) + }, + ) +} + +fn profile() -> Generator(Profile) { + qcheck.map4( + qcheck.option_from( + one_of([ + "openai", "opencode-go", "anthropic-api", "alibaba", "codex", "claude", + "antigravity", + ]), + ), + qcheck.option_from(one_of(["", "http://h/a", "http://h/b", "http://h/a/"])), + qcheck.option_from(qcheck.from_generators(qcheck.return(""), [secret()])), + qcheck.from_generators(qcheck.return(Plain), [ + qcheck.return(Null), + qcheck.map(pinned(), Pin), + qcheck.map(pinned(), fn(id) { Rotation([id]) }), + ]), + Profile, + ) +} + +fn account() -> Generator(Account) { + qcheck.map4( + qcheck.bool(), + one_of(["apiKey", "key", "access"]), + secret(), + qcheck.option_from(one_of(["http://h/a", "http://h/b"])), + Account, + ) +} + +fn pinned() -> Generator(String) { + one_of(["openai-codex-1", "opencode-go-1", "openai-2"]) +} + +/// A few secrets, so profiles and accounts share keys. +fn secret() -> Generator(String) { + one_of(["k1", "k2", "k3"]) +} + +fn one_of(values: List(String)) -> Generator(String) { + let assert [first, ..rest] = values + qcheck.from_generators(qcheck.return(first), list.map(rest, qcheck.return)) +} + +/// A JSON object keeps the last of each name. +fn dedupe(entries: List(#(String, a))) -> List(#(String, a)) { + list.fold(entries, [], fn(kept: List(#(String, a)), entry: #(String, a)) { + [entry, ..list.filter(kept, fn(other: #(String, a)) { other.0 != entry.0 })] + }) + |> list.reverse +} + +fn config_json(home: Home) -> Json { + let profiles = + list.map(home.profiles, fn(entry) { + let #(name, profile) = entry + let fields = + list.flatten([ + option.map(profile.extension, fn(value) { + #("extension", json.string(value)) + }) + |> option.to_result(Nil) + |> result.map(list.wrap) + |> result.unwrap([]), + option.map(profile.base_url, fn(value) { + #("baseUrl", json.string(value)) + }) + |> option.to_result(Nil) + |> result.map(list.wrap) + |> result.unwrap([]), + option.map(profile.key, fn(value) { #("apiKey", json.string(value)) }) + |> option.to_result(Nil) + |> result.map(list.wrap) + |> result.unwrap([]), + case profile.binding { + Plain -> [] + Null -> [#("accountIds", json.null())] + Pin(id) -> [#("accountId", json.string(id))] + Rotation(ids) -> [#("accountIds", json.array(ids, json.string))] + }, + ]) + #(name, json.object(fields)) + }) + json.object( + list.flatten([ + [#("providers", json.object(profiles))], + case home.version { + Some(version) -> [#("accountsVersion", json.int(version))] + None -> [] + }, + ]), + ) +} + +fn creds_json(home: Home) -> Json { + let accounts = + list.map(home.accounts, fn(entry) { + #( + entry.0, + json.preprocessed_array( + list.index_map(entry.1, fn(account, index) { + json.object( + list.flatten([ + [#(account.field, json.string(account.secret))], + case account.field { + "access" -> [#("type", json.string("oauth"))] + _ -> [] + }, + case account.id { + True -> [ + #( + "_albedo_account_id", + json.string(entry.0 <> "-" <> int.to_string(index + 1)), + ), + ] + False -> [] + }, + case account.at { + Some(url) -> [#("endpoint", json.string(url))] + None -> [] + }, + ]), + ) + }), + ), + ) + }) + json.object([ + #("accounts", json.object(accounts)), + #( + "providers", + json.object( + list.map(home.secrets, fn(entry) { + #(entry.0, json.object([#("apiKey", json.string(entry.1))])) + }), + ), + ), + ]) +} + +// ---- documents -------------------------------------------------------------- + +fn read(home: String, file: String) -> Dynamic { + let assert Ok(value) = json.parse(raw(home, file), decode.dynamic) + value +} + +fn at(value: Dynamic, path: List(String)) -> Dynamic { + let assert Ok(found) = decode.run(value, decode.at(path, decode.dynamic)) + as { "missing " <> string.join(path, ".") } + found +} + +fn field(value: Dynamic, name: String) -> Result(Dynamic, Nil) { + decode.run(value, decode.at([name], decode.dynamic)) + |> result.replace_error(Nil) +} + +fn text(value: Dynamic, name: String) -> String { + decode.run(value, decode.at([name], decode.string)) |> result.unwrap("") +} + +/// The accounts saved under `store`, a single object read as a list of one. +fn values(creds: Dynamic, store: String) -> List(Dynamic) { + case field(at(creds, ["accounts"]), store) { + Error(Nil) -> [] + Ok(saved) -> + decode.run(saved, decode.list(decode.dynamic)) + |> result.unwrap([saved]) + } +} + +fn ids(accounts: List(Dynamic)) -> List(String) { + list.map(accounts, text(_, "_albedo_account_id")) +} + +fn first_id(accounts: List(Dynamic)) -> Dynamic { + let assert [first, ..] = ids(accounts) + dyn(first) +} + +/// Every string anywhere in a JSON document. +fn strings(value: Dynamic) -> Set(String) { + case decode.run(value, decode.string) { + Ok(text) -> set.from_list([text]) + Error(_) -> + case decode.run(value, decode.list(decode.dynamic)) { + Ok(items) -> + list.fold(items, set.new(), fn(all, item) { + set.union(all, strings(item)) + }) + Error(_) -> + case decode.run(value, decode.dict(decode.string, decode.dynamic)) { + Ok(object) -> + dict.fold(object, set.new(), fn(all, _, item) { + set.union(all, strings(item)) + }) + Error(_) -> set.new() + } + } + } +} + +fn add_profile(home: String, name: String, profile: Json) -> Nil { + let assert Ok(config) = + json.parse( + raw(home, "config.json"), + decode.dict(decode.string, decode.dynamic), + ) + let assert Ok(profiles) = + decode.run( + at(dyn(config), ["providers"]), + decode.dict(decode.string, decode.dynamic), + ) + let profiles = dict.insert(profiles, name, dyn_json(profile)) + write_raw( + home, + "config.json", + encode(dyn(dict.insert(config, "providers", dyn(profiles)))), + ) +} + +fn dyn_json(value: Json) -> Dynamic { + let assert Ok(parsed) = json.parse(json.to_string(value), decode.dynamic) + parsed +} + +fn encode(value: Dynamic) -> String { + iolist_to_binary(json_encode(value)) +} + +@external(erlang, "json", "encode") +fn json_encode(value: Dynamic) -> Dynamic + +@external(erlang, "erlang", "iolist_to_binary") +fn iolist_to_binary(value: Dynamic) -> String + +@external(erlang, "gleam_stdlib", "identity") +fn dyn(value: a) -> Dynamic + +// ---- homes ------------------------------------------------------------------ + +fn fixture(name: String, run: fn(String) -> Nil) -> Nil { + use home <- scratch + list.each(["config.json", "creds.json"], fn(file) { + case read_file(fixtures <> name <> "/" <> file) { + Ok(bytes) -> write_raw(home, file, bytes) + Error(_) -> Nil + } + }) + run(home) +} + +fn scratch(run: fn(String) -> Nil) -> Nil { + let home = + "/tmp/albedo-account-migration-test-" + <> int.to_string(system_time()) + <> "-" + <> int.to_string(unique_integer([atom.create("positive")])) + let assert True = make_dir(home) == ok() + let saved = + list.map(environment, fn(name) { #(name, albedo_env.lookup(name)) }) + list.each(environment, albedo_env.unset) + run(home) + list.each(saved, fn(entry) { + case entry.1 { + Some(value) -> albedo_env.set(entry.0, value) + None -> albedo_env.unset(entry.0) + } + }) + let _ = del_dir_r(home) + Nil +} + +fn with_env(name: String, value: String, run: fn() -> Nil) -> Nil { + albedo_env.set(name, value) + run() + albedo_env.unset(name) +} + +fn write(home: String, file: String, value: Json) -> Nil { + write_raw(home, file, json.to_string(value)) +} + +fn write_raw(home: String, file: String, text: String) -> Nil { + let assert True = write_file(home <> "/" <> file, text) == ok() + Nil +} + +fn raw(home: String, file: String) -> String { + let assert Ok(text) = read_file(home <> "/" <> file) + text +} + +fn ok() -> Dynamic { + atom.to_dynamic(atom.create("ok")) +} + +@external(erlang, "erlang", "unique_integer") +fn unique_integer(modifiers: List(Atom)) -> Int + +@external(erlang, "erlang", "system_time") +fn system_time() -> Int + +@external(erlang, "file", "make_dir") +fn make_dir(path: String) -> Dynamic + +@external(erlang, "file", "write_file") +fn write_file(path: String, text: String) -> Dynamic + +@external(erlang, "file", "read_file") +fn read_file(path: String) -> Result(String, Dynamic) + +@external(erlang, "file", "del_dir_r") +fn del_dir_r(path: String) -> Dynamic diff --git a/packages/albedo_sdk/test/fixtures/accounts-v1/alibaba-environment/config.json b/packages/albedo_sdk/test/fixtures/accounts-v1/alibaba-environment/config.json new file mode 100644 index 000000000..5f1e15e5f --- /dev/null +++ b/packages/albedo_sdk/test/fixtures/accounts-v1/alibaba-environment/config.json @@ -0,0 +1,10 @@ +{ + "providers": { + "ali": { + "extension": "alibaba", + "baseUrl": "http://127.0.0.1:9/v1", + "model": "fixture-model" + } + }, + "active": "ali" +} diff --git a/packages/albedo_sdk/test/fixtures/accounts-v1/alibaba/config.json b/packages/albedo_sdk/test/fixtures/accounts-v1/alibaba/config.json new file mode 100644 index 000000000..b6fcc538d --- /dev/null +++ b/packages/albedo_sdk/test/fixtures/accounts-v1/alibaba/config.json @@ -0,0 +1,20 @@ +{ + "providers": { + "fixture": { + "extension": "openai", + "baseUrl": "http://127.0.0.1:9/v1", + "apiKey": "fixture-key" + }, + "ali-a": { + "extension": "alibaba", + "apiKey": "ali-a", + "baseUrl": "" + }, + "ali-b": { + "extension": "alibaba", + "apiKey": "ali-b", + "baseUrl": "http://127.0.0.1:9/v1" + } + }, + "active": "fixture" +} diff --git a/packages/albedo_sdk/test/fixtures/accounts-v1/alibaba/creds.json b/packages/albedo_sdk/test/fixtures/accounts-v1/alibaba/creds.json new file mode 100644 index 000000000..da6132426 --- /dev/null +++ b/packages/albedo_sdk/test/fixtures/accounts-v1/alibaba/creds.json @@ -0,0 +1,9 @@ +{ + "accounts": { + "alibaba": { + "key": "legacy-ali", + "baseUrl": "http://127.0.0.1:9/v1/legacy", + "limitedUntil": 456 + } + } +} diff --git a/packages/albedo_sdk/test/fixtures/accounts-v1/codex-pool/config.json b/packages/albedo_sdk/test/fixtures/accounts-v1/codex-pool/config.json new file mode 100644 index 000000000..5d525fc77 --- /dev/null +++ b/packages/albedo_sdk/test/fixtures/accounts-v1/codex-pool/config.json @@ -0,0 +1,12 @@ +{ + "providers": { + "fixture": { + "extension": "openai", + "baseUrl": "http://127.0.0.1:9/v1", + "apiKey": "fixture-key", + "model": "fixture-model", + "protocol": "chat_completions" + } + }, + "active": "fixture" +} diff --git a/packages/albedo_sdk/test/fixtures/accounts-v1/codex-pool/creds.json b/packages/albedo_sdk/test/fixtures/accounts-v1/codex-pool/creds.json new file mode 100644 index 000000000..44e6213ec --- /dev/null +++ b/packages/albedo_sdk/test/fixtures/accounts-v1/codex-pool/creds.json @@ -0,0 +1,14 @@ +{ + "accounts": { + "openai-codex": [ + { + "type": "oauth", + "access": "one" + }, + { + "type": "oauth", + "access": "two" + } + ] + } +} diff --git a/packages/albedo_sdk/test/fixtures/accounts-v1/key-endpoints/config.json b/packages/albedo_sdk/test/fixtures/accounts-v1/key-endpoints/config.json new file mode 100644 index 000000000..fd49d99f0 --- /dev/null +++ b/packages/albedo_sdk/test/fixtures/accounts-v1/key-endpoints/config.json @@ -0,0 +1,47 @@ +{ + "providers": { + "anthropic-api-a": { + "extension": "anthropic-api", + "baseUrl": "http://127.0.0.1:9/a", + "model": "claude-fixture", + "protocol": "chat_completions", + "apiKey": "a-key" + }, + "anthropic-api-b": { + "extension": "anthropic-api", + "baseUrl": "http://127.0.0.1:9/b", + "model": "claude-fixture", + "protocol": "chat_completions", + "apiKey": "b-key" + }, + "opencode-go-a": { + "extension": "opencode-go", + "baseUrl": "http://127.0.0.1:9/a", + "model": "qwen-fixture", + "protocol": "chat_completions", + "apiKey": "a-key" + }, + "opencode-go-b": { + "extension": "opencode-go", + "baseUrl": "http://127.0.0.1:9/b", + "model": "qwen-fixture", + "protocol": "chat_completions", + "apiKey": "b-key" + }, + "alibaba-a": { + "extension": "alibaba", + "baseUrl": "http://127.0.0.1:9/a", + "model": "fixture-model", + "protocol": "chat_completions", + "apiKey": "a-key" + }, + "alibaba-b": { + "extension": "alibaba", + "baseUrl": "http://127.0.0.1:9/b", + "model": "fixture-model", + "protocol": "chat_completions", + "apiKey": "b-key" + } + }, + "active": "anthropic-api-a" +} diff --git a/packages/albedo_sdk/test/fixtures/accounts-v1/pools/config.json b/packages/albedo_sdk/test/fixtures/accounts-v1/pools/config.json new file mode 100644 index 000000000..13e95b99f --- /dev/null +++ b/packages/albedo_sdk/test/fixtures/accounts-v1/pools/config.json @@ -0,0 +1,45 @@ +{ + "providers": { + "fixture": { + "extension": "openai", + "baseUrl": "http://127.0.0.1:9/v1", + "apiKey": "same-key", + "model": "fixture-model", + "protocol": "chat_completions" + }, + "same": { + "extension": "openai", + "baseUrl": "http://127.0.0.1:9/v1", + "apiKey": "same-key" + }, + "codex": { + "extension": "codex" + }, + "claude": { + "extension": "claude" + }, + "empty": { + "extension": "antigravity" + }, + "pinned": { + "extension": "codex", + "accountId": "codex-two" + }, + "explicit": { + "extension": "codex", + "accountIds": ["codex-two"] + }, + "go-a": { + "extension": "opencode-go", + "apiKey": "go-a" + }, + "go-b": { + "extension": "opencode-go", + "apiKey": "go-b" + }, + "go-oauth": { + "extension": "opencode-go" + } + }, + "active": "fixture" +} diff --git a/packages/albedo_sdk/test/fixtures/accounts-v1/pools/creds.json b/packages/albedo_sdk/test/fixtures/accounts-v1/pools/creds.json new file mode 100644 index 000000000..52d01898a --- /dev/null +++ b/packages/albedo_sdk/test/fixtures/accounts-v1/pools/creds.json @@ -0,0 +1,34 @@ +{ + "accounts": { + "openai-codex": [ + { + "type": "oauth", + "access": "one" + }, + { + "type": "oauth", + "access": "two", + "_albedo_account_id": "codex-two" + } + ], + "anthropic": { + "type": "oauth", + "access": "claude" + }, + "opencode-go": [ + { + "type": "oauth", + "access": "go-oauth" + }, + { + "key": "legacy-go", + "limitedUntil": 123 + } + ] + }, + "providers": { + "fixture": { + "apiKey": "older-key" + } + } +} -- knotmirror 0.0.1 From 89cdf7a02b3361eb9ad41ad9a3042a9ee90541ce Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Thu, 19 Nov 2026 15:31:41 -0500 Subject: [PATCH 2/7] fix(accounts): apply an account-wide limit to every meter A saved account records a limit on one meter in `limitedMeters`, or in `limitedUntil` when the limit named no meter. Once an account had any meter mark, `until_of` read only that meter's mark, so an account-wide limit (for example an Antigravity limit Google attributed to no model) stopped counting for every metered lookup: rotation offered the limited account to the next request and got another limit back. `/login`'s account detail hid the same mark beside meter marks. The contract only said a meter falls back to `limitedUntil` while the account has no `limitedMeters`. The least surprising rule is that a mark naming no meter limits the whole account, so a meter's limit now ends at the later of the two, and the account detail lists both. auth.md states the rule. --- .../albedo_ext_antigravity/extension.gleam | 51 +++++++++---------- .../albedo_sdk/src/albedo_sdk/accounts.gleam | 7 +-- .../test/albedo_sdk/limit_marks_test.gleam | 34 +++++++++++++ robot-docs/auth.md | 5 ++ 4 files changed, 68 insertions(+), 29 deletions(-) create mode 100644 packages/albedo_sdk/test/albedo_sdk/limit_marks_test.gleam diff --git a/extensions/antigravity/src/albedo_ext_antigravity/extension.gleam b/extensions/antigravity/src/albedo_ext_antigravity/extension.gleam index 0b2ec846a..5ea8e0dab 100644 --- a/extensions/antigravity/src/albedo_ext_antigravity/extension.gleam +++ b/extensions/antigravity/src/albedo_ext_antigravity/extension.gleam @@ -622,9 +622,8 @@ fn account(credential: Dynamic) -> oauth.Account { } } -/// "suspended by Google" for a suspended account; else each meter still -/// limited, by meter name, or, for a credential without per-meter marks, its -/// legacy `limitedUntil`. +/// "suspended by Google" for a suspended account; else its account-wide +/// `limitedUntil` and each meter still limited, by meter name. fn limit_detail(credential: Dynamic, now: Int) -> String { case is_suspended(credential) { True -> "suspended by Google" @@ -647,28 +646,28 @@ fn meter_detail(credential: Dynamic, now: Int) -> String { decode.at(["limitedMeters"], decode.dict(decode.string, decode.dynamic)), ) |> result.unwrap(dict.new()) - case dict.is_empty(meters) { - True -> - case decode.run(credential, decode.at(["limitedUntil"], decode.int)) { - Ok(until) if until > now -> "limited until " <> oauth.local_time(until) - _ -> "" - } - False -> - meters - |> dict.to_list - |> list.sort(fn(left, right) { string.compare(left.0, right.0) }) - |> list.filter_map(fn(meter) { - case decode.run(meter.1, decode.int) { - Ok(until) if until > now -> - Ok( - "limited on " - <> accounts.meter_title(meter.0) - <> " until " - <> oauth.local_time(until), - ) - _ -> Error(Nil) - } - }) - |> string.join(" · ") + // A mark without a meter limits the whole account, beside any meter's. + let account = case + decode.run(credential, decode.at(["limitedUntil"], decode.int)) + { + Ok(until) if until > now -> ["limited until " <> oauth.local_time(until)] + _ -> [] } + meters + |> dict.to_list + |> list.sort(fn(left, right) { string.compare(left.0, right.0) }) + |> list.filter_map(fn(meter) { + case decode.run(meter.1, decode.int) { + Ok(until) if until > now -> + Ok( + "limited on " + <> accounts.meter_title(meter.0) + <> " until " + <> oauth.local_time(until), + ) + _ -> Error(Nil) + } + }) + |> list.append(account, _) + |> string.join(" · ") } diff --git a/packages/albedo_sdk/src/albedo_sdk/accounts.gleam b/packages/albedo_sdk/src/albedo_sdk/accounts.gleam index 6615e90c0..36aa61d38 100644 --- a/packages/albedo_sdk/src/albedo_sdk/accounts.gleam +++ b/packages/albedo_sdk/src/albedo_sdk/accounts.gleam @@ -297,9 +297,9 @@ pub fn limited(value: Dynamic, now: Int) -> Bool { } /// When a raw account's limit for `meter` ends, in Unix milliseconds, or 0. -/// Without a meter, the latest of its legacy and per-meter limits. A meter -/// falls back to the legacy `limitedUntil` while the account has no -/// `limitedMeters` object. +/// `limitedUntil` is a mark no meter was named for, so it limits every meter: +/// a meter's limit is the later of it and the meter's own mark. Without a +/// meter, the latest of all of them. pub fn until_of(value: Dynamic, meter: Option(String)) -> Int { let legacy = integer(value, "limitedUntil") |> result.unwrap(0) case meters(value), meter { @@ -309,6 +309,7 @@ pub fn until_of(value: Dynamic, meter: Option(String)) -> Int { decode.run(until, decode.int) |> result.replace_error(Nil) }) |> result.unwrap(0) + |> int.max(legacy) Error(_), Some(_) -> legacy Ok(meters), None -> dict.values(meters) diff --git a/packages/albedo_sdk/test/albedo_sdk/limit_marks_test.gleam b/packages/albedo_sdk/test/albedo_sdk/limit_marks_test.gleam new file mode 100644 index 000000000..a680843c2 --- /dev/null +++ b/packages/albedo_sdk/test/albedo_sdk/limit_marks_test.gleam @@ -0,0 +1,34 @@ +//// When a stored account's recorded limits end, by meter. A mark Google or a +//// provider did not attribute to a meter limits the whole account, so a +//// metered lookup that misses it offers a limited account to the next request. + +import albedo_sdk/accounts +import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode +import gleam/json +import gleam/option.{None, Some} + +pub fn an_account_wide_mark_limits_every_meter_beside_meter_marks_test() -> Nil { + let account = + parse("{\"limitedUntil\":5000,\"limitedMeters\":{\"claude\":3000}}") + assert accounts.until_of(account, Some("gemini")) == 5000 + assert accounts.until_of(account, Some("claude")) == 5000 + assert accounts.until_of(account, None) == 5000 +} + +pub fn a_meter_mark_outlasting_the_account_wide_one_wins_test() -> Nil { + let account = + parse("{\"limitedUntil\":2000,\"limitedMeters\":{\"claude\":3000}}") + assert accounts.until_of(account, Some("claude")) == 3000 + assert accounts.until_of(account, Some("gemini")) == 2000 + assert accounts.until_of( + parse("{\"limitedMeters\":{\"claude\":3000}}"), + Some("gemini"), + ) + == 0 +} + +fn parse(text: String) -> Dynamic { + let assert Ok(value) = json.parse(text, decode.dynamic) + value +} diff --git a/robot-docs/auth.md b/robot-docs/auth.md index 57812f5c6..d804eca01 100644 --- a/robot-docs/auth.md +++ b/robot-docs/auth.md @@ -145,6 +145,11 @@ request retains its captured label. A snapshot is not a revocation lease: it cannot prevent an already selected request from using a subsequently deleted key. +A saved account records a limit on one meter in `limitedMeters`, or in +`limitedUntil` when the limit named no meter. A `limitedUntil` mark limits the +whole account, so a meter's limit ends at the later of the two +([`accounts.until_of`](../packages/albedo_sdk/src/albedo_sdk/accounts.gleam)). + Environment and inline limits use the process registry in [`accounts.gleam`](../packages/albedo_sdk/src/albedo_sdk/accounts.gleam) rather than credential persistence. Environment marking rechecks the captured variable, -- knotmirror 0.0.1 From 9e695ba8d7c7aaa360a29decc517255e3e383d08 Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Thu, 19 Nov 2026 15:33:54 -0500 Subject: [PATCH 3/7] test(antigravity): check quota reconciliation of limit marks as a property A report must drop ended marks, mark a full meter until its reset, never let a reading with room extend a mark, keep the live mark of a meter it did not mention, and give the same marks on a second identical report. The property replaces nothing in e2e by itself; antigravity_test.py's limit cases rely on it and on rotation_test. --- extensions/antigravity/gleam.toml | 2 + extensions/antigravity/manifest.toml | 7 + .../reconcile_test.gleam | 169 ++++++++++++++++++ 3 files changed, 178 insertions(+) create mode 100644 extensions/antigravity/test/albedo_ext_antigravity/reconcile_test.gleam diff --git a/extensions/antigravity/gleam.toml b/extensions/antigravity/gleam.toml index a50a5f907..867c56c50 100644 --- a/extensions/antigravity/gleam.toml +++ b/extensions/antigravity/gleam.toml @@ -28,3 +28,5 @@ albedo_sdk = { path = "../../packages/albedo_sdk" } [dev_dependencies] gleeunit = ">= 1.0.0 and < 2.0.0" +qcheck = ">= 1.0.5 and < 2.0.0" +albedo_property = { path = "../../packages/albedo_property" } diff --git a/extensions/antigravity/manifest.toml b/extensions/antigravity/manifest.toml index 4c63fe4ef..ec7a16db2 100644 --- a/extensions/antigravity/manifest.toml +++ b/extensions/antigravity/manifest.toml @@ -22,6 +22,7 @@ packages = [ { name = "albedo_openai", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_bytes", "albedo_http", "albedo_json", "albedo_model", "albedo_model_stream", "albedo_sse", "gleam_json", "gleam_stdlib"], source = "local", path = "../../packages/albedo_openai" }, { name = "albedo_ports", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_clock", "albedo_protect", "gleam_erlang", "gleam_stdlib"], source = "local", path = "../../packages/albedo_ports" }, { name = "albedo_process", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_clock", "albedo_protect", "gleam_erlang", "gleam_otp", "gleam_stdlib"], source = "local", path = "../../packages/albedo_process" }, + { name = "albedo_property", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_env", "albedo_protect", "gleam_erlang", "gleam_stdlib", "qcheck"], source = "local", path = "../../packages/albedo_property" }, { name = "albedo_protect", version = "0.1.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_stdlib"], source = "local", path = "../../packages/albedo_protect" }, { name = "albedo_sdk", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_bytes", "albedo_clock", "albedo_env", "albedo_file", "albedo_http", "albedo_image", "albedo_json", "albedo_model", "albedo_model_stream", "albedo_oauth", "albedo_openai", "albedo_ports", "albedo_process", "albedo_protect", "albedo_sqlite", "albedo_web", "gleam_crypto", "gleam_erlang", "gleam_http", "gleam_json", "gleam_otp", "gleam_stdlib", "mist", "sqlight", "yamerl"], source = "local", path = "../../packages/albedo_sdk" }, { name = "albedo_sqlite", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_clock", "albedo_process", "esqlite", "gleam_erlang", "gleam_otp", "gleam_stdlib", "sqlight"], source = "local", path = "../../packages/albedo_sqlite" }, @@ -34,13 +35,17 @@ packages = [ { name = "gleam_http", version = "4.4.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_http", source = "hex", outer_checksum = "F065CE9941A7756ABBAEAE7F9F32A96CAD29DA3311A381DB2D926EA8E8C156DC" }, { name = "gleam_json", version = "3.1.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_json", source = "hex", outer_checksum = "44FDAA8847BE8FC48CA7A1C089706BD54BADCC4C45B237A992EDDF9F2CDB2836" }, { name = "gleam_otp", version = "1.3.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_stdlib"], otp_app = "gleam_otp", source = "hex", outer_checksum = "DE4CA6850842F0266EE95317A25DD6A0A0F20CDFAB7C0ADC2E63251D7C3C72EC" }, + { name = "gleam_regexp", version = "1.1.1", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_regexp", source = "hex", outer_checksum = "9C215C6CA84A5B35BB934A9B61A9A306EC743153BE2B0425A0D032E477B062A9" }, { name = "gleam_stdlib", version = "1.0.5", build_tools = ["gleam"], requirements = [], otp_app = "gleam_stdlib", source = "hex", outer_checksum = "CEE5B6C076A85B45F60C585F4316C63EC8B7127C119D5738C3958A9C4D50404E" }, + { name = "gleam_yielder", version = "1.1.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_yielder", source = "hex", outer_checksum = "8E4E4ECFA7982859F430C57F549200C7749823C106759F4A19A78AEA6687717A" }, { name = "gleeunit", version = "1.11.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleeunit", source = "hex", outer_checksum = "EC31ABA74256AEA531EDF8169931D775BBB384FED0A8A1BDC4DD9354E3E21826" }, { name = "glisten", version = "9.0.1", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_otp", "gleam_stdlib", "logging"], otp_app = "glisten", source = "hex", outer_checksum = "7795AA50830656F3A0316A6B26595F893C83272DA901B3405E31339CAA31A10B" }, { name = "gramps", version = "6.0.1", build_tools = ["gleam"], requirements = ["gleam_crypto", "gleam_erlang", "gleam_http", "gleam_stdlib"], otp_app = "gramps", source = "hex", outer_checksum = "D55636072DEE173F6586A5679D3C02EC7A0DE3F8646B78C351B72908FF223DF7" }, { name = "hpack_erl", version = "0.3.0", build_tools = ["rebar3"], requirements = [], otp_app = "hpack", source = "hex", outer_checksum = "D6137D7079169D8C485C6962DFE261AF5B9EF60FBC557344511C1E65E3D95FB0" }, { name = "logging", version = "1.5.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "logging", source = "hex", outer_checksum = "BC5F18CE5DD9686100229FE5409BDC3DD5C46D5A7DF2F804AD2D8F0DD6C5060E" }, { name = "mist", version = "6.0.3", build_tools = ["gleam"], requirements = ["exception", "gleam_erlang", "gleam_http", "gleam_otp", "gleam_stdlib", "glisten", "gramps", "hpack_erl", "logging"], source = "local", path = "../../vendor/mist" }, + { name = "prng", version = "6.0.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "prng", source = "hex", outer_checksum = "7FE3879E13150248BD370469205ED07B9404DD90670FEBB8CD0E7643707C420E" }, + { name = "qcheck", version = "1.0.5", build_tools = ["gleam"], requirements = ["exception", "gleam_regexp", "gleam_stdlib", "gleam_yielder", "prng"], otp_app = "qcheck", source = "hex", outer_checksum = "D27C12074776EC95F082EE56E0FC74685506B6EE26176F194D10F0322A39AC11" }, { name = "sqlight", version = "1.2.0", build_tools = ["gleam"], requirements = ["esqlite", "gleam_stdlib"], otp_app = "sqlight", source = "hex", outer_checksum = "841768D0A81107EE2DB46B949354F284A68B2E8098315C28A1FE3C07D206C17A" }, { name = "yamerl", version = "0.10.0", build_tools = ["rebar3"], requirements = [], otp_app = "yamerl", source = "hex", outer_checksum = "346ADB2963F1051DC837A2364E4ACF6EB7D80097C0F53CBDC3046EC8EC4B4E6E" }, ] @@ -58,10 +63,12 @@ albedo_model_stream = { path = "../../packages/albedo_model_stream" } albedo_models_dev = { path = "../../packages/albedo_models_dev" } albedo_openai = { path = "../../packages/albedo_openai" } albedo_process = { path = "../../packages/albedo_process" } +albedo_property = { path = "../../packages/albedo_property" } albedo_protect = { path = "../../packages/albedo_protect" } albedo_sdk = { path = "../../packages/albedo_sdk" } gleam_erlang = { version = ">= 1.3.0 and < 2.0.0" } gleam_json = { version = ">= 3.1.0 and < 4.0.0" } gleam_stdlib = { version = ">= 1.0.0 and < 2.0.0" } gleeunit = { version = ">= 1.0.0 and < 2.0.0" } +qcheck = { version = ">= 1.0.5 and < 2.0.0" } sqlight = { version = ">= 1.2.0 and < 2.0.0" } diff --git a/extensions/antigravity/test/albedo_ext_antigravity/reconcile_test.gleam b/extensions/antigravity/test/albedo_ext_antigravity/reconcile_test.gleam new file mode 100644 index 000000000..b40d98064 --- /dev/null +++ b/extensions/antigravity/test/albedo_ext_antigravity/reconcile_test.gleam @@ -0,0 +1,169 @@ +//// How a quota report updates an Antigravity account's limit marks. The +//// defects: a mark kept after it ended, a full meter left selectable before +//// its reset, a reading with room extending a mark, a meter the report did not +//// mention losing its mark, and a second identical report changing the +//// result. `reconcile_marks` is the pure policy the heal applies. + +import albedo_ext_antigravity/accounts +import albedo_property +import gleam/dict.{type Dict} +import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode +import gleam/int +import gleam/json +import gleam/list +import gleam/option.{type Option, None, Some} +import qcheck.{type Generator} + +const now = 1000 + +type Reading = + #(String, Option(Float), Option(Int)) + +type Case { + Case(marks: Dict(String, Int), global: Option(Int), readings: List(Reading)) +} + +pub fn a_report_updates_marks_without_extending_or_dropping_live_ones_test() -> Nil { + use Case(marks:, global:, readings:) <- albedo_property.run(400, case_()) + let #(remove_global, out) = + accounts.reconcile_marks(raw(marks, global), readings, now) + assert remove_global == option.is_some(global) + dict.each(out, fn(meter, until) { + assert until > now as { meter <> " keeps a mark that has ended" } + }) + let reported = list.map(readings, fn(reading) { reading.0 }) + dict.each(marks, fn(meter, until) { + case list.contains(reported, meter) { + True -> Nil + False -> { + let expected = case until > now { + True -> Ok(until) + False -> Error(Nil) + } + assert dict.get(out, meter) == expected + as { meter <> " was not reported, so its live mark stays" } + } + } + }) + list.each(readings, fn(reading) { + let #(meter, used, reset) = reading + case used, reset { + Some(used), Some(reset) if used >=. 100.0 && reset > now -> { + assert dict.get(out, meter) == Ok(reset) + as { meter <> " is full until its reset" } + } + Some(used), _ if used <. 100.0 -> { + let before = + int.max(dict.get(marks, meter) |> result_or(0), case global, reset { + Some(global), Some(reset) if global == reset -> global + _, _ -> 0 + }) + assert dict.get(out, meter) |> result_or(0) <= before + as { meter <> " has room, so its mark must not grow" } + } + _, _ -> Nil + } + }) + assert accounts.reconcile_marks(raw(out, None), readings, now) + == #(False, out) + as "a second identical report changes the marks" +} + +/// A legacy mark the report has no meter for is removed: the report is newer +/// than the mark and quota.md states it. A matching meter takes it over. +pub fn a_legacy_mark_moves_to_the_meter_whose_reset_it_matches_test() -> Nil { + assert accounts.reconcile_marks( + raw(dict.new(), Some(2000)), + [ + #("claude", Some(100.0), Some(2000)), + #("gemini", Some(10.0), Some(1500)), + ], + now, + ) + == #(True, dict.from_list([#("claude", 2000)])) + assert accounts.reconcile_marks(raw(dict.new(), Some(2000)), [], now) + == #(True, dict.new()) +} + +fn case_() -> Generator(Case) { + qcheck.map3( + qcheck.generic_list( + qcheck.tuple2(meter(), time()), + qcheck.bounded_int(0, 4), + ), + qcheck.option_from(time()), + qcheck.generic_list( + qcheck.tuple3( + meter(), + qcheck.option_from(used()), + qcheck.option_from(time()), + ), + qcheck.bounded_int(0, 4), + ), + fn(marks, global, readings) { + // A report names each meter once. + let readings = + list.fold(readings, [], fn(kept: List(Reading), reading: Reading) { + case list.any(kept, fn(other: Reading) { other.0 == reading.0 }) { + True -> kept + False -> [reading, ..kept] + } + }) + Case(dict.from_list(marks), global, readings) + }, + ) +} + +fn meter() -> Generator(String) { + qcheck.from_generators(qcheck.return("claude"), [ + qcheck.return("gemini"), + qcheck.return("gpt-oss"), + qcheck.return("other"), + ]) +} + +/// Before, at, and after `now`, so marks end, match resets, and collide. +fn time() -> Generator(Int) { + qcheck.from_generators(qcheck.return(0), [ + qcheck.return(500), + qcheck.return(now), + qcheck.return(1500), + qcheck.return(2000), + ]) +} + +fn used() -> Generator(Float) { + qcheck.from_generators(qcheck.return(0.0), [ + qcheck.return(50.0), + qcheck.return(99.9), + qcheck.return(100.0), + qcheck.return(120.0), + ]) +} + +fn raw(marks: Dict(String, Int), global: Option(Int)) -> Dynamic { + let fields = [ + #( + "limitedMeters", + json.object( + dict.to_list(marks) + |> list.map(fn(entry) { #(entry.0, json.int(entry.1)) }), + ), + ), + ..case global { + Some(until) -> [#("limitedUntil", json.int(until))] + None -> [] + } + ] + let assert Ok(value) = + json.parse(json.to_string(json.object(fields)), decode.dynamic) + value +} + +fn result_or(result: Result(Int, Nil), default: Int) -> Int { + case result { + Ok(value) -> value + Error(Nil) -> default + } +} -- knotmirror 0.0.1 From 72ab792147dfd218b73e24d5134e1bb885138ea0 Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Thu, 19 Nov 2026 15:39:22 -0500 Subject: [PATCH 4/7] test(openai): check the chat reducer and reasoning echo as properties Generated turns (text, reasoning in each field a provider uses, interleaved tool calls, usage, OpenRouter's repeated finish trailers) are encoded as SSE by a test-side encoder, cut at random byte boundaries, and read back through the SSE parser and the chat reducer. One-defect mutations ([DONE] before a finish, no [DONE], a late choice, another finish, a late tool call) must fail and never yield a turn. A second property checks that once the history has `reasoning_content` every assistant message carries it, and otherwise none does. Removed from e2e/chat_stream_test.py (5 of 6 tests, about 8 s), and what now catches each defect: - repeated finish keeping trailing usage and committing the answer once -> a_chat_stream_reads_back_the_turn_it_encodes_at_any_chunking - choices after the finish reason -> a_broken_chat_stream_never_yields_ executable_calls (and the deleted chat_rejects_data_after_finish_reason example it covers) - assistant messages echoing reasoning_content -> assistant_messages_echo_reasoning_once_the_history_has_it - a delta streaming reasoning_text -> the property's reasoning_text field and stream_test.chat_reads_a_delta_that_streams_reasoning_text - reasoning_text portable after a profile change -> albedo_sdk reasoning_text_test.chat_reasoning_text_stays_portable_on_another_profile The [DONE]-before-finish retry stays in chat_stream_test.py for the session area, which owns the model loop's retry. --- e2e/chat_stream_test.py | 173 +----- packages/albedo_openai/gleam.toml | 2 + packages/albedo_openai/manifest.toml | 9 + .../albedo_openai/chat_property_test.gleam | 541 ++++++++++++++++++ .../test/albedo_openai/stream_test.gleam | 12 - .../test/albedo_sdk/reasoning_text_test.gleam | 38 ++ 6 files changed, 597 insertions(+), 178 deletions(-) create mode 100644 packages/albedo_openai/test/albedo_openai/chat_property_test.gleam diff --git a/e2e/chat_stream_test.py b/e2e/chat_stream_test.py index c925bc908..46ece5b6c 100644 --- a/e2e/chat_stream_test.py +++ b/e2e/chat_stream_test.py @@ -1,10 +1,14 @@ -"""Chat finish trailers retain usage without admitting late response data, and -replayed assistant messages keep the reasoning field the provider speaks.""" +"""A chat stream that ends with `[DONE]` before any finish reason is retried, +and its partial output salvaged and resumed, by the model loop. + +How the chat reducer reads a stream is checked in +packages/albedo_openai/test/albedo_openai/chat_property_test.gleam. +""" import json import unittest -from harness import Albedo, Provider, Reply, python, text +from harness import Albedo, Provider, Reply, text def chunk(delta, finish=None): @@ -19,169 +23,6 @@ class ChatStreamTest(unittest.TestCase): self.provider = Provider(lambda _: Reply("text")) self.addCleanup(self.provider.close) - def request_row(self, app, session): - with app.api(f"/sessions/{session}/requests") as response: - [row] = json.load(response)["items"] - return row - - def test_repeated_finish_retains_trailing_usage_and_commits_answer_once(self): - # OpenRouter's shape: both finish chunks repeat the assistant role with - # empty content, and the second carries usage. - finish = chunk({"content": "", "role": "assistant", "reasoning": None}, "stop") - trailer = chunk({"content": "", "role": "assistant"}, "stop") - trailer["usage"] = {"prompt_tokens": 123, "completion_tokens": 7} - self.provider.script = lambda _: Reply( - "text", - events=[chunk({"content": "answer"}), finish, trailer], - ) - with Albedo(self.provider, protocol="chat_completions") as app: - session = app.session(name="chat stream test") - app.prompt(session, "answer once").close() - app.idle(session) - row = self.request_row(app, session) - self.assertEqual(row["outcome"], "completed") - self.assertEqual(row["prompt_tokens"]["observed"], 123) - self.assertEqual(row["completion_tokens"]["observed"], 7) - [answer] = [ - entry - for entry in app.history(session)["items"] - if entry["kind"] == "assistant" - ] - self.assertEqual(answer["content"], [{"kind": "text", "text": "answer"}]) - - def test_post_finish_choices_must_be_empty_and_repeat_the_same_finish(self): - with Albedo(self.provider, protocol="chat_completions") as app: - for delta, finish in [ - ({}, "length"), - ({}, None), - ({"content": "late"}, "stop"), - ({"refusal": "late"}, "stop"), - ({"reasoning": "late"}, "stop"), - ({"reasoning_content": "late"}, "stop"), - ( - {"reasoning_details": [{"type": "reasoning.text", "index": 0}]}, - "stop", - ), - ({"tool_calls": [{"index": 0}]}, "stop"), - ]: - with self.subTest(delta=delta, finish=finish): - self.provider.script = lambda _: Reply( - "text", - events=[ - chunk({"content": "answer"}, "stop"), - chunk(delta, finish), - ], - ) - session = app.session(name="chat stream test") - app.prompt(session, "reject the late choice").close() - app.idle(session) - row = self.request_row(app, session) - self.assertEqual(row["outcome"], "failed") - self.assertIn( - "chat choice after finish reason", row["failure"]["detail"] - ) - # What streamed before the late choice is kept as - # unfinished output; the late choice itself is not. - answers = [ - entry["content"] - for entry in app.history(session)["items"] - if entry["kind"] == "assistant" - ] - self.assertEqual(answers, [[{"kind": "text", "text": "answer"}]]) - - def test_every_assistant_message_echoes_reasoning_once_the_provider_speaks_it(self): - # DeepSeek's thinking mode rejects a tools request whose assistant - # messages lack reasoning_content, even one that never reasoned. - self.provider.script = lambda _: [ - python("x = 1", reasoning="weigh it"), - python("x = 2"), - text("done"), - ] - with Albedo(self.provider, protocol="chat_completions") as app: - session = app.session(name="chat stream test") - app.prompt(session, "two steps").close() - app.idle(session) - last = self.provider.requests[-1]["request"]["messages"] - echoed = [ - message.get("reasoning_content") - for message in last - if message["role"] == "assistant" - ] - self.assertEqual(echoed, ["weigh it", ""]) - - def test_a_provider_that_streams_reasoning_text_completes_the_turn(self): - # Copilot's Gemini route streams its thinking as reasoning_text, in the - # same delta as content. Refusing that field failed the whole turn with - # "unsupported nonempty field reasoning_text". - self.provider.script = lambda _: Reply( - "text", - events=[ - chunk( - {"content": None, "role": "assistant", "reasoning_text": "weigh it"} - ), - chunk( - {"content": "answer", "role": "assistant", "reasoning_text": None} - ), - chunk({}, "stop"), - ], - ) - with Albedo(self.provider, protocol="chat_completions") as app: - session = app.session(name="chat stream test") - app.prompt(session, "think").close() - app.idle(session) - answers = [ - entry["content"] - for entry in app.history(session)["items"] - if entry["kind"] == "assistant" - ] - self.assertEqual(answers, [[{"kind": "text", "text": "answer"}]]) - - def test_reasoning_text_remains_portable_after_a_profile_change(self): - first = Reply( - "raw", - events=[ - chunk( - { - "role": "assistant", - "content": "answer", - "reasoning_text": "weigh it", - } - ), - chunk({}, "stop"), - ], - ) - replies = iter([first, text("continued")]) - self.provider.script = lambda _: next(replies, text("summary")) - profile = { - "extension": "openai", - "baseUrl": self.provider.url, - "apiKey": "fixture", - "model": "fixture", - "protocol": "chat_completions", - } - with Albedo(providers={"first": profile, "second": profile}) as app: - session = app.session() - app.prompt(session, "think").close() - app.idle(session) - route = f"/sessions/{session}/configuration" - with app.api(route) as response: - etag = response.headers["ETag"] - app.api( - route, - {"provider_profile": "second"}, - method="PATCH", - headers={"If-Match": etag}, - ).close() - app.prompt(session, "continue under another profile").close() - app.idle(session) - self.assertIn("continued", json.dumps(app.history(session))) - assistant = [ - message["content"] - for message in self.provider.requests[-1]["request"]["messages"] - if message.get("role") == "assistant" - ] - self.assertIn("weigh it", "\n".join(assistant)) - def test_done_before_finish_reason_retries_empty_and_resumes_partial_output(self): # Copilot's Gemini chat route can send an opening chunk and `[DONE]` # without ever emitting `finish_reason`, or cut off mid-answer with diff --git a/packages/albedo_openai/gleam.toml b/packages/albedo_openai/gleam.toml index 3e1419899..4f2a423bd 100644 --- a/packages/albedo_openai/gleam.toml +++ b/packages/albedo_openai/gleam.toml @@ -18,3 +18,5 @@ albedo_sse = { path = "../albedo_sse" } [dev_dependencies] gleeunit = ">= 1.0.0 and < 2.0.0" +qcheck = ">= 1.0.5 and < 2.0.0" +albedo_property = { path = "../albedo_property" } diff --git a/packages/albedo_openai/manifest.toml b/packages/albedo_openai/manifest.toml index cd1ae2f84..824b6e379 100644 --- a/packages/albedo_openai/manifest.toml +++ b/packages/albedo_openai/manifest.toml @@ -9,19 +9,26 @@ packages = [ { name = "albedo_bytes", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_protect", "gleam_crypto", "gleam_erlang", "gleam_stdlib"], source = "local", path = "../albedo_bytes" }, { name = "albedo_clock", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_protect", "gleam_erlang", "gleam_stdlib"], source = "local", path = "../albedo_clock" }, + { name = "albedo_env", version = "0.1.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_stdlib"], source = "local", path = "../albedo_env" }, { name = "albedo_http", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_bytes", "albedo_clock", "albedo_protect", "gleam_erlang", "gleam_stdlib"], source = "local", path = "../albedo_http" }, { name = "albedo_json", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_bytes", "albedo_protect", "gleam_erlang", "gleam_json", "gleam_stdlib"], source = "local", path = "../albedo_json" }, { name = "albedo_model", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_http", "albedo_json", "albedo_process", "albedo_protect", "gleam_crypto", "gleam_json", "gleam_stdlib"], source = "local", path = "../albedo_model" }, { name = "albedo_model_stream", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_clock", "albedo_http", "albedo_model", "gleam_stdlib"], source = "local", path = "../albedo_model_stream" }, { name = "albedo_process", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_clock", "albedo_protect", "gleam_erlang", "gleam_otp", "gleam_stdlib"], source = "local", path = "../albedo_process" }, + { name = "albedo_property", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_env", "albedo_protect", "gleam_erlang", "gleam_stdlib", "qcheck"], source = "local", path = "../albedo_property" }, { name = "albedo_protect", version = "0.1.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_stdlib"], source = "local", path = "../albedo_protect" }, { name = "albedo_sse", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_bytes", "gleam_stdlib"], source = "local", path = "../albedo_sse" }, + { name = "exception", version = "2.1.1", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "exception", source = "hex", outer_checksum = "6BDEA95248093599391C3B5DF1835C5C6A86C353C2F99CE539B450E3432FE117" }, { name = "gleam_crypto", version = "1.6.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_crypto", source = "hex", outer_checksum = "2DE9E4EF53CF6FEE049D4F765731F7178F7A11AEFAE00EEE63BF7536B354AD3F" }, { name = "gleam_erlang", version = "1.3.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_erlang", source = "hex", outer_checksum = "1124AD3AA21143E5AF0FC5CF3D9529F6DB8CA03E43A55711B60B6B7B3874375C" }, { name = "gleam_json", version = "3.1.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_json", source = "hex", outer_checksum = "44FDAA8847BE8FC48CA7A1C089706BD54BADCC4C45B237A992EDDF9F2CDB2836" }, { name = "gleam_otp", version = "1.3.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_stdlib"], otp_app = "gleam_otp", source = "hex", outer_checksum = "DE4CA6850842F0266EE95317A25DD6A0A0F20CDFAB7C0ADC2E63251D7C3C72EC" }, + { name = "gleam_regexp", version = "1.1.1", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_regexp", source = "hex", outer_checksum = "9C215C6CA84A5B35BB934A9B61A9A306EC743153BE2B0425A0D032E477B062A9" }, { name = "gleam_stdlib", version = "1.0.5", build_tools = ["gleam"], requirements = [], otp_app = "gleam_stdlib", source = "hex", outer_checksum = "CEE5B6C076A85B45F60C585F4316C63EC8B7127C119D5738C3958A9C4D50404E" }, + { name = "gleam_yielder", version = "1.1.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_yielder", source = "hex", outer_checksum = "8E4E4ECFA7982859F430C57F549200C7749823C106759F4A19A78AEA6687717A" }, { name = "gleeunit", version = "1.11.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleeunit", source = "hex", outer_checksum = "EC31ABA74256AEA531EDF8169931D775BBB384FED0A8A1BDC4DD9354E3E21826" }, + { name = "prng", version = "6.0.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "prng", source = "hex", outer_checksum = "7FE3879E13150248BD370469205ED07B9404DD90670FEBB8CD0E7643707C420E" }, + { name = "qcheck", version = "1.0.5", build_tools = ["gleam"], requirements = ["exception", "gleam_regexp", "gleam_stdlib", "gleam_yielder", "prng"], otp_app = "qcheck", source = "hex", outer_checksum = "D27C12074776EC95F082EE56E0FC74685506B6EE26176F194D10F0322A39AC11" }, ] [requirements] @@ -30,7 +37,9 @@ albedo_http = { path = "../albedo_http" } albedo_json = { path = "../albedo_json" } albedo_model = { path = "../albedo_model" } albedo_model_stream = { path = "../albedo_model_stream" } +albedo_property = { path = "../albedo_property" } albedo_sse = { path = "../albedo_sse" } gleam_json = { version = ">= 3.1.0 and < 4.0.0" } gleam_stdlib = { version = ">= 1.0.0 and < 2.0.0" } gleeunit = { version = ">= 1.0.0 and < 2.0.0" } +qcheck = { version = ">= 1.0.5 and < 2.0.0" } diff --git a/packages/albedo_openai/test/albedo_openai/chat_property_test.gleam b/packages/albedo_openai/test/albedo_openai/chat_property_test.gleam new file mode 100644 index 000000000..6a6fc9184 --- /dev/null +++ b/packages/albedo_openai/test/albedo_openai/chat_property_test.gleam @@ -0,0 +1,541 @@ +//// Chat Completions streams, generated from a turn and read back through the +//// SSE parser and the chat reducer. The defects: text, reasoning, or tool +//// arguments lost, doubled, or reordered at a chunk or UTF-8 boundary; a +//// trailing usage chunk dropped; a repeated finish committing the answer +//// twice; and a stream that broke off, or sent data after its finish, still +//// yielding a turn with calls to execute. The encoder below writes the wire +//// shapes from the Chat Completions reference and the gateways named in +//// provider-requests.md, independently of the reducer. + +import albedo_model as types +import albedo_openai/request +import albedo_openai/stream +import albedo_property +import albedo_sse as sse +import gleam/bit_array +import gleam/dynamic/decode +import gleam/int +import gleam/json.{type Json} +import gleam/list +import gleam/option.{type Option, None, Some} +import gleam/string +import qcheck.{type Generator} + +type Call { + Call(id: String, name: String, arguments: List(String)) +} + +type Turn { + Turn( + texts: List(String), + reasoning_field: String, + reasoning: List(String), + calls: List(Call), + finish: String, + usage: Option(#(Int, Int)), + trailers: Int, + ) +} + +type Read { + Read( + turn: Option(types.Turn), + text: String, + thinking: String, + error: Option(types.Error), + ) +} + +pub fn a_chat_stream_reads_back_the_turn_it_encodes_at_any_chunking_test_() -> #( + Atom, + Int, + fn() -> Nil, +) { + timeout(fn() { + use #(turn, cuts) <- albedo_property.run(300, qcheck.tuple2(turn(), cuts())) + let read = read(encode(turn), cuts) + let assert None = read.error as "a valid stream failed" + let assert Some(got) = read.turn as "a valid stream yielded no turn" + let content = string.concat(turn.texts) + let thought = string.concat(turn.reasoning) + assert read.text == content + assert read.thinking == thought + assert got.finish == finish(turn.finish) + assert list.map(got.tool_calls, fn(call) { + #(call.id, call.name, call.arguments) + }) + == case turn.finish { + "tool_calls" -> + list.map(turn.calls, fn(call) { + #(call.id, call.name, string.concat(call.arguments)) + }) + _ -> [] + } + assert option.map(got.usage, fn(usage) { + #(usage.input_tokens, usage.output_tokens) + }) + == turn.usage + let assert [item] = got.output + let message = types.replay_value(item) + assert decode.run( + message, + decode.at(["content"], decode.optional(decode.string)), + ) + == Ok(case content { + "" -> None + _ -> Some(content) + }) + let reasoned = + decode.run(message, decode.at([turn.reasoning_field], decode.string)) + |> option.from_result + assert reasoned + == case thought { + "" -> None + _ -> Some(thought) + } + }) +} + +/// A stream cut short, or one that keeps talking after its finish, fails and +/// never yields calls to execute, whatever was streamed before. +pub fn a_broken_chat_stream_never_yields_executable_calls_test_() -> #( + Atom, + Int, + fn() -> Nil, +) { + timeout(fn() { + use #(turn, mutation, cuts) <- albedo_property.run( + 300, + qcheck.tuple3(turn(), qcheck.bounded_int(0, 4), cuts()), + ) + let frames = encode(turn) + let broken = case mutation { + // [DONE] before any finish reason. + 0 -> list.append(before_finish(turn), ["[DONE]"]) + // No [DONE]. + 1 -> list.take(frames, list.length(frames) - 1) + // A late choice with content after the finish. + 2 -> late(frames, delta([#("content", json.string("late"))]), turn.finish) + // A later chunk with another finish reason. + 3 -> late(frames, delta([]), "content_filter") + // A late tool call fragment. + _ -> + late( + frames, + delta([ + #( + "tool_calls", + json.preprocessed_array([ + json.object([ + #("index", json.int(7)), + #("id", json.string("late")), + #( + "function", + json.object([ + #("name", json.string("python")), + #("arguments", json.string("{}")), + ]), + ), + ]), + ]), + ), + ]), + turn.finish, + ) + } + let read = read(broken, cuts) + assert read.turn == None as "a broken stream yielded a turn" + case mutation { + 1 -> Nil + _ -> { + let assert Some(_) = read.error as "a broken stream did not fail" + Nil + } + } + }) +} + +/// DeepSeek's thinking mode refuses a request whose assistant messages lack +/// `reasoning_content` once any has it. Each assistant message then carries +/// the field, its own value kept; without one in the history none gains it. +pub fn assistant_messages_echo_reasoning_once_the_history_has_it_test() -> Nil { + use history <- albedo_property.run(300, history()) + let assert Ok(messages) = request.inputs(types.ChatCompletions, history) + let speaks = + list.any(history, fn(input) { + case input { + types.Replay(item) -> types.replay_has(item, "reasoning_content") + _ -> False + } + }) + assert list.length(messages) == list.length(history) + list.zip(history, messages) + |> list.each(fn(pair) { + let #(input, message) = pair + let message = json.to_string(message) + let role = json.parse(message, decode.at(["role"], decode.string)) + let reasoning = + json.parse(message, decode.at(["reasoning_content"], decode.string)) + |> option.from_result + let expected = case role, input { + Ok("assistant"), types.Replay(item) -> + case + types.inspect_item( + item, + decode.at(["reasoning_content"], decode.string), + ) + { + Ok(own) -> Some(own) + Error(_) if speaks -> Some("") + Error(_) -> None + } + Ok("assistant"), _ if speaks -> Some("") + _, _ -> None + } + assert reasoning == expected + }) +} + +fn history() -> Generator(List(types.Input)) { + qcheck.generic_list( + qcheck.from_generators(qcheck.map(text(), types.User), [ + qcheck.map(text(), types.Assistant), + qcheck.map(text(), fn(text) { types.ToolOutput("call_0", text, []) }), + qcheck.map2(text(), qcheck.option_from(text()), fn(text, reasoning) { + let fields = [ + #("role", json.string("assistant")), + #("content", json.string(text)), + ..case reasoning { + Some(reasoning) -> [#("reasoning_content", json.string(reasoning))] + None -> [] + } + ] + let assert Ok(item) = + json.parse( + json.to_string(json.object(fields)), + types.replay_decoder(types.ChatCompletions), + ) + types.Replay(item) + }), + ]), + qcheck.bounded_int(0, 6), + ) +} + +/// No line of text crashes the reducer; it answers with a result. +pub fn arbitrary_chunk_data_never_crashes_the_chat_reducer_test() -> Nil { + use data <- albedo_property.run( + 300, + qcheck.from_generators(qcheck.string(), [ + qcheck.map(turn(), fn(turn) { string.join(encode(turn), "") }), + qcheck.map(qcheck.string(), fn(text) { "{\"choices\":" <> text }), + ]), + ) + let _ = stream.feed(stream.new(types.ChatCompletions), sse.Event("", data)) + Nil +} + +// ---- the reference encoder -------------------------------------------------- + +/// Each frame's data, ending with `[DONE]`. +fn encode(turn: Turn) -> List(String) { + list.flatten([before_finish(turn), finish_frames(turn), ["[DONE]"]]) +} + +fn before_finish(turn: Turn) -> List(String) { + let opening = [ + chunk( + delta([ + #("role", json.string("assistant")), + #("content", json.null()), + ]), + None, + None, + ), + ] + let reasoning = + list.map(turn.reasoning, fn(text) { + chunk(delta([#(turn.reasoning_field, json.string(text))]), None, None) + }) + let texts = + list.map(turn.texts, fn(text) { + chunk(delta([#("content", json.string(text))]), None, None) + }) + list.flatten([opening, reasoning, texts, tool_frames(turn.calls)]) +} + +/// The calls' fragments, interleaved: every call opens with its id and name, +/// then their argument fragments alternate between calls. +fn tool_frames(calls: List(Call)) -> List(String) { + let indexed = list.index_map(calls, fn(call, index) { #(index, call) }) + let opening = + list.map(indexed, fn(entry) { + let #(index, call) = entry + tool_chunk(index, [ + #("id", json.string(call.id)), + #("type", json.string("function")), + #( + "function", + json.object([ + #("name", json.string(call.name)), + #("arguments", json.string("")), + ]), + ), + ]) + }) + let longest = + list.fold(calls, 0, fn(most, call) { + int.max(most, list.length(call.arguments)) + }) + let fragments = + positions(longest) + |> list.flat_map(fn(position) { + list.filter_map(indexed, fn(entry) { + let #(index, call) = entry + case list.drop(call.arguments, position) { + [fragment, ..] -> + Ok( + tool_chunk(index, [ + #( + "function", + json.object([#("arguments", json.string(fragment))]), + ), + ]), + ) + [] -> Error(Nil) + } + }) + }) + list.append(opening, fragments) +} + +fn positions(count: Int) -> List(Int) { + case count <= 0 { + True -> [] + False -> list.append(positions(count - 1), [count - 1]) + } +} + +fn tool_chunk(index: Int, fields: List(#(String, Json))) -> String { + chunk( + delta([ + #( + "tool_calls", + json.preprocessed_array([ + json.object([#("index", json.int(index)), ..fields]), + ]), + ), + ]), + None, + None, + ) +} + +/// The finish chunk, then OpenRouter's trailers: each repeats the finish with +/// the assistant role and empty content, and the last carries the usage. +fn finish_frames(turn: Turn) -> List(String) { + let usage = option.map(turn.usage, usage_json) + let empty = + delta([#("content", json.string("")), #("role", json.string("assistant"))]) + case turn.trailers { + 0 -> [chunk(delta([]), Some(turn.finish), usage)] + count -> [ + chunk(delta([]), Some(turn.finish), None), + ..list.append( + list.repeat(chunk(empty, Some(turn.finish), None), count - 1), + [chunk(empty, Some(turn.finish), usage)], + ) + ] + } +} + +/// `frames` with a chunk carrying `delta` and `finish` before `[DONE]`. +fn late(frames: List(String), delta: Json, finish: String) -> List(String) { + list.append(list.take(frames, list.length(frames) - 1), [ + chunk(delta, Some(finish), None), + "[DONE]", + ]) +} + +fn delta(fields: List(#(String, Json))) -> Json { + json.object(fields) +} + +fn chunk(delta: Json, finish: Option(String), usage: Option(Json)) -> String { + let choice = + json.object([ + #("index", json.int(0)), + #("delta", delta), + #("finish_reason", json.nullable(finish, json.string)), + ]) + json.object([ + #("id", json.string("chatcmpl-1")), + #("choices", json.preprocessed_array([choice])), + ..case usage { + Some(usage) -> [#("usage", usage)] + None -> [] + } + ]) + |> json.to_string +} + +fn usage_json(usage: #(Int, Int)) -> Json { + json.object([ + #("prompt_tokens", json.int(usage.0)), + #("completion_tokens", json.int(usage.1)), + ]) +} + +fn finish(reason: String) -> types.Finish { + case reason { + "stop" -> types.Complete + "tool_calls" -> types.ToolCalls + "length" -> types.LengthLimit + other -> types.OtherFinish(other) + } +} + +// ---- reading ---------------------------------------------------------------- + +/// Reads the frames as SSE bytes cut at `cuts`, through the parser and the +/// reducer, until a turn or an error. +fn read(frames: List(String), cuts: List(Int)) -> Read { + let bytes = + frames + |> list.map(fn(data) { "data: " <> data <> "\n\n" }) + |> string.concat + |> bit_array.from_string + let start = #( + sse.new(1_000_000), + stream.new(types.ChatCompletions), + Read(None, "", "", None), + ) + let #(_, _, read) = + list.fold(pieces(bytes, cuts), start, fn(state, piece) { + let #(parser, reducer, read) = state + case read.error, read.turn { + None, None -> { + let assert Ok(#(parser, events)) = sse.feed(parser, piece) + let #(reducer, read) = + list.fold(events, #(reducer, read), fn(state, event) { + let #(reducer, read) = state + case read.error, read.turn { + None, None -> + case stream.feed(reducer, event) { + Error(error) -> #(reducer, Read(..read, error: Some(error))) + Ok(#(reducer, events, turn)) -> #( + reducer, + Read(..seen(read, events), turn:), + ) + } + _, _ -> state + } + }) + #(parser, reducer, read) + } + _, _ -> state + } + }) + read +} + +fn seen(read: Read, events: List(types.Event)) -> Read { + list.fold(events, read, fn(read, event) { + case event { + types.TextDelta(_, _, text) -> Read(..read, text: read.text <> text) + types.ThinkingDelta(text) -> Read(..read, thinking: read.thinking <> text) + _ -> read + } + }) +} + +/// `bytes` cut after each size in `cuts` in turn, the rest whole. A cut can +/// split a UTF-8 sequence. +fn pieces(bytes: BitArray, cuts: List(Int)) -> List(BitArray) { + case cuts { + [] -> [bytes] + [size, ..rest] -> { + let total = bit_array.byte_size(bytes) + case size >= total { + True -> [bytes] + False -> { + let assert Ok(head) = bit_array.slice(bytes, 0, size) + let assert Ok(tail) = bit_array.slice(bytes, size, total - size) + [head, ..pieces(tail, rest)] + } + } + } + } +} + +// ---- generators ------------------------------------------------------------- + +fn turn() -> Generator(Turn) { + use texts <- qcheck.bind(fragments(text())) + use reasoning_field <- qcheck.bind( + one_of(["reasoning_content", "reasoning", "reasoning_text"]), + ) + use reasoning <- qcheck.bind(fragments(text())) + use calls <- qcheck.bind(qcheck.generic_list(call(), qcheck.bounded_int(0, 3))) + use finish <- qcheck.bind(case calls { + [] -> one_of(["stop", "length"]) + _ -> qcheck.return("tool_calls") + }) + use usage <- qcheck.bind( + qcheck.option_from(qcheck.tuple2( + qcheck.bounded_int(0, 500), + qcheck.bounded_int(0, 500), + )), + ) + use trailers <- qcheck.map(qcheck.bounded_int(0, 2)) + // Ids follow the call's place, so they are unique, as a provider's are. + let calls = + list.index_map(calls, fn(call, index) { + Call(..call, id: "call_" <> int.to_string(index)) + }) + Turn(texts, reasoning_field, reasoning, calls, finish, usage, trailers) +} + +fn call() -> Generator(Call) { + qcheck.map2( + one_of(["python", "read_file"]), + fragments(one_of(["{", "\"x\":", "1", "}", "\"é\"", " "])), + fn(name, arguments) { Call("", name, arguments) }, + ) +} + +/// Short nonempty fragments with multibyte and combining characters. +fn text() -> Generator(String) { + one_of(["a", " ", "é", "e\u{301}", "日本", "🚀x", "\n", "\"q\""]) +} + +fn fragments(fragment: Generator(String)) -> Generator(List(String)) { + qcheck.generic_list(fragment, qcheck.bounded_int(0, 4)) +} + +/// Byte sizes to cut the stream at: often tiny, so cuts fall inside a line, +/// a field name, or a UTF-8 sequence. +fn cuts() -> Generator(List(Int)) { + qcheck.generic_list( + qcheck.from_generators(qcheck.bounded_int(1, 3), [ + qcheck.bounded_int(1, 40), + qcheck.bounded_int(40, 400), + ]), + qcheck.bounded_int(0, 30), + ) +} + +fn one_of(values: List(String)) -> Generator(String) { + let assert [first, ..rest] = values + qcheck.from_generators(qcheck.return(first), list.map(rest, qcheck.return)) +} + +/// An eunit test with a timeout long enough for a discovery budget. +fn timeout(run: fn() -> Nil) -> #(Atom, Int, fn() -> Nil) { + #(atom_create("timeout"), 3600, run) +} + +pub type Atom + +@external(erlang, "erlang", "binary_to_atom") +fn atom_create(name: String) -> Atom diff --git a/packages/albedo_openai/test/albedo_openai/stream_test.gleam b/packages/albedo_openai/test/albedo_openai/stream_test.gleam index ed62c7ca8..1e652cd43 100644 --- a/packages/albedo_openai/test/albedo_openai/stream_test.gleam +++ b/packages/albedo_openai/test/albedo_openai/stream_test.gleam @@ -347,18 +347,6 @@ pub fn chat_assembles_name_fragments_and_encodes_tool_only_content_as_null_test( let assert Error(types.InvalidEvent(_)) = send(state, "", "[DONE]") } -pub fn chat_rejects_data_after_finish_reason_test() -> Result( - #(stream.State, List(types.Event), Option(types.Turn)), - types.Error, -) { - let first = - "{\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}" - let late = "{\"choices\":[{\"index\":0,\"delta\":{\"content\":\"late\"}}]}" - let assert Ok(#(state, _, None)) = - send(stream.new(types.ChatCompletions), "", first) - let assert Error(types.InvalidEvent(_)) = send(state, "", late) -} - pub fn responses_rejects_incomplete_call_in_completed_response_test() -> Result( #(stream.State, List(types.Event), Option(types.Turn)), types.Error, diff --git a/packages/albedo_sdk/test/albedo_sdk/reasoning_text_test.gleam b/packages/albedo_sdk/test/albedo_sdk/reasoning_text_test.gleam index 589ccdc77..4d15b8095 100644 --- a/packages/albedo_sdk/test/albedo_sdk/reasoning_text_test.gleam +++ b/packages/albedo_sdk/test/albedo_sdk/reasoning_text_test.gleam @@ -5,8 +5,12 @@ import albedo_model as types import albedo_sdk/message_content +import albedo_sdk/projection +import albedo_sdk/transcript import gleam/json +import gleam/list import gleam/option +import gleam/string import gleeunit/should fn responses(body: String) -> types.ReplayItem { @@ -33,3 +37,37 @@ pub fn a_message_item_is_still_an_answer_test() -> Nil { message_content.output_text(item) |> should.equal("use the first route") message_content.thinking_text(item) |> should.equal("") } + +/// Copilot's Gemini route keeps its thinking in `reasoning_text`. Moved to +/// another profile, the answer and that thinking both reach the new model as +/// portable text. +pub fn chat_reasoning_text_stays_portable_on_another_profile_test() -> Nil { + let assert Ok(item) = + json.parse( + "{\"role\":\"assistant\",\"content\":\"answer\",\"reasoning_text\":\"weigh it\"}", + types.replay_decoder(types.ChatCompletions), + ) + let entry = + transcript.Entry( + types.Replay(item), + option.None, + option.Some("first"), + option.None, + option.None, + option.None, + False, + ) + let assert Ok(inputs) = + projection.for_model([entry], "second", types.ChatCompletions, fn(item) { + item + }) + let texts = + list.filter_map(inputs, fn(input) { + case input { + types.Assistant(text) -> Ok(text) + _ -> Error(Nil) + } + }) + assert list.any(texts, string.contains(_, "weigh it")) + assert list.any(texts, string.contains(_, "answer")) +} -- knotmirror 0.0.1 From 689166ad2d4605547d6f7d3c0912be9f7fb0792d Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Thu, 19 Nov 2026 15:43:50 -0500 Subject: [PATCH 5/7] fix(providers): publish no tool calls from an unfinished reply The model loop runs any tool calls a turn carries, whatever its finish. The Gemini reducer already drops calls from a limited, filtered or failed completion, but the Anthropic Messages reducer and Antigravity's did not: - Anthropic: a `tool_use` block cut by `max_tokens` before any input became a call with `{}` input, which the loop then ran. With partial input the whole turn failed on invalid JSON and lost the text before it. A refusal or a pause after a tool block published the call too. - Antigravity: a functionCall part in a reply that finished with MAX_TOKENS, SAFETY or another non-STOP reason was published as a call. Both now keep calls only when the reply finished normally or to call tools, and drop the call blocks from the replayed message, so a later request never carries a call without its result. workspace-packages.md states the rule for every reducer. --- .../src/albedo_ext_antigravity/stream.gleam | 17 ++++- .../extension_test.gleam | 23 +++++++ .../src/albedo_anthropic/stream.gleam | 16 ++++- .../unfinished_calls_test.gleam | 68 +++++++++++++++++++ robot-docs/workspace-packages.md | 5 +- 5 files changed, 125 insertions(+), 4 deletions(-) create mode 100644 packages/albedo_anthropic/test/albedo_anthropic/unfinished_calls_test.gleam diff --git a/extensions/antigravity/src/albedo_ext_antigravity/stream.gleam b/extensions/antigravity/src/albedo_ext_antigravity/stream.gleam index 9ed706076..09e425444 100644 --- a/extensions/antigravity/src/albedo_ext_antigravity/stream.gleam +++ b/extensions/antigravity/src/albedo_ext_antigravity/stream.gleam @@ -225,8 +225,21 @@ fn calls(blocks: List(Block)) -> List(types.ToolCall) { } fn finish(state: State) -> Result(types.Turn, types.Error) { - let blocks = list.reverse(state.blocks) - let calls = calls(state.blocks) + // The loop executes any nonempty tool_calls regardless of finish. A reply + // stopped for its token limit, a filter, or a failure never finished its + // calls, so neither they nor their parts are published or replayed. + let published = case state.finish { + None | Some("STOP") -> state.blocks + Some(_) -> + list.filter(state.blocks, fn(block) { + case block { + Call(..) -> False + _ -> True + } + }) + } + let blocks = list.reverse(published) + let calls = calls(published) case blocks, state.finish { // An empty body is a failed attempt the loop may retry, not an answer. [], None -> Error(types.UnexpectedEnd) diff --git a/extensions/antigravity/test/albedo_ext_antigravity/extension_test.gleam b/extensions/antigravity/test/albedo_ext_antigravity/extension_test.gleam index 576203497..8d9f10252 100644 --- a/extensions/antigravity/test/albedo_ext_antigravity/extension_test.gleam +++ b/extensions/antigravity/test/albedo_ext_antigravity/extension_test.gleam @@ -456,6 +456,29 @@ pub fn a_stream_reports_usage_before_it_fails_test() -> Nil { Nil } +/// The loop runs any calls a turn carries. A reply cut at its token limit or +/// stopped by a safety filter never finished its calls, so none is published, +/// and none is replayed without its result. +pub fn a_limited_or_filtered_reply_publishes_no_calls_test() -> Nil { + list.each(["MAX_TOKENS", "SAFETY", "MALFORMED_FUNCTION_CALL"], fn(reason) { + let payload = + chunk( + "{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"running it\"},{\"functionCall\":{\"name\":\"bash\",\"args\":{\"command\":\"rm\"}}}]},\"finishReason\":\"" + <> reason + <> "\"}]}", + ) + let #(outcome, _) = reduce(gemini, [payload]) + let assert Ok(turn) = outcome + assert turn.tool_calls == [] + assert turn.finish != types.ToolCalls + let assert [item] = turn.output + let replayed = json.to_string(types.replay_json(item)) + assert !string.contains(replayed, "functionCall") + assert !string.contains(replayed, "tool_calls") + assert string.contains(replayed, "running it") + }) +} + pub fn stream_maps_multiple_calls_to_their_emitted_output_indices_test() -> Nil { let payload = chunk( diff --git a/packages/albedo_anthropic/src/albedo_anthropic/stream.gleam b/packages/albedo_anthropic/src/albedo_anthropic/stream.gleam index d252a8cce..07aba4e76 100644 --- a/packages/albedo_anthropic/src/albedo_anthropic/stream.gleam +++ b/packages/albedo_anthropic/src/albedo_anthropic/stream.gleam @@ -329,7 +329,21 @@ fn update( } fn finish(state: State) -> Result(types.Turn, types.Error) { - let blocks = list.reverse(state.blocks) + // The loop executes any nonempty tool_calls regardless of finish. A reply + // stopped for its token limit, a refusal, or a pause never finished its + // calls, so neither they nor their blocks are published or replayed. + let blocks = case state.reason { + None | Some("tool_use") | Some("end_turn") | Some("stop_sequence") -> + state.blocks + Some(_) -> + list.filter(state.blocks, fn(block) { + case block { + Tool(..) -> False + _ -> True + } + }) + } + let blocks = list.reverse(blocks) let calls = list.filter_map(blocks, fn(block) { case block { diff --git a/packages/albedo_anthropic/test/albedo_anthropic/unfinished_calls_test.gleam b/packages/albedo_anthropic/test/albedo_anthropic/unfinished_calls_test.gleam new file mode 100644 index 000000000..11ad02b22 --- /dev/null +++ b/packages/albedo_anthropic/test/albedo_anthropic/unfinished_calls_test.gleam @@ -0,0 +1,68 @@ +//// The model loop runs any tool calls a turn carries, whatever its finish. A +//// reply stopped at its token limit, or refused, never finished its calls, so +//// the reducer must not publish them, nor replay their blocks without results. + +import albedo_anthropic/stream +import albedo_model as types +import albedo_model/cost +import gleam/json +import gleam/list +import gleam/option.{None, Some} +import gleam/string + +pub fn a_tool_call_cut_by_the_token_limit_is_not_published_test() -> Nil { + list.each(["max_tokens", "refusal", "pause_turn"], fn(reason) { + let assert Ok(turn) = + read([ + "{\"type\":\"message_start\",\"message\":{\"id\":\"msg_1\",\"usage\":{\"input_tokens\":3}}}", + "{\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}", + "{\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"running it\"}}", + "{\"type\":\"content_block_start\",\"index\":1,\"content_block\":{\"type\":\"tool_use\",\"id\":\"toolu_1\",\"name\":\"python\",\"input\":{}}}", + "{\"type\":\"content_block_delta\",\"index\":1,\"delta\":{\"type\":\"input_json_delta\",\"partial_json\":\"{\\\"code\\\":\\\"rm\"}}", + "{\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"" + <> reason + <> "\"},\"usage\":{\"output_tokens\":9}}", + "{\"type\":\"message_stop\"}", + ]) + as { reason <> " fails the turn" } + assert turn.tool_calls == [] + assert turn.finish != types.ToolCalls + let assert [item] = turn.output + let replayed = types.replay_json(item) |> json_text + assert !string.contains(replayed, "toolu_1") + assert string.contains(replayed, "running it") + }) +} + +pub fn a_call_cut_before_its_input_is_not_run_with_empty_input_test() -> Nil { + let assert Ok(turn) = + read([ + "{\"type\":\"message_start\",\"message\":{\"id\":\"msg_1\"}}", + "{\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"tool_use\",\"id\":\"toolu_1\",\"name\":\"python\",\"input\":{}}}", + "{\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"max_tokens\"}}", + "{\"type\":\"message_stop\"}", + ]) + assert turn.tool_calls == [] + assert turn.finish == types.LengthLimit +} + +fn read(payloads: List(String)) -> Result(types.Turn, types.Error) { + let reducer = stream.reducer("claude-fixture", [], cost.none) + list.fold(payloads, #(reducer, Error(types.UnexpectedEnd)), fn(state, data) { + let #(reducer, result) = state + case result { + Ok(_) -> state + Error(types.UnexpectedEnd) -> + case reducer.feed(data) { + Ok(#(next, _, Some(turn))) -> #(next, Ok(turn)) + Ok(#(next, _, None)) -> #(next, Error(types.UnexpectedEnd)) + Error(error) -> #(reducer, Error(error)) + } + Error(_) -> state + } + }).1 +} + +fn json_text(value: json.Json) -> String { + json.to_string(value) +} diff --git a/robot-docs/workspace-packages.md b/robot-docs/workspace-packages.md index 2fadfe8b3..a52d51043 100644 --- a/robot-docs/workspace-packages.md +++ b/robot-docs/workspace-packages.md @@ -291,7 +291,10 @@ Two packages hold the model contract every provider protocol shares. a provider stream's `Reducer`, which turns each payload of a response body into `albedo_model` events and settles the turn on a terminal payload or when the body ends. A wire builds one with `wrap` from a state value and its two - transitions. + transitions. The model loop runs any tool calls a turn carries, whatever its + finish, so a reducer publishes calls only from a turn that finished to call + tools. A reply stopped by its token limit, a filter, or a refusal carries no + calls, and its replay keeps no call blocks without results. [`albedo_model_stream/http`](../packages/albedo_model_stream/src/albedo_model_stream/http.gleam) is the streaming HTTP pump every provider wire shares. `exchange` opens the request over the `Transport` its caller passes, the connection options and a -- knotmirror 0.0.1 From ddee139af7326772d134929d6bfe9bc490e20d27 Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Thu, 19 Nov 2026 15:46:21 -0500 Subject: [PATCH 6/7] test(anthropic): check the Messages reducer as a property Generated content blocks (text, signed and unsigned thinking, redacted thinking, tool use with input cut anywhere) are encoded as Messages events, sequential or with every block open at once, and read back. The turn must keep every block's text, signature, and input in block order, replay the signed blocks natively, and keep usage from message_start and message_delta. Every prefix that ends before message_stop, and a stream that sends an error, must yield no turn. The package had no reducer test of its own. --- packages/albedo_anthropic/gleam.toml | 2 + packages/albedo_anthropic/manifest.toml | 9 + .../stream_property_test.gleam | 426 ++++++++++++++++++ 3 files changed, 437 insertions(+) create mode 100644 packages/albedo_anthropic/test/albedo_anthropic/stream_property_test.gleam diff --git a/packages/albedo_anthropic/gleam.toml b/packages/albedo_anthropic/gleam.toml index fbaa1d451..d6426ae96 100644 --- a/packages/albedo_anthropic/gleam.toml +++ b/packages/albedo_anthropic/gleam.toml @@ -15,3 +15,5 @@ albedo_model_stream = { path = "../albedo_model_stream" } [dev_dependencies] gleeunit = ">= 1.0.0 and < 2.0.0" +qcheck = ">= 1.0.5 and < 2.0.0" +albedo_property = { path = "../albedo_property" } diff --git a/packages/albedo_anthropic/manifest.toml b/packages/albedo_anthropic/manifest.toml index 7a3e4b831..a71f8aeff 100644 --- a/packages/albedo_anthropic/manifest.toml +++ b/packages/albedo_anthropic/manifest.toml @@ -9,24 +9,33 @@ packages = [ { name = "albedo_bytes", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_protect", "gleam_crypto", "gleam_erlang", "gleam_stdlib"], source = "local", path = "../albedo_bytes" }, { name = "albedo_clock", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_protect", "gleam_erlang", "gleam_stdlib"], source = "local", path = "../albedo_clock" }, + { name = "albedo_env", version = "0.1.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_stdlib"], source = "local", path = "../albedo_env" }, { name = "albedo_http", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_bytes", "albedo_clock", "albedo_protect", "gleam_erlang", "gleam_stdlib"], source = "local", path = "../albedo_http" }, { name = "albedo_json", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_bytes", "albedo_protect", "gleam_erlang", "gleam_json", "gleam_stdlib"], source = "local", path = "../albedo_json" }, { name = "albedo_model", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_http", "albedo_json", "albedo_process", "albedo_protect", "gleam_crypto", "gleam_json", "gleam_stdlib"], source = "local", path = "../albedo_model" }, { name = "albedo_model_stream", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_clock", "albedo_http", "albedo_model", "gleam_stdlib"], source = "local", path = "../albedo_model_stream" }, { name = "albedo_process", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_clock", "albedo_protect", "gleam_erlang", "gleam_otp", "gleam_stdlib"], source = "local", path = "../albedo_process" }, + { name = "albedo_property", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_env", "albedo_protect", "gleam_erlang", "gleam_stdlib", "qcheck"], source = "local", path = "../albedo_property" }, { name = "albedo_protect", version = "0.1.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_stdlib"], source = "local", path = "../albedo_protect" }, + { name = "exception", version = "2.1.1", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "exception", source = "hex", outer_checksum = "6BDEA95248093599391C3B5DF1835C5C6A86C353C2F99CE539B450E3432FE117" }, { name = "gleam_crypto", version = "1.6.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_crypto", source = "hex", outer_checksum = "2DE9E4EF53CF6FEE049D4F765731F7178F7A11AEFAE00EEE63BF7536B354AD3F" }, { name = "gleam_erlang", version = "1.3.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_erlang", source = "hex", outer_checksum = "1124AD3AA21143E5AF0FC5CF3D9529F6DB8CA03E43A55711B60B6B7B3874375C" }, { name = "gleam_json", version = "3.1.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_json", source = "hex", outer_checksum = "44FDAA8847BE8FC48CA7A1C089706BD54BADCC4C45B237A992EDDF9F2CDB2836" }, { name = "gleam_otp", version = "1.3.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_stdlib"], otp_app = "gleam_otp", source = "hex", outer_checksum = "DE4CA6850842F0266EE95317A25DD6A0A0F20CDFAB7C0ADC2E63251D7C3C72EC" }, + { name = "gleam_regexp", version = "1.1.1", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_regexp", source = "hex", outer_checksum = "9C215C6CA84A5B35BB934A9B61A9A306EC743153BE2B0425A0D032E477B062A9" }, { name = "gleam_stdlib", version = "1.0.5", build_tools = ["gleam"], requirements = [], otp_app = "gleam_stdlib", source = "hex", outer_checksum = "CEE5B6C076A85B45F60C585F4316C63EC8B7127C119D5738C3958A9C4D50404E" }, + { name = "gleam_yielder", version = "1.1.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_yielder", source = "hex", outer_checksum = "8E4E4ECFA7982859F430C57F549200C7749823C106759F4A19A78AEA6687717A" }, { name = "gleeunit", version = "1.11.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleeunit", source = "hex", outer_checksum = "EC31ABA74256AEA531EDF8169931D775BBB384FED0A8A1BDC4DD9354E3E21826" }, + { name = "prng", version = "6.0.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "prng", source = "hex", outer_checksum = "7FE3879E13150248BD370469205ED07B9404DD90670FEBB8CD0E7643707C420E" }, + { name = "qcheck", version = "1.0.5", build_tools = ["gleam"], requirements = ["exception", "gleam_regexp", "gleam_stdlib", "gleam_yielder", "prng"], otp_app = "qcheck", source = "hex", outer_checksum = "D27C12074776EC95F082EE56E0FC74685506B6EE26176F194D10F0322A39AC11" }, ] [requirements] albedo_json = { path = "../albedo_json" } albedo_model = { path = "../albedo_model" } albedo_model_stream = { path = "../albedo_model_stream" } +albedo_property = { path = "../albedo_property" } gleam_json = { version = ">= 3.1.0 and < 4.0.0" } gleam_stdlib = { version = ">= 1.0.0 and < 2.0.0" } gleeunit = { version = ">= 1.0.0 and < 2.0.0" } +qcheck = { version = ">= 1.0.5 and < 2.0.0" } diff --git a/packages/albedo_anthropic/test/albedo_anthropic/stream_property_test.gleam b/packages/albedo_anthropic/test/albedo_anthropic/stream_property_test.gleam new file mode 100644 index 000000000..aebbf5e0f --- /dev/null +++ b/packages/albedo_anthropic/test/albedo_anthropic/stream_property_test.gleam @@ -0,0 +1,426 @@ +//// Anthropic Messages streams, generated from a list of content blocks and +//// read back through the reducer. The defects: text, thinking, a signature, +//// or tool input lost, doubled, or misordered across deltas and interleaved +//// block indices; a signed thinking block replayed without its signature or +//// out of place; usage from `message_start` or `message_delta` dropped; and a +//// stream that broke off, or failed, yielding a turn. The encoder writes the +//// event shapes of Anthropic's streaming reference, independently of the +//// reducer. + +import albedo_anthropic/stream +import albedo_model as types +import albedo_model/cost +import albedo_property +import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode +import gleam/int +import gleam/json.{type Json} +import gleam/list +import gleam/option.{None, Some} +import gleam/string +import qcheck.{type Generator} + +type Block { + Text(chunks: List(String)) + Thinking(chunks: List(String), signature: List(String)) + Redacted(data: String) + Tool(id: String, name: String, input: List(String)) +} + +type Message { + Message( + blocks: List(Block), + stop: String, + input_tokens: Int, + output_tokens: Int, + ) +} + +pub type Atom + +pub fn a_messages_stream_reads_back_the_blocks_it_encodes_test_() -> #( + Atom, + Int, + fn() -> Nil, +) { + timeout(fn() { + use #(message, interleave) <- albedo_property.run( + 300, + qcheck.tuple2(message(), qcheck.bool()), + ) + let #(result, text, thinking) = read(encode(message, interleave), True) + let assert Ok(turn) = result as "a complete stream failed" + let texts = + list.filter_map(message.blocks, fn(block) { + case block { + Text(chunks) -> Ok(string.concat(chunks)) + _ -> Error(Nil) + } + }) + let thoughts = + list.filter_map(message.blocks, fn(block) { + case block { + Thinking(chunks, _) -> Ok(string.concat(chunks)) + _ -> Error(Nil) + } + }) + let tools = + list.filter_map(message.blocks, fn(block) { + case block { + Tool(id, name, input) -> + Ok(types.ToolCall(id, name, arguments(input))) + _ -> Error(Nil) + } + }) + // Streamed deltas arrive in wire order; the settled text in block order. + assert string.length(text) == string.length(string.concat(texts)) + assert string.length(thinking) == string.length(string.concat(thoughts)) + assert turn.tool_calls == tools + assert turn.finish + == case message.stop, tools { + "max_tokens", _ -> types.LengthLimit + _, [] -> types.Complete + _, _ -> types.ToolCalls + } + assert option.map(turn.usage, fn(usage) { + #(usage.input_tokens, usage.output_tokens) + }) + == Some(#(message.input_tokens, message.output_tokens)) + let assert [item] = turn.output + let replay = types.replay_value(item) + assert decode.run(replay, decode.at(["content"], decode.string)) + == Ok(string.concat(texts)) + // Native blocks replay in order with their signatures; an unsigned + // thinking block cannot be replayed to Claude and is left out. + assert native(replay) + == list.filter_map(message.blocks, fn(block) { + case block { + Text(chunks) -> Ok(#("text", string.concat(chunks))) + Thinking(_, []) -> Error(Nil) + Thinking(chunks, signature) -> + Ok(#( + "thinking", + string.concat(chunks) <> "|" <> string.concat(signature), + )) + Redacted(data) -> Ok(#("redacted_thinking", data)) + Tool(id, _, _) -> Ok(#("tool_use", id)) + } + }) + }) +} + +/// Every strict prefix of a stream that ends before `message_stop` settles as +/// an unexpected end, and an error event fails the stream. +pub fn a_cut_or_failed_messages_stream_yields_no_turn_test_() -> #( + Atom, + Int, + fn() -> Nil, +) { + timeout(fn() { + use #(message, cut, fail) <- albedo_property.run( + 300, + qcheck.tuple3(message(), qcheck.small_non_negative_int(), qcheck.bool()), + ) + let events = encode(message, False) + let kept = list.take(events, cut % list.length(events)) + let kept = case fail { + True -> + list.append(kept, [ + "{\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}", + ]) + False -> kept + } + let #(result, _, _) = read(kept, True) + let assert Error(_) = result as "a cut stream settled as a turn" + Nil + }) +} + +// ---- the reference encoder -------------------------------------------------- + +fn encode(message: Message, interleave: Bool) -> List(String) { + let indexed = + list.index_map(message.blocks, fn(block, index) { #(index, block) }) + let starts = list.map(indexed, fn(entry) { start(entry.0, entry.1) }) + let deltas = list.map(indexed, fn(entry) { deltas(entry.0, entry.1) }) + let stops = list.map(indexed, fn(entry) { stop(entry.0) }) + // Sequential blocks, or every block open at once with deltas alternating. + let body = case interleave { + False -> + list.index_map(starts, fn(start, index) { + let assert Ok(own) = list.drop(deltas, index) |> list.first + let assert Ok(stop) = list.drop(stops, index) |> list.first + [start, ..list.append(own, [stop])] + }) + |> list.flatten + True -> list.flatten([starts, alternate(deltas), stops]) + } + list.flatten([ + [ + event("message_start", [ + #( + "message", + json.object([ + #("id", json.string("msg_1")), + #( + "usage", + json.object([ + #("input_tokens", json.int(message.input_tokens)), + #("output_tokens", json.int(1)), + ]), + ), + ]), + ), + ]), + ], + body, + [ + event("message_delta", [ + #("delta", json.object([#("stop_reason", json.string(message.stop))])), + #( + "usage", + json.object([#("output_tokens", json.int(message.output_tokens))]), + ), + ]), + event("message_stop", []), + ], + ]) +} + +fn alternate(lists: List(List(String))) -> List(String) { + case list.filter(lists, fn(items) { items != [] }) { + [] -> [] + lists -> { + let heads = list.filter_map(lists, list.first) + let tails = list.map(lists, fn(items) { list.drop(items, 1) }) + list.append(heads, alternate(tails)) + } + } +} + +fn start(index: Int, block: Block) -> String { + let content = case block { + Text(_) -> [#("type", json.string("text")), #("text", json.string(""))] + Thinking(_, _) -> [ + #("type", json.string("thinking")), + #("thinking", json.string("")), + ] + Redacted(data) -> [ + #("type", json.string("redacted_thinking")), + #("data", json.string(data)), + ] + Tool(id, name, _) -> [ + #("type", json.string("tool_use")), + #("id", json.string(id)), + #("name", json.string(name)), + #("input", json.object([])), + ] + } + event("content_block_start", [ + #("index", json.int(index)), + #("content_block", json.object(content)), + ]) +} + +fn deltas(index: Int, block: Block) -> List(String) { + let delta = fn(kind, field, text) { + event("content_block_delta", [ + #("index", json.int(index)), + #( + "delta", + json.object([#("type", json.string(kind)), #(field, json.string(text))]), + ), + ]) + } + case block { + Text(chunks) -> list.map(chunks, delta("text_delta", "text", _)) + Thinking(chunks, signature) -> + list.append( + list.map(chunks, delta("thinking_delta", "thinking", _)), + list.map(signature, delta("signature_delta", "signature", _)), + ) + Redacted(_) -> [] + Tool(_, _, input) -> + list.map(input, delta("input_json_delta", "partial_json", _)) + } +} + +fn stop(index: Int) -> String { + event("content_block_stop", [#("index", json.int(index))]) +} + +fn event(kind: String, fields: List(#(String, Json))) -> String { + json.object([#("type", json.string(kind)), ..fields]) |> json.to_string +} + +fn arguments(input: List(String)) -> String { + case string.concat(input) { + "" -> "{}" + text -> text + } +} + +// ---- reading ---------------------------------------------------------------- + +/// The settled turn, or the error, with the streamed text and thinking. +/// `settle` ends the body after the last event. +fn read( + events: List(String), + settle: Bool, +) -> #(Result(types.Turn, types.Error), String, String) { + let reducer = stream.reducer("claude-fixture", [], cost.none) + let #(reducer, outcome, text, thinking) = + list.fold(events, #(reducer, None, "", ""), fn(state, data) { + let #(reducer, outcome, text, thinking) = state + case outcome { + Some(_) -> state + None -> + case reducer.feed(data) { + Error(error) -> #(reducer, Some(Error(error)), text, thinking) + Ok(#(next, events, turn)) -> { + let #(text, thinking) = + list.fold(events, #(text, thinking), fn(seen, event) { + case event { + types.TextDelta(_, _, delta) -> #(seen.0 <> delta, seen.1) + types.ThinkingDelta(delta) -> #(seen.0, seen.1 <> delta) + _ -> seen + } + }) + #(next, option.map(turn, Ok), text, thinking) + } + } + } + }) + let outcome = case outcome, settle { + Some(outcome), _ -> outcome + None, True -> reducer.finish() + None, False -> Error(types.UnexpectedEnd) + } + #(outcome, text, thinking) +} + +/// The replayed native blocks as (type, what identifies its content). +fn native(replay: Dynamic) -> List(#(String, String)) { + let block = { + use kind <- decode.field("type", decode.string) + let text = fn(name) { + decode.optional_field(name, "", decode.string, decode.success) + } + use body <- decode.then(case kind { + "text" -> text("text") + "thinking" -> { + use thinking <- decode.field("thinking", decode.string) + use signature <- decode.field("signature", decode.string) + decode.success(thinking <> "|" <> signature) + } + "redacted_thinking" -> text("data") + _ -> text("id") + }) + decode.success(#(kind, body)) + } + decode.run( + replay, + decode.at( + ["reasoning_details"], + decode.list(decode.at(["blocks"], decode.list(block))), + ), + ) + |> option.from_result + |> option.map(list.flatten) + |> option.unwrap([]) +} + +// ---- generators ------------------------------------------------------------- + +fn message() -> Generator(Message) { + use blocks <- qcheck.bind(qcheck.generic_list( + block(), + qcheck.bounded_int(0, 5), + )) + let calls = + list.any(blocks, fn(block) { + case block { + Tool(..) -> True + _ -> False + } + }) + // `tool_use` names a reply with tool blocks; Claude may also end a turn + // that has them. + use stop <- qcheck.bind(case calls { + True -> one_of(["tool_use", "end_turn"]) + False -> one_of(["end_turn", "stop_sequence"]) + }) + use input_tokens <- qcheck.bind(qcheck.bounded_int(0, 1000)) + use output_tokens <- qcheck.map(qcheck.bounded_int(0, 1000)) + // Tool ids are unique, as Anthropic's are. + let blocks = + list.index_map(blocks, fn(block, index) { + case block { + Tool(_, name, input) -> + Tool("toolu_" <> int.to_string(index), name, input) + other -> other + } + }) + Message(blocks, stop, input_tokens, output_tokens) +} + +fn block() -> Generator(Block) { + qcheck.from_generators(qcheck.map(fragments(text()), Text), [ + qcheck.map2( + fragments(text()), + fragments(one_of(["c2ln", "bmF0", "=="])), + Thinking, + ), + qcheck.map(one_of(["EqQBCgIYAh", "b3BhcXVl"]), Redacted), + qcheck.map2(one_of(["python", "read_file"]), input(), fn(name, input) { + Tool("", name, input) + }), + ]) +} + +/// Valid JSON objects, cut into fragments anywhere, multibyte included. +fn input() -> Generator(List(String)) { + use value <- qcheck.bind( + one_of([ + "{}", + "{\"code\":\"print('é')\"}", + "{\"a\":[1,2],\"b\":{\"c\":null}}", + ]), + ) + use cuts <- qcheck.map(qcheck.generic_list( + qcheck.bounded_int(1, 6), + qcheck.bounded_int(0, 4), + )) + split(value, cuts) +} + +fn split(text: String, cuts: List(Int)) -> List(String) { + case cuts, text { + _, "" -> [] + [], _ -> [text] + [size, ..rest], _ -> [ + string.slice(text, 0, size), + ..split(string.drop_start(text, size), rest) + ] + } +} + +fn text() -> Generator(String) { + one_of(["a", " ", "é", "e\u{301}", "日本", "🚀x", "\n"]) +} + +fn fragments(fragment: Generator(String)) -> Generator(List(String)) { + qcheck.generic_list(fragment, qcheck.bounded_int(0, 3)) +} + +fn one_of(values: List(String)) -> Generator(String) { + let assert [first, ..rest] = values + qcheck.from_generators(qcheck.return(first), list.map(rest, qcheck.return)) +} + +fn timeout(run: fn() -> Nil) -> #(Atom, Int, fn() -> Nil) { + #(atom_create("timeout"), 3600, run) +} + +@external(erlang, "erlang", "binary_to_atom") +fn atom_create(name: String) -> Atom -- knotmirror 0.0.1 From 42423915da5b3a269cb81ca5455c3252ee2ecd86 Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Thu, 19 Nov 2026 19:01:48 -0500 Subject: [PATCH 7/7] test(accounts): check one request's rotation against a scripted pool A fake pool of one to ten accounts scripts each attempt's outcome (answer, brief, lasting or unattributed limit, refused credential, failure) and records every attempt and pause. Each step must follow auth.md's rotation rules: hop only to a ready sibling after an attributed limit, wait the documented backoff only when no sibling has room, never wait on a lasting limit, renew a refused credential once in place, and stop after an answer or a failure. Its three renewal examples in albedo's rotation_test are removed. Removed from e2e/account_rotation_test.py (4 of 12 tests), and what now catches each defect: - a plain key profile falling back to another saved key, and a `first` rotation leaving its first key -> plain_and_first_key_profiles_never_reach_another_saved_key - a plain sign-in switching on a limit or rejection -> opencode_go_plain_and_pinned_profiles_do_not_hop and codex_plain_rejected_account_does_not_switch_on_this_or_later_turns - spread starting each session on the next key and keeping it -> spread_starts_each_new_session_on_the_next_account The /auth/keys HTTP cases stay in e2e until the key-store operation model lands. --- .../test/albedo/accounts/rotation_test.gleam | 128 ++++--- e2e/account_rotation_test.py | 99 ------ .../test/albedo_sdk/rotation_test.gleam | 326 ++++++++++++++++++ 3 files changed, 388 insertions(+), 165 deletions(-) create mode 100644 packages/albedo_sdk/test/albedo_sdk/rotation_test.gleam diff --git a/apps/albedo/test/albedo/accounts/rotation_test.gleam b/apps/albedo/test/albedo/accounts/rotation_test.gleam index 06d5f4d8e..ad142162c 100644 --- a/apps/albedo/test/albedo/accounts/rotation_test.gleam +++ b/apps/albedo/test/albedo/accounts/rotation_test.gleam @@ -641,6 +641,68 @@ pub fn openai_rotates_only_between_explicit_key_accounts_test() -> Nil { cleanup(root) } +/// A profile that names no account and keeps its own key, and a `first` +/// rotation, each send only their own key: a limit fails the request rather +/// than move it to another saved key. +pub fn plain_and_first_key_profiles_never_reach_another_saved_key_test() -> Nil { + let #(root, _, home) = fixture() + let first_key = "ka-" <> int.to_string(unique()) + let second_key = "kb-" <> int.to_string(unique()) + let own_key = "own-" <> int.to_string(unique()) + let _ = + write( + home, + "config.json", + "{\"accountsVersion\":2,\"providers\":{\"first\":{\"extension\":\"openai\",\"accountIds\":[\"one\",\"two\"],\"rotation\":\"first\",\"protocol\":\"chat_completions\"},\"plain\":{\"extension\":\"openai\",\"baseUrl\":\"http://127.0.0.1:1/a\",\"protocol\":\"chat_completions\"}}}", + ) + let saved = key_accounts("openai", first_key, second_key) + let _ = + write( + home, + "creds.json", + string.drop_end(saved, 1) + <> ",\"providers\":{\"plain\":{\"apiKey\":\"" + <> own_key + <> "\"}}}", + ) + let body = + "{\"error\":{\"message\":\"Account billing exhausted.\",\"code\":\"Throttling.AllocationQuota\"}}" + list.each([#("first", first_key), #("plain", own_key)], fn(entry) { + let #(profile, key) = entry + let tried = process.new_subject() + let pool = + openai.pool( + home, + profile, + profile <> "-session", + types.ChatCompletions, + key_environment.empty(), + ) + let assert Ok(account) = pool.current() + assert account.client.api_key == key + let outcome = + rotation.stream( + rotation.Pool( + ..pool, + stream: limited_stream( + [first_key, second_key, own_key], + refusal.openai(429, body), + tried, + api_key, + ), + ), + account, + albedo_openai.request("qwen3.8-max", [types.User("hi")]), + fn(_) { types.Continue }, + rotation.Budget(8, 0, fn(_) { Nil }, False), + fn(_) { Nil }, + ) + should_be_limited(outcome) + assert list.unique(drain(tried, [])) == [key] + }) + cleanup(root) +} + pub fn opencode_go_rotates_and_sends_session_header_test() -> Nil { let #(root, _, home) = fixture() let first_key = "go-a-" <> int.to_string(unique()) @@ -1242,69 +1304,3 @@ pub fn claude_quota_heal_marks_a_spent_account_test() -> Nil { credentials.until(two, None) |> should.equal(0) cleanup(root) } - -/// A pool over two tokens where a rejection makes `current` sign in afresh, -/// recording every attempt. -fn renewing_pool( - tried: process.Subject(String), - answer: fn(String) -> Result(types.Turn, types.Error), - renews: Bool, -) -> rotation.Pool(String) { - let rejected = process.new_subject() - rotation.Pool( - current: fn() { - case process.receive(rejected, 0), renews { - Ok(_), True -> Ok("fresh") - _, _ -> Ok("stale") - } - }, - mark: fn(_, _) { None }, - same: fn(a, b) { a == b }, - stream: fn(account, _, _) { - process.send(tried, account) - answer(account) - }, - reject: fn(account) { process.send(rejected, account) }, - ) -} - -fn renew(pool: rotation.Pool(String)) -> Result(types.Turn, types.Error) { - rotation.stream( - pool, - "stale", - request(), - fn(_) { types.Continue }, - rotation.Budget(8, 0, no_wait, False), - fn(_) { Nil }, - ) -} - -pub fn a_refused_credential_is_renewed_and_retried_once_test() -> Nil { - let tried = process.new_subject() - let answer = fn(account) { - case account { - "stale" -> Error(refusal.openai(401, "expired")) - _ -> Error(refusal.openai(500, "fresh answered")) - } - } - renewing_pool(tried, answer, True) - |> renew - |> should.equal(Error(refusal.openai(500, "fresh answered"))) - drain(tried, []) |> should.equal(["stale", "fresh"]) -} - -pub fn a_credential_that_cannot_be_renewed_fails_at_once_test() -> Nil { - let tried = process.new_subject() - renewing_pool(tried, fn(_) { Error(refusal.openai(401, "bad key")) }, False) - |> renew - |> should.equal(Error(refusal.openai(401, "bad key"))) - drain(tried, []) |> should.equal(["stale"]) -} - -pub fn a_renewed_credential_refused_again_is_not_retried_test() -> Nil { - let tried = process.new_subject() - renewing_pool(tried, fn(_) { Error(refusal.openai(401, "revoked")) }, True) - |> renew - |> should.equal(Error(refusal.openai(401, "revoked"))) - drain(tried, []) |> should.equal(["stale", "fresh"]) -} diff --git a/e2e/account_rotation_test.py b/e2e/account_rotation_test.py index 9ffea5d5e..55a9a3ba4 100644 --- a/e2e/account_rotation_test.py +++ b/e2e/account_rotation_test.py @@ -14,7 +14,6 @@ import urllib.error from harness import ( Albedo, Provider, - error, exclusive, operation_id, quota_error, @@ -232,68 +231,6 @@ class AccountRotationTest(unittest.TestCase): profile = self.read(app, "/settings/providers")["profiles"][app.profile] self.assertEqual(profile["account_ids"], [first["id"], second["id"]]) - def test_plain_key_profile_never_falls_back_to_another_saved_key(self): - app = self.app_for(lambda _request: quota_error()) - app.store_secrets("providers", {app.profile: {"apiKey": "own-secret"}}) - self.save_key(app, "unrelated-secret", label="unrelated") - self.turn(app) - self.assertTrue(self.provider.requests) - self.assertEqual( - {r["authorization"] for r in self.provider.requests}, {"Bearer own-secret"} - ) - - def test_plain_signin_never_switches_on_limit_or_rejection(self): - def prepare(app): - app.store_secrets( - "accounts", - { - "opencode-go": [ - { - "type": "oauth", - "access": "other-access", - "refresh": "other-refresh", - "expires": int(time.time() * 1000) + 3600000, - "accountId": "other", - }, - { - "type": "oauth", - "access": "selected-access", - "refresh": "selected-refresh", - "expires": int(time.time() * 1000) + 3600000, - "accountId": "selected", - "selected": True, - "server": self.provider.url, - }, - ] - }, - ) - - app = self.app_for( - lambda _request: [ - quota_error(), - quota_error(), - error(401, "revoked"), - ], - prepare=prepare, - extension="opencode-go", - ) - selected = next(row for row in self.accounts(app) if row["label"] == "selected") - self.patch_profile(app, account_ids=None, account_id=selected["id"]) - unchanged = self.patch_profile(app, api_key=None) - self.assertEqual(unchanged["account_id"], selected["id"]) - # Clear any startup migration's explicit rotation: this is a deliberate plain profile. - self.patch_profile(app, account_id=None, account_ids=None) - session = self.turn(app) - self.turn(app, session) - self.turn(app, session) - model_requests = [row for row in self.provider.requests if row["model"]] - self.assertEqual(len(model_requests), 3) - self.assertEqual( - {row["authorization"] for row in model_requests}, {"Bearer selected-access"} - ) - rows = self.read(app, f"/sessions/{session}/requests")["items"] - self.assertEqual([row["http_status"] for row in rows], [429, 429, 401]) - def test_environment_key_is_visible_used_read_only_and_never_saved(self): def prepare(app): app.env["ALBEDO_FIXTURE_API_KEY"] = "environment-secret" @@ -417,42 +354,6 @@ class AccountRotationTest(unittest.TestCase): ) self.assertEqual(self.patch_profile(app, rotation=None)["rotation"], "failover") - def test_spread_starts_each_session_on_the_next_key_and_keeps_it(self): - app = self.app_for() - _, first = self.save_key(app, "first-secret", label="first") - _, second = self.save_key(app, "second-secret", label="second") - self.patch_profile( - app, account_ids=[first["id"], second["id"]], rotation="spread" - ) - used = [] - sessions = [app.session(name=f"spread {index}") for index in range(3)] - for session in sessions + sessions[:1]: - start = len(self.provider.requests) - self.turn(app, session) - requests = self.provider.requests[start:] - self.assertEqual(len(requests), 1, f"expected one request for {session}") - used.append(requests[0]["authorization"]) - # Sessions take turns, and a session's later turns keep its key. - self.assertEqual(used[0], used[2]) - self.assertNotEqual(used[0], used[1]) - self.assertEqual(used[3], used[0]) - self.assertEqual(set(used), {"Bearer first-secret", "Bearer second-secret"}) - - def test_first_never_leaves_the_first_key(self): - app = self.app_for(lambda _request: quota_error()) - _, first = self.save_key(app, "first-secret", label="first") - _, second = self.save_key(app, "second-secret", label="second") - self.patch_profile( - app, account_ids=[first["id"], second["id"]], rotation="first" - ) - session = self.turn(app) - self.turn(app, session) - self.assertTrue(self.provider.requests) - self.assertEqual( - {r["authorization"] for r in self.provider.requests}, - {"Bearer first-secret"}, - ) - def test_hand_edited_key_rows_leave_the_other_accounts_usable(self): app = self.app_for() _, valid = self.save_key(app, "valid-secret", label="valid") diff --git a/packages/albedo_sdk/test/albedo_sdk/rotation_test.gleam b/packages/albedo_sdk/test/albedo_sdk/rotation_test.gleam new file mode 100644 index 000000000..447d17fd1 --- /dev/null +++ b/packages/albedo_sdk/test/albedo_sdk/rotation_test.gleam @@ -0,0 +1,326 @@ +//// How one request moves through an account pool on limits and refused +//// credentials (auth.md "Rotation"). The defects: an extra hop or wait, a +//// renewal retried twice, a hop on a limit the provider did not attribute to +//// the account, a wait on a lasting limit, a hop to an account that is also +//// limited, an impatient request that hops or waits, and a request that keeps +//// going after an answer or a failure. A fake pool scripts each attempt's +//// outcome and records every attempt and pause. + +import albedo_model as types +import albedo_property +import albedo_sdk/rotation +import gleam/dict.{type Dict} +import gleam/dynamic.{type Dynamic} +import gleam/list +import gleam/option.{None, Some} +import qcheck.{type Generator} + +const waits = [4000, 8000, 15_000, 30_000] + +type Outcome { + Answer + Brief + Lasting + /// A limit the provider does not attribute to the account. + Unattributed + Rejected + Failed +} + +type Case { + Case(accounts: Int, renewable: Bool, patient: Bool, script: List(Outcome)) +} + +/// An account and its credential's generation, which a renewal advances. +type Account { + Account(id: Int, generation: Int) +} + +/// One attempt as the pool saw it: the account, what it answered, and which +/// accounts were limited when it answered. +type Attempt { + Attempt(account: Account, outcome: Outcome, limited: Dict(Int, Outcome)) +} + +type Pool { + Pool( + limited: Dict(Int, Outcome), + sticky: Int, + generations: Dict(Int, Int), + script: List(Outcome), + attempts: List(Attempt), + pauses: List(Int), + ) +} + +pub type Atom + +pub fn a_request_moves_through_its_pool_only_as_rotation_allows_test_() -> #( + Atom, + Int, + fn() -> Nil, +) { + #(atom_create("timeout"), 3600, fn() { + use case_ <- albedo_property.run(500, case_()) + let #(result, attempts, pauses) = run(case_) + let assert [first, ..] = attempts + assert first.account == Account(0, 0) + assert list.length(attempts) <= 1 + 8 + 4 + 1 + assert list.take(waits, list.length(pauses)) == pauses + as "pauses are not the documented backoff" + case case_.patient { + True -> Nil + False -> { + assert pauses == [] as "an impatient request waited" + assert list.all(attempts, fn(attempt) { attempt.account.id == 0 }) + as "an impatient request hopped" + } + } + // The last attempt's outcome is the result. + let assert Ok(last) = list.last(attempts) + assert case result { + Ok(_) -> last.outcome == Answer + Error(_) -> last.outcome != Answer + } + let renewals = + list.window_by_2(attempts) + |> list.filter(fn(pair) { + { pair.1 }.account.id == { pair.0 }.account.id + && { pair.1 }.account.generation > { pair.0 }.account.generation + }) + assert list.length(renewals) <= 1 as "a credential was renewed twice" + check_steps(attempts, pauses, case_) + }) +} + +/// Each step from one attempt to the next follows the rule for the outcome +/// that caused it. +fn check_steps(attempts: List(Attempt), pauses: List(Int), case_: Case) -> Nil { + let hops = case case_.patient { + True -> 8 + False -> 0 + } + let _ = + list.window_by_2(attempts) + |> list.fold(#(pauses, hops), fn(budget, pair) { + let #(pauses, hops) = budget + let #(this, next) = pair + let moved = next.account.id != this.account.id + let renewed = next.account.generation > this.account.generation + let room = + list.any(int_range(case_.accounts), fn(id) { + id != this.account.id && !dict.has_key(this.limited, id) + }) + case this.outcome { + Answer | Failed -> panic as "an attempt followed an answer or a failure" + Rejected -> { + assert case_.renewable && renewed && !moved + as "a refused credential was not renewed in place" + #(pauses, hops) + } + Lasting -> { + assert moved && room && hops > 0 + as "a lasting limit waited or hopped to no room" + assert !dict.has_key(this.limited, next.account.id) + #(pauses, hops - 1) + } + Brief if room && hops > 0 -> { + assert moved as "a brief limit with a sibling ready did not hop" + assert !dict.has_key(this.limited, next.account.id) + as "a hop went to a limited account" + #(pauses, hops - 1) + } + Brief | Unattributed -> { + assert !moved as "a limit with no room moved the request" + let assert [_, ..rest] = pauses as "a retry came without a wait" + #(rest, hops) + } + } + }) + Nil +} + +// ---- the fake pool ----------------------------------------------------------- + +fn run( + case_: Case, +) -> #(Result(types.Turn, types.Error), List(Attempt), List(Int)) { + put(Pool(dict.new(), 0, dict.new(), case_.script, [], [])) + let pool = + rotation.Pool( + current: fn() { Ok(current(case_.accounts)) }, + mark: fn(account: Account, limit: types.RateLimit) { + case limit.scope { + Some("unattributed") -> None + _ -> { + let kind = case limit.limit { + Some(types.Lasting) -> Lasting + _ -> Brief + } + let state = get() + let limited = dict.insert(state.limited, account.id, kind) + put(Pool(..state, limited:)) + let room = + list.any(int_range(case_.accounts), fn(id) { + !dict.has_key(limited, id) + }) + Some(rotation.Marked( + case kind { + Lasting -> types.Lasting + _ -> types.Brief + }, + room, + )) + } + } + }, + same: fn(a, b) { a == b }, + stream: fn(account, _, _) { attempt(account) }, + reject: fn(account: Account) { + case case_.renewable { + True -> { + let state = get() + put( + Pool( + ..state, + generations: dict.insert( + state.generations, + account.id, + account.generation + 1, + ), + ), + ) + } + False -> Nil + } + }, + ) + let pause = fn(ms) { + let state = get() + put(Pool(..state, pauses: [ms, ..state.pauses])) + } + let budget = case case_.patient { + True -> rotation.Budget(8, 0, pause, False) + False -> rotation.Budget(0, list.length(waits), pause, False) + } + let result = + rotation.stream( + pool, + current(case_.accounts), + request(), + fn(_) { types.Continue }, + budget, + fn(_) { Nil }, + ) + let state = get() + #(result, list.reverse(state.attempts), list.reverse(state.pauses)) +} + +/// The session's account while it has room, else the first ready one in +/// order, which the session then keeps; with none ready, the session's own. +fn current(accounts: Int) -> Account { + let state = get() + let id = case dict.has_key(state.limited, state.sticky) { + False -> state.sticky + True -> + list.find(int_range(accounts), fn(id) { !dict.has_key(state.limited, id) }) + |> option.from_result + |> option.unwrap(state.sticky) + } + put(Pool(..state, sticky: id)) + Account( + id, + dict.get(state.generations, id) |> option.from_result |> option.unwrap(0), + ) +} + +fn attempt(account: Account) -> Result(types.Turn, types.Error) { + let state = get() + let #(outcome, script) = case state.script { + [] -> #(Answer, []) + [outcome, ..rest] -> #(outcome, rest) + } + // A limit is recorded after the attempt answers, so log the state the + // attempt answered in, then the limit the rotation marks. + put( + Pool(..state, script:, attempts: [ + Attempt(account, outcome, state.limited), + ..state.attempts + ]), + ) + let refused = fn(reason) { Error(types.Refused(reason, None, "")) } + let limited = fn(kind, scope) { + refused(types.RateLimited(types.RateLimit(Some(kind), None, scope))) + } + case outcome { + Answer -> Ok(types.Turn(None, [], [], None, types.Complete, None, [])) + Brief -> limited(types.Brief, None) + Lasting -> limited(types.Lasting, None) + Unattributed -> limited(types.Brief, Some("unattributed")) + Rejected -> refused(types.CredentialRejected) + Failed -> refused(types.ModelUnavailable) + } +} + +fn request() -> types.Request { + types.Request("model", None, [types.User("hi")], [], None, types.defaults) +} + +// ---- generators -------------------------------------------------------------- + +fn case_() -> Generator(Case) { + qcheck.map4( + // Up to ten accounts, so a request can exhaust its eight hops. + qcheck.from_weighted_generators(#(3, qcheck.bounded_int(1, 4)), [ + #(1, qcheck.bounded_int(9, 10)), + ]), + qcheck.bool(), + qcheck.from_weighted_generators(#(3, qcheck.return(True)), [ + #(1, qcheck.return(False)), + ]), + qcheck.generic_list( + qcheck.from_weighted_generators(#(4, qcheck.return(Brief)), [ + #(2, qcheck.return(Lasting)), + #(2, qcheck.return(Unattributed)), + #(2, qcheck.return(Rejected)), + #(1, qcheck.return(Failed)), + #(1, qcheck.return(Answer)), + ]), + qcheck.bounded_int(0, 20), + ), + Case, + ) +} + +fn int_range(count: Int) -> List(Int) { + case count <= 0 { + True -> [] + False -> list.append(int_range(count - 1), [count - 1]) + } +} + +// ---- state -------------------------------------------------------------------- + +fn put(pool: Pool) -> Nil { + let _ = erlang_put(atom_create("rotation_test_pool"), to_dynamic(pool)) + Nil +} + +fn get() -> Pool { + from_dynamic(erlang_get(atom_create("rotation_test_pool"))) +} + +@external(erlang, "erlang", "put") +fn erlang_put(key: Atom, value: Dynamic) -> Dynamic + +@external(erlang, "erlang", "get") +fn erlang_get(key: Atom) -> Dynamic + +@external(erlang, "gleam_stdlib", "identity") +fn to_dynamic(value: a) -> Dynamic + +@external(erlang, "gleam_stdlib", "identity") +fn from_dynamic(value: Dynamic) -> a + +@external(erlang, "erlang", "binary_to_atom") +fn atom_create(name: String) -> Atom