Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
153 changes: 94 additions & 59 deletions extensions/agent-question/agent_question.py

Large diffs are not rendered by default.

1,025 changes: 616 additions & 409 deletions extensions/agent-tools/agent_tools.py

Large diffs are not rendered by default.

164 changes: 97 additions & 67 deletions extensions/ask-person/ask_person.py

Large diffs are not rendered by default.

86 changes: 55 additions & 31 deletions extensions/llm-helper/llm_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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]:
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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


Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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)
Expand All @@ -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",
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion src/mercury_composable/async_http_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)``.
"""
Expand Down
Loading
Loading