Skip to content

refactor(daemon): table-drive route contract coverage (#1847) - #2158

Merged
Sinity merged 2 commits into
masterfrom
feature/refactor/daemon-route-contracts-1847
Jun 19, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/refactor/daemon-route-contracts-1847

Conversation

@Sinity

@Sinity Sinity commented Jun 19, 2026 •

Copy link
Copy Markdown
Owner

Summary

Refactors the daemon HTTP route boundary so implemented route patterns are exposed from the routing tables used at runtime, then checks those live routes against ROUTE_CONTRACTS in both directions. This keeps #1847's route-class/auth/payload metadata from drifting away from the dispatcher while preserving the existing auth behavior.

Problem

#1847 already had route-contract metadata and route/security tests, but the daemon dispatcher still carried most routes in an ad hoc conditional chain. The security matrix derived from ROUTE_CONTRACTS, so a newly implemented route could still skip classification if a future edit touched dispatch but forgot the metadata. That weakens the web/API boundary exactly where #1847 is trying to make it explicit.

Solution

  • Move authenticated daemon GET dispatch into static and parameterized route tables in polylogue/daemon/http.py.
  • Move durable user-state HTTP dispatch into a UserStateRoute table in polylogue/daemon/user_state_http.py.
  • Expose implemented_daemon_route_patterns() from the live dispatcher tables and compare it against ROUTE_CONTRACTS in both directions.
  • Preserve the existing empty-parameter behavior for user-state parameterized routes: empty :id segments do not route.
  • Update daemon docs and route-contract module text to describe the checked dispatcher/contract relationship.

Verification

  • devtools test tests/unit/daemon/test_route_contracts.py tests/unit/daemon/test_daemon_http_security.py tests/unit/daemon/test_web_reader.py -k 'route_contract or auth or cross_origin or read_view_execution or recovery_endpoint or assertions_endpoint' -> 324 passed, 197 deselected.
  • Initial devtools verify --seed-testmon --skip-slow caught a route-table regression: tests/unit/daemon/test_user_state_http.py::TestDispatchRouting::test_empty_id_in_get_path_does_not_route failed because empty :id matched. Fixed the matcher.
  • devtools test tests/unit/daemon/test_user_state_http.py::TestDispatchRouting::test_empty_id_in_get_path_does_not_route tests/unit/daemon/test_route_contracts.py tests/unit/daemon/test_daemon_http_security.py -> 404 passed.
  • devtools verify --quick -> exit_code: 0.
  • devtools verify --seed-testmon --skip-slow -> 11493 passed, 1 xfailed, exit_code: 0, peak pytest RSS 3419.1 MiB.
  • devtools verify -> 7 passed, exit_code: 0.

Summary by CodeRabbit

Release Notes

  • Refactor
    • Reworked daemon HTTP request routing to use table-driven, pattern-based dispatch for GET/POST endpoints, improving consistency across authentication, observability, and route handling.
  • Tests
    • Added unit tests that verify route-contract metadata stays perfectly synchronized with the live implemented route patterns (no missing or stale entries).
  • Documentation
    • Updated routing documentation to explain the separation between implemented dispatcher patterns and validated route-contract security/response posture.

Problem: #1847 had route-contract metadata, but the daemon dispatcher still kept most implemented routes in ad hoc conditionals. Tests derived auth coverage from ROUTE_CONTRACTS, so a new implemented route could still skip classification if the dispatcher and metadata drifted apart.\n\nWhat changed: authenticated daemon GET routes now dispatch through static and parameterized route tables that expose implemented route patterns. User-state HTTP routing now uses the same table-shaped model. Route-contract tests compare the live dispatcher patterns against ROUTE_CONTRACTS in both directions, and docs describe the checked relationship.\n\nVerification: devtools test tests/unit/daemon/test_user_state_http.py::TestDispatchRouting::test_empty_id_in_get_path_does_not_route tests/unit/daemon/test_route_contracts.py tests/unit/daemon/test_daemon_http_security.py -> 404 passed. devtools verify --quick -> exit_code 0. devtools verify --seed-testmon --skip-slow -> 11493 passed, 1 xfailed, exit_code 0.
@coderabbitai

coderabbitai Bot commented Jun 19, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 45ecfa4c-1e50-4f51-9ac2-1326d54a4e9c

📥 Commits

Reviewing files that changed from the base of the PR and between 2273437 and 050e456.

📒 Files selected for processing (2)
  • polylogue/daemon/http.py
  • tests/unit/daemon/test_route_contracts.py

📝 Walkthrough

Walkthrough

Replaces if/elif GET path dispatch chains in polylogue/daemon/http.py and user_state_http.py with structured route tables using dataclasses and helper functions. Introduces implemented_daemon_route_patterns() as a public API exposing all GET and POST route patterns. Adds bidirectional tests verifying that ROUTE_CONTRACTS metadata exactly matches live dispatcher patterns, preventing auth and response-posture drift. Updates documentation and docstrings to reflect the routing-table versus contract-metadata split.

Changes

Table-driven HTTP routing and route-contract enforcement

Layer / File(s) Summary
Route type definitions, table helpers, and implemented_daemon_route_patterns
polylogue/daemon/http.py, polylogue/daemon/user_state_http.py, polylogue/daemon/route_contracts.py
Adds RouteMethod literal type and UserStateRoute dataclass in user_state_http.py with pattern-matching and identifier-extraction helpers; adds _StaticGetRoute, _ParameterizedGetRoute, and _StaticPostRoute dataclasses in http.py plus enumerators _static_get_routes(), _parameterized_get_routes(), _observability_post_routes(), _authenticated_post_routes(); exposes implemented_daemon_route_patterns() aggregating GET and POST patterns; updates route_contracts.py docstring to reference live-pattern verification; adjusts imports in http.py.
Table-driven dispatch in user_state_http.py
polylogue/daemon/user_state_http.py
Introduces _routes() to enumerate supported HTTP endpoints and _dispatch() to iterate the route table and invoke _handle_user_state with extracted identifier, params, or no extra arg per route configuration; refactors dispatch_get, dispatch_post, dispatch_delete into thin wrappers delegating to _dispatch().
Table-driven dispatch in http.py
polylogue/daemon/http.py
Replaces _dispatch_get large if/elif chain with table-driven static-segment matching first, then fallback to workspace/user_state dispatchers, then parameterized-route matching by prefix/suffix and identifier extraction, ending with 404 not_found. Refactors _do_post_impl POST handling to use route tables for OTLP receiver and authenticated daemon endpoints, replacing explicit path checks while preserving observability_enabled gating and auth enforcement.
Route-contract validation tests and documentation
tests/unit/daemon/test_route_contracts.py, docs/daemon.md
Adds test_implemented_daemon_routes_have_contract_metadata and test_route_contract_metadata_targets_live_daemon_routes asserting bidirectional set equality between ROUTE_CONTRACTS and implemented_daemon_route_patterns(); updates docs/daemon.md to describe the runtime routing table versus durable contract metadata split and test-driven verification of consistency.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

  • Stabilize web API DTOs and local auth boundary #1847: The structured route tables, implemented_daemon_route_patterns() public API, and bidirectional contract validation tests directly support the route stabilization and explicit auth/response-posture classification goals.

Possibly related PRs

  • Sinity/polylogue#1128: Modifies DaemonAPIHandler GET dispatch in polylogue/daemon/http.py for /api/events and /api/status endpoint routing, overlapping with this PR's table-driven refactor of the same _dispatch_get code path.

Poem

🐇 Routes once tangled in if-elif chains,
Now table-driven, no more pains!
Static and parameterized patterns align,
With contracts that verify at design time.
The dispatcher marches, tests stand guard—
Clean routing made simple, not hard! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: refactoring daemon HTTP routes into table-driven patterns with contract coverage validation.
Description check ✅ Passed The description follows the template structure with Summary, Problem, Solution, and Verification sections covering the refactoring scope, rationale, implementation details, and comprehensive test results.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/refactor/daemon-route-contracts-1847

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

github-actions Bot pushed a commit that referenced this pull request Jun 19, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@polylogue/daemon/http.py`:
- Around line 191-207: The POST route patterns are currently hardcoded in two
separate locations: the routes list in `implemented_daemon_route_patterns()` and
the actual POST matching logic in `_do_post_impl()`. This duplication creates a
maintenance gap where routes can drift out of sync. Extract the POST route
definitions into a shared constant or class-level data structure (e.g., a list
of tuples containing the POST endpoints) that both `_do_post_impl()` and the
routes list in `implemented_daemon_route_patterns()` can reference, ensuring a
single source of truth for all POST route patterns.
- Around line 11-16: Fix the 8 mypy --strict errors across the polylogue
directory: In machine_main.py at line 117, remove the redundant condition
causing the error. In gateway.py at line 174, add explicit return type
annotations instead of returning Any. In sqlite_vec_embeddings.py at line 42,
add proper type annotations to the untyped decorator. In registry.py at line 61,
provide missing or correct type arguments to fix the type-arg error. In
raw_state.py at lines 217 and 248, add explicit return type annotations to avoid
no-any-return violations. In query_output_contracts.py at line 78, add explicit
return type annotations to fix the no-any-return error. In
click_option_groups.py at line 47, remove the unused type: ignore comment.
Ensure all changes pass mypy --strict validation before merging.

In `@tests/unit/daemon/test_route_contracts.py`:
- Around line 30-40: The tests convert the result of
implemented_daemon_route_patterns() to a set before comparison, which masks any
duplicate route pairs in the actual implementation since sets automatically
remove duplicates. Add an explicit assertion that checks for uniqueness in the
raw sequence returned by implemented_daemon_route_patterns() before converting
it to a set. This assertion should verify that the length of the raw sequence
equals the length of the set, or compare the sequence to its set representation
to catch accidental duplicate (method, pattern) entries in both
test_route_contract_no_stale_docs and
test_route_contract_metadata_targets_live_daemon_routes functions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 6d3713b4-7fb4-4b68-a9c8-b707076d22d6

📥 Commits

Reviewing files that changed from the base of the PR and between e62a2d9 and 2273437.

📒 Files selected for processing (5)
  • docs/daemon.md
  • polylogue/daemon/http.py
  • polylogue/daemon/route_contracts.py
  • polylogue/daemon/user_state_http.py
  • tests/unit/daemon/test_route_contracts.py

Comment thread polylogue/daemon/http.py
Comment on lines +11 to +16
from dataclasses import dataclass, replace
from datetime import datetime
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path, PurePath
from typing import TYPE_CHECKING, Any, cast
from typing import TYPE_CHECKING, Any, Literal, cast

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

targets=()
for d in polylogue tests devtools; do
  if [ -d "$d" ]; then
    targets+=("$d")
  fi
done

ruff format --check "${targets[@]}"
ruff check "${targets[@]}"
mypy --strict "${targets[@]}"

Repository: Sinity/polylogue

Length of output: 183


🏁 Script executed:

pip install mypy --quiet && \
mypy --strict polylogue tests devtools 2>&1 | head -100

Repository: Sinity/polylogue

Length of output: 739


🏁 Script executed:

/home/jailuser/.local/bin/mypy --strict polylogue tests devtools 2>&1 | head -150

Repository: Sinity/polylogue

Length of output: 21275


🏁 Script executed:

/home/jailuser/.local/bin/mypy --strict polylogue/daemon/http.py && \
cat -n polylogue/daemon/http.py | head -30

Repository: Sinity/polylogue

Length of output: 1037


🏁 Script executed:

cat -n polylogue/daemon/http.py | head -30

Repository: Sinity/polylogue

Length of output: 1268


🏁 Script executed:

/home/jailuser/.local/bin/mypy --strict polylogue/daemon/http.py 2>&1 | grep "polylogue/daemon/http.py"

Repository: Sinity/polylogue

Length of output: 42


🏁 Script executed:

/home/jailuser/.local/bin/mypy --strict polylogue/daemon/http.py 2>&1

Repository: Sinity/polylogue

Length of output: 1037


🏁 Script executed:

/home/jailuser/.local/bin/mypy --strict polylogue/daemon/http.py --show-traceback 2>&1 | head -30

Repository: Sinity/polylogue

Length of output: 1037


Quality gates are not passing. Fix 8 mypy --strict errors before merge.

The code fails mypy --strict type checking in the polylogue directory:

  • polylogue/cli/machine_main.py:117 - redundant condition
  • polylogue/sources/drive/gateway.py:174 - no-any-return
  • polylogue/storage/search_providers/sqlite_vec_embeddings.py:42 - untyped decorator
  • polylogue/insights/registry.py:61 - type-arg error
  • polylogue/storage/sqlite/queries/raw_state.py:217, 248 - no-any-return
  • polylogue/cli/query_output_contracts.py:78 - no-any-return
  • polylogue/cli/click_option_groups.py:47 - unused type: ignore comment

ruff format and ruff check pass, but per the coding guidelines, all code in polylogue/, tests/, and devtools/ must pass mypy --strict with no excludes.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@polylogue/daemon/http.py` around lines 11 - 16, Fix the 8 mypy --strict
errors across the polylogue directory: In machine_main.py at line 117, remove
the redundant condition causing the error. In gateway.py at line 174, add
explicit return type annotations instead of returning Any. In
sqlite_vec_embeddings.py at line 42, add proper type annotations to the untyped
decorator. In registry.py at line 61, provide missing or correct type arguments
to fix the type-arg error. In raw_state.py at lines 217 and 248, add explicit
return type annotations to avoid no-any-return violations. In
query_output_contracts.py at line 78, add explicit return type annotations to
fix the no-any-return error. In click_option_groups.py at line 47, remove the
unused type: ignore comment. Ensure all changes pass mypy --strict validation
before merging.

Source: Coding guidelines

Comment thread polylogue/daemon/http.py Resolved
Address CodeRabbit review on #2158. POST route patterns now come from the same table used by dispatch and implemented-route inventory, and route-contract tests assert implemented route pairs are unique before set comparison.\n\nVerification: devtools test tests/unit/daemon/test_route_contracts.py tests/unit/daemon/test_daemon_http_security.py tests/unit/daemon/test_user_state_http.py::TestDispatchRouting::test_empty_id_in_get_path_does_not_route -> 404 passed. devtools verify --quick -> exit_code 0. devtools verify -> 701 passed, exit_code 0.
@Sinity

Sinity commented Jun 19, 2026

Copy link
Copy Markdown
Owner Author

Review follow-up:

  • Addressed the POST route duplication finding in 050e45641: _observability_post_routes() and _authenticated_post_routes() now drive both POST dispatch and implemented_daemon_route_patterns().
  • Addressed the duplicate-route masking finding in 050e45641: route-contract tests now assert the raw implemented route sequence is unique before converting to a set.
  • Classified the reported cross-file mypy failures as stale/noise for this PR: local devtools verify --quick, local devtools verify, pre-push quick gate, and CI typecheck all run mypy and pass on this branch.

Verification after review fixes:

  • focused route/security slice: 404 passed.
  • devtools verify --quick: exit_code 0.
  • devtools verify: 701 passed, exit_code 0.

@Sinity
Sinity merged commit 81e3caa into master Jun 19, 2026
13 of 14 checks passed
@Sinity
Sinity deleted the feature/refactor/daemon-route-contracts-1847 branch June 19, 2026 09:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant