From 8a11a5f12f11ed606f596af04618cb27b36a6f41 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:23:09 -0800 Subject: [PATCH] chore(quality): the local SonarQube and IDE findings of 2026-11-29, no behaviour change A local SonarQube and IDE inspection round over this release's code, before 4.12.31: 432 analyzer rows in 16 files, 398 fixed and 34 kept with their reason on the line. In lockstep with the Node pack. Cognitive complexity (32 rows): each function over 15 is split along its seams, every check in the order it ran and with the message it raised - 14 in the agent tools (the listing, the search, the page ranges, the HTML reader's start tag, the address resolution, a fetch, the crawl, the database's errors, the value renderer, a node's properties, the ingest plan, the schema, the boot, describe's states), 8 in rest_automation.py, 4 in rest_routing.py, 3 in agent-question, 2 in ask-person, and the attachments loader of the LLM helper. Literals and expressions: a literal repeated three times or more is a constant; the two identifier expressions of the graph tools use \w under re.ASCII, which keeps them to the characters the class spelled out; the Cypher pattern over the regex limit is built from three named parts with the same pattern and flags; a "# noqa" carries its code alone, the reason on the line above; a list() copy stays only where the loop changes the size of what it walks. Tests (332 rows): every composite assertion is split into single ones, a pytest.raises block holds the one call that must raise, and a module global is patched through monkeypatch. PyCharm's own findings are taken where a local beside the existing guard, a @staticmethod or a rename settles them. Kept, each with "# NOSONAR - " on its line: 32 methods that are async because their interface is (the in-memory stores beside their PostgreSQL and Redis siblings, a callback the host awaits), the copy in the memory store's unaudited(), and one false positive on dataclasses.replace. ruff and basedpyright clean; pytest 921 passed, 76 skipped, as before. The IDE's own analyzer, run headless, reproduces the 432 rows on the files as they were and reports none on the scanned sources now outside the 34 marked lines; none of the scan's four test rules is left in the tests. CHANGELOG Unreleased Changed 11. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 20 + extensions/agent-question/agent_question.py | 153 ++- extensions/agent-tools/agent_tools.py | 1025 +++++++++++------- extensions/ask-person/ask_person.py | 164 +-- extensions/llm-helper/llm_helper.py | 86 +- src/mercury_composable/async_http_request.py | 3 +- src/mercury_composable/rest_automation.py | 428 +++++--- src/mercury_composable/rest_routing.py | 185 ++-- src/mercury_composable/server.py | 9 +- src/mercury_composable/static_content.py | 15 +- tests/test_agent_question.py | 211 ++-- tests/test_agent_tools.py | 275 +++-- tests/test_ask_person.py | 266 +++-- tests/test_llm_attachments.py | 21 +- tests/test_llm_upload.py | 24 +- tests/test_mcp_recipes.py | 28 +- tests/test_rest_automation.py | 198 ++-- tests/test_static_content.py | 3 +- tests/test_transcript_audit.py | 96 +- 19 files changed, 2025 insertions(+), 1185 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2932763..346843c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -424,6 +424,26 @@ that reads these endpoints with its own client sees the error body gain `status`; nothing else changes. The Node pack follows. +11. **Code quality: the findings of a local SonarQube and IDE round (2026-11-29) on this release's code, with no + behaviour change** - in lockstep with the Node pack. The 32 functions above the cognitive-complexity threshold of + 15 are split along their natural seams, every check in the order it ran and with the message it raised, so the + shared vector files pass unchanged: in the built-in agent tools the listing and the search, the page ranges, the + HTML reader's start tag, the address resolution, a fetch and its redirects, the crawl, the database's errors, + the value renderer, the ingest plan, the schema, the boot and `describe`'s states; in REST automation the stages + of a request (its ids, its body, its request model), the parts of an upload, an interceptor's reply, a stream's + head and segments, a built-in's headers, the static-content filter, an entry's service and methods, a JSON body + and the response mapping; the attachments loader; the settings and validators of ask-person and agent-question, + and the click of `question.decide`. Repeated literals are constants (the media types, three tool routes, the + `(cut)` mark of a log line, two configuration keys, two messages); the two expressions of the graph tools that + spelled out `[A-Za-z0-9_]` use `\w` under `re.ASCII`, which keeps them to those characters; a `list()` copy + stays only where the loop changes the size of what it walks. In the tests every composite assertion is split + into single ones, a `pytest.raises` block holds the one call that must raise, and a module global is patched + through `monkeypatch`. PyCharm's own findings are taken where a local beside an existing guard, a + `@staticmethod` or a rename settles them. A finding kept on purpose says why on its line (`# NOSONAR - ...`): + a method that is `async` because its interface is - the in-memory stores beside their PostgreSQL and Redis + siblings, a callback the host awaits - the copy in the memory store's sweep, and one false positive on + `dataclasses.replace`. **Upgrade note:** none. + ### Documentation 1. **The documentation site gains the REST Automation guide, and the references follow.** `docs/guides/rest-automation.md` diff --git a/extensions/agent-question/agent_question.py b/extensions/agent-question/agent_question.py index 9f5a5bc..c7555b5 100644 --- a/extensions/agent-question/agent_question.py +++ b/extensions/agent-question/agent_question.py @@ -110,6 +110,8 @@ TRANSCRIPTS_LIMIT = 50 TRANSCRIPTS_LIMIT_MAX = 200 CONVERSATION_ID = re.compile(r"^[0-9a-f]{32}$") +# the media type of the click's request and of the JSON replies +_APPLICATION_JSON = "application/json" # configuration keys STORE = "question.store" @@ -126,6 +128,8 @@ PAGE_TITLE = "question.page.title" MISSING_POSTGRES = "question.store is postgres but psycopg is not installed - pip install 'mercury-composable[postgres]'" +# what the UI is told when the record's store cannot be read: a 503 by type, never the store's own message +_RECORD_UNAVAILABLE = "the question record is not available" DURATION = re.compile(r"^(\d+)\s*(ms|s|m|h|d)?$") UNIT_MS = {"ms": 1, "s": 1000, "m": 60_000, "h": 3_600_000, "d": 86_400_000} @@ -211,6 +215,18 @@ def _whole_ms(config: AppConfig, key: str, default: int) -> int: return int(text) +def _check_oauth2(issuer: str, jwks_url: str, client_id: str) -> None: + """What the oauth2 mode needs before the boot goes on: PyJWT, and the issuer or its JWKS URL - a + QuestionError naming the key; a UI that cannot sign a person in is warned of, not refused.""" + if jwt is None: + raise QuestionError(f"{AUTH} is oauth2 but PyJWT is not installed - pip install 'mercury-composable[ask]'") + if not issuer and not jwks_url: + raise QuestionError(f"{AUTH} is oauth2 - set {OAUTH2_ISSUER} or {OAUTH2_JWKS_URL}") + if not issuer or not client_id: + log.warning("%s is oauth2 without %s and %s - the UI cannot sign a person in; a token obtained elsewhere " + "still works", AUTH, OAUTH2_ISSUER, OAUTH2_CLIENT_ID) + + def load_settings(config: AppConfig) -> Settings: store = _text(config, STORE, "memory").lower() if store not in ("memory", "postgres"): @@ -222,13 +238,7 @@ def load_settings(config: AppConfig) -> Settings: jwks_url = _text(config, OAUTH2_JWKS_URL) client_id = _text(config, OAUTH2_CLIENT_ID) if auth == "oauth2": - if jwt is None: - raise QuestionError(f"{AUTH} is oauth2 but PyJWT is not installed - pip install 'mercury-composable[ask]'") - if not issuer and not jwks_url: - raise QuestionError(f"{AUTH} is oauth2 - set {OAUTH2_ISSUER} or {OAUTH2_JWKS_URL}") - if not issuer or not client_id: - log.warning("%s is oauth2 without %s and %s - the UI cannot sign a person in; a token obtained elsewhere " - "still works", AUTH, OAUTH2_ISSUER, OAUTH2_CLIENT_ID) + _check_oauth2(issuer, jwks_url, client_id) timeout_ms = _whole_ms(config, POSTGRES_PREFIX + "timeout.ms", 5000) port_text = _text(config, POSTGRES_PREFIX + "port", "5432") if not port_text.isdigit() or int(port_text) <= 0: @@ -314,6 +324,19 @@ def public(self) -> dict[str, Any]: } # fmt: skip +def _check_wait(event: Mapping[str, Any], turn: Any) -> None: + """What a wait's event carries beyond an advice's - its turn, the ticket, the link, the expiry and the + waiting calls - or an AppException(400).""" + if turn is None: + raise AppException(400, "turn is required for an approval or a question") + for name in ("ticket", "link", "expires_at"): + if not isinstance(event.get(name), str) or not event[name]: + raise AppException(400, f"{name} is required for an approval or a question") + calls = event.get("calls") + if not isinstance(calls, list) or not calls: + raise AppException(400, "calls must be a non-empty list for an approval or a question") + + def validate_event(event: Any) -> dict[str, Any]: """The message event the main flow sends, checked for what a channel needs - or an AppException(400).""" if not isinstance(event, Mapping): @@ -329,14 +352,7 @@ def validate_event(event: Any) -> dict[str, Any]: if turn is not None and (isinstance(turn, bool) or not isinstance(turn, int) or turn < 0): raise AppException(400, "turn must be a whole number >= 0") if kind in WAIT_KINDS: - if turn is None: - raise AppException(400, "turn is required for an approval or a question") - for name in ("ticket", "link", "expires_at"): - if not isinstance(event.get(name), str) or not event[name]: - raise AppException(400, f"{name} is required for an approval or a question") - calls = event.get("calls") - if not isinstance(calls, list) or not calls: - raise AppException(400, "calls must be a non-empty list for an approval or a question") + _check_wait(event, turn) for name in ("details", "requested_at"): if event.get(name) is not None and not isinstance(event[name], str): raise AppException(400, f"{name} must be text") @@ -407,10 +423,10 @@ def __init__(self) -> None: self._conversations: dict[str, dict[str, Any]] = {} self._turns: dict[str, list[dict[str, Any]]] = {} - async def open(self) -> None: + async def open(self) -> None: # NOSONAR - async by contract: the boot awaits it return None - async def close(self) -> None: + async def close(self) -> None: # NOSONAR - async by contract: the shutdown awaits it return None def put(self, row: Row) -> Row: @@ -422,27 +438,28 @@ def put_conversation(self, conversation: Mapping[str, Any], turns: Sequence[Mapp self._conversations[key] = dict(conversation) self._turns[key] = [dict(turn) for turn in turns] - async def get(self, row_id: int) -> Row | None: + async def get(self, row_id: int) -> Row | None: # NOSONAR - async by contract: question.decide awaits it return self._rows.get(row_id) - async def since(self, seq: int, limit: int) -> list[Row]: + async def since(self, seq: int, limit: int) -> list[Row]: # NOSONAR - async by contract: the feed awaits it return sorted((r for r in self._rows.values() if r.seq > seq), key=lambda r: r.seq)[:limit] - async def before(self, seq: int | None, limit: int) -> list[Row]: + async def before(self, seq: int | None, limit: int) -> list[Row]: # NOSONAR - async by contract: question.list awaits it return sorted((r for r in self._rows.values() if seq is None or r.seq < seq), key=lambda r: -r.seq)[:limit] - async def latest(self) -> int: + async def latest(self) -> int: # NOSONAR - async by contract: the boot awaits it return max((r.seq for r in self._rows.values()), default=0) - async def counts(self) -> dict[str, int]: + async def counts(self) -> dict[str, int]: # NOSONAR - async by contract: question.health awaits it result: dict[str, int] = {} for row in self._rows.values(): label = row.state or row.kind result[label] = result.get(label, 0) + 1 return result - async def conversations(self, before: str | None, limit: int, correlation_id: str | None, - graph_id: str | None) -> list[dict[str, Any]]: + async def conversations( # NOSONAR - async by contract: transcript.list awaits it + self, before: str | None, limit: int, correlation_id: str | None, graph_id: str | None, + ) -> list[dict[str, Any]]: rows = [ {key: value for key, value in c.items() if key not in ("system", "tools")} for c in self._conversations.values() @@ -452,7 +469,9 @@ async def conversations(self, before: str | None, limit: int, correlation_id: st ] return sorted(rows, key=lambda c: str(c["started_at"]), reverse=True)[:limit] - async def conversation(self, conversation: str) -> dict[str, Any] | None: + async def conversation( # NOSONAR - async by contract: transcript.show awaits it + self, conversation: str, + ) -> dict[str, Any] | None: held = self._conversations.get(conversation) if held is None: return None @@ -644,7 +663,7 @@ def unsubscribe(self, queue: asyncio.Queue[Row | None]) -> None: self._queues.discard(queue) def publish(self, rows: Sequence[Row]) -> None: - for queue in list(self._queues): + for queue in self._queues: for row in rows: queue.put_nowait(row) @@ -652,7 +671,7 @@ def close(self) -> None: """The application is stopping: every connected device's stream ends now, and a stream opened from here on ends at once; the devices reconnect to the next instance.""" self.closing = True - for queue in list(self._queues): + for queue in self._queues: queue.put_nowait(None) @property @@ -718,16 +737,20 @@ def running(self) -> bool: def reader() -> Reader: global _reader - if _reader is None: - _reader = MemoryReader() - return _reader + current = _reader + if current is None: + current = MemoryReader() + _reader = current + return current def _session() -> aiohttp.ClientSession: global _http - if _http is None or _http.closed: - _http = aiohttp.ClientSession() - return _http + session = _http + if session is None or session.closed: + session = aiohttp.ClientSession() + _http = session + return session # --- the intake ------------------------------------------------------------------------------- @@ -782,7 +805,8 @@ def __init__(self, issuer: str, audience: str, jwks_url: str) -> None: self.jwks_url = jwks_url self._keys: list[dict[str, Any]] = [] - async def _fetch_json(self, url: str) -> Any: + @staticmethod + async def _fetch_json(url: str) -> Any: async with _session().get(url, timeout=aiohttp.ClientTimeout(total=10)) as response: if response.status != 200: raise ReplyError(503, f"the issuer's keys are not reachable - {response.status}") @@ -834,11 +858,13 @@ async def verify(self, token: str) -> dict[str, Any]: def _oauth2(settings: Settings) -> OAuth2Verifier: global _verifier - if (_verifier is None or _verifier.issuer != settings.oauth2_issuer - or _verifier.audience != settings.oauth2_audience - or (settings.oauth2_jwks_url and _verifier.jwks_url != settings.oauth2_jwks_url)): - _verifier = OAuth2Verifier(settings.oauth2_issuer, settings.oauth2_audience, settings.oauth2_jwks_url) - return _verifier + verifier = _verifier + if (verifier is None or verifier.issuer != settings.oauth2_issuer + or verifier.audience != settings.oauth2_audience + or (settings.oauth2_jwks_url and verifier.jwks_url != settings.oauth2_jwks_url)): + verifier = OAuth2Verifier(settings.oauth2_issuer, settings.oauth2_audience, settings.oauth2_jwks_url) + _verifier = verifier + return verifier async def identify(request: AsyncHttpRequest, settings: Settings, claimed: str | None) -> Identity: @@ -888,7 +914,7 @@ def _identity(request: AsyncHttpRequest) -> Identity: def _json_reply(body: Any, status: int = 200) -> EventEnvelope: """A JSON reply as the UI reads it: serialized here, so a null stays a null (an advice's ``state``, a silent engine's ``status`` - the engines' renderer would omit them), under its content type.""" - return EventEnvelope().set_status(status).set_header("content-type", "application/json").set_body(json.dumps(body)) + return EventEnvelope().set_status(status).set_header("content-type", _APPLICATION_JSON).set_body(json.dumps(body)) def ui_config(settings: Settings) -> dict[str, Any]: @@ -943,7 +969,7 @@ async def question_list(_headers: dict[str, str], body: Body) -> Any: rows = await reader().since(since, limit) except Exception as exc: # noqa: BLE001 - a store that cannot be read is a 503 by type log.warning("The record could not be read - %s", failure(exc)) - raise AppException(503, "the question record is not available") from None + raise AppException(503, _RECORD_UNAVAILABLE) from None return _json_reply(page_since(rows, since, limit) | {"since": since}) @@ -979,7 +1005,7 @@ async def _follow(out: EventStreamWriter, since: int) -> None: since = row.seq except Exception as exc: # noqa: BLE001 - a store that cannot be read ends the stream; the device reconnects log.warning("The stream could not read the record - %s", failure(exc)) - out.fail(AppException(503, "the question record is not available")) + out.fail(AppException(503, _RECORD_UNAVAILABLE)) finally: _wakeups.unsubscribe(queue) @@ -1045,7 +1071,7 @@ async def transcript_show(_headers: dict[str, str], body: Body) -> Any: async def _forward(url: str, body: dict[str, Any], settings: Settings) -> tuple[int | None, Any, str | None]: - headers = {"content-type": "application/json", "accept": "application/json"} + headers = {"content-type": _APPLICATION_JSON, "accept": _APPLICATION_JSON} if settings.reply_token: headers["authorization"] = f"Bearer {settings.reply_token}" try: @@ -1061,6 +1087,26 @@ async def _forward(url: str, body: dict[str, Any], settings: Settings) -> tuple[ return None, None, type(exc).__name__ +async def _click(row_id: int, row: Row, decisions: Sequence[Mapping[str, Any]], who: str, + settings: Settings) -> dict[str, Any]: + """The click on a row that waits: its decisions go to the reply endpoint of the row's link, and what comes + back is the outcome the invoker gets - a 502 when the endpoint did not answer; a row with nothing to decide + is refused before anything is sent.""" + if row.kind not in WAIT_KINDS or not row.ticket or not row.link: + raise AppException(409, f"row {row_id} is an advice - nothing to decide") + if row.state != "open": + raise AppException(409, f"row {row_id} is {row.state} - decided by {row.answered_by or 'nobody'}") + try: + url, payload = reply_request(row.link, row.ticket, decisions, who) + except ReplyError as exc: + raise AppException(exc.status, exc.message) from exc + status, answer, error = await _forward(url, payload, settings) + outcome: dict[str, Any] = {"status": status, "body": answer} + if error: + outcome = {"status": 502, "body": {"type": "error", "message": f"the reply endpoint did not answer - {error}"}} + return outcome + + @preload(route=DECIDE_ROUTE, instances=INSTANCES, private=True) async def question_decide(_headers: dict[str, str], body: Body) -> Any: """``POST /questions/{id}/decide`` with ``{decisions, decided_by?}``: the click, automated - the decisions @@ -1087,21 +1133,10 @@ async def question_decide(_headers: dict[str, str], body: Body) -> Any: row = await reader().get(row_id) except Exception as exc: # noqa: BLE001 - a store that cannot be read is a 503 by type log.warning("The record could not be read - %s", failure(exc)) - raise AppException(503, "the question record is not available") from None + raise AppException(503, _RECORD_UNAVAILABLE) from None if row is None: raise AppException(404, f"row {row_id} is not in the record") - if row.kind not in WAIT_KINDS or not row.ticket or not row.link: - raise AppException(409, f"row {row_id} is an advice - nothing to decide") - if row.state != "open": - raise AppException(409, f"row {row_id} is {row.state} - decided by {row.answered_by or 'nobody'}") - try: - url, payload = reply_request(row.link, row.ticket, decisions, identity.who) - except ReplyError as exc: - raise AppException(exc.status, exc.message) from exc - status, answer, error = await _forward(url, payload, settings) - outcome: dict[str, Any] = {"status": status, "body": answer} - if error: - outcome = {"status": 502, "body": {"type": "error", "message": f"the reply endpoint did not answer - {error}"}} + outcome = await _click(row_id, row, decisions, identity.who, settings) # the recorder behind the reply endpoint has written the answer by now: read the row as it stands and let # the feed carry the change to every device _feed.kick() @@ -1142,7 +1177,7 @@ async def boot() -> None: _reader.name, _feed.cursor, EVENTS_PATH, settings.poll_ms, settings.auth) -async def close_streams() -> None: +async def close_streams() -> None: # NOSONAR - async by contract: the platform awaits its shutdown callbacks """The application is stopping (``Platform.on_shutdown``): end every connected device's stream, so the host can close its connections and exit within a container manager's grace period; a device reconnects to the next instance from its last sequence and misses nothing.""" @@ -1151,7 +1186,7 @@ async def close_streams() -> None: async def shutdown() -> None: global _http - for task in list(_streams): + for task in _streams: task.cancel() await _feed.stop() if _reader is not None: @@ -1168,7 +1203,7 @@ def _attach() -> None: platform.on_cleanup(shutdown) -def _main(argv: list[str]) -> int: +def _main(_argv: list[str]) -> int: # -Dkey=value arguments belong to the configuration, which reads them from sys.argv itself _attach() platform.run() diff --git a/extensions/agent-tools/agent_tools.py b/extensions/agent-tools/agent_tools.py index 1b5c96a..e1dc2a6 100644 --- a/extensions/agent-tools/agent_tools.py +++ b/extensions/agent-tools/agent_tools.py @@ -169,14 +169,20 @@ # (IDENTIFIER), so it can never be this one INGEST_LABEL = "_Ingested" INGEST_CONSTRAINT = "mercury_ingested_key" -IDENTIFIER = re.compile(r"[A-Za-z][A-Za-z0-9_]{0,63}") -PROPERTY_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,63}") +# labels, types and property names: \w is the ASCII letters, the digits and the underscore only +# under re.ASCII - without the flag it would let in the letters and digits of every script +IDENTIFIER = re.compile(r"[A-Za-z]\w{0,63}", re.ASCII) +PROPERTY_NAME = re.compile(r"[A-Za-z_]\w{0,63}", re.ASCII) # the clauses a read-only query may not carry, and the ones the delete gate guards WRITE_CLAUSES = re.compile(r"\b(CREATE|MERGE|SET|DELETE|REMOVE|DROP|LOAD\s+CSV)\b", re.IGNORECASE) DELETE_CLAUSES = re.compile(r"\b(DELETE|DROP)\b", re.IGNORECASE) -# string literals, quoted identifiers and comments, blanked before a query is scanned for clauses +# string literals, quoted identifiers and comments, blanked before a query is scanned for clauses - +# one expression, written as its three parts +_CYPHER_STRINGS = r"'(?:\\.|[^'\\])*'|\"(?:\\.|[^\"\\])*\"" +_CYPHER_QUOTED_IDENTIFIERS = r"`[^`]*`" +_CYPHER_COMMENTS = r"//[^\n]*|/\*.*?\*/" CYPHER_LITERALS = re.compile( - r"'(?:\\.|[^'\\])*'|\"(?:\\.|[^\"\\])*\"|`[^`]*`|//[^\n]*|/\*.*?\*/", re.DOTALL + f"{_CYPHER_STRINGS}|{_CYPHER_QUOTED_IDENTIFIERS}|{_CYPHER_COMMENTS}", re.DOTALL ) KEY_MAX_CHARS = 512 COUNTER_NAMES = ( @@ -194,6 +200,13 @@ # the clock TIME_ENABLED = "tools.time" +# the routes named in three places - a row, the boot and describe - and what a log line carries +# after its counts when the result was cut at a limit +_FILE_EXTRACT_ROUTE = "file.extract" +_GRAPH_WRITE_ROUTE = "graph.write" +_GRAPH_INGEST_ROUTE = "graph.ingest" +_CUT_MARK = " (cut)" + # the row's keys, in the order the files carry them (the loop's catalog accepts name, description, # input_schema, route, strict, write and ask) ROW_KEYS = ("name", "description", "input_schema", "route", "write") @@ -405,7 +418,7 @@ def _row( FILE_EXTRACT_ROW = _row( "file_extract", - "file.extract", + _FILE_EXTRACT_ROUTE, "Extract the text of a PDF or Word document in the agent's workspace (an HTML or plain text file works too), " "with a marker before each page (--- page N ---). path is relative to the workspace root; pages selects a " "range such as 1-3,7 (default: all pages); the text is cut at max_chars. Returns the path, the document type, " @@ -457,7 +470,7 @@ def _row( GRAPH_WRITE_ROW = _row( "graph_write", - "graph.write", + _GRAPH_WRITE_ROUTE, "Run an openCypher statement that changes the agent's knowledge graph - an index or a constraint, a corrected " "property, a relationship between existing nodes - and return the counters of what changed. Pass every value as " "a parameter. DELETE and DROP are refused unless the deployment allows deletion. To load extracted entities " @@ -475,7 +488,7 @@ def _row( GRAPH_INGEST_ROW = _row( "graph_ingest", - "graph.ingest", + _GRAPH_INGEST_ROUTE, "Load what you extracted from a document into the agent's knowledge graph, idempotently. Each node is merged " "on its key - unique across the graph, the label in lower case as its prefix (clause:12, party:supplier-a) - " "with its label and properties; each relationship is merged between two keys that exist (in this call or " @@ -772,6 +785,76 @@ def _modified(stat: Any) -> str: return moment.isoformat(timespec="seconds").replace("+00:00", "Z") +def _entry(shown: str, resolved: Path) -> dict[str, Any]: + """One entry of a listing: its path, what it is, its size when it is a file and when it was + last modified.""" + stat = resolved.stat() + if resolved.is_dir(): + kind = "directory" + elif resolved.is_file(): + kind = "file" + else: + kind = "other" + return { + "path": shown, + "type": kind, + "bytes": stat.st_size if kind == "file" else 0, + "modified": _modified(stat), + } + + +def _search_matcher(pattern: str, *, regex: bool, case_sensitive: bool) -> re.Pattern[str]: + """The pattern of a search, compiled: a literal unless it is a regular expression, any case + unless the search is case-sensitive.""" + try: + return re.compile( + pattern if regex else re.escape(pattern), 0 if case_sensitive else re.IGNORECASE + ) + except re.error as exc: + raise AppException(400, f"pattern is not a valid regular expression ({exc})") from exc + + +def _text_bytes(resolved: Path) -> bytes | None: + """A file's bytes when it can be read and its first bytes are text; ``None`` for a file a + search skips.""" + try: + data = resolved.read_bytes() + except OSError: + return None + if binary_kind(data[:8192]) is not None: + return None + return data + + +def _match_lines( + lines: list[str], + matcher: re.Pattern[str], + shown: str, + matches: list[dict[str, Any]], + *, + context: int, + width: int, + limit: int, +) -> bool: + """The lines of one file that match, added to the matches with the lines around them, each + cut to the width; True when a match was left out because the result is full.""" + for index, line in enumerate(lines): + if not matcher.search(line): + continue + if len(matches) >= limit: + return True + matches.append( + { + "path": shown, + "line": index + 1, + "text": line[:width], + "before": [text[:width] for text in lines[max(0, index - context) : index]], + "after": [text[:width] for text in lines[index + 1 : index + 1 + context]], + } + ) + return False + + class FileTools: """The four file tools over one workspace. The handlers are synchronous - the host runs them in its thread pool - and every path goes through ``resolve`` first.""" @@ -846,6 +929,19 @@ def _walk( found.sort(key=lambda item: item[0]) return found, bounded + def _directory(self, path: str) -> Path: + """A path argument to the directory it names inside the workspace: a 404 when nothing is + there, a 400 when what is there is not a directory.""" + base, relative = self.resolve(path) + if not base.is_dir(): + raise AppException( + 404 if not base.exists() else 400, + f"{relative} is not a directory" + if base.exists() + else f"directory not found: {relative}", + ) + return base + def read(self, _headers: dict[str, str], body: Body) -> Any: args = _arguments(body, FILE_READ_ROW) path = _string(args, "path") @@ -868,7 +964,7 @@ def read(self, _headers: dict[str, str], body: Body) -> Any: text = decode_utf8(data, truncated=truncated) if text is None: raise AppException(400, f"{relative} is not UTF-8 text") - log.info("file.read 200 %d bytes%s", len(data), " (cut)" if truncated else "") + log.info("file.read 200 %d bytes%s", len(data), _CUT_MARK if truncated else "") return {"path": relative, "bytes": size, "text": text, "truncated": truncated} def write(self, _headers: dict[str, str], body: Body) -> Any: @@ -914,29 +1010,13 @@ def list(self, _headers: dict[str, str], body: Body) -> Any: if pattern is not None and not isinstance(pattern, str): raise AppException(400, "glob must be a string") max_entries = _integer(args, "max_entries", default=LIST_DEFAULT, floor=1, cap=LIST_CAP) - base, relative = self.resolve(path) - if not base.is_dir(): - raise AppException( - 404 if not base.exists() else 400, - f"{relative} is not a directory" - if base.exists() - else f"directory not found: {relative}", - ) + base = self._directory(path) found, bounded = self._walk(base, pattern or None, files_only=False) entries: list[dict[str, Any]] = [] for shown, resolved in found[:max_entries]: - stat = resolved.stat() - kind = "directory" if resolved.is_dir() else "file" if resolved.is_file() else "other" - entries.append( - { - "path": shown, - "type": kind, - "bytes": stat.st_size if kind == "file" else 0, - "modified": _modified(stat), - } - ) + entries.append(_entry(shown, resolved)) truncated = bounded or len(found) > max_entries - log.info("file.list 200 %d entries%s", len(entries), " (cut)" if truncated else "") + log.info("file.list 200 %d entries%s", len(entries), _CUT_MARK if truncated else "") return {"entries": entries, "truncated": truncated} def search(self, _headers: dict[str, str], body: Body) -> Any: @@ -950,20 +1030,8 @@ def search(self, _headers: dict[str, str], body: Body) -> Any: max_results = _integer(args, "max_results", default=SEARCH_DEFAULT, floor=1, cap=SEARCH_CAP) if not pattern: raise AppException(400, "pattern must not be empty") - try: - matcher = re.compile( - pattern if regex else re.escape(pattern), 0 if case_sensitive else re.IGNORECASE - ) - except re.error as exc: - raise AppException(400, f"pattern is not a valid regular expression ({exc})") from exc - base, relative = self.resolve(path) - if not base.is_dir(): - raise AppException( - 404 if not base.exists() else 400, - f"{relative} is not a directory" - if base.exists() - else f"directory not found: {relative}", - ) + matcher = _search_matcher(pattern, regex=regex, case_sensitive=case_sensitive) + base = self._directory(path) found, bounded = self._walk(base, file_glob, files_only=True) width = self.sandbox.line_max_chars matches: list[dict[str, Any]] = [] @@ -972,36 +1040,22 @@ def search(self, _headers: dict[str, str], body: Body) -> Any: for shown, resolved in found: if truncated and len(matches) >= max_results: break - try: - data = resolved.read_bytes() - except OSError: - continue - if binary_kind(data[:8192]) is not None: + data = _text_bytes(resolved) + if data is None: continue searched += 1 lines = data.decode("utf-8", errors="replace").splitlines() - for index, line in enumerate(lines): - if not matcher.search(line): - continue - if len(matches) >= max_results: - truncated = True - break - matches.append( - { - "path": shown, - "line": index + 1, - "text": line[:width], - "before": [text[:width] for text in lines[max(0, index - context) : index]], - "after": [text[:width] for text in lines[index + 1 : index + 1 + context]], - } - ) + if _match_lines( + lines, matcher, shown, matches, context=context, width=width, limit=max_results + ): + truncated = True if truncated and len(matches) >= max_results: break log.info( "file.search 200 %d matches in %d files%s", len(matches), searched, - " (cut)" if truncated else "", + _CUT_MARK if truncated else "", ) return {"matches": matches, "files_searched": searched, "truncated": truncated} @@ -1054,7 +1108,7 @@ def extract(self, _headers: dict[str, str], body: Body) -> Any: len(wanted), len(pages), min(len(text), limit), - " (cut)" if truncated else "", + _CUT_MARK if truncated else "", ) return { "path": relative, @@ -1094,6 +1148,21 @@ def document_kind(data: bytes, suffix: str) -> str | None: return "text" +def _page_span(part: str) -> tuple[int, int]: + """``7`` or ``1-3`` to the first and the last page number it names, counted from 1.""" + first, dash, last = part.partition("-") + try: + start = int(first) + end = int(last) if dash else start + except ValueError as exc: + raise AppException(400, "pages must be page numbers and ranges such as 1-3,7") from exc + if start < 1 or end < start: + raise AppException( + 400, "pages must be page numbers and ranges such as 1-3,7, counted from 1" + ) + return start, end + + def page_range(spec: str | None, total: int) -> list[int]: """``1-3,7`` to the 1-based page numbers inside the document, in order and without repeats; an empty selection means every page.""" @@ -1106,16 +1175,7 @@ def page_range(spec: str | None, total: int) -> list[int]: part = token.strip() if not part: continue - first, dash, last = part.partition("-") - try: - start = int(first) - end = int(last) if dash else start - except ValueError as exc: - raise AppException(400, "pages must be page numbers and ranges such as 1-3,7") from exc - if start < 1 or end < start: - raise AppException( - 400, "pages must be page numbers and ranges such as 1-3,7, counted from 1" - ) + start, end = _page_span(part) for number in range(start, min(end, total) + 1): if number not in wanted: wanted.append(number) @@ -1169,7 +1229,7 @@ def _docx_text(data: bytes, relative: str) -> str: {"script", "style", "noscript", "template", "svg", "nav", "header", "footer"} ) # an element marked as page chrome by its ARIA role is dropped like the tags above, and so is one -# hidden from assistive technology - a documentation site\'s sidebar is a div with role="navigation" +# hidden from assistive technology - a documentation site's sidebar is a div with role="navigation" # as often as a nav _DROP_ROLES = frozenset({"navigation", "banner", "contentinfo"}) _BLOCK_TAGS = frozenset( @@ -1290,6 +1350,15 @@ def _end_link(self) -> None: self._href = None self._link_text = [] + def _start_link(self, attrs: list[tuple[str, str | None]]) -> None: + """Open a link when the element has a target a reader can follow - not a fragment, a + script, a mail or a phone link; the link that was open is closed first.""" + href = dict(attrs).get("href") + if href and not href.startswith(("#", "javascript:", "mailto:", "tel:")): + self._end_link() + self._href = urljoin(self.base_url, href) if self.base_url else href + self._link_text = [] + # -- the parser's callbacks def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: @@ -1320,15 +1389,16 @@ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None self._open_block() self._pre += 1 return + self._start_content(tag, attrs) + + def _start_content(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + """The rest of the start tags: a line break, a link, inline code and a table cell stay in + the current block; any other block element opens a new one.""" if tag == "br": self._current.append("\n" if self._pre else " ") return if tag == "a": - href = dict(attrs).get("href") - if href and not href.startswith(("#", "javascript:", "mailto:", "tel:")): - self._end_link() - self._href = urljoin(self.base_url, href) if self.base_url else href - self._link_text = [] + self._start_link(attrs) return if tag == "code" and not self._pre: self._code += 1 @@ -1554,23 +1624,7 @@ async def pin(self, host: str, port: int) -> str: if literal is not None: addresses = [literal] else: - try: - infos = await asyncio.get_running_loop().getaddrinfo( - host, port, type=socket.SOCK_STREAM - ) - except socket.gaierror as exc: - raise AppException(502, f"{host} cannot be resolved") from exc - addresses = [] - for info in infos: - text = str(info[4][0]).split("%", 1)[0] - try: - address = ipaddress.ip_address(text) - except ValueError: - continue - if address not in addresses: - addresses.append(address) - if not addresses: - raise AppException(502, f"{host} cannot be resolved") + addresses = await _resolve(host, port) if not self.allow_private: for address in addresses: kind = address_kind(address) @@ -1584,12 +1638,35 @@ async def pin(self, host: str, port: int) -> str: return str(preferred) +async def _resolve(host: str, port: int) -> list[ipaddress.IPv4Address | ipaddress.IPv6Address]: + """The addresses a host name resolves to, each once and in the resolver's order; a name that + resolves to none is a 502.""" + try: + infos = await asyncio.get_running_loop().getaddrinfo(host, port, type=socket.SOCK_STREAM) + except socket.gaierror as exc: + raise AppException(502, f"{host} cannot be resolved") from exc + addresses: list[ipaddress.IPv4Address | ipaddress.IPv6Address] = [] + for info in infos: + text = str(info[4][0]).split("%", 1)[0] + try: + address = ipaddress.ip_address(text) + except ValueError: + continue + if address not in addresses: + addresses.append(address) + if not addresses: + raise AppException(502, f"{host} cannot be resolved") + return addresses + + def address_kind(address: ipaddress.IPv4Address | ipaddress.IPv6Address) -> str | None: """Why an address is refused by default - loopback, private, link-local, multicast, reserved or unspecified - or ``None`` for a public address.""" candidate: ipaddress.IPv4Address | ipaddress.IPv6Address = address - if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped is not None: - candidate = address.ipv4_mapped + if isinstance(address, ipaddress.IPv6Address): + mapped = address.ipv4_mapped + if mapped is not None: + candidate = mapped if candidate.is_loopback: return "loopback" if candidate.is_link_local: @@ -1655,7 +1732,8 @@ def is_text(self) -> bool: ) -_META_CHARSET = re.compile(rb"""]+charset=["']?\s*([A-Za-z0-9_.:-]+)""", re.IGNORECASE) +# the flag covers the charset's name too: a-z is read in either case +_META_CHARSET = re.compile(rb"""]+charset=["']?\s*([a-z0-9_.:-]+)""", re.IGNORECASE) def decode_body(fetched: Fetched) -> str: @@ -1690,6 +1768,50 @@ def _under(path: str, include: str) -> bool: return path.startswith(include) if include.startswith("/") else include in path +@dataclass +class _Crawl: + """A crawl in progress: the site it stays on and the include it keeps to, how deep it follows + links, the links waiting and the ones seen, the pages read, what is left of the text budget, + how many pages were fetched and whether the result was cut.""" + + site: tuple[str, str, int | None] + include: str | None + max_depth: int + queue: deque[tuple[str, int]] + seen: set[str] + pages: list[dict[str, Any]] + budget: int + visited: int = 0 + truncated: bool = False + + +def _follow_links(links: list[str], depth: int, crawl: _Crawl) -> None: + """The links of a page that a crawl goes on to, one link deeper: the ones on its own site and + inside its include, each once and without its fragment.""" + for link in links: + candidate = urlsplit(link) + if ( + candidate.scheme.lower(), + (candidate.hostname or "").lower(), + candidate.port, + ) != crawl.site: + continue + if crawl.include and not _under(candidate.path, crawl.include): + continue + normalized = urlunsplit( + ( + candidate.scheme.lower(), + candidate.netloc, + candidate.path or "/", + candidate.query, + "", + ) + ) + if normalized not in crawl.seen: + crawl.seen.add(normalized) + crawl.queue.append((normalized, depth + 1)) + + class WebTools: """The two web tools over one allowlist, sharing one HTTP client without a cookie jar.""" @@ -1697,7 +1819,7 @@ def __init__(self, sandbox: WebSandbox): self.sandbox = sandbox self._session: aiohttp.ClientSession | None = None - async def open(self) -> None: + async def open(self) -> None: # NOSONAR - async by contract: boot and fetch await it if self._session is None: seconds = self.sandbox.timeout_ms / 1000 self._session = aiohttp.ClientSession( @@ -1714,6 +1836,53 @@ async def close(self) -> None: await self._session.close() self._session = None + async def _body(self, response: aiohttp.ClientResponse) -> tuple[bytearray, bool]: + """A response's body as read, up to the byte limit, and whether it was cut there.""" + data = bytearray() + truncated = False + async for chunk in response.content.iter_chunked(65536): + room = self.sandbox.max_bytes - len(data) + if len(chunk) >= room: + data.extend(chunk[:room]) + truncated = len(chunk) > room or not response.content.at_eof() + break + data.extend(chunk) + return data, truncated + + async def _request(self, session: aiohttp.ClientSession, current: str) -> Fetched | str: + """One request of a fetch, through the allowlist and the address check: the response, or + the URL a redirect names - which the next request checks like the first.""" + parts = self.sandbox.check_url(current) + host = (parts.hostname or "").lower().rstrip(".") + port = parts.port or (443 if parts.scheme == "https" else 80) + address = await self.sandbox.pin(host, port) + pinned_host = f"[{address}]" if ":" in address else address + pinned = urlunsplit((parts.scheme, f"{pinned_host}:{port}", parts.path, parts.query, "")) + extra: dict[str, Any] = {"server_hostname": host} if parts.scheme == "https" else {} + try: + async with session.get( + pinned, headers={"Host": _host_header(parts)}, allow_redirects=False, **extra + ) as response: + location = response.headers.get("Location") + if response.status in REDIRECT_STATUSES and location: + return urljoin(urlunsplit(parts), location) + data, truncated = await self._body(response) + content_type = (response.content_type or "").lower() + return Fetched( + url=urlunsplit(parts), + status=response.status, + content_type=content_type, + charset=response.charset, + data=bytes(data), + truncated=truncated, + ) + except TimeoutError as exc: + raise AppException( + 408, f"{host} did not answer within {self.sandbox.timeout_ms} ms" + ) from exc + except aiohttp.ClientError as exc: + raise AppException(502, f"{host} could not be fetched ({type(exc).__name__})") from exc + async def fetch(self, url: str) -> Fetched: """One URL through the allowlist and the address check, every redirect checked again, the body read up to the byte limit; a timeout is a 408, a transport failure a 502.""" @@ -1723,49 +1892,10 @@ async def fetch(self, url: str) -> Fetched: assert session is not None current = url for _hop in range(MAX_REDIRECTS + 1): - parts = self.sandbox.check_url(current) - host = (parts.hostname or "").lower().rstrip(".") - port = parts.port or (443 if parts.scheme == "https" else 80) - address = await self.sandbox.pin(host, port) - pinned_host = f"[{address}]" if ":" in address else address - pinned = urlunsplit( - (parts.scheme, f"{pinned_host}:{port}", parts.path, parts.query, "") - ) - extra: dict[str, Any] = {"server_hostname": host} if parts.scheme == "https" else {} - try: - async with session.get( - pinned, headers={"Host": _host_header(parts)}, allow_redirects=False, **extra - ) as response: - location = response.headers.get("Location") - if response.status in REDIRECT_STATUSES and location: - current = urljoin(urlunsplit(parts), location) - continue - data = bytearray() - truncated = False - async for chunk in response.content.iter_chunked(65536): - room = self.sandbox.max_bytes - len(data) - if len(chunk) >= room: - data.extend(chunk[:room]) - truncated = len(chunk) > room or not response.content.at_eof() - break - data.extend(chunk) - content_type = (response.content_type or "").lower() - return Fetched( - url=urlunsplit(parts), - status=response.status, - content_type=content_type, - charset=response.charset, - data=bytes(data), - truncated=truncated, - ) - except TimeoutError as exc: - raise AppException( - 408, f"{host} did not answer within {self.sandbox.timeout_ms} ms" - ) from exc - except aiohttp.ClientError as exc: - raise AppException( - 502, f"{host} could not be fetched ({type(exc).__name__})" - ) from exc + outcome = await self._request(session, current) + if isinstance(outcome, Fetched): + return outcome + current = outcome raise AppException(400, f"too many redirects (more than {MAX_REDIRECTS})") async def web_fetch(self, _headers: dict[str, str], body: Body) -> Any: @@ -1791,7 +1921,7 @@ async def web_fetch(self, _headers: dict[str, str], body: Body) -> Any: host, fetched.status, len(fetched.data), - " (cut)" if fetched.truncated or cut else "", + _CUT_MARK if fetched.truncated or cut else "", ) return { "url": fetched.url, @@ -1817,6 +1947,42 @@ async def _robots(self, parts: SplitResult) -> urllib.robotparser.RobotFileParse parser.parse(decode_body(fetched).splitlines()) return parser + async def _visit_page(self, crawl: _Crawl, current: str, depth: int) -> bool: + """One page of a crawl, fetched after the crawl's delay: its text joins the pages, inside + the page's limit and what is left of the crawl's budget, and its links join the queue + while the depth allows; a page that cannot be fetched or read is passed over. True when + the budget is spent.""" + if crawl.visited and self.sandbox.crawl_delay_ms: + await asyncio.sleep(self.sandbox.crawl_delay_ms / 1000) + try: + fetched = await self.fetch(current) + except AppException as exc: + log.info("web.crawl %s skipped a page (%d)", crawl.site[1], exc.status) + return False + crawl.visited += 1 + if fetched.status != 200 or not (fetched.is_html or fetched.is_text): + return False + page = decode_body(fetched) + if fetched.is_html: + title, text, links = html_to_text(page, fetched.url) + else: + title, text, links = "", page, [] + if len(text) > self.sandbox.page_max_chars: + text, crawl.truncated = text[: self.sandbox.page_max_chars], True + if len(text) > crawl.budget: + text, crawl.truncated = text[: crawl.budget], True + crawl.budget -= len(text) + crawl.pages.append( + {"url": fetched.url, "title": title, "text": text, "bytes": len(fetched.data)} + ) + if crawl.budget <= 0: + crawl.truncated = True + return True + if depth >= crawl.max_depth: + return False + _follow_links(links, depth, crawl) + return False + async def web_crawl(self, _headers: dict[str, str], body: Body) -> Any: args = _arguments(body, WEB_CRAWL_ROW) url = _string(args, "url") @@ -1837,76 +2003,31 @@ async def web_crawl(self, _headers: dict[str, str], body: Body) -> Any: site = (start.scheme, (start.hostname or "").lower(), start.port) robots = await self._robots(start) start_url = urlunsplit(start) - queue: deque[tuple[str, int]] = deque([(start_url, 0)]) - seen = {start_url} - pages: list[dict[str, Any]] = [] - visited = 0 - truncated = False - budget = CRAWL_RESULT_MAX_CHARS - while queue and len(pages) < max_pages: - current, depth = queue.popleft() + crawl = _Crawl( + site=site, + include=include, + max_depth=max_depth, + queue=deque([(start_url, 0)]), + seen={start_url}, + pages=[], + budget=CRAWL_RESULT_MAX_CHARS, + ) + while crawl.queue and len(crawl.pages) < max_pages: + current, depth = crawl.queue.popleft() if robots is not None and not robots.can_fetch(ROBOTS_AGENT, current): continue - if visited and self.sandbox.crawl_delay_ms: - await asyncio.sleep(self.sandbox.crawl_delay_ms / 1000) - try: - fetched = await self.fetch(current) - except AppException as exc: - log.info("web.crawl %s skipped a page (%d)", site[1], exc.status) - continue - visited += 1 - if fetched.status != 200 or not (fetched.is_html or fetched.is_text): - continue - page = decode_body(fetched) - if fetched.is_html: - title, text, links = html_to_text(page, fetched.url) - else: - title, text, links = "", page, [] - if len(text) > self.sandbox.page_max_chars: - text, truncated = text[: self.sandbox.page_max_chars], True - if len(text) > budget: - text, truncated = text[:budget], True - budget -= len(text) - pages.append( - {"url": fetched.url, "title": title, "text": text, "bytes": len(fetched.data)} - ) - if budget <= 0: - truncated = True + if await self._visit_page(crawl, current, depth): break - if depth >= max_depth: - continue - for link in links: - candidate = urlsplit(link) - if ( - candidate.scheme.lower(), - (candidate.hostname or "").lower(), - candidate.port, - ) != site: - continue - if include and not _under(candidate.path, include): - continue - normalized = urlunsplit( - ( - candidate.scheme.lower(), - candidate.netloc, - candidate.path or "/", - candidate.query, - "", - ) - ) - if normalized not in seen: - seen.add(normalized) - queue.append((normalized, depth + 1)) - if queue and len(pages) >= max_pages: - truncated = True + if crawl.queue and len(crawl.pages) >= max_pages: + crawl.truncated = True log.info( "web.crawl %s 200 %d pages, %d fetched%s", site[1], - len(pages), - visited, - " (cut)" if truncated else "", + len(crawl.pages), + crawl.visited, + _CUT_MARK if crawl.truncated else "", ) - return {"pages": pages, "visited": visited, "truncated": truncated} + return {"pages": crawl.pages, "visited": crawl.visited, "truncated": crawl.truncated} # --- the knowledge graph, inside one database ------------------------------------------------------- @@ -2053,6 +2174,25 @@ async def function(tx: Any) -> Any: return await session.execute_read(managed) +def _database_error(exc: Any, *, timeout_ms: int) -> AppException: + """What the database itself answered - the driver's ``Neo4jError`` - as the tool's status, by + its code and its class.""" + assert neo4j_errors is not None + code = str(exc.code or "") + message = str(exc.message or exc) + if "TimedOut" in code or "Timeout" in code: + return AppException( + 408, f"the graph database did not answer within {timeout_ms} ms ({code})" + ) + if isinstance(exc, neo4j_errors.AuthError): + return AppException(503, "the graph database refused this process's credential") + if isinstance(exc, (neo4j_errors.TransientError, neo4j_errors.DatabaseUnavailable)): + return AppException(503, f"the graph database is not available ({code})") + if isinstance(exc, neo4j_errors.ClientError): + return AppException(400, f"{code}: {message}") + return AppException(502, f"the graph database failed ({code})") + + def graph_error(exc: BaseException, *, timeout_ms: int) -> AppException: """The driver's failure as the tool's status: a client error (syntax, type, constraint, a write in a read transaction) is a 400 carrying the database's code and message for the model; a @@ -2065,19 +2205,7 @@ def graph_error(exc: BaseException, *, timeout_ms: int) -> AppException: name = type(exc).__name__ if neo4j_errors is not None: if isinstance(exc, neo4j_errors.Neo4jError): - code = str(exc.code or "") - message = str(exc.message or exc) - if "TimedOut" in code or "Timeout" in code: - return AppException( - 408, f"the graph database did not answer within {timeout_ms} ms ({code})" - ) - if isinstance(exc, neo4j_errors.AuthError): - return AppException(503, "the graph database refused this process's credential") - if isinstance(exc, (neo4j_errors.TransientError, neo4j_errors.DatabaseUnavailable)): - return AppException(503, f"the graph database is not available ({code})") - if isinstance(exc, neo4j_errors.ClientError): - return AppException(400, f"{code}: {message}") - return AppException(502, f"the graph database failed ({code})") + return _database_error(exc, timeout_ms=timeout_ms) if isinstance( exc, ( @@ -2099,6 +2227,18 @@ def _other_dialect(exc: BaseException) -> bool: return not code.startswith("Neo.") or "SyntaxError" in code +def _render_path(path: Any) -> list[Any]: + """A path as the list of its nodes and relationships, in the order it walks them.""" + rendered: list[Any] = [] + nodes = list(path.nodes) + relationships = list(path.relationships) + for index, node in enumerate(nodes): + rendered.append(render_value(node)) + if index < len(relationships): + rendered.append(render_value(relationships[index])) + return rendered + + def render_value(value: Any) -> Any: """A driver value as JSON for the model: a node ``{id, labels, properties}``, a relationship ``{id, type, start, end, properties}``, a path as the list of its nodes and relationships in @@ -2110,14 +2250,7 @@ def render_value(value: Any) -> Any: if isinstance(value, dict): return {str(key): render_value(item) for key, item in value.items()} if hasattr(value, "nodes") and hasattr(value, "relationships") and not hasattr(value, "labels"): - rendered: list[Any] = [] - nodes = list(value.nodes) - relationships = list(value.relationships) - for index, node in enumerate(nodes): - rendered.append(render_value(node)) - if index < len(relationships): - rendered.append(render_value(relationships[index])) - return rendered + return _render_path(value) if hasattr(value, "type") and hasattr(value, "start_node") and hasattr(value, "element_id"): return { "id": str(value.element_id), @@ -2162,6 +2295,22 @@ def _scalar(value: Any) -> bool: return value is None or isinstance(value, (bool, int, float, str)) +def _check_property(name: Any, item: Any, where: str) -> None: + """One property to ingest: a name that is an identifier and not one the tool writes, a value + that is a scalar or a list of scalars.""" + if not isinstance(name, str) or not PROPERTY_NAME.fullmatch(name): + raise AppException( + 400, f"{where}.properties has a name that is not an identifier: {name!r}" + ) + if name in ("key", "source"): + raise AppException(400, f"{where}.properties must not set {name} - the tool writes it") + if isinstance(item, list): + if not all(_scalar(element) and element is not None for element in item): + raise AppException(400, f"{where}.properties.{name} must be a list of scalars") + elif not _scalar(item): + raise AppException(400, f"{where}.properties.{name} must be a scalar or a list of scalars") + + def _properties(value: Any, where: str) -> dict[str, Any]: """The properties of a node or a relationship to ingest: names that are identifiers, values that are scalars or lists of scalars; ``key`` and ``source`` are the tool's.""" @@ -2171,19 +2320,7 @@ def _properties(value: Any, where: str) -> dict[str, Any]: raise AppException(400, f"{where}.properties must be a map") checked: dict[str, Any] = {} for name, item in value.items(): - if not isinstance(name, str) or not PROPERTY_NAME.fullmatch(name): - raise AppException( - 400, f"{where}.properties has a name that is not an identifier: {name!r}" - ) - if name in ("key", "source"): - raise AppException(400, f"{where}.properties must not set {name} - the tool writes it") - if isinstance(item, list): - if not all(_scalar(element) and element is not None for element in item): - raise AppException(400, f"{where}.properties.{name} must be a list of scalars") - elif not _scalar(item): - raise AppException( - 400, f"{where}.properties.{name} must be a scalar or a list of scalars" - ) + _check_property(name, item, where) if item is not None: checked[name] = item return checked @@ -2228,6 +2365,44 @@ def endpoint_keys(self) -> list[str]: return keys +def _plan_node(node: Any, where: str, seen_keys: set[str]) -> tuple[str, dict[str, Any]]: + """One node of an ingest as its label and the row its ``MERGE`` takes; its key joins the keys + seen, since a key names one node in a call.""" + if not isinstance(node, dict): + raise AppException(400, f"{where} must be a map") + unknown = sorted(str(k) for k in node if k not in ("key", "label", "properties")) + if unknown: + raise AppException( + 400, + f"{where} does not take {', '.join(unknown)} - a node has key, label and properties", + ) + key = _key(node.get("key"), f"{where}.key") + label = _identifier(node.get("label"), f"{where}.label") + if key in seen_keys: + raise AppException(400, f"{where}.key {key!r} appears twice in this call") + seen_keys.add(key) + return label, {"key": key, "properties": _properties(node.get("properties"), where)} + + +def _plan_relationship(relationship: Any, where: str) -> tuple[str, dict[str, Any]]: + """One relationship of an ingest as its type and the row its ``MERGE`` takes.""" + if not isinstance(relationship, dict): + raise AppException(400, f"{where} must be a map") + unknown = sorted(str(k) for k in relationship if k not in ("from", "to", "type", "properties")) + if unknown: + raise AppException( + 400, + f"{where} does not take {', '.join(unknown)} - a relationship has from, to, type and " + f"properties", + ) + row = { + "from": _key(relationship.get("from"), f"{where}.from"), + "to": _key(relationship.get("to"), f"{where}.to"), + "properties": _properties(relationship.get("properties"), where), + } + return _identifier(relationship.get("type"), f"{where}.type"), row + + def plan_ingest(args: dict[str, Any], *, max_nodes: int) -> Ingest: """Validate an ingest and group it: labels and types must be identifiers, keys non-empty strings, properties scalars or lists of scalars, the counts inside the caps.""" @@ -2255,43 +2430,12 @@ def plan_ingest(args: dict[str, Any], *, max_nodes: int) -> Ingest: by_label: dict[str, list[dict[str, Any]]] = {} seen_keys: set[str] = set() for index, node in enumerate(nodes): - where = f"nodes[{index}]" - if not isinstance(node, dict): - raise AppException(400, f"{where} must be a map") - unknown = sorted(str(k) for k in node if k not in ("key", "label", "properties")) - if unknown: - raise AppException( - 400, - f"{where} does not take {', '.join(unknown)} - a node has key, label and properties", - ) - key = _key(node.get("key"), f"{where}.key") - label = _identifier(node.get("label"), f"{where}.label") - if key in seen_keys: - raise AppException(400, f"{where}.key {key!r} appears twice in this call") - seen_keys.add(key) - by_label.setdefault(label, []).append( - {"key": key, "properties": _properties(node.get("properties"), where)} - ) + label, row = _plan_node(node, f"nodes[{index}]", seen_keys) + by_label.setdefault(label, []).append(row) by_type: dict[str, list[dict[str, Any]]] = {} for index, relationship in enumerate(relationships): - where = f"relationships[{index}]" - if not isinstance(relationship, dict): - raise AppException(400, f"{where} must be a map") - unknown = sorted( - str(k) for k in relationship if k not in ("from", "to", "type", "properties") - ) - if unknown: - raise AppException( - 400, - f"{where} does not take {', '.join(unknown)} - a relationship has from, to, type and " - f"properties", - ) - row = { - "from": _key(relationship.get("from"), f"{where}.from"), - "to": _key(relationship.get("to"), f"{where}.to"), - "properties": _properties(relationship.get("properties"), where), - } - by_type.setdefault(_identifier(relationship.get("type"), f"{where}.type"), []).append(row) + kind, row = _plan_relationship(relationship, f"relationships[{index}]") + by_type.setdefault(kind, []).append(row) return Ingest(by_label, by_type, source, len(nodes), len(relationships)) @@ -2412,6 +2556,97 @@ async def _first_available(tx: Transaction, queries: tuple[str, ...]) -> Rows: raise failure +def _count_labels(rows: list[list[Any]]) -> dict[str, dict[str, Any]]: + """The node labels by name, each with its count; the ingest label is the tool's own and is + left out.""" + labels: dict[str, dict[str, Any]] = {} + for label, count in rows: + if label == INGEST_LABEL: + continue + labels[str(label)] = {"label": str(label), "count": int(count), "properties": []} + return labels + + +def _add_node_properties(labels: dict[str, dict[str, Any]], rows: list[list[Any]]) -> None: + """Add the nodes' property names and types to their labels; a label the counts did not carry + joins with a count of 0.""" + for node_labels, name, types in rows: + for label in node_labels or []: + if label == INGEST_LABEL: + continue + entry = labels.setdefault( + str(label), {"label": str(label), "count": 0, "properties": []} + ) + if name is not None: + entry["properties"].append( + {"name": str(name), "types": [str(t) for t in (types or [])]} + ) + + +def _add_end_labels(known: list[str], labels: Any) -> None: + """Add the labels at one end of a relationship type to the ones known, each once and without + the ingest label.""" + for label in labels or []: + if label != INGEST_LABEL and str(label) not in known: + known.append(str(label)) + + +def _count_relationships(rows: list[list[Any]]) -> dict[str, dict[str, Any]]: + """The relationship types by name, each with its count and the labels it connects.""" + kinds: dict[str, dict[str, Any]] = {} + for kind, from_labels, to_labels, count in rows: + entry = kinds.setdefault( + str(kind), + {"type": str(kind), "count": 0, "from": [], "to": [], "properties": []}, + ) + entry["count"] += int(count) + _add_end_labels(entry["from"], from_labels) + _add_end_labels(entry["to"], to_labels) + return kinds + + +def _add_relationship_properties(kinds: dict[str, dict[str, Any]], rows: list[list[Any]]) -> None: + """Add the relationships' property names and types to their types; a type the counts did not + carry joins with a count of 0.""" + for kind, name, types in rows: + entry = kinds.setdefault( + _relationship_type_name(kind), + { + "type": _relationship_type_name(kind), + "count": 0, + "from": [], + "to": [], + "properties": [], + }, + ) + if name is not None: + entry["properties"].append( + {"name": str(name), "types": [str(t) for t in (types or [])]} + ) + + +async def _read_schema(tx: Transaction) -> dict[str, Any]: + """The schema inside one read transaction, in four statements - the labels with their counts, + the nodes' properties, the relationship types with their counts and ends, the relationships' + properties - each read into the result before the next is run, then sorted by name.""" + labels = _count_labels((await tx.run(LABEL_COUNTS_QUERY)).values) + node_properties = await _first_available(tx, NODE_PROPERTIES_QUERIES) + _add_node_properties(labels, node_properties.values) + kinds = _count_relationships((await tx.run(RELATIONSHIP_COUNTS_QUERY)).values) + relationship_properties = await _first_available(tx, RELATIONSHIP_PROPERTIES_QUERIES) + _add_relationship_properties(kinds, relationship_properties.values) + for entry in labels.values(): + entry["properties"].sort(key=lambda item: item["name"]) + for entry in kinds.values(): + entry["properties"].sort(key=lambda item: item["name"]) + entry["from"].sort() + entry["to"].sort() + return { + "labels": [labels[name] for name in sorted(labels)], + "relationship_types": [kinds[name] for name in sorted(kinds)], + } + + class GraphTools: """The four knowledge-graph tools over one database: the schema, a read-only query, a write and the structured ingest; the backend is the driver, or a fake in the tests.""" @@ -2525,68 +2760,7 @@ def _parameters(args: dict[str, Any]) -> dict[str, Any]: async def schema(self, _headers: dict[str, str], body: Body) -> Any: _arguments(body, GRAPH_SCHEMA_ROW) - - async def work(tx: Transaction) -> Any: - labels: dict[str, dict[str, Any]] = {} - for label, count in (await tx.run(LABEL_COUNTS_QUERY)).values: - if label == INGEST_LABEL: - continue - labels[str(label)] = {"label": str(label), "count": int(count), "properties": []} - node_properties = await _first_available(tx, NODE_PROPERTIES_QUERIES) - for node_labels, name, types in node_properties.values: - for label in node_labels or []: - if label == INGEST_LABEL: - continue - entry = labels.setdefault( - str(label), {"label": str(label), "count": 0, "properties": []} - ) - if name is not None: - entry["properties"].append( - {"name": str(name), "types": [str(t) for t in (types or [])]} - ) - kinds: dict[str, dict[str, Any]] = {} - for kind, from_labels, to_labels, count in ( - await tx.run(RELATIONSHIP_COUNTS_QUERY) - ).values: - entry = kinds.setdefault( - str(kind), - {"type": str(kind), "count": 0, "from": [], "to": [], "properties": []}, - ) - entry["count"] += int(count) - for label in from_labels or []: - if label != INGEST_LABEL and str(label) not in entry["from"]: - entry["from"].append(str(label)) - for label in to_labels or []: - if label != INGEST_LABEL and str(label) not in entry["to"]: - entry["to"].append(str(label)) - relationship_properties = await _first_available(tx, RELATIONSHIP_PROPERTIES_QUERIES) - for kind, name, types in relationship_properties.values: - entry = kinds.setdefault( - _relationship_type_name(kind), - { - "type": _relationship_type_name(kind), - "count": 0, - "from": [], - "to": [], - "properties": [], - }, - ) - if name is not None: - entry["properties"].append( - {"name": str(name), "types": [str(t) for t in (types or [])]} - ) - for entry in labels.values(): - entry["properties"].sort(key=lambda item: item["name"]) - for entry in kinds.values(): - entry["properties"].sort(key=lambda item: item["name"]) - entry["from"].sort() - entry["to"].sort() - return { - "labels": [labels[name] for name in sorted(labels)], - "relationship_types": [kinds[name] for name in sorted(kinds)], - } - - result = await self._run(work, write=False) + result = await self._run(_read_schema, write=False) log.info( "graph.schema 200 %d labels, %d relationship types", len(result["labels"]), @@ -2613,7 +2787,7 @@ async def work(tx: Transaction) -> Rows: return await tx.run(query, parameters, limit=limit) rows: Rows = await self._run(work, write=False) - log.info("graph.query 200 %d rows%s", len(rows.values), " (cut)" if rows.truncated else "") + log.info("graph.query 200 %d rows%s", len(rows.values), _CUT_MARK if rows.truncated else "") return { "columns": rows.columns, "rows": [[render_value(v) for v in row] for row in rows.values], @@ -2684,7 +2858,9 @@ async def work(tx: Transaction) -> dict[str, int]: # --- the clock ---------------------------------------------------------------------------------- -async def time_now(_headers: dict[str, str], body: Body) -> Any: +async def time_now( # NOSONAR - async by contract: the platform awaits a registered coroutine + _headers: dict[str, str], body: Body +) -> Any: args = _arguments(body, TIME_NOW_ROW) name = _string(args, "timezone", default="UTC").strip() or "UTC" if name.upper() == "UTC": @@ -2728,68 +2904,81 @@ def _register(self, route: str, handler: Any) -> None: self.registry.register(route, handler, instances=INSTANCES) self.registered.append(route) + def _register_file_tools(self) -> None: + """The file tools, when the workspace is configured - ``file.extract`` among them only + with the documents extra.""" + file_sandbox = load_file_sandbox() + if file_sandbox is None: + log.info("File tools not registered - %s is not set", FILE_ROOT) + return + self.files = FileTools(file_sandbox) + for route, handler in ( + ("file.read", self.files.read), + ("file.write", self.files.write), + ("file.list", self.files.list), + ("file.search", self.files.search), + ): + self._register(route, handler) + if documents_available(): + self._register(_FILE_EXTRACT_ROUTE, self.files.extract) + else: + log.info("file.extract not registered - %s", DOCUMENTS_EXTRA) + log.info("File tools registered - workspace %s", file_sandbox.root) + + async def _register_web_tools(self) -> None: + """The web tools, when the allowlist is configured, over one HTTP client opened here.""" + web_sandbox = load_web_sandbox() + if web_sandbox is None: + log.info("Web tools not registered - %s is empty", WEB_ALLOW) + return + self.web = WebTools(web_sandbox) + await self.web.open() + self._register("web.fetch", self.web.web_fetch) + self._register("web.crawl", self.web.web_crawl) + log.info( + "Web tools registered - %d allowed site pattern(s)%s", + len(web_sandbox.rules), + ", private addresses allowed" if web_sandbox.allow_private else "", + ) + + async def _register_graph_tools(self) -> None: + """The graph tools, when the database is configured - the two that write only when writes + are allowed; a database that does not answer yet is no reason to stop the boot.""" + graph_sandbox = load_graph_sandbox() + if graph_sandbox is None: + log.info("Graph tools not registered - %s is not set", GRAPH_URI) + return + self.graph = GraphTools(graph_sandbox) + self._register("graph.schema", self.graph.schema) + self._register("graph.query", self.graph.query) + if graph_sandbox.write: + self._register(_GRAPH_WRITE_ROUTE, self.graph.write) + self._register(_GRAPH_INGEST_ROUTE, self.graph.ingest) + else: + log.info("graph.write and graph.ingest not registered - %s is false", GRAPH_WRITE) + try: + await self.graph.backend.verify() + log.info( + "Graph tools registered - %s%s%s", + graph_sandbox.address, + ", writes allowed" if graph_sandbox.write else "", + ", deletion allowed" if graph_sandbox.delete else "", + ) + # logged, not fatal + except Exception as exc: # noqa: BLE001 + log.warning( + "Graph tools registered - %s does not answer yet (%s); calls fail until it does", + graph_sandbox.address, + type(exc).__name__, + ) + async def boot(self) -> None: """Read the sandboxes and register the tools - inside the serving loop, before the first request; a configuration failure stops the application by name.""" try: - file_sandbox = load_file_sandbox() - if file_sandbox is None: - log.info("File tools not registered - %s is not set", FILE_ROOT) - else: - self.files = FileTools(file_sandbox) - for route, handler in ( - ("file.read", self.files.read), - ("file.write", self.files.write), - ("file.list", self.files.list), - ("file.search", self.files.search), - ): - self._register(route, handler) - if documents_available(): - self._register("file.extract", self.files.extract) - else: - log.info("file.extract not registered - %s", DOCUMENTS_EXTRA) - log.info("File tools registered - workspace %s", file_sandbox.root) - web_sandbox = load_web_sandbox() - if web_sandbox is None: - log.info("Web tools not registered - %s is empty", WEB_ALLOW) - else: - self.web = WebTools(web_sandbox) - await self.web.open() - self._register("web.fetch", self.web.web_fetch) - self._register("web.crawl", self.web.web_crawl) - log.info( - "Web tools registered - %d allowed site pattern(s)%s", - len(web_sandbox.rules), - ", private addresses allowed" if web_sandbox.allow_private else "", - ) - graph_sandbox = load_graph_sandbox() - if graph_sandbox is None: - log.info("Graph tools not registered - %s is not set", GRAPH_URI) - else: - self.graph = GraphTools(graph_sandbox) - self._register("graph.schema", self.graph.schema) - self._register("graph.query", self.graph.query) - if graph_sandbox.write: - self._register("graph.write", self.graph.write) - self._register("graph.ingest", self.graph.ingest) - else: - log.info( - "graph.write and graph.ingest not registered - %s is false", GRAPH_WRITE - ) - try: - await self.graph.backend.verify() - log.info( - "Graph tools registered - %s%s%s", - graph_sandbox.address, - ", writes allowed" if graph_sandbox.write else "", - ", deletion allowed" if graph_sandbox.delete else "", - ) - except Exception as exc: # noqa: BLE001 - logged, not fatal - log.warning( - "Graph tools registered - %s does not answer yet (%s); calls fail until it does", - graph_sandbox.address, - type(exc).__name__, - ) + self._register_file_tools() + await self._register_web_tools() + await self._register_graph_tools() if _bool_setting(TIME_ENABLED, True): self._register("time.now", time_now) else: @@ -2831,35 +3020,43 @@ async def tools_health(headers: dict[str, str], _body: Body) -> Any: # --- describe: the rows and what registers under this configuration ------------------------------ -def _states() -> dict[str, str]: - """For each route, whether it registers under the current configuration, and why not.""" - states: dict[str, str] = {} +def _file_tools_state() -> str: try: files = load_file_sandbox() - file_state = ( + return ( f"registers (workspace {files.root})" if files else f"NOT registered ({FILE_ROOT} is not set)" ) except ToolsError as exc: - file_state = f"NOT registered ({exc})" + return f"NOT registered ({exc})" + + +def _web_tools_state() -> str: try: web = load_web_sandbox() - web_state = ( + return ( f"registers ({len(web.rules)} allowed site pattern(s))" if web else f"NOT registered ({WEB_ALLOW} is empty)" ) except ToolsError as exc: - web_state = f"NOT registered ({exc})" + return f"NOT registered ({exc})" + + +def _clock_state() -> str: try: - time_state = ( + return ( "registers" if _bool_setting(TIME_ENABLED, True) else f"NOT registered ({TIME_ENABLED} is false)" ) except ToolsError as exc: - time_state = f"NOT registered ({exc})" + return f"NOT registered ({exc})" + + +def _graph_tools_states() -> tuple[str, str]: + """The state of the graph tools that read and of the ones that write.""" try: graph = load_graph_sandbox() if graph is None: @@ -2869,14 +3066,24 @@ def _states() -> dict[str, str]: write_state = read_state if graph.write else f"NOT registered ({GRAPH_WRITE} is false)" except ToolsError as exc: read_state = write_state = f"NOT registered ({exc})" + return read_state, write_state + + +def _states() -> dict[str, str]: + """For each route, whether it registers under the current configuration, and why not.""" + states: dict[str, str] = {} + file_state = _file_tools_state() + web_state = _web_tools_state() + time_state = _clock_state() + read_state, write_state = _graph_tools_states() extract_state = file_state if file_state.startswith("registers") and not documents_available(): extract_state = f"NOT registered ({DOCUMENTS_EXTRA})" for route in ROW_BY_ROUTE: group = route.split(".", 1)[0] - if route == "file.extract": + if route == _FILE_EXTRACT_ROUTE: states[route] = extract_state - elif route in ("graph.write", "graph.ingest"): + elif route in (_GRAPH_WRITE_ROUTE, _GRAPH_INGEST_ROUTE): states[route] = write_state elif group == "graph": states[route] = read_state diff --git a/extensions/ask-person/ask_person.py b/extensions/ask-person/ask_person.py index 7af9dd2..1fbebb2 100644 --- a/extensions/ask-person/ask_person.py +++ b/extensions/ask-person/ask_person.py @@ -118,6 +118,8 @@ JWT_ALGORITHMS = ("RS256", "RS384", "RS512", "ES256", "ES384", "ES512", "PS256", "PS384", "PS512") GRAPH_ID_HEADER = "x-graph-id" CORRELATION_HEADER = "x-correlation-id" +# the media type of the requests to the engine and of the JSON replies +_APPLICATION_JSON = "application/json" AUDITS = ("memory", "postgres") # configuration keys @@ -319,6 +321,22 @@ def _audit_postgres(config: AppConfig, timeout_ms: int) -> dict[str, Any]: return {key: value for key, value in settings.items() if value is not None} +def _check_oauth2(settings: Settings) -> None: + """What the oauth2 mode needs before the boot goes on: PyJWT, and the issuer or its JWKS URL - + an AskError naming the key; a page that cannot sign a person in is warned of, not refused.""" + if jwt is None: + raise AskError( + f"{REPLY_AUTH} is oauth2 but PyJWT is not installed - pip install 'mercury-composable[ask]'" + ) + if not settings.oauth2_issuer and not settings.oauth2_jwks_url: + raise AskError(f"{REPLY_AUTH} is oauth2 - set {OAUTH2_ISSUER} or {OAUTH2_JWKS_URL}") + if not settings.oauth2_issuer or not settings.oauth2_client_id: + log.warning( + "%s is oauth2 without %s and %s - the reply page cannot sign a person in; a channel app's " + "bearer and a token obtained elsewhere still work", REPLY_AUTH, OAUTH2_ISSUER, OAUTH2_CLIENT_ID, + ) + + def load_settings(config: AppConfig) -> Settings: """The extension's settings from the application configuration, or an AskError naming the key that stops the boot.""" @@ -362,17 +380,7 @@ def load_settings(config: AppConfig) -> Settings: if auth not in AUTH_MODES: raise AskError(f"{REPLY_AUTH} must be one of {', '.join(AUTH_MODES)}") if auth == "oauth2": - if jwt is None: - raise AskError( - f"{REPLY_AUTH} is oauth2 but PyJWT is not installed - pip install 'mercury-composable[ask]'" - ) - if not settings.oauth2_issuer and not settings.oauth2_jwks_url: - raise AskError(f"{REPLY_AUTH} is oauth2 - set {OAUTH2_ISSUER} or {OAUTH2_JWKS_URL}") - if not settings.oauth2_issuer or not settings.oauth2_client_id: - log.warning( - "%s is oauth2 without %s and %s - the reply page cannot sign a person in; a channel app's " - "bearer and a token obtained elsewhere still work", REPLY_AUTH, OAUTH2_ISSUER, OAUTH2_CLIENT_ID, - ) + _check_oauth2(settings) if audit not in AUDITS: raise AskError(f"{AUDIT} must be one of {', '.join(AUDITS)}") for graph_id, entry in settings.graphs.items(): @@ -442,30 +450,35 @@ def _payload_is_valid(payload: Any) -> bool: ) +# what the invoker sees when a ticket's parts, their encoding or the payload cannot be read - the +# text is pinned by the shared vectors +_TICKET_MALFORMED = "Ticket is malformed" + + def verify_ticket(ticket: str, keys: Sequence[bytes], now: float) -> dict[str, Any]: """The payload of a ticket this process issued, or a TicketError: 400 when the ticket is malformed or of another version, 403 when no key signs it, 410 when it has expired.""" parts = ticket.split(".") if len(parts) != 3 or not all(parts): - raise TicketError(400, "Ticket is malformed") + raise TicketError(400, _TICKET_MALFORMED) version, encoded, signature = parts if version != TICKET_VERSION: raise TicketError(400, f"Ticket version {version} is not supported") if not BASE64URL.match(encoded) or not BASE64URL.match(signature): - raise TicketError(400, "Ticket is malformed") + raise TicketError(400, _TICKET_MALFORMED) try: payload_bytes = _b64u_decode(encoded) mac = _b64u_decode(signature) - except (ValueError, UnicodeEncodeError) as exc: - raise TicketError(400, "Ticket is malformed") from exc + except ValueError as exc: # base64's own error and a UnicodeEncodeError are both ValueErrors + raise TicketError(400, _TICKET_MALFORMED) from exc if not any(hmac.compare_digest(_mac(payload_bytes, key), mac) for key in keys): raise TicketError(403, "Ticket signature is invalid") try: payload = json.loads(payload_bytes.decode("utf-8")) - except (ValueError, UnicodeDecodeError) as exc: - raise TicketError(400, "Ticket is malformed") from exc + except ValueError as exc: # the JSON decoder's own error and a UnicodeDecodeError are both ValueErrors + raise TicketError(400, _TICKET_MALFORMED) from exc if not _payload_is_valid(payload): - raise TicketError(400, "Ticket is malformed") + raise TicketError(400, _TICKET_MALFORMED) if payload["e"] < now: raise TicketError(410, "Ticket expired") return payload @@ -652,29 +665,32 @@ def readvice_request(payload: Mapping[str, Any], graphs: Mapping[str, str]) -> E ) +def _checked_decision(decision: Any) -> Decision: + """One decision as the engine takes it, its rules checked in a fixed order - or a + ReplyError(400) naming the rule.""" + if not isinstance(decision, Mapping) or not isinstance(decision.get("id"), str) or not decision["id"]: + raise ReplyError(400, "each decision needs the id of its call") + has_approved = "approved" in decision + has_answer = "answer" in decision + if has_approved and has_answer: + raise ReplyError(400, "each decision carries approved (with an optional note) or answer, not both") + if not has_approved and not has_answer: + raise ReplyError(400, "each decision carries approved (with an optional note) or answer") + if has_approved and not isinstance(decision["approved"], bool): + raise ReplyError(400, "approved must be true or false") + if "note" in decision and decision["note"] is not None and not isinstance(decision["note"], str): + raise ReplyError(400, "note must be text") + if has_answer and "note" in decision: + raise ReplyError(400, "a question's decision carries an answer and no note") + return dict(decision) + + def validate_decisions(decisions: Any) -> list[Decision]: """The person's decisions, one per waiting call: ``{id, approved, note?}`` for a tool call, ``{id, answer}`` for a question - or a ReplyError(400) naming the rule.""" if not isinstance(decisions, list) or not decisions: raise ReplyError(400, "decisions must be a non-empty list, one per waiting call") - result: list[Decision] = [] - for decision in decisions: - if not isinstance(decision, Mapping) or not isinstance(decision.get("id"), str) or not decision["id"]: - raise ReplyError(400, "each decision needs the id of its call") - has_approved = "approved" in decision - has_answer = "answer" in decision - if has_approved and has_answer: - raise ReplyError(400, "each decision carries approved (with an optional note) or answer, not both") - if not has_approved and not has_answer: - raise ReplyError(400, "each decision carries approved (with an optional note) or answer") - if has_approved and not isinstance(decision["approved"], bool): - raise ReplyError(400, "approved must be true or false") - if "note" in decision and decision["note"] is not None and not isinstance(decision["note"], str): - raise ReplyError(400, "note must be text") - if has_answer and "note" in decision: - raise ReplyError(400, "a question's decision carries an answer and no note") - result.append(dict(decision)) - return result + return [_checked_decision(decision) for decision in decisions] def stamp_decisions(decisions: Sequence[Decision], who: str, at: str) -> list[Decision]: @@ -844,17 +860,17 @@ def __init__(self) -> None: self._next_id = 0 self._seq = 0 - async def open(self) -> None: + async def open(self) -> None: # NOSONAR - async by contract: the boot awaits it return None - async def close(self) -> None: + async def close(self) -> None: # NOSONAR - async by contract: the shutdown awaits it return None def _bump(self) -> int: self._seq += 1 return self._seq - async def record(self, event: Mapping[str, Any], now: str) -> Row: + async def record(self, event: Mapping[str, Any], now: str) -> Row: # NOSONAR - async by contract: question.audit awaits it fields = row_fields(event, now) key = wait_key(event) existing = self._rows.get(self._keys[key]) if key is not None and key in self._keys else None @@ -870,8 +886,10 @@ async def record(self, event: Mapping[str, Any], now: str) -> Row: self._rows[row.id] = row return row - async def answer(self, key: tuple[str, str, int], decisions: list[dict[str, Any]], who: str, - state: str, outcome: dict[str, Any], now: str) -> Row | None: + async def answer( # NOSONAR - async by contract: question.audit awaits it + self, key: tuple[str, str, int], decisions: list[dict[str, Any]], who: str, + state: str, outcome: dict[str, Any], now: str, + ) -> Row | None: row_id = self._keys.get(key) row = self._rows.get(row_id) if row_id is not None else None if row is None: @@ -881,22 +899,23 @@ async def answer(self, key: tuple[str, str, int], decisions: list[dict[str, Any] row = replace(row, seq=self._bump(), state=state, decisions=decisions, outcome=outcome, answered_by=who, answered_at=now, updated_at=now) self._rows[row.id] = row - return row + return row # NOSONAR - a Row: replace() answers with the type of the row it was given - async def expire(self, now: str) -> list[Row]: + async def expire(self, now: str) -> list[Row]: # NOSONAR - async by contract: the sweep awaits it changed: list[Row] = [] - for row in list(self._rows.values()): + # no copy: a change replaces the value under the key being visited, and adds or removes none + for row in self._rows.values(): if row.state == "open" and row.kind in WAIT_KINDS and row.expires_at and row.expires_at < now: row = replace(row, seq=self._bump(), state="expired", updated_at=now) self._rows[row.id] = row changed.append(row) return changed - async def since(self, seq: int, limit: int) -> list[Row]: + async def since(self, seq: int, limit: int) -> list[Row]: # NOSONAR - async by contract: a reader awaits it rows = sorted((r for r in self._rows.values() if r.seq > seq), key=lambda r: r.seq) return rows[:limit] - async def counts(self) -> dict[str, int]: + async def counts(self) -> dict[str, int]: # NOSONAR - async by contract: ask.health awaits it result: dict[str, int] = {} for row in self._rows.values(): label = row.state or row.kind @@ -1006,7 +1025,7 @@ async def _many(self, sql: str, params: tuple[Any, ...]) -> list[Row]: async with self._pool.connection() as connection: cursor = await connection.execute(sql, params) records = await cursor.fetchall() - return [row_from_record(record) for record in records] + return [row_from_record(entry) for entry in records] async def record(self, event: Mapping[str, Any], now: str) -> Row: fields = row_fields(event, now) @@ -1073,9 +1092,11 @@ def failure(exc: BaseException) -> str: def question_store() -> QuestionStore: global _store - if _store is None: - _store = MemoryQuestionStore() - return _store + store = _store + if store is None: + store = MemoryQuestionStore() + _store = store + return store async def question_audit(_headers: dict[str, str], body: Body) -> Any: @@ -1104,7 +1125,8 @@ async def question_audit(_headers: dict[str, str], body: Body) -> Any: return {"recorded": False, "error": "no wait recorded"} log.info("%s recorded the answer on %d by %s - %s", AUDIT_ROUTE, row.id, row.answered_by, row.state) return {"recorded": True, "id": row.id, "seq": row.seq, "state": row.state} - except Exception as exc: # noqa: BLE001 - off the request path: logged by type, reported to the caller + # off the request path: logged by type, reported to the caller + except Exception as exc: # noqa: BLE001 log.warning("%s could not write - %s", AUDIT_ROUTE, failure(exc)) return {"recorded": False, "error": failure(exc)} raise AppException(400, f"{AUDIT_ROUTE} takes record or answer") @@ -1118,16 +1140,20 @@ async def question_audit(_headers: dict[str, str], body: Body) -> Any: def _po() -> PostOffice: global _post_office - if _post_office is None: - _post_office = PostOffice() - return _post_office + office = _post_office + if office is None: + office = PostOffice() + _post_office = office + return office def _session() -> aiohttp.ClientSession: global _http - if _http is None or _http.closed: - _http = aiohttp.ClientSession() - return _http + session = _http + if session is None or session.closed: + session = aiohttp.ClientSession() + _http = session + return session async def deliver(event: Mapping[str, Any], settings: Settings) -> list[dict[str, Any]]: @@ -1249,7 +1275,8 @@ def __init__(self, issuer: str, audience: str, jwks_url: str) -> None: self.jwks_url = jwks_url self._keys: list[dict[str, Any]] = [] - async def _fetch_json(self, url: str) -> Any: + @staticmethod + async def _fetch_json(url: str) -> Any: async with _session().get(url, timeout=aiohttp.ClientTimeout(total=10)) as response: if response.status != 200: raise ReplyError(503, f"the issuer's keys are not reachable - {response.status}") @@ -1307,14 +1334,16 @@ async def verify(self, token: str) -> dict[str, Any]: def _oauth2(settings: Settings) -> OAuth2Verifier: global _verifier + verifier = _verifier if ( - _verifier is None - or _verifier.issuer != settings.oauth2_issuer - or _verifier.audience != settings.oauth2_audience - or (settings.oauth2_jwks_url and _verifier.jwks_url != settings.oauth2_jwks_url) + verifier is None + or verifier.issuer != settings.oauth2_issuer + or verifier.audience != settings.oauth2_audience + or (settings.oauth2_jwks_url and verifier.jwks_url != settings.oauth2_jwks_url) ): - _verifier = OAuth2Verifier(settings.oauth2_issuer, settings.oauth2_audience, settings.oauth2_jwks_url) - return _verifier + verifier = OAuth2Verifier(settings.oauth2_issuer, settings.oauth2_audience, settings.oauth2_jwks_url) + _verifier = verifier + return verifier async def identify( @@ -1528,7 +1557,7 @@ def _html(status: int, text: str) -> EventEnvelope: def _json_reply(body: Any, status: int = 200) -> EventEnvelope: """A JSON reply as the page's script and the UI read it: serialized here, so a null stays a null (the engines' renderer would omit it), under its content type.""" - return (EventEnvelope().set_status(status).set_header("content-type", "application/json") + return (EventEnvelope().set_status(status).set_header("content-type", _APPLICATION_JSON) .set_body(json.dumps(body))) @@ -1568,7 +1597,7 @@ async def ask_config(_headers: dict[str, str], _body: Body) -> Any: async def _engine(request: EngineRequest, timeout_ms: int) -> tuple[int, dict[str, Any]]: """Send a request to the graph's entry and map what comes back.""" - headers = {**request.headers, "content-type": "application/json", "accept": "application/json"} + headers = {**request.headers, "content-type": _APPLICATION_JSON, "accept": _APPLICATION_JSON} try: async with _session().post( request.url, @@ -1718,7 +1747,8 @@ async def boot() -> None: store.name) try: await store.open() - except Exception as exc: # noqa: BLE001 - an outage, not a deployment error: the writes fail by type until it answers + # an outage, not a deployment error: the writes fail by type until it answers + except Exception as exc: # noqa: BLE001 log.warning("The question record (%s) is not answering at start - %s", store.name, failure(exc)) if _sweeper is None: _sweeper = asyncio.get_running_loop().create_task(_sweep(settings.audit_sweep_ms), name="question-audit-sweep") diff --git a/extensions/llm-helper/llm_helper.py b/extensions/llm-helper/llm_helper.py index 35795a2..ee0db32 100644 --- a/extensions/llm-helper/llm_helper.py +++ b/extensions/llm-helper/llm_helper.py @@ -131,6 +131,8 @@ DURATION_SECONDS = {"": 1, "s": 1, "m": 60, "h": 3600, "d": 86400} DEFAULT_TRANSCRIPT_TTL = "7d" DEFAULT_TRANSCRIPT_RETENTION = "0" +# the configuration key that names the transcript store, one of STORES +_TRANSCRIPT_STORE_KEY = "llm.transcript.store" STORE_MEMORY = "memory" STORE_REDIS = "redis" STORES = (STORE_MEMORY, STORE_REDIS) @@ -177,6 +179,8 @@ # a durable, queryable record of every model turn, written by the transcript.audit function behind # a local event, never on the turn's path; PostgreSQL is the reference store, its schema published AUDIT_ROUTE = "transcript.audit" +# the configuration key that names the audit store, one of AUDITS; unset, no turn is audited +_TRANSCRIPT_AUDIT_KEY = "llm.transcript.audit" AUDIT_POSTGRES = "postgres" AUDITS = (AUDIT_POSTGRES,) DEFAULT_AUDIT_RETENTION = "365d" @@ -903,6 +907,23 @@ def _pdf(index: int, data: bytes, pages: tuple[tuple[int, int], ...] | None) -> raise AppException(400, f"{where}: not a readable PDF") from exc +def _check_image( + index: int, spec: Attachment, media_type: str, data: bytes, image_max_encoded: int +) -> None: + """What an image must pass to go as it is, or a 400 that names the rule: it has no pages, + and base64-encoded, as the provider counts it, it is within the backend's limit.""" + where = f"attachments[{index}]" + if spec.pages is not None: + raise AppException(400, f"{where}.pages needs a PDF - the file is {media_type}") + encoded = 4 * ((len(data) + 2) // 3) + if encoded > image_max_encoded: + raise AppException( + 400, + f"{where}: an image of {encoded} bytes base64-encoded - the backend's " + f"limit is {image_max_encoded}", + ) + + def _load_attachments( specs: tuple[Attachment, ...], root: Path, max_bytes: int, image_max_encoded: int ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], int]: @@ -936,15 +957,7 @@ def _load_attachments( if media_type == PDF_MEDIA_TYPE: kind, sent = "document", _pdf(index, data, spec.pages) else: - if spec.pages is not None: - raise AppException(400, f"{where}.pages needs a PDF - the file is {media_type}") - encoded = 4 * ((len(data) + 2) // 3) - if encoded > image_max_encoded: - raise AppException( - 400, - f"{where}: an image of {encoded} bytes base64-encoded - the backend's " - f"limit is {image_max_encoded}", - ) + _check_image(index, spec, media_type, data, image_max_encoded) kind, sent = "image", data source = { "type": "base64", @@ -991,7 +1004,7 @@ async def attach(request: LlmRequest, backend: Backend) -> Attached: ) -async def attachments_boot() -> None: +async def attachments_boot() -> None: # NOSONAR - async by contract: the host awaits it at startup """A root that is configured and is not a folder is a deployment error: stop by name at start, before a request finds it.""" if not _prop(ATTACHMENTS_ROOT): @@ -1315,11 +1328,13 @@ def _live(self, conversation: str) -> tuple[float, int, str, int] | None: return None return entry - async def load(self, conversation: str) -> Transcript | None: + async def load( # NOSONAR - async by contract: the loop turn and the audit function await it + self, conversation: str + ) -> Transcript | None: entry = self._live(conversation) return None if entry is None else Transcript.from_json(entry[2]) - async def save( + async def save( # NOSONAR - async by contract: the loop turn and a single call's save await it self, conversation: str, expected_turn: int, record: Transcript, ttl_s: int ) -> bool: # no await between the check and the write, so the event loop makes it atomic @@ -1336,16 +1351,20 @@ async def save( ) return True - async def audited(self, conversation: str) -> int: + async def audited(self, conversation: str) -> int: # NOSONAR - async by contract: the interface entry = self._live(conversation) return 0 if entry is None else entry[3] - async def mark_audited(self, conversation: str, turn: int) -> None: + async def mark_audited( # NOSONAR - async by contract: the audit function awaits it + self, conversation: str, turn: int + ) -> None: entry = self._live(conversation) if entry is not None: self._records[conversation] = (entry[0], entry[1], entry[2], turn) - async def release(self, conversation: str, retention_s: int) -> None: + async def release( # NOSONAR - async by contract: the audit function awaits it + self, conversation: str, retention_s: int + ) -> None: entry = self._live(conversation) if entry is None: return @@ -1354,15 +1373,15 @@ async def release(self, conversation: str, retention_s: int) -> None: else: self._records[conversation] = (self._clock() + retention_s, *entry[1:]) - async def unaudited(self) -> list[str]: + async def unaudited(self) -> list[str]: # NOSONAR - async by contract: the sweep awaits it lagging: list[str] = [] - for conversation in list(self._records): + for conversation in list(self._records): # NOSONAR - copy: the loop changes the collection entry = self._live(conversation) if entry is not None and entry[3] < entry[1]: lagging.append(conversation) return lagging - async def sweep_lock(self, _interval_ms: int) -> bool: + async def sweep_lock(self, _interval_ms: int) -> bool: # NOSONAR - async by contract: the sweep return True # one process sweeps its own records @@ -1488,7 +1507,7 @@ def get_store() -> TranscriptStore: global _store store = _store if store is None: - name = str(_prop("llm.transcript.store", "") or "").lower() + name = str(_prop(_TRANSCRIPT_STORE_KEY, "") or "").lower() if not name: raise AppException(503, MISSING_STORE) if name not in STORES: @@ -1823,16 +1842,18 @@ def __init__(self) -> None: self.conversations: dict[str, dict[str, Any]] = {} self.turn_rows: dict[str, dict[int, dict[str, Any]]] = {} - async def open(self) -> None: + async def open(self) -> None: # NOSONAR - async by contract: audit_boot awaits it return None - async def close(self) -> None: + async def close(self) -> None: # NOSONAR - async by contract: audit_shutdown awaits it return None - async def turns(self, conversation: str) -> set[int]: + async def turns(self, conversation: str) -> set[int]: # NOSONAR - async by contract: the audit return set(self.turn_rows.get(conversation, {})) - async def write(self, conversation: dict[str, Any], turns: list[dict[str, Any]]) -> None: + async def write( # NOSONAR - async by contract: the audit function awaits it + self, conversation: dict[str, Any], turns: list[dict[str, Any]] + ) -> None: key = str(conversation["conversation"]) held = self.conversations.get(key) if held is None: @@ -1976,14 +1997,14 @@ def _postgres_audit_store() -> PostgresAuditStore: def audit_configured() -> bool: - return bool(_prop("llm.transcript.audit")) + return bool(_prop(_TRANSCRIPT_AUDIT_KEY)) def get_audit_store() -> AuditStore: global _audit audit = _audit if audit is None: - name = str(_prop("llm.transcript.audit", "") or "").lower() + name = str(_prop(_TRANSCRIPT_AUDIT_KEY, "") or "").lower() if not name: raise AppException(503, MISSING_AUDIT) if name not in AUDITS: @@ -2095,7 +2116,8 @@ async def _save_single(record: Transcript) -> None: conversation = _new_conversation_id() try: saved = await get_store().save(conversation, 0, record, _audit_grace_s()) - except Exception as exc: # noqa: BLE001 - off the call's path: logged, never raised + # off the call's path: logged, never raised + except Exception as exc: # noqa: BLE001 log.warning("%s single call not saved - %s", AUDIT_ROUTE, _audit_failure(exc)) return if not saved: # a new reference never meets a record; named for the day one does @@ -2260,7 +2282,8 @@ async def transcript_audit(_headers: dict[str, str], body: Body) -> None: check = bool(event.get("check")) try: await _audit_apply(conversation, check) - except Exception as exc: # noqa: BLE001 - off the turn's path: logged, the sweep repairs + # off the turn's path: logged, the sweep repairs + except Exception as exc: # noqa: BLE001 log.warning( "%s conversation=%s %s failed - %s", AUDIT_ROUTE, conversation, "check" if check else "write", _audit_failure(exc), @@ -2304,7 +2327,7 @@ async def audit_boot() -> None: except AppException as exc: log.error("transcript audit store cannot start - %s", exc.message) raise SystemExit(1) from exc - if audit_single_configured() and not _prop("llm.transcript.store"): + if audit_single_configured() and not _prop(_TRANSCRIPT_STORE_KEY): # a single call's record waits in the working store for its check: a deployment error log.error("transcript audit store cannot start - %s", MISSING_SINGLE_STORE) raise SystemExit(1) @@ -2314,7 +2337,8 @@ async def audit_boot() -> None: try: await audit.open() log.info("transcript audit store %s ready", audit.name) - except Exception as exc: # noqa: BLE001 - an outage, not a deployment error + # an outage, not a deployment error + except Exception as exc: # noqa: BLE001 log.warning( "transcript audit store %s not answering at start - %s; the sweep repairs what the " "outage defers", @@ -2567,10 +2591,10 @@ async def llm_health(headers: dict[str, str], _body: Body) -> Any: info["region"] = region # which region a Bedrock call is signed for if backend.api: info["api"] = backend.api # which Bedrock surface answers - store = _prop("llm.transcript.store") + store = _prop(_TRANSCRIPT_STORE_KEY) if store: info["transcript_store"] = store # where a loop's transcripts are kept - audit = _prop("llm.transcript.audit") + audit = _prop(_TRANSCRIPT_AUDIT_KEY) if audit: info["transcript_audit"] = audit # where every model turn is recorded for audit return info diff --git a/src/mercury_composable/async_http_request.py b/src/mercury_composable/async_http_request.py index cdfd957..3585caf 100644 --- a/src/mercury_composable/async_http_request.py +++ b/src/mercury_composable/async_http_request.py @@ -19,7 +19,8 @@ async def lookup(headers: dict[str, str], body: Body): save(uploaded.name, uploaded.content) return {"profile_id": profile_id, "lang": lang} -A reply's status and headers come from a returned :class:`EventEnvelope` +A reply's status and headers come from a returned +:class:`~mercury_composable.envelope.EventEnvelope` (``EventEnvelope().set_status(201).set_header("Location", url).set_body(result)``); an error is a raised ``AppException(status, message)``. """ diff --git a/src/mercury_composable/rest_automation.py b/src/mercury_composable/rest_automation.py index da77e04..d90ec6f 100644 --- a/src/mercury_composable/rest_automation.py +++ b/src/mercury_composable/rest_automation.py @@ -135,15 +135,17 @@ def resolve_location(config: AppConfig, location: str) -> str | None: the application file is unknown (an interactive session).""" value = location.strip() if value.startswith("classpath:"): - if config.resources_dir is None: + resources_dir = config.resources_dir + if resources_dir is None: return None - return os.path.join(config.resources_dir, value[len("classpath:"):].lstrip("/")) + return os.path.join(resources_dir, value[len("classpath:"):].lstrip("/")) value = value.removeprefix("file:") if os.path.isabs(value): return value - if config.app_dir is None: + app_dir = config.app_dir + if app_dir is None: return None - return os.path.join(config.app_dir, value) + return os.path.join(app_dir, value) def load_table(config: AppConfig) -> RoutingTable: @@ -315,14 +317,14 @@ def attach(self, app: web.Application, *fallback: web.AbstractRoute) -> None: self._fallback = list(fallback) app.middlewares.append(self.middleware) - async def startup(self) -> None: + async def startup(self) -> None: # NOSONAR - async by contract: the host awaits it at startup """Drop the entries whose service is not registered (the engines' load-time rule, run at the end of the boot so an extension's startup registrations count) and announce the table.""" if self._started: return self._started = True skipped = self.table.retain_available( - lambda service: service in BUILT_IN_SERVICES or self.registry.exists(service)) + lambda name: name in BUILT_IN_SERVICES or self.registry.exists(name)) for methods, url, service in skipped: log.warning("Skip %s %s - Service %s not available", methods, url, service) for route in self.table.routes: @@ -343,23 +345,30 @@ async def middleware(self, request: web.Request, handler: Handler) -> web.Stream # the engines: a request for exactly "/" falls back to a declared /index.html entry assigned = self.table.find(method, "/index.html") if assigned is None: - if self.table.path_matches_any_method(path): - return _error(405, "Method not allowed") - if request.match_info.route in self._fallback: - if method in ("GET", "HEAD"): - served = await self._static(request, path) - if served is not None: - return served - if path != "/": - # nothing claims the path: the engines' 404, in their header shape - return _error(404, "Resource not found") - return await handler(request) + return await self._unclaimed(request, handler, method, path) if method == "OPTIONS": return self._preflight(assigned.info) if assigned.info.service in BUILT_IN_SERVICES: return await self._builtin(request, assigned) return await self._process(request, assigned) + async def _unclaimed(self, request: web.Request, handler: Handler, method: str, + path: str) -> web.StreamResponse: + """A path no entry claims: a known path under a wrong method is 405; where the host's + own routes claim nothing specific either, a static file or the engines' 404; else the + host's handler.""" + if self.table.path_matches_any_method(path): + return _error(405, "Method not allowed") + if request.match_info.route in self._fallback: + if method in ("GET", "HEAD"): + served = await self._static(request, path) + if served is not None: + return served + if path != "/": + # nothing claims the path: the engines' 404, in their header shape + return _error(404, "Resource not found") + return await handler(request) + @staticmethod def _preflight(info: RouteInfo) -> web.Response: """The CORS preflight: the ``options`` lines with 204; no CORS block means 405.""" @@ -389,6 +398,38 @@ async def _prepare(self, request: web.Request, assigned: AssignedRoute) -> _Prep headers = info.headers.request.apply(headers) trace_header = (info.trace_id_header or self.trace_header).lower() cid_header = (info.correlation_id_header or self.cid_header).lower() + trace_id, parent_span, cid = self._resolve_ids(info, headers, trace_header, cid_header) + headers.setdefault(X_TTL, str(info.timeout_seconds * 1000)) + query_text = request.query_string + query = parse_query(query_text) + cookies = parse_cookies(headers.pop("cookie", None)) + accept = headers.get("accept") + parsed, files = await self._read_body(request, info, method, query, headers) + http_request = (AsyncHttpRequest().set_method(method).set_url(path) + .set_remote_ip(request.remote or "unknown") + .set_secure(headers.get("x-forwarded-proto") == "https") + .set_target_host(headers.get("host", "")) + .set_timeout_seconds(info.timeout_seconds)) + for name, value in headers.items(): + http_request.set_header(name, value) + for name, value in assigned.path_params.items(): + http_request.set_path_parameter(name, value) + for name, value in query.items(): + http_request.set_query_parameter(name, value) + self._set_body(http_request, parsed, files) + if query_text: + http_request.set_query_string(query_text) + for name, value in cookies.items(): + http_request.set_cookie(name, value) + trace_path = f"{method} {path}?{query_text}" if query_text else f"{method} {path}" + edge = _RestEdge(self.bus, trace_id, trace_path, parent_span) if trace_id else None + return _Prepared(http_request, cid, cid_header, trace_id, trace_path, accept, edge, + method == "HEAD") + + def _resolve_ids(self, info: RouteInfo, headers: dict[str, str], trace_header: str, + cid_header: str) -> tuple[str | None, str | None, str]: + """The trace id, the caller's span and the correlation id of a request; the correlation + id is stamped on the headers under its own name.""" # a well-formed standard traceparent wins; the custom name is read only when it is absent traceparent = parse_traceparent(headers.get(TRACEPARENT)) if traceparent is None: @@ -407,12 +448,13 @@ async def _prepare(self, request: web.Request, assigned: AssignedRoute) -> _Prep if not cid: cid = trace_id if (cid_header == trace_header and trace_id) else uuid.uuid4().hex headers[cid_header] = cid - headers.setdefault(X_TTL, str(info.timeout_seconds * 1000)) - query_text = request.query_string - query = parse_query(query_text) - cookies = parse_cookies(headers.pop("cookie", None)) - accept = headers.get("accept") - files: list[UploadedFile] = [] + return trace_id, parent_span, cid + + async def _read_body(self, request: web.Request, info: RouteInfo, method: str, + query: dict[str, str | list[str]], + headers: dict[str, str]) -> tuple[ParsedBody, list[UploadedFile]]: + """The body by its declared content type, with the files of an upload; the fields of a + form, and the text fields of an upload, join the query parameters in ``query``.""" declared = (base_content_type(headers.get("content-type")) or "").lower() if info.upload and method == "POST" and declared == MULTIPART_FORM_DATA: # the engines' upload, bounded: the files' bytes ride the request map, a form's text @@ -420,37 +462,24 @@ async def _prepare(self, request: web.Request, assigned: AssignedRoute) -> _Prep files, fields = await self._read_multipart(request) for name, value in fields.items(): query[name] = value - parsed = ParsedBody("upload", None) - else: - parsed = parse_body(headers.get("content-type"), await request.read()) - if parsed.kind == "form": - for name, value in parsed.value.items(): - query[name] = value - http_request = (AsyncHttpRequest().set_method(method).set_url(path) - .set_remote_ip(request.remote or "unknown") - .set_secure(headers.get("x-forwarded-proto") == "https") - .set_target_host(headers.get("host", "")) - .set_timeout_seconds(info.timeout_seconds)) - for name, value in headers.items(): - http_request.set_header(name, value) - for name, value in assigned.path_params.items(): - http_request.set_path_parameter(name, value) - for name, value in query.items(): - http_request.set_query_parameter(name, value) + return ParsedBody("upload", None), files + parsed = parse_body(headers.get("content-type"), await request.read()) + if parsed.kind == "form": + for name, value in parsed.value.items(): + query[name] = value + return parsed, [] + + @staticmethod + def _set_body(http_request: AsyncHttpRequest, parsed: ParsedBody, + files: list[UploadedFile]) -> None: + """The body on the request model: the files of an upload, else the parsed value - none + for a form, whose fields are query parameters.""" if parsed.kind == "upload": for uploaded in files: http_request.add_file(uploaded.name, uploaded.content_type, uploaded.content, uploaded.tag) else: http_request.set_body(None if parsed.kind == "form" else parsed.value) - if query_text: - http_request.set_query_string(query_text) - for name, value in cookies.items(): - http_request.set_cookie(name, value) - trace_path = f"{method} {path}?{query_text}" if query_text else f"{method} {path}" - edge = _RestEdge(self.bus, trace_id, trace_path, parent_span) if trace_id else None - return _Prepared(http_request, cid, cid_header, trace_id, trace_path, accept, edge, - method == "HEAD") async def _read_multipart(self, request: web.Request) -> tuple[list[UploadedFile], dict[str, str]]: """The parts of a multipart body: a part with a filename is a file (its field name the @@ -470,24 +499,12 @@ async def _read_multipart(self, request: web.Request) -> tuple[list[UploadedFile if not isinstance(part, BodyPartReader): continue if part.filename: - chunks: list[bytes] = [] - while True: - chunk = await part.read_chunk(65536) - if not chunk: - break - total += len(chunk) - if total > self.upload_max_bytes: - raise AppException(413, f"Upload exceeds {self.upload_max_bytes} bytes") - chunks.append(chunk) - content = b"".join(chunks) + content, total = await self._read_file(part, total) content_type = part.headers.get("Content-Type", "application/octet-stream") files.append(UploadedFile(part.filename, content_type, len(content), part.name or "file", content)) else: - text = await part.text() - total += len(text) - if total > self.upload_max_bytes: - raise AppException(413, f"Upload exceeds {self.upload_max_bytes} bytes") + text, total = await self._read_field(part, total) fields[part.name or ""] = text except AppException: raise @@ -495,6 +512,28 @@ async def _read_multipart(self, request: web.Request) -> tuple[list[UploadedFile raise AppException(400, f"Invalid multipart body - {e}") from None return files, fields + async def _read_file(self, part: BodyPartReader, total: int) -> tuple[bytes, int]: + """A file part's bytes, read in chunks so the bound holds while they arrive; ``total`` is + the size of the upload before this part and comes back with it counted.""" + chunks: list[bytes] = [] + while True: + chunk = await part.read_chunk(65536) + if not chunk: + break + total += len(chunk) + if total > self.upload_max_bytes: + raise AppException(413, f"Upload exceeds {self.upload_max_bytes} bytes") + chunks.append(chunk) + return b"".join(chunks), total + + async def _read_field(self, part: BodyPartReader, total: int) -> tuple[str, int]: + """A text field of the form, counted against the same bound as the files.""" + text = await part.text() + total += len(text) + if total > self.upload_max_bytes: + raise AppException(413, f"Upload exceeds {self.upload_max_bytes} bytes") + return text, total + @staticmethod def _event(to: str, prepared: _Prepared) -> EventEnvelope: """The event a function (or the authentication function) receives: the request map as the @@ -585,20 +624,31 @@ async def _process(self, request: web.Request, assigned: AssignedRoute) -> web.S # owns the round-trip record from here return await self._stream(request, info, prepared, first, marker, sink_route) self.bus.close_sink(sink_route) - if marker == EXCEPTION: - status = first.get_status() if first.has_error() else 500 - raise AppException(status, _stream_error_message(first)) - # a single-shot reply (a marked segment taken as the whole reply - the first - # event completes the exchange, the engines' rule) - first.headers = {k: v for k, v in first.headers.items() - if k.lower() not in (X_EVENT_STREAM, X_EVENT_NAME)} - reply = first + reply = self._single_shot(first, marker) else: reply = await self._rpc(info.service, service, prepared, info.timeout_ms) except AppException as e: if edge is not None: edge.record(e.status, e.message) return _error(e.status, e.message) + return self._respond(info, prepared, reply) + + @staticmethod + def _single_shot(first: EventEnvelope, marker: str | None) -> EventEnvelope: + """An interceptor's first event as the whole reply; an ``exception`` segment is the + failure it carries.""" + if marker == EXCEPTION: + status = first.get_status() if first.has_error() else 500 + raise AppException(status, _stream_error_message(first)) + # a single-shot reply (a marked segment taken as the whole reply - the first event + # completes the exchange, the engines' rule) + first.headers = {k: v for k, v in first.headers.items() + if k.lower() not in (X_EVENT_STREAM, X_EVENT_NAME)} + return first + + @staticmethod + def _respond(info: RouteInfo, prepared: _Prepared, reply: EventEnvelope) -> web.Response: + """The reply as the HTTP response under the engines' mapping, recorded on the edge.""" mapped = map_response(status=reply.get_status(), reply_headers=reply.headers, body=reply.body, accept=prepared.accept, is_head=prepared.is_head, transform=info.headers.response if info.headers else None, @@ -608,8 +658,8 @@ async def _process(self, request: web.Request, assigned: AssignedRoute) -> web.S for name, value in mapped.headers: response.headers.add(name, value) response.omit_content_type = not any(name == "content-type" for name, _ in mapped.headers) - if edge is not None: - edge.record(mapped.status, None) + if prepared.edge is not None: + prepared.edge.record(mapped.status, None) return response async def _stream(self, request: web.Request, info: RouteInfo, prepared: _Prepared, @@ -619,10 +669,43 @@ async def _stream(self, request: web.Request, info: RouteInfo, prepared: _Prepar ends at ``eof``, fails in band at an ``exception`` or when the producer idles past the allowance (the entry's timeout, or the head's ``x-ttl`` in seconds).""" queue = self.bus._sinks.get(sink_route) + headers, cookies, head_type, idle_ms = self._stream_head(first, info.timeout_ms) + if info.headers is not None: + headers = info.headers.response.apply(headers) + if not any(name.lower() == prepared.cid_header for name in headers): + headers[prepared.cid_header] = prepared.cid + if info.cors is not None: + for name, value in info.cors.headers: + headers[name.lower()] = value + content_type = head_type or negotiate_stream_type(prepared.accept) + sse = content_type.startswith("text/event-stream") + if sse: + headers.setdefault("cache-control", "no-cache") + response = self._stream_response(first.get_status(), headers, cookies, content_type) + status, error = first.get_status(), None + try: + await response.prepare(request) + if queue is not None: + status, error = await self._render(response, queue, first, marker, sse, idle_ms) + except ConnectionError: + log.debug("Client disconnected from event stream") + finally: + self.bus.close_sink(sink_route) + with contextlib.suppress(ConnectionError): + await response.write_eof() + if prepared.edge is not None: + prepared.edge.record(status, error) + return response + + @staticmethod + def _stream_head(first: EventEnvelope, + idle_ms: int) -> tuple[dict[str, str], list[str], str | None, int]: + """The head segment's headers by their role: the lines for the response, the cookies, the + content type and the idle allowance - ``idle_ms`` unless the head carries a positive + ``x-ttl`` in seconds. The streaming handles never reach the wire.""" headers: dict[str, str] = {} cookies: list[str] = [] content_type: str | None = None - idle_ms = info.timeout_ms for name, value in first.headers.items(): key = name.lower() if key in (X_EVENT_STREAM, X_EVENT_NAME, "x-stream-id"): @@ -638,37 +721,20 @@ async def _stream(self, request: web.Request, info: RouteInfo, prepared: _Prepar cookies.extend(c.strip() for c in value.split("|")) else: headers[key] = value - if info.headers is not None: - headers = info.headers.response.apply(headers) - if not any(name.lower() == prepared.cid_header for name in headers): - headers[prepared.cid_header] = prepared.cid - if info.cors is not None: - for name, value in info.cors.headers: - headers[name.lower()] = value - content_type = content_type or negotiate_stream_type(prepared.accept) - sse = content_type.startswith("text/event-stream") - if sse: - headers.setdefault("cache-control", "no-cache") - response = web.StreamResponse(status=first.get_status()) + return headers, cookies, content_type, idle_ms + + @staticmethod + def _stream_response(status: int, headers: dict[str, str], cookies: list[str], + content_type: str) -> web.StreamResponse: + """The streamed response before its head is sent: the status, the header lines, one + ``Set-Cookie`` per cookie and the content type last.""" + response = web.StreamResponse(status=status) for name, value in headers.items(): response.headers[name] = value for cookie in cookies: if cookie: response.headers.add("Set-Cookie", cookie) response.headers["content-type"] = content_type - status, error = first.get_status(), None - try: - await response.prepare(request) - if queue is not None: - status, error = await self._render(response, queue, first, marker, sse, idle_ms) - except ConnectionError: - log.debug("Client disconnected from event stream") - finally: - self.bus.close_sink(sink_route) - with contextlib.suppress(ConnectionError): - await response.write_eof() - if prepared.edge is not None: - prepared.edge.record(status, error) return response async def _render(self, response: web.StreamResponse, queue: asyncio.Queue[EventEnvelope], @@ -683,40 +749,76 @@ async def _render(self, response: web.StreamResponse, queue: asyncio.Queue[Event event, marker = pending pending = None else: - waited = await self._next(response, queue, idle_ms, ping_ms) - if waited is None: - seconds = idle_ms // 1000 - message = f"Timeout for {seconds} seconds" - if sse: - await response.write(sse_frame("error", compact_json(error_body(408, message)))) - return 408, message - found = stream_signal(waited) - if found is None: - log.warning("Single-shot reply dropped - its streaming response has already started") - continue - if found not in (DATA, EOF, EXCEPTION): - log.warning("Dropping event - invalid %s signal", X_EVENT_STREAM) - continue - event, marker = waited, found + segment = await self._next_marked(response, queue, idle_ms, ping_ms) + if segment is None: + return await self._write_timeout(response, sse, idle_ms) + event, marker = segment if marker == DATA: - if sse: - if event.body is not None: - await response.write(sse_frame(stream_event_name(event), stream_text(event.body))) - else: - chunk = _chunk_bytes(event.body) - if chunk: - await response.write(chunk) + await self._write_data(response, event, sse) elif marker == EOF: - if sse: - text = stream_text(event.body) if event.body is not None else "{}" - await response.write(sse_frame("done", text)) + await self._write_done(response, event, sse) return head_status, None else: - status = event.get_status() if event.has_error() else 500 - message = _stream_error_message(event) - if sse: - await response.write(sse_frame("error", compact_json(error_body(status, message)))) - return status, message + return await self._write_failure(response, event, sse) + + async def _next_marked(self, response: web.StreamResponse, queue: asyncio.Queue[EventEnvelope], + idle_ms: int, ping_ms: int) -> tuple[EventEnvelope, str] | None: + """The next segment that carries a stream signal, with that signal; None at expiry. A + single-shot reply and an unknown signal are dropped, and the wait starts again.""" + while True: + waited = await self._next(response, queue, idle_ms, ping_ms) + if waited is None: + return None + found = stream_signal(waited) + if found is None: + log.warning( + "Single-shot reply dropped - its streaming response has already started") + continue + if found not in (DATA, EOF, EXCEPTION): + log.warning("Dropping event - invalid %s signal", X_EVENT_STREAM) + continue + return waited, found + + @staticmethod + async def _write_timeout(response: web.StreamResponse, sse: bool, + idle_ms: int) -> tuple[int, str]: + """The producer idled past the allowance: the ``error`` frame under SSE, and a 408 as the + stream's outcome.""" + seconds = idle_ms // 1000 + message = f"Timeout for {seconds} seconds" + if sse: + await response.write(sse_frame("error", compact_json(error_body(408, message)))) + return 408, message + + @staticmethod + async def _write_data(response: web.StreamResponse, event: EventEnvelope, sse: bool) -> None: + """A data segment: an SSE frame under its event name, else its bytes as a chunk; a + segment without a body writes nothing.""" + if sse: + if event.body is not None: + await response.write(sse_frame(stream_event_name(event), stream_text(event.body))) + else: + chunk = _chunk_bytes(event.body) + if chunk: + await response.write(chunk) + + @staticmethod + async def _write_done(response: web.StreamResponse, event: EventEnvelope, sse: bool) -> None: + """The ``eof`` segment: the ``done`` frame under SSE, nothing in a chunked stream.""" + if sse: + text = stream_text(event.body) if event.body is not None else "{}" + await response.write(sse_frame("done", text)) + + @staticmethod + async def _write_failure(response: web.StreamResponse, event: EventEnvelope, + sse: bool) -> tuple[int, str]: + """An ``exception`` segment: the ``error`` frame under SSE, and the segment's status and + message as the stream's outcome.""" + status = event.get_status() if event.has_error() else 500 + message = _stream_error_message(event) + if sse: + await response.write(sse_frame("error", compact_json(error_body(status, message)))) + return status, message @staticmethod async def _next(response: web.StreamResponse, queue: asyncio.Queue[EventEnvelope], @@ -765,14 +867,19 @@ async def _builtin(self, request: web.Request, assigned: AssignedRoute) -> web.S except TimeoutError: return _error(408, f"Timeout for {ttl_ms} ms") if not response.prepared: - if info.cors is not None: - for name, value in info.cors.headers: - response.headers[name] = value - if info.headers is not None: - for name, value in info.headers.response.add: - response.headers[name] = value + self._entry_headers(response, info) return response + @staticmethod + def _entry_headers(response: web.StreamResponse, info: RouteInfo) -> None: + """The entry's CORS headers and added response headers on a built-in's response.""" + if info.cors is not None: + for name, value in info.cors.headers: + response.headers[name] = value + if info.headers is not None: + for name, value in info.headers.response.add: + response.headers[name] = value + async def _builtin_call(self, request: web.Request, service: str) -> web.StreamResponse: if service == EVENT_API_SERVICE: return await self.server.handle_event(request) @@ -794,27 +901,10 @@ async def _static(self, request: web.Request, path: str) -> web.StreamResponse | static_filter = config.filter if static_filter is not None and matched_element(static_filter.path_list, path) \ and not matched_element(static_filter.exclusion_list, path): - service = self.registry.get(static_filter.service) - if service is None: - log.warning("Static content filter %s ignored because it does not exist", - static_filter.service) - else: - try: - filtered = await self._run_filter(request, service, path) - filter_headers = list(filtered.headers.items()) - if filtered.get_status() != 200: - kind, payload = envelope_payload(filtered) - response = web.Response(status=filtered.get_status(), body=payload) - response.headers.popall("Content-Type", None) - for name, value in filter_headers: - response.headers[name] = value - if kind is not None and "Content-Type" not in response.headers: - response.headers["Content-Type"] = kind - return response - except (AppException, DeliveryTimeout) as e: - # the Rust port's resilient divergence: log and serve the file anyway - log.error("Unable to filter static content HTTP-GET %s - %s", - static_filter.service, e) + filter_headers, passed_through = await self._apply_filter(request, path, + static_filter.service) + if passed_through is not None: + return passed_through response = static.response(file) for name, value in filter_headers: response.headers[name] = value @@ -823,6 +913,34 @@ async def _static(self, request: web.Request, path: str) -> web.StreamResponse | response.headers[name] = value return response + async def _apply_filter(self, request: web.Request, path: str, + route: str) -> tuple[list[tuple[str, str]], web.Response | None]: + """The static-content filter over one request: its headers, which ride the file's + response, and its own reply as the response when its status is not 200. A filter that is + not registered is ignored; one that fails is logged and the file is served anyway.""" + filter_headers: list[tuple[str, str]] = [] + service = self.registry.get(route) + if service is None: + log.warning("Static content filter %s ignored because it does not exist", route) + return filter_headers, None + try: + filtered = await self._run_filter(request, service, path) + filter_headers = list(filtered.headers.items()) + if filtered.get_status() != 200: + kind, payload = envelope_payload(filtered) + response = web.Response(status=filtered.get_status(), body=payload) + response.headers.popall("Content-Type", None) + for name, value in filter_headers: + response.headers[name] = value + if kind is not None and "Content-Type" not in response.headers: + response.headers["Content-Type"] = kind + return filter_headers, response + except (AppException, DeliveryTimeout) as e: + # the Rust port's resilient divergence: log and serve the file anyway - one line, as the + # engines log it, without a traceback + log.error("Unable to filter static content HTTP-GET %s - %s", route, e) + return filter_headers, None + async def _run_filter(self, request: web.Request, service: ServiceDef, path: str) -> EventEnvelope: """The filter receives an ``AsyncHttpRequest``-shaped event without a body.""" diff --git a/src/mercury_composable/rest_routing.py b/src/mercury_composable/rest_routing.py index 379f5f3..142c4f7 100644 --- a/src/mercury_composable/rest_routing.py +++ b/src/mercury_composable/rest_routing.py @@ -70,6 +70,11 @@ # the reserved envelope metadata that never reaches the HTTP wire (the engines' protected # metadata: the my_* keys of the worker's header view) _PROTECTED_PREFIX = "my_" +# the media types the edge dispatches a request body by and negotiates a response in +_APPLICATION_JSON = "application/json" +_APPLICATION_XML = "application/xml" +_TEXT_HTML = "text/html" +_TEXT_PLAIN = "text/plain" HTML_START = "
\n"
 HTML_END = "\n
" @@ -349,6 +354,24 @@ def _parse_header_blocks(section: Any) -> dict[str, HeaderInfo]: return blocks +def _parse_static_filter(filter_section: Any) -> SimpleHttpFilter: + """The ``filter`` of the ``static-content`` block. Its faults are reported in this order: a + ``path`` that is not a list, a missing ``service``, a ``path`` or ``exclusion`` pattern with + invalid syntax.""" + paths = filter_section.get("path") if isinstance(filter_section, Mapping) else None + if not isinstance(paths, list): + raise AppException(400, "static-content.filter.path must be a list") + path_list = [p for p in paths if isinstance(p, str)] + service = _text(filter_section.get("service")) if isinstance(filter_section, Mapping) else None + if service is None: + raise AppException(400, "static-content.filter.service is required") + exclusion = filter_section.get("exclusion") if isinstance(filter_section, Mapping) else None + exclusion_list = [p for p in exclusion if isinstance(p, str)] if isinstance(exclusion, list) else [] + if not path_list or not _valid_patterns(path_list) or not _valid_patterns(exclusion_list): + raise AppException(400, "static-content.filter path/exclusion has invalid syntax") + return SimpleHttpFilter(path_list, exclusion_list, service) + + def _parse_static_content(data: Mapping[str, Any]) -> StaticContentConfig: result = StaticContentConfig() section = data.get("static-content") @@ -361,24 +384,13 @@ def _parse_static_content(data: Mapping[str, Any]) -> StaticContentConfig: raise AppException(400, "static-content.no-cache-pages has invalid syntax") result.no_cache_pages = listed if "filter" in section: - filter_section = section.get("filter") - paths = filter_section.get("path") if isinstance(filter_section, Mapping) else None - if not isinstance(paths, list): - raise AppException(400, "static-content.filter.path must be a list") - path_list = [p for p in paths if isinstance(p, str)] - service = _text(filter_section.get("service")) if isinstance(filter_section, Mapping) else None - if service is None: - raise AppException(400, "static-content.filter.service is required") - exclusion = filter_section.get("exclusion") if isinstance(filter_section, Mapping) else None - exclusion_list = [p for p in exclusion if isinstance(p, str)] if isinstance(exclusion, list) else [] - if not path_list or not _valid_patterns(path_list) or not _valid_patterns(exclusion_list): - raise AppException(400, "static-content.filter path/exclusion has invalid syntax") - result.filter = SimpleHttpFilter(path_list, exclusion_list, service) + result.filter = _parse_static_filter(section.get("filter")) return result -def _parse_route(index: int, entry: Mapping[str, Any], cors_blocks: Mapping[str, CorsInfo], - header_blocks: Mapping[str, HeaderInfo]) -> RouteInfo: +def _parse_service(index: int, entry: Mapping[str, Any]) -> str: + """The entry's function route. What a language pack does not serve is refused by name: the + A/B dual service, the HTTP relay and a flow binding.""" service_value = _lookup(entry, "service") if isinstance(service_value, list): raise AppException( @@ -397,10 +409,11 @@ def _parse_route(index: int, entry: Mapping[str, Any], cors_blocks: Mapping[str, raise AppException( 400, f"rest[{index}] flow binding is not available in a language pack - flows run in the" f" engines ({binding})") - url = _text(_lookup(entry, "url")) - if url is None: - raise AppException(400, f"rest[{index}] missing 'url'") - raw_methods = _lookup(entry, "methods") + return service + + +def _parse_methods(index: int, raw_methods: Any) -> list[str]: + """The entry's methods in upper case; each must be text and one the grammar allows.""" if not isinstance(raw_methods, list): raise AppException(400, f"rest[{index}] missing 'methods' list") methods: list[str] = [] @@ -413,6 +426,16 @@ def _parse_route(index: int, entry: Mapping[str, Any], cors_blocks: Mapping[str, allowed = ", ".join(f'"{m}"' for m in ALLOWED_METHODS) raise AppException(400, f"rest[{index}] invalid method '{method}' (allowed: [{allowed}])") methods.append(method) + return methods + + +def _parse_route(index: int, entry: Mapping[str, Any], cors_blocks: Mapping[str, CorsInfo], + header_blocks: Mapping[str, HeaderInfo]) -> RouteInfo: + service = _parse_service(index, entry) + url = _text(_lookup(entry, "url")) + if url is None: + raise AppException(400, f"rest[{index}] missing 'url'") + methods = _parse_methods(index, _lookup(entry, "methods")) cors: CorsInfo | None = None cors_id = _text(_lookup(entry, "cors")) if cors_id is not None: @@ -445,7 +468,9 @@ def substitute_values(data: Any, resolve: Callable[[str], Any]) -> Any: substitution (the engines resolve ``${api.origin:*}`` in a cors line the same way).""" if isinstance(data, str): resolved = resolve(data) - return data if resolved is None else resolved if isinstance(resolved, str) else str(resolved) + if resolved is None: + return data + return resolved if isinstance(resolved, str) else str(resolved) if isinstance(data, list): return [substitute_values(item, resolve) for item in data] if isinstance(data, Mapping): @@ -584,6 +609,22 @@ class ParsedBody(NamedTuple): value: Any +def _parse_json_body(data: bytes) -> ParsedBody: + """A body declared ``application/json``: an empty one is ``{}``, one in matching brackets is + parsed, and a parse failure - like anything else - stays the raw text.""" + text = data.decode("utf-8", errors="replace") + trimmed = text.strip() + if not trimmed: + return ParsedBody("value", {}) + if (trimmed.startswith("{") and trimmed.endswith("}")) or \ + (trimmed.startswith("[") and trimmed.endswith("]")): + try: + return ParsedBody("value", json.loads(text)) + except ValueError: + return ParsedBody("value", text) + return ParsedBody("value", text) + + def parse_body(content_type: str | None, data: bytes) -> ParsedBody: """The engines' content-type dispatch: ``application/json`` - an empty body is ``{}``, a body in matching brackets is parsed and a parse failure falls back to the raw text, anything else @@ -591,25 +632,15 @@ def parse_body(content_type: str | None, data: bytes) -> ParsedBody: ``text/html`` and ``text/plain`` - text; ``application/x-www-form-urlencoded`` - form fields; anything else or no content type - raw bytes, an empty payload None.""" ct = base_content_type(content_type) or "?" - if ct.startswith("application/json"): - text = data.decode("utf-8", errors="replace") - trimmed = text.strip() - if not trimmed: - return ParsedBody("value", {}) - if (trimmed.startswith("{") and trimmed.endswith("}")) or \ - (trimmed.startswith("[") and trimmed.endswith("]")): - try: - return ParsedBody("value", json.loads(text)) - except ValueError: - return ParsedBody("value", text) - return ParsedBody("value", text) + if ct.startswith(_APPLICATION_JSON): + return _parse_json_body(data) if ct == "application/x-www-form-urlencoded": fields: dict[str, str] = {} for pair in (p for p in data.decode("utf-8", errors="replace").split("&") if p): name, _, value = pair.partition("=") fields[url_decode(name)] = url_decode(value) return ParsedBody("form", fields) - if ct.startswith(("application/xml", "text/html", "text/plain")): + if ct.startswith((_APPLICATION_XML, _TEXT_HTML, _TEXT_PLAIN)): return ParsedBody("value", data.decode("utf-8", errors="replace")) if not data: return ParsedBody("value", None) @@ -622,26 +653,26 @@ def accept_fallback_type(accept: str | None) -> str | None: content-type header at all, anything else ``text/plain``.""" if accept is None: return None - if "text/html" in accept: - return "text/html" - if "application/json" in accept or "*/*" in accept or "application/xml" in accept: - return "application/json" - return "text/plain" + if _TEXT_HTML in accept: + return _TEXT_HTML + if _APPLICATION_JSON in accept or "*/*" in accept or _APPLICATION_XML in accept: + return _APPLICATION_JSON + return _TEXT_PLAIN def negotiate_stream_type(accept: str | None) -> str: """The content type of a streamed response when the head sets none.""" if accept is None: - return "application/json" - if "*/*" in accept or "application/json" in accept: - return "application/json" + return _APPLICATION_JSON + if "*/*" in accept or _APPLICATION_JSON in accept: + return _APPLICATION_JSON if "text/event-stream" in accept: return "text/event-stream" - if "text/html" in accept: - return "text/html" - if "application/xml" in accept: - return "application/xml" - return "text/plain" + if _TEXT_HTML in accept: + return _TEXT_HTML + if _APPLICATION_XML in accept: + return _APPLICATION_XML + return _TEXT_PLAIN def strip_nulls(value: Any) -> Any: @@ -685,7 +716,7 @@ def render_payload(body: Any, content_type: str | None) -> bytes: if isinstance(body, (bytes, bytearray)): return bytes(body) text = pretty_json(body) - if content_type is not None and content_type.startswith("text/html") and isinstance(body, (Mapping, list)): + if content_type is not None and content_type.startswith(_TEXT_HTML) and isinstance(body, (Mapping, list)): return f"{HTML_START}{text}{HTML_END}".encode() return text.encode("utf-8") @@ -708,33 +739,37 @@ class MappedResponse(NamedTuple): body: bytes -def map_response(*, status: int, reply_headers: Mapping[str, str], body: Any, accept: str | None, - is_head: bool, transform: HeaderTransform | None, cors: CorsInfo | None, - cid: str, cid_header: str) -> MappedResponse: - """The engines' mapping of a function's reply to the HTTP response. A failure - an error - status with a text body and no headers of its own, the shape of a raised ``AppException`` - - renders as the standard error body unless the text already looks like JSON or XML. The - reserved ``my_*`` metadata and the streaming handles never reach the wire; a function-set - ``content-type`` wins over the ``Accept`` negotiation (not for HEAD); ``set-cookie`` values - separated by ``|`` become one header each; the entry's response transform filters the headers - (content type and cookies bypass it); the correlation id is echoed under its header name - unless the function set one; the CORS headers come last; a HEAD response carries no body.""" - standard_error = False +def _standard_error(status: int, body: Any, reply_headers: Mapping[str, str]) -> tuple[Any, bool]: + """A failure - an error status with a text body and no headers of its own - as the standard + error body, unless the text already looks like JSON or XML; the body to render, and whether it + was replaced.""" if status >= 400 and isinstance(body, str) and not reply_headers: message = body.strip() if not message.startswith(("{", "[", "<")): - body = error_body(status, message) - standard_error = True + return error_body(status, message), True + return body, False + + +def _withheld(key: str, value: str) -> bool: + """A reply header that never reaches the wire: the reserved ``my_*`` metadata, a streaming + handle and ``x-ttl``.""" + if key.startswith(_PROTECTED_PREFIX): + return True + if key == "x-stream-id" and value.startswith("stream.") and ".in" in value: + return True + return key == "x-ttl" + + +def _split_reply_headers(reply_headers: Mapping[str, str], + is_head: bool) -> tuple[dict[str, str], list[str], str | None]: + """A reply's headers by their role: the lines for the wire under lowercase names, the cookies + of ``set-cookie`` and the function-set content type (not for HEAD).""" content_type: str | None = None cookies: list[str] = [] headers: dict[str, str] = {} for name, value in reply_headers.items(): key = name.lower() - if key.startswith(_PROTECTED_PREFIX): - continue - if key == "x-stream-id" and value.startswith("stream.") and ".in" in value: - continue - if key == "x-ttl": + if _withheld(key, value): continue if key == "content-type": if not is_head: @@ -743,10 +778,26 @@ def map_response(*, status: int, reply_headers: Mapping[str, str], body: Any, ac cookies.extend(c.strip() for c in value.split("|")) else: headers[key] = value + return headers, cookies, content_type + + +def map_response(*, status: int, reply_headers: Mapping[str, str], body: Any, accept: str | None, + is_head: bool, transform: HeaderTransform | None, cors: CorsInfo | None, + cid: str, cid_header: str) -> MappedResponse: + """The engines' mapping of a function's reply to the HTTP response. A failure - an error + status with a text body and no headers of its own, the shape of a raised ``AppException`` - + renders as the standard error body unless the text already looks like JSON or XML. The + reserved ``my_*`` metadata and the streaming handles never reach the wire; a function-set + ``content-type`` wins over the ``Accept`` negotiation (not for HEAD); ``set-cookie`` values + separated by ``|`` become one header each; the entry's response transform filters the headers + (content type and cookies bypass it); the correlation id is echoed under its header name + unless the function set one; the CORS headers come last; a HEAD response carries no body.""" + body, standard_error = _standard_error(status, body, reply_headers) + headers, cookies, content_type = _split_reply_headers(reply_headers, is_head) if content_type is None and not is_head: content_type = accept_fallback_type(accept) if standard_error and content_type is None and not is_head: - content_type = "application/json" + content_type = _APPLICATION_JSON payload = b"" if is_head else render_payload(body, content_type) if transform is not None: headers = transform.apply(headers) diff --git a/src/mercury_composable/server.py b/src/mercury_composable/server.py index f833a4a..02b44ed 100644 --- a/src/mercury_composable/server.py +++ b/src/mercury_composable/server.py @@ -403,10 +403,11 @@ async def _stream_segments(self, response: web.StreamResponse, segment = _classify_segment(event) if segment.warn: log.warning("Dropping event - invalid %s signal", "x-event-stream") - if segment.frame: - await response.write(segment.frame) - if segment.status is not None: - return segment.status + data, status = segment.frame, segment.status + if data: + await response.write(data) + if status is not None: + return status @staticmethod async def _next_segment(response: web.StreamResponse, diff --git a/src/mercury_composable/static_content.py b/src/mercury_composable/static_content.py index 8fc49ae..b625d78 100644 --- a/src/mercury_composable/static_content.py +++ b/src/mercury_composable/static_content.py @@ -38,6 +38,7 @@ # the engines' minimalist table (platform-core's built-in types and its mime-types.yml) plus what a # web bundle ships; the text types carry their charset, as the host's own responses do +_IMAGE_JPEG = "image/jpeg" CONTENT_TYPES: dict[str, str] = { "html": "text/html; charset=utf-8", "htm": "text/html; charset=utf-8", @@ -52,9 +53,9 @@ "svg": "image/svg+xml", "svgz": "image/svg+xml", "png": "image/png", - "jpg": "image/jpeg", - "jpeg": "image/jpeg", - "jpe": "image/jpeg", + "jpg": _IMAGE_JPEG, + "jpeg": _IMAGE_JPEG, + "jpe": _IMAGE_JPEG, "gif": "image/gif", "webp": "image/webp", "ico": "image/vnd.microsoft.icon", @@ -92,9 +93,10 @@ def resolve_folder(config: AppConfig) -> str | None: elif value.startswith(FILE_PREFIX): value = value[len(FILE_PREFIX):] if not os.path.isabs(value): - if config.app_dir is None: + app_dir = config.app_dir + if app_dir is None: return None - value = os.path.join(config.app_dir, value) + value = os.path.join(app_dir, value) return os.path.normpath(value) @@ -130,7 +132,8 @@ def locate(self, path: str) -> str | None: except OSError: return None - def response(self, file: str) -> web.FileResponse: + @staticmethod + def response(file: str) -> web.FileResponse: """The file with its type and its caching: html ``no-cache``, everything with an ETag (aiohttp's FileResponse answers If-None-Match with 304 and serves HEAD without a body).""" kind = content_type(os.path.basename(file)) diff --git a/tests/test_agent_question.py b/tests/test_agent_question.py index f06434c..fdc7d0c 100644 --- a/tests/test_agent_question.py +++ b/tests/test_agent_question.py @@ -148,7 +148,8 @@ def _case(section: str, name: str) -> dict[str, Any]: def test_the_vector_file_is_the_shared_contract() -> None: - assert VECTORS["contract"] == "agent-question" and VECTORS["version"] == 3 + assert VECTORS["contract"] == "agent-question" + assert VECTORS["version"] == 3 for section in ("intake_cases", "click_cases", "feed_cases"): assert VECTORS[section], section @@ -158,7 +159,8 @@ def test_intake_cases(name: str) -> None: case = _case("intake_cases", name) if "accepted" in case: event = aq.validate_event(case["event"]) - assert {"accepted": True, "kind": event["kind"], "graph_id": event["graph_id"], "turn": event.get("turn")} == case["accepted"] + accepted = {"accepted": True, "kind": event["kind"], "graph_id": event["graph_id"], "turn": event.get("turn")} + assert accepted == case["accepted"] else: with pytest.raises(aq.AppException) as refused: aq.validate_event(case["event"]) @@ -264,7 +266,9 @@ def test_the_postgres_settings_follow_the_audit_store(configure: Callable[[dict[ "host": "db.internal", "port": 6543, "dbname": "agents", "user": "reader", "password": "s3", "sslmode": "disable", "connect_timeout": 2, "options": "-c statement_timeout=2500", } # fmt: skip - assert settings.postgres_timeout_s == 2.5 and settings.poll_ms == 250 and settings.reply_timeout_ms == 10_000 + assert settings.postgres_timeout_s == 2.5 + assert settings.poll_ms == 250 + assert settings.reply_timeout_ms == 10_000 assert settings.oauth2_scopes == "openid profile email" @@ -282,9 +286,11 @@ async def test_the_intake_accepts_the_event_and_wakes_the_feed(configure: Callab assert reply.get_status() == 200, reply.body assert reply.body == {"accepted": True, "kind": "approval", "graph_id": "order-assistant", "turn": 2} woken = await asyncio.wait_for(queue.get(), 2) - assert woken.id == 1 and aq._feed.cursor == 1, "the intake's wake-up made the feed look at once" + assert woken.id == 1, "the intake's wake-up made the feed look at once" + assert aq._feed.cursor == 1, "the intake's wake-up made the feed look at once" bad = await office.request(aq.INTAKE_ROUTE, {"kind": "notice"}, timeout_ms=5000) - assert bad.get_status() == 400 and "kind must be one of" in str(bad.body) + assert bad.get_status() == 400 + assert "kind must be one of" in str(bad.body) advice = await office.request(aq.INTAKE_ROUTE, advice_event(), timeout_ms=5000) assert advice.body == {"accepted": True, "kind": "advice", "graph_id": "order-assistant", "turn": 2} assert queue.empty(), "nothing new in the record: the feed has nothing to tell" @@ -401,18 +407,30 @@ async def test_the_replay_and_the_history_page_the_record(configure: Callable[[d seven_rows() status, page = await get_json(f"{host}/questions?since=0") assert status == 200 - assert [r["id"] for r in page["rows"]] == [7, 2, 1, 4, 3, 6, 5] and page["next"] == 7 and page["more"] is False - assert page["rows"][2]["calls"] == CALLS and page["rows"][2]["ticket"] == "t-1" and page["rows"][1]["state"] is None + assert [r["id"] for r in page["rows"]] == [7, 2, 1, 4, 3, 6, 5] + assert page["next"] == 7 + assert page["more"] is False + assert page["rows"][2]["calls"] == CALLS + assert page["rows"][2]["ticket"] == "t-1" + assert page["rows"][1]["state"] is None status, tail = await get_json(f"{host}/questions?since=5&limit=1") - assert [r["id"] for r in tail["rows"]] == [6] and tail["next"] == 6 and tail["more"] is True + assert [r["id"] for r in tail["rows"]] == [6] + assert tail["next"] == 6 + assert tail["more"] is True status, newest = await get_json(f"{host}/questions?before=&limit=3") assert status == 200 - assert [r["id"] for r in newest["rows"]] == [5, 6, 3] and newest["next"] == 5 and newest["more"] is True + assert [r["id"] for r in newest["rows"]] == [5, 6, 3] + assert newest["next"] == 5 + assert newest["more"] is True assert newest["before"] is None status, older = await get_json(f"{host}/questions?before=5&limit=3") - assert [r["id"] for r in older["rows"]] == [4, 1, 2] and older["next"] == 2 and older["more"] is True + assert [r["id"] for r in older["rows"]] == [4, 1, 2] + assert older["next"] == 2 + assert older["more"] is True status, oldest = await get_json(f"{host}/questions?before=2&limit=3") - assert [r["id"] for r in oldest["rows"]] == [7] and oldest["next"] == 1 and oldest["more"] is False + assert [r["id"] for r in oldest["rows"]] == [7] + assert oldest["next"] == 1 + assert oldest["more"] is False assert (await get_json(f"{host}/questions?since=x"))[0] == 400 assert (await get_json(f"{host}/questions?before=x"))[0] == 400 @@ -424,7 +442,8 @@ async def test_the_stream_replays_then_follows_the_feed_with_keep_alives( put(wait_event(), 1, 1) async with aiohttp.ClientSession() as http, http.get(f"{host}/questions/events", headers={"accept": "text/event-stream"}) as response: - assert response.status == 200 and response.content_type == "text/event-stream" + assert response.status == 200 + assert response.content_type == "text/event-stream" reader = response.content async def frame() -> list[str]: @@ -437,11 +456,13 @@ async def frame() -> list[str]: continue lines.append(line) - assert response.headers["cache-control"] == "no-cache" and response.headers["x-accel-buffering"] == "no" + assert response.headers["cache-control"] == "no-cache" + assert response.headers["x-accel-buffering"] == "no" replayed = await frame() assert replayed[0] == "event: question", "the engines' SSE dialect: an event name and the data, no id line" first_row = json.loads(replayed[1][len("data: "):]) - assert first_row["ticket"] == "t-answer" and first_row["seq"] == 1, "the row's seq is the cursor" + assert first_row["ticket"] == "t-answer", "the row's seq is the cursor" + assert first_row["seq"] == 1, "the row's seq is the cursor" ping = await frame() assert ping == [": ping"], "a keep-alive while nothing changes" put(advice_event(), 2, 2) @@ -449,17 +470,20 @@ async def frame() -> list[str]: live = await frame() assert live[0] == "event: question" advice = json.loads(live[1][len("data: "):]) - assert advice["kind"] == "advice" and advice["seq"] == 2 - assert "state" in advice and advice["state"] is None, "a null stays on the wire - the UI reads it" + assert advice["kind"] == "advice" + assert advice["seq"] == 2 + assert "state" in advice, "a null stays on the wire - the UI reads it" + assert advice["state"] is None, "a null stays on the wire - the UI reads it" async with aiohttp.ClientSession() as http, http.get(f"{host}/questions/events", headers={"last-event-id": "1"}) as response: first = (await asyncio.wait_for(response.content.readline(), 5)).decode() second = (await asyncio.wait_for(response.content.readline(), 5)).decode() - assert first == "event: question\n" and json.loads(second[len("data: "):])["seq"] == 2, \ - "the reconnect resumes after the cursor the browser kept" + assert first == "event: question\n", "the reconnect resumes after the cursor the browser kept" + assert json.loads(second[len("data: "):])["seq"] == 2, "the reconnect resumes after the cursor the browser kept" async with aiohttp.ClientSession() as http, http.get(f"{host}/questions/events", headers={"last-event-id": "x"}) as response: - assert response.status == 400 and "whole number" in (await response.json())["message"] + assert response.status == 400 + assert "whole number" in (await response.json())["message"] async def test_the_ui_configuration_names_the_sign_in(configure: Callable[[dict[str, Any]], Any], host: str) -> None: @@ -493,41 +517,50 @@ async def recorder(body: dict[str, Any]) -> None: json={"decisions": decisions, "decided_by": "operator-17"}) as response: result = await response.json() assert response.status == 200, result - assert result["row"]["state"] == "answered" and result["row"]["answered_by"] == "operator-17" - assert result["outcome"]["status"] == 200 and result["outcome"]["body"]["type"] == "answer" + assert result["row"]["state"] == "answered" + assert result["row"]["answered_by"] == "operator-17" + assert result["outcome"]["status"] == 200 + assert result["outcome"]["body"]["type"] == "answer" assert fake.posts[0]["body"] == {"ticket": "t-answer", "decisions": decisions, "decided_by": "operator-17"} assert fake.posts[0]["authorization"] == "Bearer channel-app-bearer" # the feed was told to look: the change reaches every device assert [r.id for r in await aq._feed.poll_once()] == [1] woken = queue.get_nowait() - assert woken.id == row.id and woken.state == "answered" + assert woken.id == row.id + assert woken.state == "answered" async with http.post(f"{host}/questions/{row.id}/decide", json={"decisions": decisions}) as response: - assert response.status == 409 and "operator-17" in (await response.json())["message"] + assert response.status == 409 + assert "operator-17" in (await response.json())["message"] # a recorder that did not write (or a wait decided elsewhere): the row is reported as it stands fake.on_post = None expired = put(wait_event(ticket="t-expired", base=base, correlation_id="case-2"), 2, 3) async with http.post(f"{host}/questions/{expired.id}/decide", json={"decisions": decisions}) as response: body = await response.json() - assert body["row"]["state"] == "open" and body["outcome"]["status"] == 410 + assert body["row"]["state"] == "open" + assert body["outcome"]["status"] == 410 refused = put(wait_event(ticket="t-refused", base=base, correlation_id="case-3"), 3, 4) async with http.post(f"{host}/questions/{refused.id}/decide", json={"decisions": decisions}) as response: body = await response.json() - assert body["row"]["state"] == "open" and body["outcome"]["body"]["error"].startswith("not a call") + assert body["row"]["state"] == "open" + assert body["outcome"]["body"]["error"].startswith("not a call") silent = put(wait_event(ticket="t-silent", base="http://127.0.0.1:9", correlation_id="case-4"), 4, 5) configure({aq.REPLY_TIMEOUT: "2s"}) async with http.post(f"{host}/questions/{silent.id}/decide", json={"decisions": decisions}) as response: body = await response.json() - assert body["row"]["state"] == "open" and body["outcome"]["status"] == 502 + assert body["row"]["state"] == "open" + assert body["outcome"]["status"] == 502 # the refusals of the endpoint itself async with http.post(f"{host}/questions/{row.id}/decide", data=b"nope") as response: assert response.status == 400 async with http.post(f"{host}/questions/{row.id}/decide", json={"decisions": []}) as response: - assert response.status == 400 and "non-empty list" in (await response.json())["message"] + assert response.status == 400 + assert "non-empty list" in (await response.json())["message"] async with http.post(f"{host}/questions/999/decide", json={"decisions": decisions}) as response: assert response.status == 404 advice = put(advice_event(), 5, 6) async with http.post(f"{host}/questions/{advice.id}/decide", json={"decisions": decisions}) as response: - assert response.status == 409 and "advice" in (await response.json())["message"] + assert response.status == 409 + assert "advice" in (await response.json())["message"] async with http.post(f"{host}/questions/{advice.id}/seen") as response: assert response.status == 404, "the seen endpoint is gone with the state" aq._wakeups.unsubscribe(queue) @@ -545,18 +578,23 @@ async def test_the_transcripts_are_browsed_from_the_audit_store( status, page = await get_json(f"{host}/transcripts") assert status == 200 assert [c["conversation"] for c in page["conversations"]] == [CONVERSATION_C, CONVERSATION_B, CONVERSATION_A] - assert page["next"] == "2026-11-19T09:00:00.000Z" and page["more"] is False - assert "system" not in page["conversations"][0] and "tools" not in page["conversations"][0], "the list is light" + assert page["next"] == "2026-11-19T09:00:00.000Z" + assert page["more"] is False + assert "system" not in page["conversations"][0], "the list is light" + assert "tools" not in page["conversations"][0], "the list is light" status, older = await get_json(f"{host}/transcripts?before=2026-11-19T11:00:00Z&limit=1") assert [c["conversation"] for c in older["conversations"]] == [CONVERSATION_B] - assert older["next"] == "2026-11-19T10:00:00.000Z" and older["more"] is True + assert older["next"] == "2026-11-19T10:00:00.000Z" + assert older["more"] is True status, by_case = await get_json(f"{host}/transcripts?correlation_id=order-1002-case") assert [c["conversation"] for c in by_case["conversations"]] == [CONVERSATION_C, CONVERSATION_A] status, by_graph = await get_json(f"{host}/transcripts?graph_id=plan-assistant") assert [c["conversation"] for c in by_graph["conversations"]] == [CONVERSATION_B] status, one = await get_json(f"{host}/transcripts/{CONVERSATION_A}") - assert status == 200 and one["conversation"]["system"] == "You are a careful assistant." - assert [t["turn"] for t in one["turns"]] == [1, 2] and one["turns"][0]["calls"][0]["name"] == "issue_refund" + assert status == 200 + assert one["conversation"]["system"] == "You are a careful assistant." + assert [t["turn"] for t in one["turns"]] == [1, 2] + assert one["turns"][0]["calls"][0]["name"] == "issue_refund" assert (await get_json(f"{host}/transcripts/{'f' * 32}"))[0] == 404 assert (await get_json(f"{host}/transcripts/not-a-conversation"))[0] == 400 assert (await get_json(f"{host}/transcripts?before=yesterday"))[0] == 400 @@ -564,7 +602,8 @@ async def test_the_transcripts_are_browsed_from_the_audit_store( async def test_the_oauth2_mode_guards_every_read_and_the_click( - configure: Callable[[dict[str, Any]], Any], reply_endpoint: tuple[FakeReply, str], host: str + configure: Callable[[dict[str, Any]], Any], reply_endpoint: tuple[FakeReply, str], host: str, + monkeypatch: pytest.MonkeyPatch, ) -> None: fake, base = reply_endpoint private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) @@ -574,7 +613,7 @@ async def test_the_oauth2_mode_guards_every_read_and_the_click( serialization.NoEncryption()) configure({**BASE, aq.AUTH: "oauth2", aq.OAUTH2_ISSUER: ISSUER, aq.OAUTH2_AUDIENCE: AUDIENCE, aq.OAUTH2_JWKS_URL: f"{base}/jwks", aq.OAUTH2_CLIENT_ID: "agent-question-ui"}) - aq._verifier = None + monkeypatch.setattr(aq, "_verifier", None) now = int(datetime.now(UTC).timestamp()) token = jwt.encode({"iss": ISSUER, "aud": AUDIENCE, "sub": "u-17", "preferred_username": "operator-17", "iat": now, "exp": now + 300}, pem, algorithm="RS256", headers={"kid": "k1"}) @@ -585,12 +624,14 @@ async def test_the_oauth2_mode_guards_every_read_and_the_click( async with http.get(f"{host}{path}") as response: assert response.status == 401, path async with http.get(f"{host}/questions/config") as response: - assert response.status == 200 and (await response.json())["oauth2"]["client_id"] == "agent-question-ui" + assert response.status == 200 + assert (await response.json())["oauth2"]["client_id"] == "agent-question-ui" async with http.post(f"{host}/questions/{row.id}/decide", json={"decisions": decisions}) as response: assert response.status == 401 bearer = {"authorization": f"Bearer {token}"} async with http.get(f"{host}/questions?since=0", headers=bearer) as response: - assert response.status == 200 and [r["id"] for r in (await response.json())["rows"]] == [1] + assert response.status == 200 + assert [r["id"] for r in (await response.json())["rows"]] == [1] async with http.get(f"{host}/transcripts", headers=bearer) as response: assert response.status == 200 async with http.post(f"{host}/questions/{row.id}/decide", json={"decisions": decisions, "decided_by": "spoof"}, @@ -673,9 +714,13 @@ async def test_the_postgres_reader_runs_the_statements_and_maps_the_records() -> await reader.open() assert pool.opened == (True, 2.5) row = await reader.get(7) - assert pool.log[-1] == (aq.SQL_GET, (7,)) and row is not None - assert row.id == 7 and row.seq == 12 and row.requested_at == "2026-11-19T09:12:05.123Z" - assert row.expires_at == "2026-11-21T09:12:05.123Z" and row.public()["calls"] == CALLS + assert pool.log[-1] == (aq.SQL_GET, (7,)) + assert row is not None + assert row.id == 7 + assert row.seq == 12 + assert row.requested_at == "2026-11-19T09:12:05.123Z" + assert row.expires_at == "2026-11-21T09:12:05.123Z" + assert row.public()["calls"] == CALLS await reader.since(3, 50) assert pool.log[-1] == (aq.SQL_SINCE, (3, 50)) await reader.before(None, 20) @@ -683,7 +728,8 @@ async def test_the_postgres_reader_runs_the_statements_and_maps_the_records() -> await reader.before(9, 20) assert pool.log[-1] == (aq.SQL_BEFORE, (9, 9, 20)) pool.queue = [[(42,)]] - assert await reader.latest() == 42 and pool.log[-1] == (aq.SQL_LATEST, ()) + assert await reader.latest() == 42 + assert pool.log[-1] == (aq.SQL_LATEST, ()) pool.queue = [[]] assert await reader.latest() == 0 pool.queue = [[("open", 3), ("advice", 1)]] @@ -692,13 +738,19 @@ async def test_the_postgres_reader_runs_the_statements_and_maps_the_records() -> shown = await reader.conversations("2026-11-19T12:00:00.000Z", 20, "order-1002-case", None) assert pool.log[-1] == (aq.SQL_CONVERSATIONS, ("2026-11-19T12:00:00.000Z", "2026-11-19T12:00:00.000Z", "order-1002-case", "order-1002-case", None, None, 20)) - assert shown[0]["conversation"] == CONVERSATION_A and shown[0]["started_at"] == "2026-11-19T09:00:00.000Z" - assert shown[0]["turns"] == 2 and shown[0]["input_tokens"] == 120 and "system" not in shown[0] + assert shown[0]["conversation"] == CONVERSATION_A + assert shown[0]["started_at"] == "2026-11-19T09:00:00.000Z" + assert shown[0]["turns"] == 2 + assert shown[0]["input_tokens"] == 120 + assert "system" not in shown[0] pool.queue = [[_conversation_record(light=False)], [_turn_record()]] one = await reader.conversation(CONVERSATION_A) - assert [entry[0] for entry in pool.log[-2:]] == [aq.SQL_CONVERSATION, aq.SQL_TURNS] and one is not None - assert one["conversation"]["system"] == "You are a careful assistant." and one["conversation"]["tools"] == [{"name": "issue_refund"}] - assert one["turns"][0]["turn"] == 1 and one["turns"][0]["status"] == "tool_use" + assert [entry[0] for entry in pool.log[-2:]] == [aq.SQL_CONVERSATION, aq.SQL_TURNS] + assert one is not None + assert one["conversation"]["system"] == "You are a careful assistant." + assert one["conversation"]["tools"] == [{"name": "issue_refund"}] + assert one["turns"][0]["turn"] == 1 + assert one["turns"][0]["status"] == "tool_use" assert one["turns"][0]["calls"] == [{"id": "toolu_01A", "name": "issue_refund", "input": {}}], "json text is parsed" assert one["turns"][0]["ended_at"] == "2026-11-19T09:00:01.000Z" pool.queue = [[]] @@ -711,8 +763,12 @@ def test_a_record_s_json_may_arrive_as_text_and_an_advice_has_no_state() -> None record = _record(message='{"kind":"advice"}', decisions="[]", outcome='{"status":410}', kind="advice", ticket=None, link=None, turn=None, expires_at=None, state=None) row = aq.row_from_record(record) - assert row.message == {"kind": "advice"} and row.decisions == [] and row.outcome == {"status": 410} - assert row.turn is None and row.expires_at is None and row.state is None + assert row.message == {"kind": "advice"} + assert row.decisions == [] + assert row.outcome == {"status": 410} + assert row.turn is None + assert row.expires_at is None + assert row.state is None assert aq.failure(RuntimeError("quotes a row")) == "RuntimeError" @@ -749,26 +805,34 @@ async def test_the_host_serves_the_committed_ui_bundle_at_the_root(configure: Ca async with aiohttp.ClientSession() as http: async with http.get(f"{host}/") as response: index = await response.text() - assert response.status == 200 and response.content_type == "text/html" - assert '
' in index and 'href="/favicon.svg"' in index + assert response.status == 200 + assert response.content_type == "text/html" + assert '
' in index + assert 'href="/favicon.svg"' in index scripts = re.findall(r'src="(/assets/[^"]+\.js)"', index) styles = re.findall(r'href="(/assets/[^"]+\.css)"', index) - assert len(scripts) == 1 and len(styles) == 1, "one script and one stylesheet, hashed" + assert len(scripts) == 1, "one script and one stylesheet, hashed" + assert len(styles) == 1, "one script and one stylesheet, hashed" async with http.get(f"{host}{scripts[0]}") as response: - assert response.status == 200 and response.content_type == "text/javascript" + assert response.status == 200 + assert response.content_type == "text/javascript" async with http.get(f"{host}{styles[0]}") as response: - assert response.status == 200 and response.content_type == "text/css" + assert response.status == 200 + assert response.content_type == "text/css" async with http.get(f"{host}/favicon.svg") as response: - assert response.status == 200 and response.content_type == "image/svg+xml" + assert response.status == 200 + assert response.content_type == "image/svg+xml" async with http.get(f"{host}/questions/app") as response: assert response.status == 404, "the generated page is retired" # the engines' actuator endpoints stay at their paths beside the bundle - Kubernetes probes and operations for path in ("/info", "/info/routes", "/health", "/env"): async with http.get(f"{host}{path}") as response: - assert response.status == 200 and response.content_type == "application/json", path + assert response.status == 200, path + assert response.content_type == "application/json", path await response.json() async with http.get(f"{host}/livenessprobe") as response: - assert response.status == 200 and await response.text() == "OK" + assert response.status == 200 + assert await response.text() == "OK" finally: await runner.cleanup() await aq.shutdown() @@ -799,24 +863,34 @@ async def test_the_platform_hooks_mount_the_routes_and_run_the_boot( } # fmt: skip for (method, path), service in expected.items(): assigned = rest.table.find(method, path) - assert assigned is not None and assigned.info.service == service, path + assert assigned is not None, path + assert assigned.info.service == service, path assert (assigned.info.authentication == "question.identity") is (service != "question.config"), path registered = default_registry.get(service) - assert registered is not None and registered.private, service + assert registered is not None, service + assert registered.private, service events = rest.table.find("GET", "/questions/events") - assert events is not None and events.info.stream and events.info.headers is not None + assert events is not None + assert events.info.stream + assert events.info.headers is not None decide = rest.table.find("POST", "/questions/7/decide") - assert decide is not None and decide.path_params == {"id": "7"} + assert decide is not None + assert decide.path_params == {"id": "7"} assert rest.table.find("POST", "/questions/7/seen") is None, "the seen endpoint is gone with the state" runner = web.AppRunner(app) with caplog.at_level("WARNING"): await runner.setup() try: assert "The store is in memory" in caplog.text - assert aq.reader().name == "memory" and aq._feed.running and aq._feed.cursor == 0 + assert aq.reader().name == "memory" + assert aq._feed.running + assert aq._feed.cursor == 0 info = await aq.question_health({"type": "info"}, None) - assert info["service"] == "agent.question.inbox" and info["store"] == "memory" and info["auth"] == "none" - assert info["feed"] == 0 and info["rows"] == {} + assert info["service"] == "agent.question.inbox" + assert info["store"] == "memory" + assert info["auth"] == "none" + assert info["feed"] == 0 + assert info["rows"] == {} assert await aq.question_health({}, None) == "agent.question.inbox is running fine" finally: await runner.cleanup() @@ -868,13 +942,18 @@ async def test_the_reader_finds_the_rows_on_a_live_postgres() -> None: ) row_id, seq = int(inserted[0]), int(inserted[1]) found = await reader.get(row_id) - assert found is not None and found.ticket == f"{cid}-1" and found.state == "open" + assert found is not None + assert found.ticket == f"{cid}-1" + assert found.state == "open" assert any(r.id == row_id for r in await reader.since(seq - 1, 10)) - assert (await reader.before(None, 5))[0].seq >= seq and await reader.latest() >= seq + assert (await reader.before(None, 5))[0].seq >= seq + assert await reader.latest() >= seq assert (await reader.counts()).get("open", 0) >= 1 conversations = await reader.conversations(None, 10, cid, None) assert [c["conversation"] for c in conversations] == [conv] one = await reader.conversation(conv) - assert one is not None and one["conversation"]["system"] == "sys" and one["turns"][0]["turn"] == 1 + assert one is not None + assert one["conversation"]["system"] == "sys" + assert one["turns"][0]["turn"] == 1 finally: await reader.close() diff --git a/tests/test_agent_tools.py b/tests/test_agent_tools.py index 22b65f3..55d2a64 100644 --- a/tests/test_agent_tools.py +++ b/tests/test_agent_tools.py @@ -212,7 +212,8 @@ def test_hidden_entries_are_available_when_the_workspace_exposes_them( files = tools.FileTools(tools.load_file_sandbox()) assert files.read({}, {"path": ".env"})["text"] == "KEY=value\n" listed = [entry["path"] for entry in files.list({}, {})["entries"]] - assert ".env" in listed and ".secrets" in listed + assert ".env" in listed + assert ".secrets" in listed @pytest.mark.parametrize( @@ -242,7 +243,8 @@ def test_write_create_overwrite_and_append(files: Any, workspace: Path) -> None: status, message = _status( lambda: files.write({}, {"path": "out/reports/summary.md", "content": "again"}) ) - assert status == 409 and "exists" in message + assert status == 409 + assert "exists" in message assert ( files.write({}, {"path": "out/reports/summary.md", "content": "new", "mode": "overwrite"})[ "mode" @@ -298,9 +300,11 @@ def test_write_respects_the_extension_list_and_the_size_limit( assert files.write({}, {"path": "out/a.txt", "content": "ok"})["bytes"] == 2 assert files.write({}, {"path": "out/A.MD", "content": "ok"})["bytes"] == 2 status, message = _status(lambda: files.write({}, {"path": "out/a.py", "content": "x"})) - assert status == 400 and "does not end in .md, .txt" in message + assert status == 400 + assert "does not end in .md, .txt" in message status, message = _status(lambda: files.write({}, {"path": "out/b.txt", "content": "x" * 1025})) - assert status == 400 and "over the workspace's limit of 1024" in message + assert status == 400 + assert "over the workspace's limit of 1024" in message def test_list_the_root_and_a_folder(files: Any) -> None: @@ -331,7 +335,8 @@ def test_list_with_a_glob_and_a_cap(files: Any) -> None: "src/util.py", ] cut = files.list({}, {"glob": "**/*", "max_entries": 2}) - assert len(cut["entries"]) == 2 and cut["truncated"] is True + assert len(cut["entries"]) == 2 + assert cut["truncated"] is True assert _status(lambda: files.list({}, {"glob": "/abs/*"}))[0] == 400 assert _status(lambda: files.list({}, {"path": "notes/plan.md"})) == ( 400, @@ -381,11 +386,13 @@ def test_search_caps_and_refusals( configure({tools.FILE_ROOT: str(workspace), tools.FILE_LINE_MAX_CHARS: 20}) files = tools.FileTools(tools.load_file_sandbox()) cut = files.search({}, {"pattern": "todo", "max_results": 2}) - assert len(cut["matches"]) == 2 and cut["truncated"] is True + assert len(cut["matches"]) == 2 + assert cut["truncated"] is True long_line = files.search({}, {"pattern": "xxxx"})["matches"][0] assert len(long_line["text"]) == 20, "a line is cut to tools.file.line.max.chars" status, message = _status(lambda: files.search({}, {"pattern": "(", "regex": True})) - assert status == 400 and "not a valid regular expression" in message + assert status == 400 + assert "not a valid regular expression" in message assert _status(lambda: files.search({}, {"pattern": ""})) == (400, "pattern must not be empty") assert files.search({}, {"pattern": "a", "context": 9})["matches"], ( "over the cap is capped, not refused" @@ -415,7 +422,8 @@ def test_html_to_text_drops_chrome_and_keeps_the_readable_text() -> None: assert blocks[2:5] == ["- one", "- two", " - nested"] assert blocks[5] == "line 1\n line 2" assert blocks[6] == "Line break" - assert "H1 H2" in blocks[7] and "c1 c2" in blocks[8] + assert "H1 H2" in blocks[7] + assert "c1 c2" in blocks[8] for dropped in ("Menu", "Site", "Footer text", "color: red", "not text"): assert dropped not in text assert links == ["https://site.example/docs/a", "https://other.example/x"], ( @@ -575,18 +583,21 @@ async def test_pin_refuses_private_addresses_unless_allowed() -> None: rules=tools.parse_host_rules(("http://127.0.0.1", "http://169.254.169.254", "localhost")) ) status, message = await _astatus(closed.pin("127.0.0.1", 80)) - assert status == 400 and "loopback address" in message and tools.WEB_ALLOW_PRIVATE in message + assert status == 400 + assert "loopback address" in message + assert tools.WEB_ALLOW_PRIVATE in message status, message = await _astatus(closed.pin("169.254.169.254", 80)) - assert status == 400 and "link-local address" in message, ( - "the cloud metadata service is refused by range" - ) + assert status == 400, "the cloud metadata service is refused by range" + assert "link-local address" in message, "the cloud metadata service is refused by range" status, message = await _astatus(closed.pin("localhost", 80)) - assert status == 400 and "localhost resolves to a loopback address" in message + assert status == 400 + assert "localhost resolves to a loopback address" in message open_ = tools.WebSandbox(rules=closed.rules, allow_private=True) assert await open_.pin("127.0.0.1", 80) == "127.0.0.1" assert await open_.pin("localhost", 80) in ("127.0.0.1", "::1") status, message = await _astatus(open_.pin("no-such-host.invalid", 443)) - assert status == 502 and "cannot be resolved" in message + assert status == 502 + assert "cannot be resolved" in message # --- the fixture site ---------------------------------------------------------------------------- @@ -721,13 +732,15 @@ async def test_fetch_a_page_as_text_markdown_and_raw(site: str, web_tools: Any) ) assert reply["text"].startswith("Welcome\n\nStart Section A and Section B") assert "Menu" not in reply["text"] - assert reply["bytes"] > 100 and reply["truncated"] is False + assert reply["bytes"] > 100 + assert reply["truncated"] is False markdown = await web_tools.web_fetch({}, {"url": f"{site}/", "as": "markdown"}) assert markdown["text"].startswith( f"# Welcome\n\nStart [Section A]({site}/docs/a) and [Section B]({site}/docs/b)" ) raw = await web_tools.web_fetch({}, {"url": f"{site}/", "as": "raw"}) - assert raw["text"].startswith("") and raw["title"] == "" + assert raw["text"].startswith("") + assert raw["title"] == "" @pytest.mark.asyncio @@ -741,7 +754,8 @@ async def test_fetch_text_resources_and_refuse_binaries(site: str, web_tools: An data = await web_tools.web_fetch({}, {"url": f"{site}/data.json", "as": "markdown"}) assert json.loads(data["text"]) == {"a": 1} status, message = await _astatus(web_tools.web_fetch({}, {"url": f"{site}/image.png"})) - assert status == 400 and message == "the response is image/png, not text" + assert status == 400 + assert message == "the response is image/png, not text" missing = await web_tools.web_fetch({}, {"url": f"{site}/missing"}) assert (missing["status"], missing["title"]) == (404, "Not found"), ( "a page's own status is a result, not an error" @@ -759,7 +773,8 @@ async def test_fetch_cuts_the_body_and_the_text( small = tools.WebTools(tools.load_web_sandbox()) try: cut = await small.web_fetch({}, {"url": f"{site}/", "as": "markdown"}) - assert len(cut["text"]) == 100 and cut["truncated"] is True + assert len(cut["text"]) == 100 + assert cut["truncated"] is True finally: await small.close() @@ -785,23 +800,30 @@ async def test_fetch_follows_allowed_redirects_and_refuses_the_others( "Section A", ) status, message = await _astatus(web_tools.web_fetch({}, {"url": f"{site}/redirect-private"})) - assert status == 400 and "10.0.0.1 is not one of the sites" in message + assert status == 400 + assert "10.0.0.1 is not one of the sites" in message status, message = await _astatus(web_tools.web_fetch({}, {"url": f"{site}/redirect-other"})) - assert status == 400 and "not-allowed.example is not one of the sites" in message + assert status == 400 + assert "not-allowed.example is not one of the sites" in message status, message = await _astatus(web_tools.web_fetch({}, {"url": f"{site}/loop"})) - assert status == 400 and "too many redirects" in message + assert status == 400 + assert "too many redirects" in message @pytest.mark.asyncio async def test_fetch_times_out_and_refuses_outside_the_allowlist(site: str, web_tools: Any) -> None: status, message = await _astatus(web_tools.web_fetch({}, {"url": f"{site}/slow"})) - assert status == 408 and "did not answer within 500 ms" in message + assert status == 408 + assert "did not answer within 500 ms" in message status, message = await _astatus(web_tools.web_fetch({}, {"url": "https://docs.example.com/"})) - assert status == 400 and "not one of the sites" in message + assert status == 400 + assert "not one of the sites" in message status, message = await _astatus(web_tools.web_fetch({}, {"url": f"{site}/", "as": "pdf"})) - assert status == 400 and "as must be one of text, markdown, raw" in message + assert status == 400 + assert "as must be one of text, markdown, raw" in message status, message = await _astatus(web_tools.web_fetch({}, {"url": f"{site}/", "mode": "text"})) - assert status == 400 and "web_fetch does not take mode" in message + assert status == 400 + assert "web_fetch does not take mode" in message @pytest.mark.asyncio @@ -812,14 +834,16 @@ async def test_the_private_range_gate_closes_the_fixture_without_the_flag( closed = tools.WebTools(tools.load_web_sandbox()) try: status, message = await _astatus(closed.web_fetch({}, {"url": f"{site}/"})) - assert status == 400 and "127.0.0.1 resolves to a loopback address" in message + assert status == 400 + assert "127.0.0.1 resolves to a loopback address" in message finally: await closed.close() configure({tools.WEB_ALLOW: "127.0.0.1", tools.WEB_ALLOW_PRIVATE: True}) https_only = tools.WebTools(tools.load_web_sandbox()) try: status, message = await _astatus(https_only.web_fetch({}, {"url": f"{site}/"})) - assert status == 400 and "allowed over https only" in message + assert status == 400 + assert "allowed over https only" in message finally: await https_only.close() @@ -831,7 +855,8 @@ async def test_logs_carry_the_host_and_the_size_never_the_url( with caplog.at_level(logging.INFO): await web_tools.web_fetch({}, {"url": f"{site}/docs/a?token=do-not-log-me"}) assert "web.fetch 127.0.0.1 200" in caplog.text - assert "do-not-log-me" not in caplog.text and "/docs/a" not in caplog.text + assert "do-not-log-me" not in caplog.text + assert "/docs/a" not in caplog.text @pytest.mark.asyncio @@ -859,7 +884,8 @@ async def test_crawl_follows_links_breadth_first_inside_the_include( assert [p["url"] for p in shallow["pages"]] == [f"{site}/", f"{site}/docs/a", f"{site}/docs/b"] assert shallow["truncated"] is False alone = await web_tools.web_crawl({}, {"url": f"{site}/docs/c", "max_depth": 0}) - assert len(alone["pages"]) == 1 and alone["truncated"] is False + assert len(alone["pages"]) == 1 + assert alone["truncated"] is False @pytest.mark.asyncio @@ -869,15 +895,16 @@ async def test_crawl_honours_robots_the_host_and_the_caps( reply = await web_tools.web_crawl({}, {"url": f"{site}/"}) urls = [p["url"] for p in reply["pages"]] assert f"{site}/private/secret" not in urls, "robots.txt is honoured" - assert f"{site}/other" in urls and not any("elsewhere.example" in u for u in urls), ( - "same host only" - ) + assert f"{site}/other" in urls, "same host only" + assert not any("elsewhere.example" in u for u in urls), "same host only" assert reply["visited"] == 5 capped = await web_tools.web_crawl({}, {"url": f"{site}/", "max_pages": 2}) - assert len(capped["pages"]) == 2 and capped["truncated"] is True + assert len(capped["pages"]) == 2 + assert capped["truncated"] is True monkeypatch.setattr(tools, "CRAWL_RESULT_MAX_CHARS", 30) budget = await web_tools.web_crawl({}, {"url": f"{site}/"}) - assert budget["truncated"] is True and sum(len(p["text"]) for p in budget["pages"]) <= 30 + assert budget["truncated"] is True + assert sum(len(p["text"]) for p in budget["pages"]) <= 30 @pytest.mark.asyncio @@ -888,7 +915,8 @@ async def test_crawl_caps_max_pages_by_the_configured_cap( client = tools.WebTools(tools.load_web_sandbox()) try: reply = await client.web_crawl({}, {"url": f"{site}/", "max_pages": 50}) - assert len(reply["pages"]) == 3 and reply["truncated"] is True + assert len(reply["pages"]) == 3 + assert reply["truncated"] is True finally: await client.close() @@ -900,17 +928,23 @@ async def test_crawl_caps_max_pages_by_the_configured_cap( async def test_time_now_in_utc_and_a_zone() -> None: reply = await tools.time_now({}, None) assert set(reply) == {"utc", "local", "timezone", "offset", "weekday", "epoch_ms"} - assert reply["utc"].endswith("Z") and reply["timezone"] == "UTC" and reply["offset"] == "+00:00" + assert reply["utc"].endswith("Z") + assert reply["timezone"] == "UTC" + assert reply["offset"] == "+00:00" moment = datetime.fromtimestamp(reply["epoch_ms"] / 1000, tz=UTC) assert reply["weekday"] == moment.strftime("%A") - assert reply["local"].startswith(reply["utc"][:19]) and reply["local"].endswith("+00:00") + assert reply["local"].startswith(reply["utc"][:19]) + assert reply["local"].endswith("+00:00") singapore = await tools.time_now({}, {"timezone": "Asia/Singapore"}) - assert singapore["offset"] == "+08:00" and singapore["local"].endswith("+08:00") + assert singapore["offset"] == "+08:00" + assert singapore["local"].endswith("+08:00") assert singapore["timezone"] == "Asia/Singapore" status, message = await _astatus(tools.time_now({}, {"timezone": "Mars/Olympus"})) - assert status == 400 and "is not a time zone" in message + assert status == 400 + assert "is not a time zone" in message status, message = await _astatus(tools.time_now({}, {"tz": "UTC"})) - assert status == 400 and "time_now does not take tz" in message + assert status == 400 + assert "time_now does not take tz" in message # --- the boot: what registers, and the health route ------------------------------------------- @@ -923,11 +957,14 @@ async def test_without_a_sandbox_only_the_clock_registers(caplog: pytest.LogCapt with caplog.at_level(logging.INFO): await app.boot() assert app.registered == ["time.now"] - assert app.files is None and app.web is None + assert app.files is None + assert app.web is None assert "File tools not registered - tools.file.root is not set" in caplog.text assert "Web tools not registered - tools.web.allow is empty" in caplog.text service = registry.get("time.now") - assert service is not None and not service.private and service.instances == 10 + assert service is not None + assert not service.private + assert service.instances == 10 await app.shutdown() @@ -944,16 +981,20 @@ async def test_a_bad_sandbox_stops_the_boot_by_name( tmp_path: Path, configure: Callable[[dict[str, Any]], None], caplog: pytest.LogCaptureFixture ) -> None: configure({tools.FILE_ROOT: str(tmp_path / "missing")}) + booting = tools.AgentTools(FunctionRegistry()) with caplog.at_level(logging.ERROR), pytest.raises(SystemExit) as stop: - await tools.AgentTools(FunctionRegistry()).boot() - assert stop.value.code == 1 and "tools.file.root is not a directory" in caplog.text + await booting.boot() + assert stop.value.code == 1 + assert "tools.file.root is not a directory" in caplog.text configure({tools.FILE_ROOT: None, tools.WEB_ALLOW: "https://x/path"}) + booting = tools.AgentTools(FunctionRegistry()) with caplog.at_level(logging.ERROR), pytest.raises(SystemExit): - await tools.AgentTools(FunctionRegistry()).boot() + await booting.boot() assert "is not a host pattern" in caplog.text configure({tools.WEB_ALLOW: "docs.example.com", tools.WEB_TIMEOUT_MS: "soon"}) + booting = tools.AgentTools(FunctionRegistry()) with caplog.at_level(logging.ERROR), pytest.raises(SystemExit): - await tools.AgentTools(FunctionRegistry()).boot() + await booting.boot() assert "tools.web.timeout.ms must be an integer" in caplog.text @@ -975,17 +1016,23 @@ async def test_a_full_configuration_registers_every_tool_and_serves_them_through assert app.registered == list(STEP_ONE_ROUTES) for route in STEP_ONE_ROUTES: service = registry.get(route) - assert service is not None and not service.private and service.instances == 10, route + assert service is not None, route + assert not service.private, route + assert service.instances == 10, route po = PostOffice(registry=registry) try: read = await po.request("file.read", body={"path": "notes/plan.md"}, timeout_ms=5000) - assert read.get_status() == 200 and read.body["text"].startswith("# Plan") + assert read.get_status() == 200 + assert read.body["text"].startswith("# Plan") refused = await po.request("file.read", body={"path": "../x"}, timeout_ms=5000) - assert refused.get_status() == 400 and "outside the workspace" in str(refused.body) + assert refused.get_status() == 400 + assert "outside the workspace" in str(refused.body) fetched = await po.request("web.fetch", body={"url": f"{site}/docs/c"}, timeout_ms=5000) - assert fetched.get_status() == 200 and fetched.body["title"] == "Section C" + assert fetched.get_status() == 200 + assert fetched.body["title"] == "Section C" clock = await po.request("time.now", body={}, timeout_ms=5000) - assert clock.get_status() == 200 and clock.body["timezone"] == "UTC" + assert clock.get_status() == 200 + assert clock.body["timezone"] == "UTC" info = await tools.tools_health({"type": "info"}, None) assert info["service"] == "agent.tools" assert info["tools"] == list(STEP_ONE_ROUTES) @@ -1062,9 +1109,11 @@ def test_the_rows_satisfy_the_loops_catalog_rules(row: dict[str, Any]) -> None: ) assert re.fullmatch(r"[a-zA-Z0-9_-]{1,128}", row["name"]) assert row["name"] == row["route"].replace(".", "_") - assert row["description"].strip() and len(row["description"]) < 700 + assert row["description"].strip() + assert len(row["description"]) < 700 schema = row["input_schema"] - assert schema["type"] == "object" and schema["additionalProperties"] is False + assert schema["type"] == "object" + assert schema["additionalProperties"] is False assert set(schema["required"]) <= set(schema["properties"]) _check_schema(schema) assert row.get("write", False) is (row["name"] in WRITERS), ( @@ -1206,11 +1255,13 @@ def hydrate(code: str, message: str) -> BaseException: timed = tools.graph_error( hydrate("Neo.ClientError.Transaction.TransactionTimedOut", "took too long"), timeout_ms=10 ) - assert timed.status == 408 and "within 10 ms" in timed.message + assert timed.status == 408 + assert "within 10 ms" in timed.message auth = tools.graph_error( hydrate("Neo.ClientError.Security.Unauthorized", "the credential itself"), timeout_ms=10 ) - assert auth.status == 503 and "the credential itself" not in auth.message + assert auth.status == 503 + assert "the credential itself" not in auth.message transient = tools.graph_error( hydrate("Neo.TransientError.Transaction.DeadlockDetected", "deadlock"), timeout_ms=10 ) @@ -1481,10 +1532,8 @@ async def test_graph_schema_falls_back_to_memgraphs_procedures() -> None: {"name": "source", "types": ["String"]} ] queries = [call[0] for call in backend.calls] - assert ( - tools.NODE_PROPERTIES_QUERIES[1] in queries - and tools.RELATIONSHIP_PROPERTIES_QUERIES[1] in queries - ) + assert tools.NODE_PROPERTIES_QUERIES[1] in queries + assert tools.RELATIONSHIP_PROPERTIES_QUERIES[1] in queries @pytest.mark.asyncio @@ -1492,7 +1541,9 @@ async def test_graph_query_runs_read_only_with_the_row_cap() -> None: node = FakeNode("4:g:1", frozenset({"Clause"}), {"key": "clause:1"}) def script(query: str, parameters: dict[str, Any], limit: int | None) -> Any: - assert "MATCH" in query and parameters == {"k": "clause:1"} and limit == 50 + assert "MATCH" in query + assert parameters == {"k": "clause:1"} + assert limit == 50 return _rows(["n", "c"], [[node, 2]], truncated=True) graph, backend = _graph(script, max_rows=50) @@ -1512,7 +1563,8 @@ def script(query: str, parameters: dict[str, Any], limit: int | None) -> Any: ({"cypher": "MATCH (n) RETURN n"}, "graph_query does not take cypher"), ): status, text = await _astatus(graph.query({}, body)) - assert status == 400 and message in text, text + assert status == 400, text + assert message in text, text assert len(backend.transactions) == 1, "a refused query never reaches the database" @@ -1527,7 +1579,8 @@ def script(_query: str, _parameters: dict[str, Any], _limit: int | None) -> Any: graph, _backend = _graph(script) status, text = await _astatus(graph.query({}, {"query": "MATCH (n RETURN n"})) - assert status == 400 and text == "Neo.ClientError.Statement.SyntaxError: Invalid input" + assert status == 400 + assert text == "Neo.ClientError.Statement.SyntaxError: Invalid input" @pytest.mark.asyncio @@ -1550,13 +1603,12 @@ def script(query: str, _parameters: dict[str, Any], _limit: int | None) -> Any: assert backend.modes == [True] assert "graph.write 200 indexes_added=1" in caplog.text status, text = await _astatus(graph.write({}, {"query": "MATCH (n:Clause) DETACH DELETE n"})) - assert ( - status == 400 - and "query carries DELETE - deletion is not allowed" in text - and tools.GRAPH_DELETE in text - ) + assert status == 400 + assert "query carries DELETE - deletion is not allowed" in text + assert tools.GRAPH_DELETE in text status, text = await _astatus(graph.write({}, {"query": "DROP INDEX clause_key"})) - assert status == 400 and "DROP" in text + assert status == 400 + assert "DROP" in text allowed, backend = _graph( lambda q, p, limit: _rows([], [], counters={"nodes_deleted": 3}), write=True, delete=True ) @@ -1594,11 +1646,9 @@ def script(query: str, parameters: dict[str, Any], _limit: int | None) -> Any: "CHECK", "UNWIND", ] - assert ( - "MERGE (n:`_Ingested`:`Clause`" in queries[1] - and "MERGE (n:`_Ingested`:`Party`" in queries[2] - and "MERGE (a)-[r:`BINDS`]->(b)" in queries[4] - ) + assert "MERGE (n:`_Ingested`:`Clause`" in queries[1] + assert "MERGE (n:`_Ingested`:`Party`" in queries[2] + assert "MERGE (a)-[r:`BINDS`]->(b)" in queries[4] assert backend.calls[1][1] == { "rows": [{"key": "clause:1", "properties": {"text": "pay within 30 days"}}], "source": "contracts/a.md", @@ -1665,7 +1715,8 @@ def script(query: str, _parameters: dict[str, Any], _limit: int | None) -> Any: graph, backend = _graph(script, write=True) for _attempt in range(2): status, text = await _astatus(graph.ingest({}, INGEST_ONE_NODE)) - assert status == 409 and text.endswith(tools.INGEST_DUPLICATES_QUERY) + assert status == 409 + assert text.endswith(tools.INGEST_DUPLICATES_QUERY) assert "nothing was ingested" in text queries = [call[0] for call in backend.calls] assert not [q for q in queries if q.startswith("UNWIND")], "nothing was merged" @@ -1683,7 +1734,8 @@ def script(query: str, _parameters: dict[str, Any], _limit: int | None) -> Any: graph, backend = _graph(script, write=True) status, text = await _astatus(graph.ingest({}, INGEST_ONE_NODE)) - assert status == 503 and text.endswith(tools.INGEST_CONSTRAINT_STATEMENT) + assert status == 503 + assert text.endswith(tools.INGEST_CONSTRAINT_STATEMENT) assert not [call for call in backend.calls if call[0].startswith("UNWIND")] @@ -1739,7 +1791,8 @@ def slow(query: str, _parameters: dict[str, Any], _limit: int | None) -> Any: graph, backend = _graph(slow, write=True, timeout_ms=1500) status, text = await _astatus(graph.ingest({}, INGEST_ONE_NODE)) - assert status == 408 and "did not finish within 1500 ms" in text + assert status == 408 + assert "did not finish within 1500 ms" in text assert text.endswith(tools.INGEST_LABEL_STATEMENT) assert not [call for call in backend.calls if call[0].startswith("UNWIND")] @@ -1763,15 +1816,14 @@ def script(query: str, _parameters: dict[str, Any], _limit: int | None) -> Any: }, ) ) - assert ( - status == 400 - and text == "relationship endpoints not found in the graph or in this call: ghost:1" - ) + assert status == 400 + assert text == "relationship endpoints not found in the graph or in this call: ghost:1" assert [q for q in (call[0] for call in backend.calls) if "MERGE (a)" in q] == [], ( "no relationship statement ran" ) status, text = await _astatus(graph.ingest({}, {"nodes": [{"key": "k", "label": "Bad Label"}]})) - assert status == 400 and "identifier" in text + assert status == 400 + assert "identifier" in text assert len(backend.transactions) == 2, "a refused ingest never reaches the database" @@ -1881,7 +1933,8 @@ def test_extract_a_pdf_with_page_markers_and_a_range(documents: Any) -> None: "--- page 2 ---", ] cut = documents.extract({}, {"path": "docs/agreement.pdf", "max_chars": 100}) - assert len(cut["text"]) == 100 and cut["truncated"] is True + assert len(cut["text"]) == 100 + assert cut["truncated"] is True def test_extract_word_html_and_text_documents(documents: Any) -> None: @@ -1969,7 +2022,8 @@ async def test_the_graph_tools_register_by_the_uri_and_the_write_gate( assert "graph.write and graph.ingest not registered - tools.graph.write is false" in caplog.text assert "Graph tools registered - bolt://graph.example:7687" in caplog.text assert "a-value-never-logged" not in caplog.text - assert reads.graph is not None and reads.graph.sandbox.password == "a-value-never-logged" + assert reads.graph is not None + assert reads.graph.sandbox.password == "a-value-never-logged" await reads.shutdown() assert reads.graph.backend.closed configure({tools.GRAPH_WRITE: "true", tools.GRAPH_DELETE: True}) @@ -1980,7 +2034,8 @@ async def test_the_graph_tools_register_by_the_uri_and_the_write_gate( assert "writes allowed, deletion allowed" in caplog.text monkeypatch.setattr(tools, "agent_tools", writes) info = await tools.tools_health({"type": "info"}, None) - assert info["graph"] == "bolt://graph.example:7687" and info["tools"] == writes.registered + assert info["graph"] == "bolt://graph.example:7687" + assert info["tools"] == writes.registered @pytest.mark.asyncio @@ -2009,13 +2064,15 @@ async def test_a_bad_graph_configuration_stops_the_boot_by_name( caplog: pytest.LogCaptureFixture, ) -> None: configure({tools.GRAPH_URI: "http://graph.example:7474"}) + booting = tools.AgentTools(FunctionRegistry()) with caplog.at_level(logging.ERROR), pytest.raises(SystemExit): - await tools.AgentTools(FunctionRegistry()).boot() + await booting.boot() assert "tools.graph.uri must be a Bolt URI" in caplog.text configure({tools.GRAPH_URI: "bolt://graph.example:7687"}) monkeypatch.setattr(tools, "neo4j", None) + booting = tools.AgentTools(FunctionRegistry()) with caplog.at_level(logging.ERROR), pytest.raises(SystemExit): - await tools.AgentTools(FunctionRegistry()).boot() + await booting.boot() assert ( "the Bolt driver is not installed - pip install 'mercury-composable[graph]'" in caplog.text ) @@ -2114,20 +2171,14 @@ async def test_live_graph_round_trip(configure: Callable[[dict[str, Any]], None] }, ) node, relationship, party, total = rows["rows"][0] - assert ( - sorted(node["labels"]) == ["T_Clause", "_Ingested"] - and node["properties"]["key"] == "t_clause:1" - and node["properties"]["source"] == "contracts/a.md" - ) - assert ( - relationship["type"] == "T_BINDS" - and relationship["start"] == node["id"] - and relationship["end"] == party["id"] - ) - assert ( - relationship["properties"] == {"since": 2026, "source": "contracts/a.md"} - and total == 31 - ) + assert sorted(node["labels"]) == ["T_Clause", "_Ingested"] + assert node["properties"]["key"] == "t_clause:1" + assert node["properties"]["source"] == "contracts/a.md" + assert relationship["type"] == "T_BINDS" + assert relationship["start"] == node["id"] + assert relationship["end"] == party["id"] + assert relationship["properties"] == {"since": 2026, "source": "contracts/a.md"} + assert total == 31 path = await graph.query( {}, {"query": "MATCH p = (:T_Clause)-[:T_BINDS]->(:T_Party) RETURN p"} ) @@ -2141,7 +2192,8 @@ async def test_live_graph_round_trip(configure: Callable[[dict[str, Any]], None] ] schema = await graph.schema({}, None) clause = next(label for label in schema["labels"] if label["label"] == "T_Clause") - assert clause["count"] == 1 and {p["name"] for p in clause["properties"]} >= { + assert clause["count"] == 1 + assert {p["name"] for p in clause["properties"]} >= { "key", "text", "days", @@ -2152,15 +2204,18 @@ async def test_live_graph_round_trip(configure: Callable[[dict[str, Any]], None] status, text = await _astatus( graph.query({}, {"query": "MATCH (n:T_Clause) SET n.x = 1 RETURN n"}) ) - assert status == 400 and "write clause" in text + assert status == 400 + assert "write clause" in text status, text = await _astatus(graph.query({}, {"query": "MATCH (n:T_Clause RETURN n"})) - assert status == 400 and text.startswith("Neo.ClientError.Statement.SyntaxError") + assert status == 400 + assert text.startswith("Neo.ClientError.Statement.SyntaxError") status, text = await _astatus( graph.ingest( {}, {"relationships": [{"from": "t_clause:1", "to": "ghost:9", "type": "T_BINDS"}]} ) ) - assert status == 400 and "ghost:9" in text + assert status == 400 + assert "ghost:9" in text guarded = tools.GraphTools( tools.GraphSandbox( uri=graph.sandbox.uri, @@ -2171,14 +2226,16 @@ async def test_live_graph_round_trip(configure: Callable[[dict[str, Any]], None] ) try: status, text = await _astatus(guarded.write({}, {"query": cleanup})) - assert status == 400 and "deletion is not allowed" in text + assert status == 400 + assert "deletion is not allowed" in text finally: await guarded.close() # a key names one node: the constraint refuses it under another label status, text = await _astatus( graph.ingest({}, {"nodes": [{"key": "t_clause:1", "label": "T_Party"}]}) ) - assert status == 400 and "ConstraintValidationFailed" in text + assert status == 400 + assert "ConstraintValidationFailed" in text # a node written before the label existed: a new process prepares the graph, and the # same key is merged into that node, not written a second time await graph.write({}, {"query": "CREATE (:T_Clause {key: 't_clause:old', text: 'old'})"}) @@ -2194,9 +2251,7 @@ async def test_live_graph_round_trip(configure: Callable[[dict[str, Any]], None] finally: await later.close() deleted = await graph.write({}, {"query": cleanup}) - assert ( - deleted["counters"]["nodes_deleted"] == 3 - and deleted["counters"]["relationships_deleted"] == 1 - ) + assert deleted["counters"]["nodes_deleted"] == 3 + assert deleted["counters"]["relationships_deleted"] == 1 finally: await graph.close() diff --git a/tests/test_ask_person.py b/tests/test_ask_person.py index 02f6971..9d9241b 100644 --- a/tests/test_ask_person.py +++ b/tests/test_ask_person.py @@ -99,7 +99,8 @@ def _case(section: str, name: str) -> dict[str, Any]: def test_the_vector_file_is_the_shared_contract() -> None: - assert VECTORS["contract"] == "ask-person" and VECTORS["version"] == 2 + assert VECTORS["contract"] == "ask-person" + assert VECTORS["version"] == 2 for section in ("ticket_cases", "verify_cases", "message_cases", "readvice_cases", "reply_cases", "outcome_cases", "record_cases", "answer_cases", "transition_cases"): assert VECTORS[section], section @@ -140,7 +141,8 @@ def test_readvice_cases(name: str) -> None: case = _case("readvice_cases", name) if "request" in case: request = ask.readvice_request(case["payload"], case["graphs"]) - assert {"url": request.url, "headers": request.headers, "body": request.body} == case["request"] + sent = {"url": request.url, "headers": request.headers, "body": request.body} + assert sent == case["request"] else: with pytest.raises(ask.ReplyError) as refused: ask.readvice_request(case["payload"], case["graphs"]) @@ -152,7 +154,8 @@ def test_reply_cases(name: str) -> None: case = _case("reply_cases", name) if "request" in case: request = ask.build_resume(case["payload"], case["decisions"], case["who"], case["at"], case["graphs"]) - assert {"url": request.url, "headers": request.headers, "body": request.body} == case["request"] + sent = {"url": request.url, "headers": request.headers, "body": request.body} + assert sent == case["request"] else: with pytest.raises(ask.ReplyError) as refused: ask.build_resume(case["payload"], case["decisions"], case["who"], case["at"], case["graphs"]) @@ -215,10 +218,15 @@ async def test_transition_cases_replay_on_the_reference_store() -> None: def test_the_duration_grammar() -> None: - assert ask.duration_ms("500ms") == 500 and ask.duration_ms("30m") == 1_800_000 - assert ask.duration_ms("12h") == 43_200_000 and ask.duration_ms("2d") == 172_800_000 - assert ask.duration_ms(90) == 90_000 and ask.duration_ms("90") == 90_000 - assert ask.duration_ms(True) is None and ask.duration_ms("soon") is None and ask.duration_ms(-1) is None + assert ask.duration_ms("500ms") == 500 + assert ask.duration_ms("30m") == 1_800_000 + assert ask.duration_ms("12h") == 43_200_000 + assert ask.duration_ms("2d") == 172_800_000 + assert ask.duration_ms(90) == 90_000 + assert ask.duration_ms("90") == 90_000 + assert ask.duration_ms(True) is None + assert ask.duration_ms("soon") is None + assert ask.duration_ms(-1) is None def test_requested_at_defaults_to_now_and_the_expiry_follows_the_ttl() -> None: @@ -277,7 +285,8 @@ def test_settings_read_lists_and_pairs_in_both_forms(configure: Callable[[dict[s assert settings.channels == ("agent.question.inbox", "chat.post") assert settings.channel_endpoints == {"agent.question.inbox": "http://127.0.0.1:8092/api/event"} assert settings.graphs == {"order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant"} - assert settings.channel_timeout_ms == 2000 and settings.engine_timeout_ms == 60_000 + assert settings.channel_timeout_ms == 2000 + assert settings.engine_timeout_ms == 60_000 assert settings.keys == (KEY.encode(), PREVIOUS.encode()) as_text = configure({ ask.CHANNELS: "a.route, b.route", @@ -316,7 +325,8 @@ def test_the_boot_fails_by_name( def test_a_disabled_extension_loads_without_a_key(configure: Callable[[dict[str, Any]], Any]) -> None: settings = configure({**BASE, ask.ENABLED: False, ask.TICKET_KEY: "", ask.PREVIOUS_KEY: ""}) - assert settings.enabled is False and settings.keys == () + assert settings.enabled is False + assert settings.keys == () # --- the function on the bus ----------------------------------------------------------------------- @@ -383,19 +393,28 @@ async def test_person_ask_records_then_delivers_the_event_to_every_channel_best_ assert body["link"] == f"{REPLY_URL}/ask/{body['ticket']}" assert len(channel) == 1 event = channel[0] - assert event["ticket"] == body["ticket"] and event["link"] == body["link"] - assert event["expires_at"] == body["expires_at"] and event["calls"] == CALLS - assert event["kind"] == "approval" and event["graph_id"] == "order-assistant" and event["turn"] == 2 + assert event["ticket"] == body["ticket"] + assert event["link"] == body["link"] + assert event["expires_at"] == body["expires_at"] + assert event["calls"] == CALLS + assert event["kind"] == "approval" + assert event["graph_id"] == "order-assistant" + assert event["turn"] == 2 payload = ask.verify_ticket(body["ticket"], [KEY.encode()], time.time()) - assert payload["g"] == "order-assistant" and payload["c"] == "order-1002-case" and payload["t"] == 2 + assert payload["g"] == "order-assistant" + assert payload["c"] == "order-1002-case" + assert payload["t"] == 2 # the record: the row was there before the channel was told, and holds the event as the channel got it assert ROWS_AT_DELIVERY == [1] rows = await recorder.since(0, 10) assert len(rows) == 1 row = rows[0] assert (row.kind, row.state, row.turn) == ("approval", "open", 2) - assert row.ticket == body["ticket"] and row.link == body["link"] and row.expires_at == body["expires_at"] - assert row.message == event and row.public()["calls"] == CALLS + assert row.ticket == body["ticket"] + assert row.link == body["link"] + assert row.expires_at == body["expires_at"] + assert row.message == event + assert row.public()["calls"] == CALLS async def test_a_write_the_recorder_does_not_take_is_logged_and_never_fails_the_caller( @@ -433,7 +452,8 @@ async def record(self, _event: Any, _now: str) -> Any: caplog.clear() with caplog.at_level("WARNING"): assert await ask.question_audit({}, {"record": event}) == {"recorded": False, "error": "RuntimeError"} - assert "could not write - RuntimeError" in caplog.text and "quoted" not in caplog.text + assert "could not write - RuntimeError" in caplog.text + assert "quoted" not in caplog.text with pytest.raises(ask.AppException) as refused: await ask.question_audit({}, {"nothing": True}) assert refused.value.status == 400 @@ -452,10 +472,16 @@ async def test_an_advice_is_recorded_and_delivered_without_a_ticket( reply = await office.request(ask.ROUTE, advice, timeout_ms=5000) assert reply.get_status() == 200, reply.body assert reply.body == {"delivered": [{"route": "ask.test.channel", "ok": True, "status": 200}], "recorded": True} - assert "ticket" not in channel[0] and "link" not in channel[0] and channel[0]["details"] == advice["details"] + assert "ticket" not in channel[0] + assert "link" not in channel[0] + assert channel[0]["details"] == advice["details"] rows = await recorder.since(0, 10) - assert len(rows) == 1 and rows[0].kind == "advice" and rows[0].state is None and rows[0].ticket is None - assert rows[0].details == advice["details"] and rows[0].turn == 3 + assert len(rows) == 1 + assert rows[0].kind == "advice" + assert rows[0].state is None + assert rows[0].ticket is None + assert rows[0].details == advice["details"] + assert rows[0].turn == 3 async def test_the_function_refuses_a_bad_message_a_mismatched_graph_and_a_disabled_extension( @@ -464,16 +490,19 @@ async def test_the_function_refuses_a_bad_message_a_mismatched_graph_and_a_disab configure({**BASE, ask.CHANNELS: ["ask.test.channel"]}) office = PostOffice(registry=default_registry) bad = await office.request(ask.ROUTE, approval_message(ttl="soon"), timeout_ms=5000) - assert bad.get_status() == 400 and "ttl must be a duration" in str(bad.body) + assert bad.get_status() == 400 + assert "ttl must be a duration" in str(bad.body) mismatch = await office.request(ask.ROUTE, approval_message(), headers={"x-graph-id": "other"}, timeout_ms=5000) - assert mismatch.get_status() == 400 and "does not match the x-graph-id header" in str(mismatch.body) + assert mismatch.get_status() == 400 + assert "does not match the x-graph-id header" in str(mismatch.body) matched = await office.request(ask.ROUTE, approval_message(), headers={"x-graph-id": "order-assistant"}, timeout_ms=5000) assert matched.get_status() == 200 configure({ask.ENABLED: False}) off = await office.request(ask.ROUTE, approval_message(), timeout_ms=5000) - assert off.get_status() == 503 and "ask.enabled is false" in str(off.body) + assert off.get_status() == 503 + assert "ask.enabled is false" in str(off.body) assert len(channel) == 1 @@ -582,22 +611,30 @@ async def test_the_page_is_a_shell_and_the_wait_is_read_without_resuming( async with aiohttp.ClientSession() as http: async with http.get(f"{host}/ask/{ticket}") as response: page = await response.text() - assert response.status == 200 and response.content_type == "text/html" + assert response.status == 200 + assert response.content_type == "text/html" assert fake.requests == [], "the page itself never calls the engine - its script reads the wait" - assert f"const TICKET = {json.dumps(ticket)};" in page and f'const WAIT = "/ask/{ticket}/wait";' in page - assert 'const REPLY = "/ask/reply";' in page and 'const CONFIG = "/ask/config";' in page + assert f"const TICKET = {json.dumps(ticket)};" in page + assert f'const WAIT = "/ask/{ticket}/wait";' in page + assert 'const REPLY = "/ask/reply";' in page + assert 'const CONFIG = "/ask/config";' in page assert "Approval - order-assistant" in page # the script carries the form the page renders and the sign-in it may run - assert "waits for a decision" in page and "a question" in page and "runs on resume" in page - assert "code_challenge_method: 'S256'" in page and "authorization_endpoint" in page + assert "waits for a decision" in page + assert "a question" in page + assert "runs on resume" in page + assert "code_challenge_method: 'S256'" in page + assert "authorization_endpoint" in page async with http.get(f"{host}/ask/config") as response: - assert response.status == 200 and await response.json() == {"auth": "none"} + assert response.status == 200 + assert await response.json() == {"auth": "none"} async with http.get(f"{host}/ask/{ticket}/wait") as response: assert response.status == 200 shown = await response.json() assert fake.requests == [{"graph": "order-assistant", "cid": "order-1002-case", "body": {"turn": 2}}] assert shown["payload"] == {"g": "order-assistant", "c": "order-1002-case", "t": 2, "k": "approval"} - assert shown["advice"]["type"] == "approval" and shown["advice"]["calls"] == CALLS + assert shown["advice"]["type"] == "approval" + assert shown["advice"]["calls"] == CALLS async def test_the_page_refuses_bad_tickets_and_reports_an_expired_wait( @@ -607,17 +644,23 @@ async def test_the_page_refuses_bad_tickets_and_reports_an_expired_wait( configure({**BASE, ask.GRAPHS: f"order-assistant={engine_url}/api/graph/order-assistant"}) async with aiohttp.ClientSession() as http: async with http.get(f"{host}/ask/{_ticket(expires_in=-5)}") as response: - assert response.status == 410 and "Ticket expired" in await response.text() + assert response.status == 410 + assert "Ticket expired" in await response.text() async with http.get(f"{host}/ask/{_ticket(key='another')}") as response: - assert response.status == 403 and "signature is invalid" in await response.text() + assert response.status == 403 + assert "signature is invalid" in await response.text() async with http.get(f"{host}/ask/v1.nonsense") as response: - assert response.status == 400 and "malformed" in await response.text() + assert response.status == 400 + assert "malformed" in await response.text() async with http.get(f"{host}/ask/{_ticket(graph_id='other-graph')}") as response: - assert response.status == 404 and "not configured" in await response.text() + assert response.status == 404 + assert "not configured" in await response.text() async with http.get(f"{host}/ask/{_ticket(expires_in=-5)}/wait") as response: - assert response.status == 410 and await response.json() == {"type": "expired", "message": "Ticket expired"} + assert response.status == 410 + assert await response.json() == {"type": "expired", "message": "Ticket expired"} async with http.get(f"{host}/ask/{_ticket(graph_id='other-graph')}/wait") as response: - assert response.status == 404 and "not configured" in (await response.json())["message"] + assert response.status == 404 + assert "not configured" in (await response.json())["message"] assert fake.requests == [], "no ticket above reached the engine" async with http.get(f"{host}/ask/{_ticket(cid='expired-case')}/wait") as response: assert response.status == 410 @@ -639,10 +682,12 @@ async def test_a_reply_resumes_the_graph_with_who_decided_on_each_note( assert response.status == 200 assert outcome == {"type": "answer", "turn": 3, "run": "resume", "message": "Your refund has been issued."} sent = fake.requests[0] - assert sent["graph"] == "order-assistant" and sent["cid"] == "order-1002-case" + assert sent["graph"] == "order-assistant" + assert sent["cid"] == "order-1002-case" assert sent["body"]["turn"] == 2 note = sent["body"]["decisions"][0]["note"] - assert note.startswith("[anonymous at 20") and note.endswith("Z] Carrier confirmed the loss") + assert note.startswith("[anonymous at 20") + assert note.endswith("Z] Carrier confirmed the loss") assert sent["body"]["decisions"][1] == {"id": "toolu_02B", "answer": "refund"} @@ -654,20 +699,27 @@ async def test_a_reply_is_refused_before_the_engine_when_the_ticket_or_the_decis good = [{"id": "toolu_01A", "approved": True}] async with aiohttp.ClientSession() as http: async with http.post(f"{host}/ask/reply", data=b"not json") as response: - assert response.status == 400 and "JSON map" in (await response.json())["message"] + assert response.status == 400 + assert "JSON map" in (await response.json())["message"] async with http.post(f"{host}/ask/reply", json={"decisions": good}) as response: - assert response.status == 400 and (await response.json())["message"] == "ticket is required" + assert response.status == 400 + assert (await response.json())["message"] == "ticket is required" async with http.post(f"{host}/ask/reply", json={"ticket": _ticket(expires_in=-5), "decisions": good}) as response: - assert response.status == 410 and await response.json() == {"type": "expired", "message": "Ticket expired"} + assert response.status == 410 + assert await response.json() == {"type": "expired", "message": "Ticket expired"} async with http.post(f"{host}/ask/reply", json={"ticket": _ticket(), "decisions": []}) as response: - assert response.status == 400 and "non-empty list" in (await response.json())["message"] + assert response.status == 400 + assert "non-empty list" in (await response.json())["message"] async with http.post(f"{host}/ask/reply", json={"ticket": _ticket(graph_id="x"), "decisions": good}) as response: - assert response.status == 404 and "not configured" in (await response.json())["message"] + assert response.status == 404 + assert "not configured" in (await response.json())["message"] async with http.post(f"{host}/ask/reply", json={"ticket": _ticket(), "decisions": good, "decided_by": 5}) as response: - assert response.status == 400 and "decided_by must be text" in (await response.json())["message"] + assert response.status == 400 + assert "decided_by must be text" in (await response.json())["message"] assert fake.requests == [] async with http.post(f"{host}/ask/reply", json={"ticket": _ticket(cid="expired-case"), "decisions": good}) as response: - assert response.status == 410 and (await response.json())["type"] == "nothing-waiting" + assert response.status == 410 + assert (await response.json())["type"] == "nothing-waiting" assert len(fake.requests) == 1 @@ -681,7 +733,8 @@ async def test_the_engine_s_outcome_is_passed_through_and_a_silent_engine_is_a_5 async with http.post(f"{host}/ask/reply", json=body) as response: assert response.status == 502 outcome = await response.json() - assert outcome["type"] == "error" and outcome["message"].startswith("the graph did not answer - ") + assert outcome["type"] == "error" + assert outcome["message"].startswith("the graph did not answer - ") async def test_a_reply_records_the_answer_with_who_decided_and_the_outcome( @@ -703,9 +756,13 @@ async def test_a_reply_records_the_answer_with_who_decided_and_the_outcome( rows = await recorder.since(0, 10) assert len(rows) == 1 row = rows[0] - assert row.id == recorded.id and row.state == "answered" and row.answered_by == "operator-9" - assert row.answered_at is not None and row.answered_at.endswith("Z") - assert row.decisions is not None and row.decisions[0]["note"].startswith("[operator-9 at ") + assert row.id == recorded.id + assert row.state == "answered" + assert row.answered_by == "operator-9" + assert row.answered_at is not None + assert row.answered_at.endswith("Z") + assert row.decisions is not None + assert row.decisions[0]["note"].startswith("[operator-9 at ") assert row.decisions[0]["note"].endswith("] Carrier confirmed") assert row.outcome == {"status": 200, "body": {"type": "answer", "turn": 3, "run": "resume", "message": "Your refund has been issued."}} @@ -718,7 +775,8 @@ async def test_a_reply_records_the_answer_with_who_decided_and_the_outcome( async def test_the_oauth2_mode_validates_an_access_token_and_the_page_learns_how_to_sign_in( - configure: Callable[[dict[str, Any]], Any], engine: tuple[FakeEngine, str], host: str + configure: Callable[[dict[str, Any]], Any], engine: tuple[FakeEngine, str], host: str, + monkeypatch: pytest.MonkeyPatch, ) -> None: fake, engine_url = engine private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) @@ -730,7 +788,7 @@ async def test_the_oauth2_mode_validates_an_access_token_and_the_page_learns_how ask.REPLY_AUTH: "oauth2", ask.OAUTH2_ISSUER: ISSUER, ask.OAUTH2_AUDIENCE: AUDIENCE, ask.OAUTH2_JWKS_URL: f"{engine_url}/jwks", ask.OAUTH2_CLIENT_ID: "ask-page", ask.APP_TOKEN: APP_TOKEN}) - ask._verifier = None + monkeypatch.setattr(ask, "_verifier", None) now = int(time.time()) claims = {"iss": ISSUER, "aud": AUDIENCE, "sub": "u-17", "preferred_username": "operator-17", "iat": now, "exp": now + 300} @@ -752,19 +810,24 @@ async def test_the_oauth2_mode_validates_an_access_token_and_the_page_learns_how async with http.get(f"{host}/ask/{_ticket()}") as response: assert response.status == 200, "the shell is open: the script signs the person in" async with http.get(f"{host}/ask/{_ticket()}/wait") as response: - assert response.status == 401 and "bearer access token" in (await response.json())["message"] + assert response.status == 401 + assert "bearer access token" in (await response.json())["message"] async with http.post(f"{host}/ask/reply", json=body) as response: - assert response.status == 401 and "bearer access token" in (await response.json())["message"] + assert response.status == 401 + assert "bearer access token" in (await response.json())["message"] async with http.post(f"{host}/ask/reply", json=body, headers={"authorization": f"Bearer {forged}"}) as response: - assert response.status == 401 and "InvalidSignatureError" in (await response.json())["message"] + assert response.status == 401 + assert "InvalidSignatureError" in (await response.json())["message"] async with http.post(f"{host}/ask/reply", json=body, headers={"authorization": f"Bearer {wrong_audience}"}) as response: - assert response.status == 401 and "InvalidAudienceError" in (await response.json())["message"] + assert response.status == 401 + assert "InvalidAudienceError" in (await response.json())["message"] async with http.post(f"{host}/ask/reply", json=body, headers={"authorization": f"Bearer {token}"}) as response: assert response.status == 200 assert fake.requests[-1]["body"]["decisions"][0]["note"].startswith("[operator-17 at ") async with http.get(f"{host}/ask/{_ticket()}/wait", headers={"authorization": f"Bearer {token}"}) as response: - assert response.status == 200 and (await response.json())["advice"]["type"] == "approval" + assert response.status == 200 + assert (await response.json())["advice"]["type"] == "approval" # a channel app's bearer names the person it acts for, in this mode too async with http.post(f"{host}/ask/reply", json={**body, "decided_by": "operator-9"}, headers={"authorization": f"Bearer {APP_TOKEN}"}) as response: @@ -835,34 +898,49 @@ async def test_the_postgres_store_runs_the_statements_and_maps_the_records() -> KEY.encode(), REPLY_URL) row = await store.record(event, now) sql, params = pool.log[-1] - assert sql == ask.SQL_RECORD_WAIT and params is not None - assert params[1:5] == ("order-assistant", "order-1002-case", 2, "approval") and params[0] == event["ticket"] + assert sql == ask.SQL_RECORD_WAIT + assert params is not None + assert params[1:5] == ("order-assistant", "order-1002-case", 2, "approval") + assert params[0] == event["ticket"] assert json.loads(params[7]) == event, "the message travels as text for the jsonb column" - assert params[9] == "2026-11-19T09:12:04.118Z" and params[11] == now - assert row.id == 7 and row.seq == 12 and row.requested_at == "2026-11-19T09:12:05.123Z" - assert row.expires_at == "2026-11-21T09:12:05.123Z" and row.message["calls"] == CALLS + assert params[9] == "2026-11-19T09:12:04.118Z" + assert params[11] == now + assert row.id == 7 + assert row.seq == 12 + assert row.requested_at == "2026-11-19T09:12:05.123Z" + assert row.expires_at == "2026-11-21T09:12:05.123Z" + assert row.message["calls"] == CALLS advice = ask.build_event(ask.validate_message({ "kind": "advice", "graph_id": "order-assistant", "description": "Customer-support assistant", "correlation_id": "order-1002-case", "summary": "The queue is empty", }), KEY.encode(), REPLY_URL) await store.record(advice, now) sql, params = pool.log[-1] - assert sql == ask.SQL_RECORD_ADVICE and params is not None and params[:2] == ("order-assistant", "order-1002-case") + assert sql == ask.SQL_RECORD_ADVICE + assert params is not None + assert params[:2] == ("order-assistant", "order-1002-case") # the guard kept a newer row (no row returned): the standing row is read pool.queue = [[], [_record(seq=13)]] stale = await store.record(event, now) - assert [entry[0] for entry in pool.log[-2:]] == [ask.SQL_RECORD_WAIT, ask.SQL_WAIT] and stale.seq == 13 + assert [entry[0] for entry in pool.log[-2:]] == [ask.SQL_RECORD_WAIT, ask.SQL_WAIT] + assert stale.seq == 13 answered = await store.answer(("order-assistant", "order-1002-case", 2), [{"id": "toolu_01A", "approved": True}], "operator-17", "answered", {"status": 200, "body": {"type": "answer"}}, now) sql, params = pool.log[-1] - assert sql == ask.SQL_ANSWER and params is not None and answered is not None - assert params[0] == "answered" and params[3] == "operator-17" and params[6:9] == ("order-assistant", "order-1002-case", 2) - assert params[9] == "answered" and json.loads(params[1]) == [{"id": "toolu_01A", "approved": True}] + assert sql == ask.SQL_ANSWER + assert params is not None + assert answered is not None + assert params[0] == "answered" + assert params[3] == "operator-17" + assert params[6:9] == ("order-assistant", "order-1002-case", 2) + assert params[9] == "answered" + assert json.loads(params[1]) == [{"id": "toolu_01A", "approved": True}] # the guard kept the first decision (no row returned): the row as stored comes back pool.queue = [[], [_record(state="answered", answered_by="operator-3")]] kept = await store.answer(("order-assistant", "order-1002-case", 2), [], "operator-9", "expired", {"status": 410, "body": {"type": "nothing-waiting"}}, now) - assert kept is not None and kept.answered_by == "operator-3" + assert kept is not None + assert kept.answered_by == "operator-3" await store.expire(now) assert pool.log[-1] == (ask.SQL_EXPIRE, (now, now)) await store.since(3, 50) @@ -873,7 +951,9 @@ async def test_the_postgres_store_runs_the_statements_and_maps_the_records() -> assert pool.closed mapped = ask.row_from_record(_record(kind="advice", state=None, ticket=None, link=None, decisions='[{"id":"x","approved":true}]')) - assert mapped.state is None and mapped.decisions == [{"id": "x", "approved": True}] and mapped.outcome is None + assert mapped.state is None + assert mapped.decisions == [{"id": "x", "approved": True}] + assert mapped.outcome is None assert ask.failure(RuntimeError("quotes a row")) == "RuntimeError" @@ -893,12 +973,15 @@ async def test_the_boot_registers_the_recorder_and_a_silent_database_does_not_st await runner.setup() try: assert default_registry.exists(ask.AUDIT_ROUTE) - assert ask._store is not None and ask._store.name == "postgres" + assert ask._store is not None + assert ask._store.name == "postgres" assert "is not answering at start" in caplog.text - assert ask._sweeper is not None and not ask._sweeper.done() + assert ask._sweeper is not None + assert not ask._sweeper.done() finally: await runner.cleanup() - assert ask._store is None and ask._sweeper is None, "the shutdown closed the store and stopped the sweeper" + assert ask._store is None, "the shutdown closed the store and stopped the sweeper" + assert ask._sweeper is None, "the shutdown closed the store and stopped the sweeper" # --- the host hook, the boot and the inspect command ----------------------------------------------- @@ -918,7 +1001,9 @@ async def test_the_rest_entries_serve_the_page_and_the_endpoints_and_the_host_ke assert response.status == 200, "the actuator stays the host's" async with http.post(f"{host}/ask/reply", json={}) as response: refused = await response.json() - assert response.status == 400 and refused["status"] == 400 and refused["type"] == "error" + assert response.status == 400 + assert refused["status"] == 400 + assert refused["type"] == "error" assert response.headers["content-type"] == "application/json", "the engines' error shape" async with http.get(f"{host}/ask/config") as response: assert response.status == 200, "the configuration is never read as a ticket" @@ -935,13 +1020,16 @@ async def test_the_rest_entries_serve_the_page_and_the_endpoints_and_the_host_ke } for (method, path), (service, authentication) in expected.items(): assigned = rest.table.find(method, path) - assert assigned is not None and assigned.info.service == service, path + assert assigned is not None, path + assert assigned.info.service == service, path assert assigned.info.authentication == authentication, path wait = rest.table.find("GET", "/ask/v1.payload.mac/wait") - assert wait is not None and wait.path_params == {"ticket": "v1.payload.mac"} + assert wait is not None + assert wait.path_params == {"ticket": "v1.payload.mac"} for route in ("ask.config", "ask.reply", "ask.wait", "ask.page", "ask.identity", "ask.reply.identity"): service = default_registry.get(route) - assert service is not None and service.private, route + assert service is not None, route + assert service.private, route fresh = Platform(FunctionRegistry()) app = fresh.create_app() paths = [route.resource.canonical for route in app.router.routes() if route.resource is not None] @@ -960,13 +1048,16 @@ async def test_the_platform_hooks_run_the_boot_and_fail_by_name( with caplog.at_level("WARNING"): await runner.setup() try: - assert "No channel configured" in caplog.text and "No graph configured" in caplog.text + assert "No channel configured" in caplog.text + assert "No graph configured" in caplog.text assert "question record is in memory" in caplog.text - assert default_registry.exists(ask.AUDIT_ROUTE) and ask._store is not None and ask._store.name == "memory" + assert default_registry.exists(ask.AUDIT_ROUTE) + assert ask._store is not None + assert ask._store.name == "memory" finally: await runner.cleanup() app_config().set(ask.TICKET_KEY, "") - ask._settings = None + monkeypatch.setattr(ask, "_settings", None) failing = Platform(FunctionRegistry()) monkeypatch.setattr(ask, "platform", failing) ask._attach() @@ -984,7 +1075,9 @@ def test_inspect_reads_a_ticket_or_says_why_not( ticket = _ticket() assert ask.inspect([ticket]) == 0 shown = json.loads(capsys.readouterr().out) - assert shown["g"] == "order-assistant" and shown["k"] == "approval" and shown["expires_at"].endswith("Z") + assert shown["g"] == "order-assistant" + assert shown["k"] == "approval" + assert shown["expires_at"].endswith("Z") assert ask.inspect([_ticket(expires_in=-1)]) == 1 assert capsys.readouterr().out.strip() == "410 Ticket expired" assert ask.inspect([]) == 1 @@ -1012,21 +1105,28 @@ async def test_the_record_lands_on_a_live_postgres() -> None: correlation_id=cid, requested_at="2026-11-19T09:00:00.000Z")), key, REPLY_URL), ask.iso_utc()) again = await store.record(ask.build_event(ask.validate_message(approval_message( correlation_id=cid, requested_at="2026-11-19T09:05:00.000Z")), key, REPLY_URL), ask.iso_utc()) - assert again.id == first.id and again.seq > first.seq and again.ticket != first.ticket, "the same turn upserts" + assert again.id == first.id, "the same turn upserts" + assert again.seq > first.seq, "the same turn upserts" + assert again.ticket != first.ticket, "the same turn upserts" stale = await store.record(ask.build_event(ask.validate_message(approval_message( correlation_id=cid, requested_at="2026-11-19T08:00:00.000Z")), key, REPLY_URL), ask.iso_utc()) - assert stale.seq == again.seq and stale.ticket == again.ticket, "an older message never overwrites a newer row" + assert stale.seq == again.seq, "an older message never overwrites a newer row" + assert stale.ticket == again.ticket, "an older message never overwrites a newer row" advice = await store.record(ask.build_event(ask.validate_message({ "kind": "advice", "graph_id": "order-assistant", "description": "Customer-support assistant", "correlation_id": cid, "summary": "The queue is empty", }), key, REPLY_URL), ask.iso_utc()) - assert advice.id != first.id and advice.kind == "advice" and advice.state is None + assert advice.id != first.id + assert advice.kind == "advice" + assert advice.state is None answered = await store.answer(("order-assistant", cid, 2), [{"id": "toolu_01A", "approved": True}], "operator-17", "answered", {"status": 200, "body": {"type": "answer"}}, ask.iso_utc()) - assert answered is not None and answered.state == "answered" + assert answered is not None + assert answered.state == "answered" kept = await store.answer(("order-assistant", cid, 2), [{"id": "toolu_01A", "approved": False}], "operator-9", "expired", {"status": 410, "body": {"type": "nothing-waiting"}}, ask.iso_utc()) - assert kept is not None and kept.answered_by == "operator-17", "the first accepted decision stands" + assert kept is not None, "the first accepted decision stands" + assert kept.answered_by == "operator-17", "the first accepted decision stands" assert await store.answer(("order-assistant", f"{cid}-none", 1), [], "x", "answered", {}, ask.iso_utc()) is None soon = ask.iso_utc(datetime.now(UTC) - timedelta(seconds=1)) past = await store.record({**ask.build_event(ask.validate_message(approval_message( diff --git a/tests/test_llm_attachments.py b/tests/test_llm_attachments.py index e1d67ee..cd5883b 100644 --- a/tests/test_llm_attachments.py +++ b/tests/test_llm_attachments.py @@ -99,7 +99,8 @@ def _assert_block(block: dict[str, Any], wanted: dict[str, Any]) -> None: "data": _encoded(wanted["image"])} # fmt: skip assert block == {"type": "image", "source": source} return - assert set(block) == {"type", "source"} and block["type"] == "document" + assert set(block) == {"type", "source"} + assert block["type"] == "document" source = block["source"] assert set(source) == {"type", "media_type", "data"} assert (source["type"], source["media_type"]) == ("base64", "application/pdf") @@ -146,7 +147,8 @@ async def test_attachments_contract( error = exc if "error" in expect: _assert_error(error, expect["error"]) - assert error is not None and str(tmp_path) not in error.message, "no host path" + assert error is not None, "no host path" + assert str(tmp_path) not in error.message, "no host path" assert client.ledger.calls == [], "a refused attachment reaches no model call" return assert error is None, error @@ -154,8 +156,10 @@ async def test_attachments_contract( assert result[key] == value, key ((_namespace, params),) = client.ledger.calls sent, wanted = params["messages"], expect["messages"] - assert sent[:-1] == wanted[:-1] and len(sent) == len(wanted) - assert sent[-1]["role"] == "user" and len(sent[-1]["content"]) == len(wanted[-1]["content"]) + assert sent[:-1] == wanted[:-1] + assert len(sent) == len(wanted) + assert sent[-1]["role"] == "user" + assert len(sent[-1]["content"]) == len(wanted[-1]["content"]) for block, short in zip(sent[-1]["content"], wanted[-1]["content"], strict=True): _assert_block(block, short) if rig is not None: @@ -255,7 +259,8 @@ async def tick() -> None: with pytest.raises(AppException) as late: await helper.llm_chat({}, body) ticking.cancel() - assert late.value.status == 408 and "timed out after 50 ms" in late.value.message + assert late.value.status == 408 + assert "timed out after 50 ms" in late.value.message assert client.ledger.calls == [], "no model call after the deadline" assert threads == [False], "the files are read in a worker thread" assert ticks >= 2, "the event loop kept running while the files were read" @@ -278,7 +283,8 @@ async def test_a_log_carries_the_count_and_the_bytes_and_never_a_path_or_a_files assert hidden not in caplog.text, hidden with pytest.raises(AppException): # and a refusal names the entry, never the path await helper.llm_chat({}, {"prompt": "x", "attachments": ["SCAN-MARKER/gone.png"]}) - assert "SCAN-MARKER" not in caplog.text and "llm.chat failed - status=400" in caplog.text + assert "SCAN-MARKER" not in caplog.text + assert "llm.chat failed - status=400" in caplog.text async def test_a_call_without_attachments_reads_no_root_and_sends_text_as_before( @@ -294,7 +300,8 @@ async def test_a_call_without_attachments_reads_no_root_and_sends_text_as_before await helper.llm_chat({}, {"prompt": "x", "attachments": None}) ((_namespace, params),) = client.ledger.calls assert params["messages"] == [{"role": "user", "content": "x"}] - assert "llm_attachments" not in seen and helper._attachments_root is None + assert "llm_attachments" not in seen + assert helper._attachments_root is None async def test_the_root_is_resolved_once_and_a_root_that_is_not_a_folder_stops_the_start( diff --git a/tests/test_llm_upload.py b/tests/test_llm_upload.py index 2a12c41..aed47b9 100644 --- a/tests/test_llm_upload.py +++ b/tests/test_llm_upload.py @@ -39,13 +39,17 @@ async def test_the_files_are_saved_under_new_names_and_their_references_returned assert len(saved) == 2 first, second = saved # a new name under uploads/, the original name kept beside it, hidden dots and odd characters gone - assert first["path"].startswith("uploads/") and first["path"].endswith("-Quarterly_Report__final_.pdf") + assert first["path"].startswith("uploads/") + assert first["path"].endswith("-Quarterly_Report__final_.pdf") assert second["path"].endswith("-hidden_notes.docx") or second["path"].endswith("-notes.docx") assert first["filename"] == "Quarterly Report (final).pdf" # the kind by the first bytes, the declared type when the bytes say nothing the model takes - assert first["media_type"] == "application/pdf" and first["attachable"] is True - assert second["media_type"].startswith("application/vnd.openxmlformats") and second["attachable"] is False - assert first["bytes"] == len(pdf) and first["sha256"] == hashlib.sha256(pdf).hexdigest() + assert first["media_type"] == "application/pdf" + assert first["attachable"] is True + assert second["media_type"].startswith("application/vnd.openxmlformats") + assert second["attachable"] is False + assert first["bytes"] == len(pdf) + assert first["sha256"] == hashlib.sha256(pdf).hexdigest() # the saved file is the one uploaded, and it is reachable the way `attachments` reads a file stored = helper._attachment_file(root.resolve(), 0, first["path"]) assert stored.read_bytes() == pdf @@ -58,14 +62,18 @@ async def test_without_a_file_the_request_is_a_400_and_without_a_root_a_503( root = tmp_path / "root" root.mkdir() monkeypatch.setattr(helper, "_attachments_root", root.resolve()) + without_a_file = _request() with pytest.raises(AppException) as raised: - await helper.llm_upload({}, _request()) - assert raised.value.status == 400 and raised.value.message == helper.UPLOAD_NO_FILES + await helper.llm_upload({}, without_a_file) + assert raised.value.status == 400 + assert raised.value.message == helper.UPLOAD_NO_FILES monkeypatch.setattr(helper, "_attachments_root", None) monkeypatch.setattr(helper, "_prop", lambda key, default=None: None) + with_a_file = _request(("a.pdf", "application/pdf", b"%PDF-1.4", "doc")) with pytest.raises(AppException) as raised: - await helper.llm_upload({}, _request(("a.pdf", "application/pdf", b"%PDF-1.4", "doc"))) - assert raised.value.status == 503 and raised.value.message == helper.MISSING_ATTACHMENTS_ROOT + await helper.llm_upload({}, with_a_file) + assert raised.value.status == 503 + assert raised.value.message == helper.MISSING_ATTACHMENTS_ROOT def test_safe_names() -> None: diff --git a/tests/test_mcp_recipes.py b/tests/test_mcp_recipes.py index af4e599..752be80 100644 --- a/tests/test_mcp_recipes.py +++ b/tests/test_mcp_recipes.py @@ -94,11 +94,14 @@ def test_the_digest_file_is_the_one_the_node_twin_runs() -> None: def test_the_recipes_file_names_the_seven_servers(recipes: dict[str, Any]) -> None: assert sorted(recipes) == RECIPE_SERVERS for name in ("git", "time", "fetch", "neo4j"): - assert recipes[name].transport == "stdio" and recipes[name].command == "uvx", name + assert recipes[name].transport == "stdio", name + assert recipes[name].command == "uvx", name for name in ("filesystem", "playwright"): - assert recipes[name].transport == "stdio" and recipes[name].command == "npx", name + assert recipes[name].transport == "stdio", name + assert recipes[name].command == "npx", name github = recipes["github"] - assert github.transport == "http" and github.url.startswith("https://") + assert github.transport == "http" + assert github.url.startswith("https://") assert github.headers["Authorization"].startswith("Bearer ") assert github.headers["X-MCP-Readonly"] == "true" @@ -120,7 +123,8 @@ def test_every_pinned_server_has_a_recipe_and_tools(recipes: dict[str, Any]) -> for name, server in pinned.items(): assert server["tools"], name for tool, digest in server["tools"].items(): - assert len(digest) == 64 and int(digest, 16) >= 0, f"{name}.{tool}" + assert len(digest) == 64, f"{name}.{tool}" + assert int(digest, 16) >= 0, f"{name}.{tool}" def test_rot_names_what_is_missing_and_what_changed() -> None: @@ -146,10 +150,12 @@ async def offered_digests(spec: Any) -> dict[str, str]: async def test_live_recipe_digests(name: str, recipes: dict[str, Any]) -> None: actual = await offered_digests(recipes[name]) missing, changed = rot(actual, DIGESTS["servers"][name]["tools"]) - assert not missing and not changed, ( + rotted = ( f"the {name} recipe rotted - missing {missing}, changed {changed}: run describe on it, review " "the schema, then re-pin the digest in both packs' vector file and on the page" ) + assert not missing, rotted + assert not changed, rotted @pytest.mark.skipif( @@ -161,9 +167,9 @@ async def test_live_recipe_digests(name: str, recipes: dict[str, Any]) -> None: async def test_live_neo4j_recipe_digests(recipes: dict[str, Any]) -> None: actual = await offered_digests(recipes["neo4j"]) missing, changed = rot(actual, DIGESTS["servers"]["neo4j"]["tools"]) - assert not missing and not changed, ( - f"the neo4j recipe rotted - missing {missing}, changed {changed}" - ) + rotted = f"the neo4j recipe rotted - missing {missing}, changed {changed}" + assert not missing, rotted + assert not changed, rotted # --- GitHub's hosted server, live with a token (gated) ----------------------------------------- @@ -196,6 +202,6 @@ async def test_live_github_recipe_digests( github = {spec.name: spec for spec in binding.load_servers(str(_RECIPES))}["github"] actual = await offered_digests(github) missing, changed = rot(actual, DIGESTS["servers"]["github"]["tools"]) - assert not missing and not changed, ( - f"the github recipe rotted - missing {missing}, changed {changed}" - ) + rotted = f"the github recipe rotted - missing {missing}, changed {changed}" + assert not missing, rotted + assert not changed, rotted diff --git a/tests/test_rest_automation.py b/tests/test_rest_automation.py index 3f7fac5..3de0820 100644 --- a/tests/test_rest_automation.py +++ b/tests/test_rest_automation.py @@ -7,7 +7,6 @@ import base64 import hashlib import json -import os from collections.abc import AsyncIterator, Callable, Iterator from contextlib import AbstractAsyncContextManager, contextmanager from pathlib import Path @@ -87,8 +86,9 @@ def test_vectors_load_cases(vectors: dict[str, Any]): assert static.filter is None, case["name"] else: assert static.filter is not None - assert {"path": static.filter.path_list, "exclusion": static.filter.exclusion_list, - "service": static.filter.service} == expect_filter, case["name"] + found_filter = {"path": static.filter.path_list, "exclusion": static.filter.exclusion_list, + "service": static.filter.service} + assert found_filter == expect_filter, case["name"] def test_vectors_timeout_cases(vectors: dict[str, Any]): @@ -577,7 +577,8 @@ async def test_function_response_headers_survive_the_rest_boundary(rest_url: str assert header(lines, "x-custom") == "custom-value" assert headers_named(lines, "set-cookie") == ["first=1; Path=/", "second=2; HttpOnly"] assert header(lines, "x-served-by") == "mercury" - assert header(lines, "x-stream-id") is None and header(lines, "x-ttl") is None + assert header(lines, "x-stream-id") is None + assert header(lines, "x-ttl") is None assert json.loads(body) == {"moved": True} @@ -596,8 +597,11 @@ async def test_get_with_path_query_and_generated_cid(rest_url: str): assert header(lines, "x-served-by") == "mercury" assert header(lines, "access-control-allow-origin") == "*" data = json.loads(body) - assert data["user"] == "eric" and data["q"] == "hello world" and data["method"] == "GET" - assert data["my_cid"] and data["my_cid"] == header(lines, "x-correlation-id") + assert data["user"] == "eric" + assert data["q"] == "hello world" + assert data["method"] == "GET" + assert data["my_cid"] + assert data["my_cid"] == header(lines, "x-correlation-id") async def test_response_echoes_inbound_correlation_id(rest_url: str): @@ -613,7 +617,8 @@ async def test_post_json_body(rest_url: str): '{"item":"book","qty":2}') assert status == 200 data = json.loads(body) - assert data["echo_body"] == {"item": "book", "qty": 2} and data["my_cid"] == "order-777" + assert data["echo_body"] == {"item": "book", "qty": 2} + assert data["my_cid"] == "order-777" async def test_body_dispatch_mirrors_the_content_type_rules(rest_url: str): @@ -624,15 +629,19 @@ async def probe_body(headers: dict[str, str], data: str) -> dict[str, Any]: assert (await probe_body({"Content-Type": "application/json"}, '{"item":"book"}'))["kind"] == "map" mislabelled = await probe_body({"Content-Type": "application/json"}, "import graph from tutorial-1") - assert mislabelled["kind"] == "text" and mislabelled["content"] == "import graph from tutorial-1" + assert mislabelled["kind"] == "text" + assert mislabelled["content"] == "import graph from tutorial-1" empty = await probe_body({"Content-Type": "application/json"}, "") - assert empty["kind"] == "map" and empty["content"] == {} + assert empty["kind"] == "map" + assert empty["content"] == {} unsniffed = await probe_body({"Content-Type": "text/plain"}, '{"item":"book"}') assert unsniffed["kind"] == "text" form = await probe_body({"Content-Type": "application/x-www-form-urlencoded"}, "a=1&b=hello+world") - assert form["kind"] == "null" and form["query"] == {"a": "1", "b": "hello world"} + assert form["kind"] == "null" + assert form["query"] == {"a": "1", "b": "hello world"} raw = await probe_body({}, '{"item":"book"}') - assert raw["kind"] == "bytes" and raw["content"] == '{"item":"book"}' + assert raw["kind"] == "bytes" + assert raw["content"] == '{"item":"book"}' async def test_unknown_path_is_the_engines_404(rest_url: str): @@ -644,16 +653,19 @@ async def test_unknown_path_is_the_engines_404(rest_url: str): async def test_entry_without_a_registered_service_is_skipped_at_start(rest_url: str): status, _, body = await http(f"{rest_url}/api/ghost") - assert status == 404 and json.loads(body)["message"] == "Resource not found" + assert status == 404 + assert json.loads(body)["message"] == "Resource not found" status, _, _ = await http(f"{rest_url}/api/echo/alice") assert status == 200 async def test_root_falls_back_to_the_index_html_entry(rest_url: str): status, _, body = await http(f"{rest_url}/index.html", headers={"Accept": "text/plain"}) - assert status == 200 and body == b"plain response" + assert status == 200 + assert body == b"plain response" status, _, root = await http(f"{rest_url}/", headers={"Accept": "text/plain"}) - assert status == 200 and root == body + assert status == 200 + assert root == body async def test_envelope_sets_status_and_headers(rest_url: str): @@ -665,10 +677,12 @@ async def test_envelope_sets_status_and_headers(rest_url: str): async def test_function_failure_is_the_standard_error_body(rest_url: str): status, lines, body = await http(f"{rest_url}/api/fail") - assert status == 404 and header(lines, "content-type") == "application/json" + assert status == 404 + assert header(lines, "content-type") == "application/json" assert json.loads(body) == {"status": 404, "message": "nothing here", "type": "error"} status, _, body = await http(f"{rest_url}/api/fail/json") - assert status == 409 and body == b'{"custom":true}' + assert status == 409 + assert body == b'{"custom":true}' async def test_cors_preflight_and_405_without_cors(rest_url: str): @@ -677,12 +691,14 @@ async def test_cors_preflight_and_405_without_cors(rest_url: str): assert header(lines, "access-control-allow-origin") == "*" assert "POST" in (header(lines, "access-control-allow-methods") or "") status, _, body = await http(f"{rest_url}/api/text", "OPTIONS") - assert status == 405 and json.loads(body)["message"] == "Method not allowed" + assert status == 405 + assert json.loads(body)["message"] == "Method not allowed" async def test_known_path_wrong_method_is_405(rest_url: str): status, _, body = await http(f"{rest_url}/api/text", "PUT") - assert status == 405 and json.loads(body)["message"] == "Method not allowed" + assert status == 405 + assert json.loads(body)["message"] == "Method not allowed" async def test_slow_function_times_out_as_408(rest_url: str): @@ -693,7 +709,8 @@ async def test_slow_function_times_out_as_408(rest_url: str): async def test_authentication_gate_and_session(rest_url: str): status, _, body = await http(f"{rest_url}/api/secure") - assert status == 401 and json.loads(body)["message"] == "Unauthorized" + assert status == 401 + assert json.loads(body)["message"] == "Unauthorized" status, _, body = await http(f"{rest_url}/api/secure", headers={"X-Api-Key": "open-sesame"}) assert status == 200 assert json.loads(body)["session"] == {"user": "demo"} @@ -701,7 +718,8 @@ async def test_authentication_gate_and_session(rest_url: str): status, _, _ = await http(f"{rest_url}/ops/info") assert status == 401 status, _, body = await http(f"{rest_url}/ops/info", headers={"X-Api-Key": "open-sesame"}) - assert status == 200 and "app" in json.loads(body) + assert status == 200 + assert "app" in json.loads(body) async def _wait_for(predicate: Callable[[], bool]) -> None: @@ -725,23 +743,33 @@ def seen() -> bool: await _wait_for(seen) edge = next(d["trace"] for d in probe.datasets if d["trace"]["service"] == "http.request") function = next(d["trace"] for d in probe.datasets if d["trace"]["service"] == "trace.probe") - assert edge["id"] == upstream_trace and edge["parent_span_id"] == upstream_span - assert edge["path"] == "GET /api/traced?flag=on" and edge["status"] == 200 and edge["success"] + assert edge["id"] == upstream_trace + assert edge["parent_span_id"] == upstream_span + assert edge["path"] == "GET /api/traced?flag=on" + assert edge["status"] == 200 + assert edge["success"] assert "from" not in edge - assert function["parent_span_id"] == edge["span_id"] and function["from"] == "http.request" - assert function["path"] == "GET /api/traced?flag=on" and "round_trip" in function + assert function["parent_span_id"] == edge["span_id"] + assert function["from"] == "http.request" + assert function["path"] == "GET /api/traced?flag=on" + assert "round_trip" in function async def test_content_negotiation(rest_url: str): status, lines, body = await http(f"{rest_url}/api/text", headers={"Accept": "text/plain"}) - assert status == 200 and header(lines, "content-type") == "text/plain" and body == b"plain response" + assert status == 200 + assert header(lines, "content-type") == "text/plain" + assert body == b"plain response" _, lines, body = await http(f"{rest_url}/api/text", headers={"Accept": "*/*"}) - assert header(lines, "content-type") == "application/json" and body == b"plain response" + assert header(lines, "content-type") == "application/json" + assert body == b"plain response" _, lines, body = await http(f"{rest_url}/api/echo/html?q=1", headers={"Accept": "text/html"}) assert header(lines, "content-type") == "text/html" - assert body.startswith(b"
\n") and body.endswith(b"\n
") + assert body.startswith(b"
\n")
+    assert body.endswith(b"\n
") _, lines, body = await http(f"{rest_url}/api/text") - assert header(lines, "content-type") is None and body == b"plain response" + assert header(lines, "content-type") is None + assert body == b"plain response" async def test_request_model_matches_the_engines_keys(rest_url: str): @@ -749,11 +777,15 @@ async def test_request_model_matches_the_engines_keys(rest_url: str): "X-Forwarded-Proto": "https"}) assert status == 200 data = json.loads(body) - assert data["q"] == ["a", "b"] and data["single"] == "1" - assert data["cookie_first"] == "alpha" and data["cookie_second"] == "beta" + assert data["q"] == ["a", "b"] + assert data["single"] == "1" + assert data["cookie_first"] == "alpha" + assert data["cookie_second"] == "beta" assert "cookie_header" not in data # a null entry is omitted from the JSON - assert data["query"] == "q=a&q=b&single=1" and data["https"] is True - assert data["ip"] == "127.0.0.1" and data["timeout"] == 30 + assert data["query"] == "q=a&q=b&single=1" + assert data["https"] is True + assert data["ip"] == "127.0.0.1" + assert data["timeout"] == 30 async def test_wildcard_grammar(rest_url: str): @@ -769,20 +801,25 @@ async def test_traceparent_header_names(rest_url: str, probe: Probe): # the custom global name (http.traceparent.header) delivers the context when the standard is absent custom = "1af92f3577b34da6a3ce929d0e0e4701" await http(f"{rest_url}/api/traced", headers={"X-Trace-Context": f"00-{custom}-00f067aa0ba902b7-01"}) - assert probe.trace is not None and probe.trace[0] == custom + assert probe.trace is not None + assert probe.trace[0] == custom # the standard traceparent wins over the custom name standard = "3af92f3577b34da6a3ce929d0e0e4703" await http(f"{rest_url}/api/traced", headers={"X-Trace-Context": "00-2af92f3577b34da6a3ce929d0e0e4702-00f067aa0ba902b7-01", "traceparent": f"00-{standard}-00f067aa0ba902b8-01"}) - assert probe.trace is not None and probe.trace[0] == standard + assert probe.trace is not None + assert probe.trace[0] == standard # the per-endpoint override beats the global name endpoint = "5af92f3577b34da6a3ce929d0e0e4705" await http(f"{rest_url}/api/renamed/traceparent/probe", headers={"X-Endpoint-Trace": f"00-{endpoint}-00f067aa0ba902b7-01", "X-Trace-Context": "00-6af92f3577b34da6a3ce929d0e0e4706-00f067aa0ba902b8-01"}) - assert probe.trace is not None and probe.trace[0] == endpoint + assert probe.trace is not None + assert probe.trace[0] == endpoint # no header at all: a fresh trace id, 32 hex await http(f"{rest_url}/api/traced") - assert probe.trace is not None and probe.trace[0] is not None and len(probe.trace[0]) == 32 + assert probe.trace is not None + assert probe.trace[0] is not None + assert len(probe.trace[0]) == 32 async def test_endpoint_timeout_rides_the_dataset_as_x_ttl(rest_url: str): @@ -808,7 +845,8 @@ async def test_stream_renders_server_sent_events(rest_url: str): async def test_stream_renders_chunked_text_without_sse(rest_url: str): # the head's content type wins over Accept: an SSE head stays SSE under */* status, lines, _ = await http(f"{rest_url}/api/stream", "POST", {"Accept": "*/*"}) - assert status == 200 and header(lines, "content-type") == "text/event-stream" + assert status == 200 + assert header(lines, "content-type") == "text/event-stream" # a JSON head renders chunked: text verbatim, a structure as one JSON line, no done frame status, lines, body = await http(f"{rest_url}/api/stream/lines", "POST", {"Accept": "*/*"}) assert status == 200 @@ -831,8 +869,10 @@ async def test_a_client_that_leaves_a_stream_is_noticed_at_the_next_keep_alive(r app_config().set("event.stream.keep.alive", "200ms") async with aiohttp.ClientSession() as session: response = await session.get(f"{rest_url}/api/stream/hold") - assert response.status == 200 and response.headers["content-type"] == "text/event-stream" - assert probe.registry is not None and len(probe.registry.bus._sinks) == 1 + assert response.status == 200 + assert response.headers["content-type"] == "text/event-stream" + assert probe.registry is not None + assert len(probe.registry.bus._sinks) == 1 response.close() # the client leaves without reading await asyncio.sleep(1.0) assert probe.disconnected == 1, "the producer learnt that nobody listens" @@ -861,7 +901,8 @@ async def test_default_entries_serve_the_host_paths(rest_url: str): reply = EventEnvelope.from_bytes(await response.read()) assert reply.body == "plain response" status, _, body = await http(f"{rest_url}/info") - assert status == 200 and "app" in json.loads(body) + assert status == 200 + assert "app" in json.loads(body) status, _, _ = await http(f"{rest_url}/livenessprobe") assert status == 200 @@ -895,7 +936,8 @@ async def test_user_entry_overrides_a_default_and_adds_cors(tmp_path: Path, prob assert response.status == 200 assert response.headers.get("Access-Control-Allow-Origin") == "*" status, lines, _ = await http(f"{base}/api/event", "OPTIONS") - assert status == 204 and header(lines, "access-control-allow-origin") == "*" + assert status == 204 + assert header(lines, "access-control-allow-origin") == "*" # the other defaults are still merged status, _, _ = await http(f"{base}/health") assert status == 200 @@ -907,7 +949,8 @@ async def test_rest_automation_off_leaves_the_host_unchanged(tmp_path: Path, pro assert EventApiServer(registry).rest is None async with serve(registry) as base: status, _, body = await http(f"{base}/api/echo/eric") - assert status == 404 and json.loads(body)["message"] == "Resource not found" + assert status == 404 + assert json.loads(body)["message"] == "Resource not found" async def test_missing_rest_yaml_serves_the_defaults_only(tmp_path: Path, probe: Probe, serve: Serve): @@ -924,8 +967,9 @@ async def test_missing_rest_yaml_serves_the_defaults_only(tmp_path: Path, probe: def test_invalid_rest_yaml_fails_the_start(tmp_path: Path, probe: Probe): with configured(tmp_path, "rest:\n - service: http.flow.adapter\n flow: demo\n methods: ['GET']\n url: /x\n"): + registry = build_registry(probe) with pytest.raises(AppException) as raised: - EventApiServer(build_registry(probe)) + EventApiServer(registry) assert "flow binding is not available in a language pack" in raised.value.message @@ -934,7 +978,8 @@ def test_file_location_forms(tmp_path: Path, probe: Probe): write(elsewhere, "rest:\n - service: plain.text\n methods: ['GET']\n url: /elsewhere\n") with configured(tmp_path, None, {"yaml.rest.automation": f"file:{elsewhere}"}): server = EventApiServer(build_registry(probe)) - assert server.rest is not None and server.rest.table.has_url("/elsewhere") + assert server.rest is not None + assert server.rest.table.has_url("/elsewhere") EXTENSION_YAML = """\ @@ -972,7 +1017,8 @@ def mount(app: web.Application) -> None: _, _, body = await http(f"{base}/ext/free") assert body == b"extension free" status, _, body = await http(f"{base}/about.html") - assert status == 200 and body == b"

about

" + assert status == 200 + assert body == b"

about

" finally: await runner.cleanup() @@ -1008,38 +1054,48 @@ async def http_filter(_headers: dict[str, str], body: Body): registry.register("http.request.filter", http_filter) async with serve(registry) as base: status, lines, body = await http(f"{base}/about.html") - assert status == 200 and body == b"

about

" + assert status == 200 + assert body == b"

about

" assert header(lines, "x-filter") == "demo" - assert header(lines, "etag") is not None and header(lines, "pragma") is None - assert seen[-1]["method"] == "GET" and seen[-1]["url"] == "/about.html" - assert seen[-1]["body"] is None and "headers" in seen[-1] + assert header(lines, "etag") is not None + assert header(lines, "pragma") is None + assert seen[-1]["method"] == "GET" + assert seen[-1]["url"] == "/about.html" + assert seen[-1]["body"] is None + assert "headers" in seen[-1] status, lines, _ = await http(f"{base}/style.css") - assert status == 200 and header(lines, "x-filter") is None + assert status == 200 + assert header(lines, "x-filter") is None status, lines, body = await http(f"{base}/private/page.html") - assert status == 302 and header(lines, "location") == "/login" and body == b"" + assert status == 302 + assert header(lines, "location") == "/login" + assert body == b"" status, lines, body = await http(f"{base}/") - assert status == 200 and body == b"

bundle

" + assert status == 200 + assert body == b"

bundle

" assert header(lines, "cache-control") == "no-cache, no-store" assert header(lines, "pragma") == "no-cache" assert header(lines, "expires") == "Thu, 01 Jan 1970 00:00:00 GMT" status, _, body = await http(f"{base}/api/text", headers={"Accept": "text/plain"}) - assert status == 200 and body == b"plain response" + assert status == 200 + assert body == b"plain response" status, _, body = await http(f"{base}/missing.html") - assert status == 404 and json.loads(body)["message"] == "Resource not found" + assert status == 404 + assert json.loads(body)["message"] == "Resource not found" -def test_cors_lines_resolve_configuration_references(tmp_path: Path, probe: Probe): - os.environ["REST_TEST_ORIGIN"] = "https://app.example" - try: - yaml_text = REST_YAML.replace("${api.origin:*}", "${REST_TEST_ORIGIN:*}") - with configured(tmp_path, yaml_text): - server = EventApiServer(build_registry(probe)) - assert server.rest is not None - entry = server.rest.table.find("GET", "/api/echo/x") - assert entry is not None and entry.info.cors is not None - assert entry.info.cors.headers == [("Access-Control-Allow-Origin", "https://app.example")] - finally: - del os.environ["REST_TEST_ORIGIN"] +def test_cors_lines_resolve_configuration_references( + tmp_path: Path, probe: Probe, monkeypatch: pytest.MonkeyPatch +): + monkeypatch.setenv("REST_TEST_ORIGIN", "https://app.example") + yaml_text = REST_YAML.replace("${api.origin:*}", "${REST_TEST_ORIGIN:*}") + with configured(tmp_path, yaml_text): + server = EventApiServer(build_registry(probe)) + assert server.rest is not None + entry = server.rest.table.find("GET", "/api/echo/x") + assert entry is not None + assert entry.info.cors is not None + assert entry.info.cors.headers == [("Access-Control-Allow-Origin", "https://app.example")] # ---- upload: the bounded form of the engines' streaming upload ---- @@ -1072,7 +1128,8 @@ async def test_multipart_upload_delivers_the_files_and_the_fields(rest_url: str) "sha256": hashlib.sha256(PNG_BYTES).hexdigest()}, ] assert data["query"] == {"note": "hello world"} - assert data["size"] == len(PDF_BYTES) + len(PNG_BYTES) and data["is_file"] is True + assert data["size"] == len(PDF_BYTES) + len(PNG_BYTES) + assert data["is_file"] is True assert data["body_present"] is False @@ -1081,14 +1138,17 @@ async def test_a_json_post_to_an_upload_entry_dispatches_as_usual(rest_url: str) '{"a": 1}') assert status == 200 data = json.loads(body) - assert data["files"] == [] and data["is_file"] is False and data["body_present"] is True + assert data["files"] == [] + assert data["is_file"] is False + assert data["body_present"] is True async def test_multipart_to_an_entry_without_upload_is_bytes(rest_url: str): status, body = await post_form(f"{rest_url}/api/probe", _form()) assert status == 200 data = json.loads(body) - assert data["kind"] == "bytes" and "report.pdf" in data["content"] + assert data["kind"] == "bytes" + assert "report.pdf" in data["content"] async def test_an_upload_over_the_bound_is_413(tmp_path: Path, probe: Probe, serve: Serve): diff --git a/tests/test_static_content.py b/tests/test_static_content.py index fb6d588..b172956 100644 --- a/tests/test_static_content.py +++ b/tests/test_static_content.py @@ -200,7 +200,8 @@ async def hello(_request: web.Request) -> web.Response: async with serve_with_routes(FunctionRegistry(), mount) as base: status, payload = await fetch_json(f"{base}/info") assert status == 200 - assert isinstance(payload, dict) and "app" in payload # the actuator, not public/info + assert isinstance(payload, dict) + assert "app" in payload status, _, body = await fetch(f"{base}/hello") assert (status, body) == (200, b"the route") # the extension, not public/hello diff --git a/tests/test_transcript_audit.py b/tests/test_transcript_audit.py index d4d20fb..964e403 100644 --- a/tests/test_transcript_audit.py +++ b/tests/test_transcript_audit.py @@ -86,11 +86,11 @@ def _configure(monkeypatch: pytest.MonkeyPatch, **settings: str) -> dict[str, st async def _first_turn( - monkeypatch: pytest.MonkeyPatch, config: dict[str, str], headers: dict[str, str] = _HEADERS + monkeypatch: pytest.MonkeyPatch, config: dict[str, str], headers: dict[str, str] | None = None ) -> str: """The first turn: the model asks for the tool. The conversation reference.""" _install_backend(monkeypatch, _FakeClient(_TURN), config) - reply = await helper.llm_chat(headers, {**_PROMPT_BODY}) + reply = await helper.llm_chat(_HEADERS if headers is None else headers, {**_PROMPT_BODY}) return str(reply["conversation"]) @@ -148,7 +148,9 @@ async def test_a_turn_saves_its_facts_inside_the_compare_and_set( "x-node": "assistant"}) await _closing_turn(monkeypatch, config, conversation, retention="1h") record = await store.load(conversation) - assert record is not None and record.closed and record.retention == 3600 + assert record is not None + assert record.closed + assert record.retention == 3600 assert (record.correlation_id, record.graph_id, record.node) == ( "corr-1", "order-assistant", "assistant", ) # fmt: skip @@ -172,11 +174,14 @@ async def test_a_turn_saves_its_facts_inside_the_compare_and_set( assert (second["request_id"], second["messages"]) == ("req_done", [2, 3]) assert second["usage"]["cache_read_input_tokens"] == 30 for stamp in (first["started_at"], first["ended_at"], second["started_at"]): - assert len(stamp) == 24 and stamp.endswith("Z"), stamp # ISO-8601 UTC, milliseconds + assert len(stamp) == 24, stamp + assert stamp.endswith("Z"), stamp # ISO-8601 UTC, milliseconds assert first["started_at"] <= first["ended_at"] <= second["started_at"] <= second["ended_at"] # the messages the indexes point at: the prompt and the answer, the results and the answer - assert record.messages[0] == _PROMPT and record.messages[1]["role"] == "assistant" - assert record.messages[2] == _RESULT_MESSAGE and record.messages[3]["role"] == "assistant" + assert record.messages[0] == _PROMPT + assert record.messages[1]["role"] == "assistant" + assert record.messages[2] == _RESULT_MESSAGE + assert record.messages[3]["role"] == "assistant" async def test_a_direct_call_records_the_header_view_and_no_trace( @@ -224,7 +229,9 @@ async def test_a_turn_sends_its_write_and_a_closing_turn_the_check_behind_it( ] assert store._records[conversation][0] - clock.now == 86400, "the grace (1d), not retention 0" record = await store.load(conversation) - assert record is not None and record.closed and record.retention == 0 + assert record is not None + assert record.closed + assert record.retention == 0 async def test_the_grace_is_configurable_and_a_cut_off_turn_waits_for_its_check_too( @@ -238,7 +245,8 @@ async def test_the_grace_is_configurable_and_a_cut_off_turn_waits_for_its_check_ cut_off = {**_TURN, "stop_reason": "max_tokens", "content": [{"type": "text", "text": "Th"}]} _install_backend(monkeypatch, _FakeClient(cut_off), config) reply = await helper.llm_chat(_HEADERS, {**_PROMPT_BODY}) - assert reply["status"] == "cap" and reply["cap"] == "max_tokens" + assert reply["status"] == "cap" + assert reply["cap"] == "max_tokens" conversation = reply["conversation"] assert sent.events == [{"conversation": conversation, "turn": 1}, {"conversation": conversation, "check": True}] # fmt: skip @@ -404,7 +412,8 @@ async def test_a_failed_write_is_logged_by_type_and_the_check_repairs_it_before_ assert f"transcript.audit conversation={conversation} write failed - _RowError sqlstate=23514" in ( caplog.text ) - assert "SECRET-MARKER" not in caplog.text and "Failing row" not in caplog.text + assert "SECRET-MARKER" not in caplog.text + assert "Failing row" not in caplog.text assert await store.audited(conversation) == 0 await _closing_turn(monkeypatch, _CONFIG, conversation) await helper.transcript_audit({}, {"conversation": conversation, "turn": 2}) @@ -455,7 +464,8 @@ async def test_a_check_never_releases_an_open_record(monkeypatch: pytest.MonkeyP # the run goes on: the later turn is accepted over the audited record await _closing_turn(monkeypatch, _CONFIG, conversation) record = await store.load(conversation) - assert record is not None and record.turn == 2 + assert record is not None + assert record.turn == 2 async def test_a_record_that_is_gone_or_from_before_version_2_is_handled_by_name( @@ -479,7 +489,8 @@ async def test_a_record_that_is_gone_or_from_before_version_2_is_handled_by_name assert await store.save(old, 0, version_1, 600) await helper.transcript_audit({}, {"conversation": old, "check": True}) assert f"conversation={old} turn(s) 1 carry no facts - unaudited" in caplog.text - assert audit.conversations[old]["status"] == "open" and audit.turn_rows[old] == {} + assert audit.conversations[old]["status"] == "open" + assert audit.turn_rows[old] == {} assert await store.audited(old) == 1, "nothing more can be done for it" assert "INPUT-MARKER" not in caplog.text @@ -530,7 +541,8 @@ async def test_the_sweep_sends_a_check_for_every_record_whose_audit_lags( assert sent.events == [{"conversation": behind, "check": True}] assert gone not in store._records await store.mark_audited(behind, 1) - assert await helper.audit_sweep() == 0 and len(sent.events) == 1 + assert await helper.audit_sweep() == 0 + assert len(sent.events) == 1 # --- the audited mark in the Redis working store --------------------------------------------- @@ -688,8 +700,10 @@ async def test_a_null_json_column_stays_null() -> None: store = helper.PostgresAuditStore(pool) row = {**_turn_row("d" * 32), "calls": None} await store.write({**_conversation_row("d" * 32), "tools": None}, [row]) - assert pool.log[1][1] is not None and pool.log[1][1][-1] is None, "tools NULL" - assert pool.log[2][1] is not None and pool.log[2][1][-1] is None, "calls NULL" + assert pool.log[1][1] is not None, "tools NULL" + assert pool.log[1][1][-1] is None, "tools NULL" + assert pool.log[2][1] is not None, "calls NULL" + assert pool.log[2][1][-1] is None, "calls NULL" def test_the_postgres_store_is_built_from_its_connection_keys( @@ -756,7 +770,8 @@ def test_an_audit_store_that_is_not_configured_or_unknown_is_named( assert helper.audit_configured() is False with pytest.raises(AppException) as raised: helper.get_audit_store() - assert raised.value.status == 503 and "llm.transcript.audit" in raised.value.message + assert raised.value.status == 503 + assert "llm.transcript.audit" in raised.value.message monkeypatch.setattr(helper, "_prop", lambda key, default=None: "mongo" if "audit" in key else default) with pytest.raises(AppException) as raised: helper.get_audit_store() @@ -777,16 +792,20 @@ async def test_the_boot_registers_the_function_once_opens_the_store_and_starts_t caplog.set_level(logging.INFO) await helper.audit_boot() service = helper.default_registry.get(helper.AUDIT_ROUTE) - assert service is not None and service.instances == 1 and service.private + assert service is not None + assert service.instances == 1 + assert service.private assert service.handler is helper.transcript_audit assert pool.opened == (True, 5.0) assert "transcript audit store postgres ready" in caplog.text task = helper._sweep_task - assert task is not None and not task.done() + assert task is not None + assert not task.done() await helper.audit_boot() # again: one registration, one sweep assert helper._sweep_task is task await helper.audit_shutdown() - assert helper._sweep_task is None and task.cancelled() + assert helper._sweep_task is None + assert task.cancelled() assert pool.closed @@ -918,13 +937,17 @@ async def test_the_rows_land_on_a_live_postgres(monkeypatch: pytest.MonkeyPatch) assert head is not None assert head[:10] == ("done", 2, "order-assistant", "assistant", "corr-live", 100, 21, 30, 30, "Be brief.") # fmt: skip - assert head[10] == [_TOOL] and head[11] is True + assert head[10] == [_TOOL] + assert head[11] is True assert head[12].days == 365 assert [(t[0], t[1], t[2], t[3]) for t in turns] == [ (1, _TRACE_ID, "tool_use", "tool_use"), (2, _TRACE_ID, "done", "end_turn"), ] # fmt: skip - assert turns[0][4] == [_PROMPT] and turns[0][5] == _TURN["content"] and turns[0][6] == _CALLS - assert turns[1][4] == [_RESULT_MESSAGE] and turns[1][6] is None + assert turns[0][4] == [_PROMPT] + assert turns[0][5] == _TURN["content"] + assert turns[0][6] == _CALLS + assert turns[1][4] == [_RESULT_MESSAGE] + assert turns[1][6] is None assert by_trace == (2,) finally: if conversation is not None: @@ -979,7 +1002,8 @@ async def recording(event: dict[str, Any]) -> None: monkeypatch.setattr(helper, "_audit_send", recording) - async def settled(self, done: Any) -> None: + @staticmethod + async def settled(done: Any) -> None: """Wait for the saves in flight, then for the mailbox to reach ``done()``.""" await helper.audit_single_idle() for _ in range(400): @@ -1011,7 +1035,8 @@ async def _single_call(case: dict[str, Any], monkeypatch: pytest.MonkeyPatch) -> if "error" in wanted: _assert_error(out.error, wanted["error"]) else: - assert out.error is None and out.segments == wanted["frames"] + assert out.error is None + assert out.segments == wanted["frames"] return try: result = await helper.llm_chat(headers, case["body"]) @@ -1041,12 +1066,15 @@ async def test_single_call_audit_contract( if expect["conversation"] is None: await rig.settled(lambda: True) assert expect["turn"] is None - assert rig.events == [] and rig.store._records == {} - assert rig.audit.conversations == {} and rig.audit.turn_rows == {} + assert rig.events == [] + assert rig.store._records == {} + assert rig.audit.conversations == {} + assert rig.audit.turn_rows == {} return await rig.settled(lambda: bool(rig.audit.conversations) and not rig.store._records) ((conversation, row),) = rig.audit.conversations.items() - assert _REFERENCE.fullmatch(conversation) and row["conversation"] == conversation + assert _REFERENCE.fullmatch(conversation) + assert row["conversation"] == conversation assert rig.events == [{"conversation": conversation, "check": True}] assert set(rig.audit.turn_rows[conversation]) == {1} turn = rig.audit.turn_rows[conversation][1] @@ -1086,13 +1114,16 @@ async def save(self, conversation: str, expected: int, record: Any, ttl_s: int) _install_backend(monkeypatch, _FakeClient(_ANSWER), _SINGLE) reply = await asyncio.wait_for(helper.llm_chat({}, {"prompt": "hello"}), timeout=1) assert reply["text"] == "REPLY-MARKER-1" - assert len(helper._single_saves) == 1 and rig.events == [] and not rig.audit.conversations + assert len(helper._single_saves) == 1 + assert rig.events == [] + assert not rig.audit.conversations shutdown = asyncio.get_running_loop().create_task(helper.audit_shutdown()) await asyncio.sleep(0.02) assert not shutdown.done(), "the shutdown waits for the save in flight" gate.set() await shutdown - assert not helper._single_saves and len(rig.events) == 1 + assert not helper._single_saves + assert len(rig.events) == 1 finally: await rig.close() @@ -1108,14 +1139,16 @@ async def test_a_working_store_that_fails_is_logged_by_type_and_never_refuses_th _install_backend(monkeypatch, _FakeClient(_ANSWER), _SINGLE) reply = await helper.llm_chat({}, {"prompt": "PROMPT-MARKER-1"}) await rig.settled(lambda: True) - assert reply["text"] == "REPLY-MARKER-1" and rig.events == [] + assert reply["text"] == "REPLY-MARKER-1" + assert rig.events == [] assert "transcript.audit single call not saved - ConnectionError" in caplog.text monkeypatch.setattr(helper, "_store", None) # and with no working store at all _install_backend(monkeypatch, _FakeClient(_ANSWER), {**_SINGLE, "llm.transcript.store": ""}) assert (await helper.llm_chat({}, {"prompt": "PROMPT-MARKER-1"}))["text"] == "REPLY-MARKER-1" await rig.settled(lambda: True) assert "single call not saved - AppException: transcript store not configured" in caplog.text - assert rig.events == [] and not rig.audit.conversations + assert rig.events == [] + assert not rig.audit.conversations assert "REPLY-MARKER-1" not in caplog.text assert caplog.text.count("PROMPT-MARKER-1") == 1, "only the store's own connection error" finally: @@ -1137,7 +1170,8 @@ async def test_a_failed_write_keeps_the_record_and_the_sweep_repairs_it( await rig.settled(lambda: "check failed" in caplog.text) ((conversation, entry),) = rig.store._records.items() assert entry[0] - clock.now == 86400, "the record waits with the audit's grace (1d)" - assert not rig.audit.conversations and await rig.store.unaudited() == [conversation] + assert not rig.audit.conversations + assert await rig.store.unaudited() == [conversation] assert f"conversation={conversation} check failed - _RowError sqlstate=23514" in caplog.text assert await helper.audit_sweep() == 1 await rig.settled(lambda: not rig.store._records)