Skip to content

feat(setup): registration terms at first-run setup through a provider seam (trinity-enterprise#1329) - #4698

Merged
vybe merged 2 commits into
devfrom
feat/1329-setup-registration-terms
Nov 21, 2026
Merged

vybe merged 2 commits into
devfrom
feat/1329-setup-registration-terms

Conversation

@trinity-ability

Copy link
Copy Markdown
Contributor

Refs abilityai/trinity-enterprise#1329

Journey Impact: extends: J01

What

Checkpoints P1 + P2: registration terms at first-run setup, through a generic provider seam. Inert when no provider is registered — a self-installed instance behaves exactly as today (route 404, setup unchanged, no instance-terms waiver).

The seam — services/setup_registration.py

register_provider(p) / clear_provider() / provider(). A provider implements:

async def current_terms(self) -> dict:
    # {"version": str (non-empty, <=100), "title": str|None (<=200),
    #  "text": str|None (<=200 000), "url": str|None (<=2 000)}
    # raise when the terms cannot be read right now

It is called with nothing from the caller (no claim code, email or address). A malformed answer counts as unavailable. The acceptance {version, accepted_at, ip} (ip ≤ 64 chars, the address this instance saw) is stored in the registration_terms_acceptance setting; recorded_acceptance() is how the provider's module reads it to report it onward.

GET /api/setup/registration-terms

Unauthenticated, no parameters. Open only while setup_completed=false and a provider is registered, else 404. 200 {"version","title","text","url"}, cached 60 s. 503 {"code":"registration_terms_unavailable","retryable":true,"message","version":null}.

POST /api/setup/admin-password (email-bound claim only)

New optional registration_terms_version. After the claim check and every password/email 400, before the claim is taken, the provider's current version is re-read (cache bypassed):

Case Answer
missing 400 registration_terms_required (+ current version)
different 409 registration_terms_changed (+ current version)
provider unreachable 503 registration_terms_unavailable, retryable: true

Each refusal leaves the claim file untouched and writes nothing. The instance-ID claim (PROV-018) is not gated.

P2

On that same path, the setup admin is recorded as having accepted the instance's own terms of use (terms_service.accept, door="setup") for the version in force at setup. People invited later are still asked, and a later version asks the admin again. This step never fails setup.

Tests

  • tests/unit/test_ent1329_setup_registration_terms.py: 21 tests, all passing. Red first (the module was missing). Mutation check: widening the P2 guard to every path made 2 tests fail, then the code was restored.
  • Regression: setup, terms, models and settings-sink suites passed (195). The route-census and auth-wiring suites passed after the new route was listed (884 + 64).
  • PROV-020 contract updated in docs/memory/requirements/infrastructure.md.

🤖 Generated with Claude Code

… seam (trinity-enterprise#1329)

A registered provider of registration terms can now gate first-run setup
from an emailed link. With none registered nothing changes.

- services/setup_registration.py: register_provider(p), p implementing
  async current_terms() -> {version, title, text, url}; 60 s cache;
  check_accepted() re-reads the current version; record_acceptance() /
  recorded_acceptance() keep {version, accepted_at, ip<=64}.
- GET /api/setup/registration-terms: unauthenticated, no parameters,
  open only while setup is open and a provider is registered (else 404);
  503 registration_terms_unavailable (retryable) when it cannot answer.
- POST /api/setup/admin-password (email-bound claim only): takes
  registration_terms_version; 400 registration_terms_required, 409
  registration_terms_changed, 503 registration_terms_unavailable; the
  claim is untouched and nothing is written on any refusal.
- On that path the setup admin is recorded as having accepted the
  instance's own terms for the version in force (door=setup).
- PROV-020 contract updated; both route censuses list the new route.

Refs abilityai/trinity-enterprise#1329

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@trinity-ability trinity-ability left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

/validate-pr — #4698 @ b8ae8b0 — REQUEST CHANGES

Lane B (no lane-C path; no schema). Validated from a fresh detached checkout of the tip. The new suite passes (21/21). I ran four mutations and a concurrency probe; results are below.

Must fix

  • The 60 s cache does not hold under concurrent calls, and failures are never cached. setup_registration.current_terms() has no single-flight lock and no negative cache. A probe against the tip (provider sleeps 50 ms):

    • 50 concurrent cold GET /api/setup/registration-terms → 50 provider calls
    • 50 warm → 0
    • provider down, 20 sequential → 20 calls

    The route is unauthenticated and open on any not-yet-set-up instance that has a provider. So any caller can drive one provider call per request whenever the provider is failing, and a burst of them at every cache expiry. Fix: an asyncio.Lock (or a shared in-flight future) around the fetch, plus a short negative cache (around 5–10 s) for the 503. Add tests for both: N concurrent cold calls make 1 provider call, and a down provider is hit at most once per negative-cache window. With both in place, provider load is capped per instance and does not depend on how many callers there are, so a per-address limit is not needed for the provider's sake. The submit path's fresh=True re-read sits behind _check_claim (claim code + login rate limit), so it is not reachable by an anonymous caller.

Warnings

  • P2 "never fails setup" is not pinned. Narrowing the P2 except Exception to except ZeroDivisionError leaves all 21 tests green. Add a test where terms_service.accept raises (e.g. TermsError version_stale, or a DB error) and assert setup still completes.
  • The stored acceptance can be rewritten by an admin. The registration_terms_acceptance setting holds {version, accepted_at, ip}. Reads are admin-only (GET /api/settings and GET /api/settings/{key} both call assert_admin, which also refuses agent keys), so non-admins cannot see it. But it is not reserved, so PUT /api/settings/{key} and DELETE /api/settings/{key} let an admin rewrite or delete the record the provider's module "reports onward". Consider registering it with reserved_settings (the ent#1174 mechanism) so only the seam writes it.
  • Ordering: record_acceptance runs before the admin write. If update_user_password then fails, the claim is put back, but the acceptance row stays, so the 503 text "nothing was changed" is not quite true. A retry overwrites it, so this is harmless; writing the row after the admin write (still inside the try), or deleting it in the except, would make the message accurate.
  • Linkage: the body says Refs abilityai/trinity-enterprise#1329, with no closing keyword. I left it unpatched on purpose: this PR covers checkpoints P1 and P2 only, and a cross-tracker ref is not auto-promoted anyway. Set status-in-dev on ent#1329 by hand after merge, or close it once the last checkpoint lands.

Checked and OK

  • (1) Route: returns 404 when no provider is registered (tested) and once setup_completed=true (mutation: removing that check → 1 test fails). The handler takes no parameters, so nothing from the request reaches the provider (pinned by a signature test). The response is bounded: version ≤100, title ≤200, text ≤200 000 chars, url ≤2 000; a malformed answer is treated as unavailable (503).
  • (2) Submit check: runs after _check_claim and every password/email 400, and before _take_claim. Moving _take_claim ahead of the check → 12 tests fail. Every refusal is asserted to leave the claim file, the password, setup_completed, the acceptance setting and the terms rows untouched. The version is re-read with fresh=True (mutation to fresh=False → test_stale_cache_does_not_pass_a_changed_version fails). The three codes are distinct: 400 registration_terms_required, 409 registration_terms_changed, 503 registration_terms_unavailable (retryable).
  • (3) No provider: every new branch is behind provider() is not None, short-circuited before the claim file is read, so setup and /api/setup/status behave as before (tested). The instance-ID claim is not gated (tested). One small edge: the new optional field has max_length=100, so a client that sends an oversized registration_terms_version to a no-provider install now gets a 422 where the field used to be ignored. In practice nothing sends it.
  • (4) P2: runs only when registration_version is not None, which happens only on the email-bound claim with a provider registered. It records terms_service.current_version() with door="setup", through accept(), which writes its own audit row and runs no acceptance hooks. An invited person is still asked, and so is the admin when a later version is published (both tested). The author's mutation (widening the guard → 2 tests fail) is consistent with this.
  • (6) Wiring: the route is in _route_census.py as unauthenticated-by-design, and the handler-level behaviour is executed directly. Provider registration is deliberately left to the optional module, so there is no production registration in OSS to pin.
  • Secret, email and IP greps are clean (test fixtures only, using TEST-NET addresses). No env vars, no Dockerfile or compose changes, no new top-level package. setup.py is an MCP-excluded router. Journey Impact extends: J01 → check_journey_impact.py PASSED. PROV-020 is updated in requirements/infrastructure.md.

Checks on the tip

All finished checks are green: CodeQL (both), schema-parity, verify-non-root, gitleaks, lints, prod-image-smoke, journey-impact, backend boots without enterprise. pytest (head, seed 12345) was still pending when this was posted, so Tier 1 is not yet confirmed.

PR #4698 — REQUEST CHANGES — merge gate: ⚠️ (Tier-1 pytest pending)

@trinity-ability trinity-ability added the status-needs-fix PR has an unaddressed review/validation finding; cleared by the author's next push (#2815) label Nov 21, 2026
…ion terms fetch (trinity-enterprise#1329)

Review of #4698. The open GET /api/setup/registration-terms made one
provider call per concurrent cold request and one per request while the
provider was failing. Now concurrent fetches share one call (a per-loop
asyncio.Lock with a re-check of the cache), and the unavailable answer is
cached for NEGATIVE_TTL_S = 10 s, so provider load is capped per instance.
The submit re-check (fresh=True) still bypasses both caches.

Also from the review:
- the registration_terms_acceptance setting is reserved (reserved_settings)
  while a provider is registered, so the generic settings routes cannot
  rewrite or delete it;
- the acceptance is written after the admin write (still inside the try
  that restores the claim), so a failed admin write leaves no row behind;
- P2's never-fails-setup guarantee is pinned by two tests (TermsError and
  a DB error from terms_service.accept).

Red before the fix: test_concurrent_cold_calls_make_one_provider_call,
test_concurrent_cold_calls_on_a_down_provider_make_one_call,
test_a_down_provider_is_asked_at_most_once_per_negative_window,
test_acceptance_setting_is_reserved_while_a_provider_is_registered,
test_failed_admin_write_leaves_no_acceptance_row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot removed the status-needs-fix PR has an unaddressed review/validation finding; cleared by the author's next push (#2815) label Nov 21, 2026

@trinity-ability trinity-ability left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fix step — #4698 @ a1ba8f0 — ready to re-validate (APPROVE-ready from the fix side)

One commit on top of b8ae8b0, no history rewritten (the stacked branch is safe).

Must fix: done

  • Single-flight. Provider fetches go through a per-event-loop asyncio.Lock, and the cache is re-checked under it. It is keyed by loop because a lock binds to the first loop that contends on it.
  • Negative cache. NEGATIVE_TTL_S = 10.0. An unavailable answer is cached for that long, and a success clears it.
  • Submit stays fresh. fresh=True skips both caches and always asks the provider.

Warnings: done

  • registration_terms_acceptance is registered with reserved_settings while a provider is registered and released on clear_provider(). The generic PUT and DELETE now refuse it.
  • The acceptance is written after the admin write, still inside the try that restores the claim. A failed admin write leaves no row.
  • P2 "never fails setup" is pinned: terms_service.accept raising TermsError, or raising a DB error, still completes setup.
  • Linkage: unchanged, as you asked.

pytest (head, seed 12345) on b8ae8b0

It finished success. It was only pending when the review was posted, so this PR had nothing to fix there.

Evidence (fresh detached checkout at a1ba8f0)

  • New suite: 30 passed (21 old + 9 new). New suite plus neighbours (setup fail-closed, instance-ID claim, ent1312 link claim, operator profile, terms gate / per-instance / inline hooks, ent1174 member seat, 3180 census): 311 passed.
  • Probe (provider sleeps 50 ms): cold 50 concurrent → 1 call; warm 50 → 0; down, 20 sequential → 1; down, 50 concurrent → 1; 1 warm read + 2 fresh → 3 (each fresh read asks).
  • Red before the fix: 5 new tests. Mutations at the tip: removing the lock turns 2 red (the concurrent tests); disabling the negative cache turns 2 red.

Decision: the must-fix and every warning are addressed. Re-run /validate-pr on a1ba8f0 once CI is green.

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approving on the validation findings all answered in the fix step at a1ba8f0 (re-run from a fresh checkout with the concurrency probe) and green checks.

@vybe
vybe merged commit 5795fca into dev Nov 21, 2026
27 checks passed
trinity-ability pushed a commit that referenced this pull request Nov 21, 2026
Backend files resolved to origin/dev (#4698 squash 5795fca); only the P3
setup-page frontend change and its spec remain as this branch's diff.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
vybe pushed a commit that referenced this pull request Nov 21, 2026
…4679/#4677 (#4680)

Accepted growth, ruled at merge-train Gate 2 (2026-11-21):
- routers/setup.py 6 -> 9 (ent#1329 setup terms, #4683/#4694/#4698)
- client_portal/work/service.py 8 -> 10, agent_service/autonomy.py 12 -> 14
  (#4679's batch prefetch reads: fewer queries, more call sites)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
vybe pushed a commit that referenced this pull request Nov 23, 2026
)

* test(backend): ratchet on blocking calls inside async def (#4674)

A sync db, Docker, HTTP or sleep call written directly inside an
`async def` runs on the event loop and blocks the whole worker.
scripts/ci/check_sync_on_loop.py counts them per file by parsing (never
importing) and compares with scripts/ci/sync_on_loop_baseline.json:

- a file's count may not exceed its entry;
- a file with no entry starts at zero;
- an entry above reality fails too, so a paydown lowers the baseline.

Today: 1,911 call sites in 831 async functions across 194 files
(db 1,363; through a module's own sync function 386; Docker 161).

Counted: db / core_db / _db / *.db method calls, get_agent_container,
list_all_agents_fast, agent_container_states, time.sleep,
subprocess.run, requests.*, and calls to the same module's plain defs
that make one. Not counted: plain def handlers, nested defs, and the
arguments of to_thread / run_in_executor / run_in_threadpool.

The ratchet runs in the unit suite (test_4674_sync_on_loop_ratchet.py).
The helper list is one constant, for trinity-dev#82 to share.

Related to #4674

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* test(backend): the ratchet does not pin the offenders it exists to remove (#4674)

Review finding. One test asserted that heartbeat_service's watch loop
and dependencies.py are in the scan. Those are exactly what #4674 goes
on to fix, so the test would have failed on the fix. It now asserts
only that the live scan sees both families. The backend is parsed once
per module instead of once per test.

Related to #4674

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* test(backend): regenerate the sync-on-loop baseline on current dev (#4674)

dev moved under the branch and changed two files' counts, which is the
ratchet doing its job on its own PR.

Related to #4674

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* merge-train: regenerate the sync-on-loop baseline on dev after #4676/#4679/#4677 (#4680)

Accepted growth, ruled at merge-train Gate 2 (2026-11-21):
- routers/setup.py 6 -> 9 (ent#1329 setup terms, #4683/#4694/#4698)
- client_portal/work/service.py 8 -> 10, agent_service/autonomy.py 12 -> 14
  (#4679's batch prefetch reads: fewer queries, more call sites)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): --write refuses to absorb growth into the baseline (#4674)

Regenerating the baseline wrote whatever the scan found, so a regeneration
could wave new blocking calls through and only the JSON diff showed it.
--write now prints each file whose count grew and writes nothing unless
--allow-growth is passed; a paydown is written as before.

Also: main() reads and writes the baseline path it names (the helpers'
default argument was bound at import), and the docstring no longer claims
a /code-health consumer that does not exist.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

---------

Co-authored-by: Claude Fable 5.2 <[email protected]>
Co-authored-by: trinity-ability <[email protected]>
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.

2 participants