askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
test_ai_usage_write_failure.py · 2.3 KB · 57 lines
| 1 | """A failed ai_usage write never turns a successful chat into a 500. |
| 2 | |
| 3 | When the permission policy file is unparseable and no ai_usage schema exists, |
| 4 | the server's own usage-row write used to raise after the provider call had |
| 5 | succeeded, and the user got a 500 instead of the reply. Recording usage is |
| 6 | bookkeeping: failures are logged and the reply is still delivered. No |
| 7 | permission check is relaxed -- the write is simply allowed to fail. |
| 8 | """ |
| 9 | |
| 10 | import json |
| 11 | import logging |
| 12 | |
| 13 | import object_permission_store |
| 14 | import object_records |
| 15 | import object_server |
| 16 | from ai_fakes import anthropic_message, chat_server, install_fake_transport, text_block |
| 17 | from test_object_server import request |
| 18 | |
| 19 | |
| 20 | def _chat(headers): |
| 21 | return request( |
| 22 | "/api/ai/chat", method="POST", |
| 23 | body=json.dumps({"message": "hi"}).encode(), headers=headers, |
| 24 | ) |
| 25 | |
| 26 | |
| 27 | def test_broken_policy_and_no_usage_schema_still_returns_the_reply(tmp_path, monkeypatch, caplog): |
| 28 | data_dir, headers = chat_server(tmp_path, monkeypatch) |
| 29 | monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true") |
| 30 | (data_dir / "schemas" / "ai_usage.json").unlink() |
| 31 | object_permission_store.policy_path(data_dir).parent.mkdir(parents=True, exist_ok=True) |
| 32 | object_permission_store.policy_path(data_dir).write_text("{not json") |
| 33 | install_fake_transport(monkeypatch, [anthropic_message([text_block("hello there")])]) |
| 34 | |
| 35 | with caplog.at_level(logging.WARNING): |
| 36 | status, _, payload = _chat(headers) |
| 37 | |
| 38 | assert status == 200, payload |
| 39 | assert payload["reply"] == "hello there" |
| 40 | assert any("ai_usage" in r.getMessage() for r in caplog.records) |
| 41 | |
| 42 | |
| 43 | def test_a_raising_usage_write_is_logged_not_fatal(tmp_path, monkeypatch, caplog): |
| 44 | data_dir, headers = chat_server(tmp_path, monkeypatch) |
| 45 | install_fake_transport(monkeypatch, [anthropic_message([text_block("still here")])]) |
| 46 | real = object_records.create_collection_record |
| 47 | |
| 48 | def boom(collection, *args, **kwargs): |
| 49 | if collection == "ai_usage": |
| 50 | raise RuntimeError("disk on fire") |
| 51 | return real(collection, *args, **kwargs) |
| 52 | |
| 53 | monkeypatch.setattr(object_records, "create_collection_record", boom) |
| 54 | with caplog.at_level(logging.WARNING): |
| 55 | status, _, payload = _chat(headers) |
| 56 | assert status == 200 and payload["reply"] == "still here" |
| 57 | assert any("ai_usage" in r.getMessage() for r in caplog.records) |