Skip to content

test(contracts): pin daemon convergence, status, and privacy contracts (#1060) - #1085

Merged
Sinity merged 1 commit into
masterfrom
feature/test/daemon-convergence-contracts
May 16, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/test/daemon-convergence-contracts

Conversation

@Sinity

@Sinity Sinity commented May 16, 2026

Copy link
Copy Markdown
Owner

Summary

Adds 16 contract tests under tests/unit/daemon/test_daemon_http_contracts.py covering five operational daemon HTTP contract families — status envelope shape, read-only convergence behavior, stale/disconnected/degraded state, privacy boundaries, and operation-spec catalog discipline.

Problem

The security-boundary contracts of the daemon HTTP surface are pinned by tests/unit/daemon/test_daemon_http_security.py (added in #1075 / #1076 — auth gates, origin allowlist, JSON serialization fallback). The operational contracts of the same surface were unpinned at the HTTP layer:

  • The documented GET /api/status envelope (daemon_liveness, component_state, fts_readiness, convergence, health, …) had no test asserting which keys are required vs. optional. A regression that dropped or renamed a key would only fail downstream in the web reader or dashboard.
  • There was no assertion that GET /api/status and GET /api/health are read-only — a future change that triggered convergence work as a side effect of status polling could pass review.
  • Degraded states (no daemon pidfile, internal health-checker error, FTS index out of sync) had no contract that they surface as structured envelope fields rather than raw exceptions.
  • No test asserted that the status payload never leaks VOYAGE_API_KEY/OPENAI_API_KEY/ANTHROPIC_API_KEY sentinel env vars, never accidentally dumps os.environ, and that the static web shell HTML has no inlined secrets.
  • No test asserted that GET /api/conversations/<id> returns only the requested row.
  • The runtime / declared OperationSpec catalog had no assertion that every spec declares the metadata downstream consumers depend on (name shape, code_refs format, effects enum membership, mutates_state consistency with declared write effects).

Solution

One new file: tests/unit/daemon/test_daemon_http_contracts.py. Five TestX classes, all marked @pytest.mark.contract, all using the in-process DaemonAPIHandler harness from test_daemon_http_security.py (no real daemon process, no socket listener):

  1. TestStatusEnvelopeContract — enumerates REQUIRED_STATUS_KEYS / REQUIRED_HEALTH_KEYS from the actual daemon_status_payload() shape. Extending the envelope requires extending the test in the same PR. Pins component_state subsystems to {api, watcher, browser_capture} and quick_check to the documented enum.
  2. TestStatusReadOnlyContract — repeated polls of /api/status and /api/health leave the archive directory hash unchanged across 3 polls each.
  3. TestDegradedStateContract — daemon_liveness=False with no pidfile; /api/health/check returns 503 on degraded health (mocks _run_fast_checks to inject a CRITICAL alert); the documented exception path translates to a bounded {ok:false, status:"error", detail:"health check failed"} envelope rather than a raw 500; fts_readiness is asserted to be a structured dict, never a free-form string.
  4. TestPrivacyContract — plants sentinel values in VOYAGE_API_KEY/OPENAI_API_KEY/ANTHROPIC_API_KEY and a uniquely-named POLYLOGUE_TEST_SENTINEL_ENV_DO_NOT_DUMP, asserts none appear in the serialized status payload; asserts the static WEB_SHELL_HTML constant never inlines env-derived secrets; seeds three conversations (c1/c2/c3) and asserts GET /api/conversations/c1 mentions c1 but not the adjacent rows' distinctive markers.
  5. TestOperationSpecContract — two-tier check. RUNTIME_OPERATION_SPECS strictly require kebab-case name, non-trivial description, well-formed code_refs, declared effects from the known enum, and mutates_state=True whenever DbWrite|FileWrite|Destructive is declared. DECLARED_OPERATION_SPECS (superset including scenario/benchmark entries) only require the structural fields — these advisory entries may legitimately omit code_refs. All names must be unique across the declared catalog.

Each test that produces something worth aggregating calls record_contract_evidence(...) and writes a bounded JSON artifact under .cache/verification/evidence/ keyed daemon.status.envelope, daemon.status.read_only, daemon.status.disconnected, daemon.status.no_secret_leak, daemon.operations.runtime_spec_contract.

No daemon source changes required — every contract pins existing behavior. The exception-path contract (the third degraded-state test) confirms the existing daemon_safe_handler-style try/except in _handle_health_check works as documented.

Verification

nix develop -c pytest tests/unit/daemon/test_daemon_http_contracts.py -v
# 16 passed in 2.26s

nix develop -c pytest tests/unit/daemon tests/unit/operations -q --basetemp=.cache/pytest-tmp
# 375 passed in 15.38s

nix develop -c ruff format tests/unit/daemon/test_daemon_http_contracts.py
nix develop -c ruff check tests/unit/daemon/test_daemon_http_contracts.py
# All checks passed!

nix develop -c mypy tests/unit/daemon/test_daemon_http_contracts.py
# Success: no issues found in 1 source file

nix develop -c devtools verify --quick
# total_duration_s: 38.32, exit_code: 0

ls .cache/verification/evidence/ | grep -E "daemon\.(status|operations)" | wc -l
# 6 new evidence artifacts

Ref #1060
Ref #1058

🤖 Generated with Claude Code

Adds 16 contract tests under tests/unit/daemon/test_daemon_http_contracts.py
covering five families that were previously unpinned at the HTTP-surface
level:

1. Status envelope shape — REQUIRED_STATUS_KEYS / REQUIRED_HEALTH_KEYS
   enumerate the documented keys; missing fields must be explicit
   null, not absent.
2. Read-only contract — GET /api/status and GET /api/health do not
   mutate archive state across repeated polls.
3. Stale/disconnected/degraded — daemon_liveness=False with no
   pidfile; health/check returns 503 on degraded health; the
   exception path translates to a bounded {ok:false,status:error,...}
   envelope rather than a raw traceback; fts_readiness is a
   structured dict.
4. Privacy — status payload never leaks VOYAGE/OPENAI/ANTHROPIC
   sentinel env vars or a stray POLYLOGUE_TEST_SENTINEL_*; the
   static web shell HTML never inlines env-derived secrets;
   GET /api/conversations/<id> never returns adjacent rows.
5. Operation specs — RUNTIME_OPERATION_SPECS are strictly
   well-formed (name, code_refs, effects, mutates_state matches
   declared write effects); DECLARED_OPERATION_SPECS satisfies the
   light-touch structural contract; all names are unique.

Tests use the in-process DaemonAPIHandler harness from
test_daemon_http_security.py — no real daemon process, no socket
listener. Each test is @pytest.mark.contract and emits bounded
evidence via record_contract_evidence under
daemon.status.*, daemon.operations.*.

Ref #1060
Ref #1058

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@coderabbitai

coderabbitai Bot commented May 16, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 40 minutes and 43 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 3fe499df-c945-4ee4-b588-1691c90c8de7

📥 Commits

Reviewing files that changed from the base of the PR and between fc3c43f and 3836cce.

📒 Files selected for processing (1)
  • tests/unit/daemon/test_daemon_http_contracts.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/test/daemon-convergence-contracts

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.

@Sinity
Sinity merged commit f263116 into master May 16, 2026
4 checks passed
@Sinity
Sinity deleted the feature/test/daemon-convergence-contracts branch May 16, 2026 11:28

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3836ccea7f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +285 to +286
archive_root = workspace_env["archive_root"]
archive_root.mkdir(parents=True, exist_ok=True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Track DB state in read-only status/health contract tests

These read-only contracts fingerprint only workspace_env["archive_root"], but daemon persistence lives under db_path() (XDG_DATA_HOME/polylogue/polylogue.db) and related WAL files. If a future regression makes GET /api/status or GET /api/health perform convergence/persistence work in the database, these tests will still pass because the mutated files are outside the hashed tree. This leaves the core "no side effects on status polling" contract effectively unguarded for the primary write path.

Useful? React with 👍 / 👎.

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