Skip to content

feat(events): grant-driven event subscriptions, resync and the broker on by default - #91

Merged
bketelsen merged 7 commits into
mainfrom
irulan/t8-event-subscriptions
Nov 16, 2026
Merged

bketelsen merged 7 commits into
mainfrom
irulan/t8-event-subscriptions

Conversation

@frostyard-machines

@frostyard-machines frostyard-machines commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Grant-driven event subscriptions on lodge's embedded broker (ADR-0022, amended in place while Proposed; roadmap Phase 9).

  • /gateway/events (new route, kind gateway): a client with an OAuth access token of scope events lists, puts and deletes its subscriptions. PUT /gateway/events/<sub> takes {"topic": "<prefix>"}; lodge makes 1 durable pull consumer whose filters are the effective read prefixes: the principal's grant read through the app's manifest events (as hearth's events.ReadFilters derives them), narrowed to the requested prefix, plus the consumer's own resync subject. A token without events is 403; a topic the grant gives nothing under is 403.
  • /nats now admits a client by its OAuth token of scope events (internal/events.Service.Tokens). Its broker name is o + base32 of its client ID. A connection closes when its token expires, and each minute lodge checks open connections' tokens again.
  • Grant changes refilter in place (broker.Refilter): undelivered events outside a narrowed grant are filtered out; a grant that gives nothing leaves the resync subject only. Grants are read inside the client's lifecycle lock, so a subscribe and a grant change of 1 client never cross. A grant that gives more than 64 filters fails closed.
  • Revoking a client or a principal revokes its broker clients (connections, then consumers).
  • Retention and resync: each app stream keeps 7 days or 1 GiB and discards old; it gains the subject lodge.<id>.>. A consumer whose position is before its stream's first message gets 1 org.frostyard.lodge.resync CloudEvent, checked when its client connects (before its CONNECT reaches the server) and each minute.
  • broker.enabled defaults to true; {"enabled": false} turns it off. packaging/config.example.json follows.
  • internal/apps reads the hearth manifest's events; internal/oauth gains Server.Client.
  • Docs: ADR-0022 (retention, limits, tokens, subscriptions, resync), specs/lodge-http.md (Event subscriptions), specs/oauth.md, specs/app-contract.md, design/overview.md, roadmap Phase 9, site/content/guides/configure.md, AGENTS.md map.

Risk tier

Risk tier: 3 — risk:high paths (each matched, and why the change is safe):

  • internal/broker/** (L1, auth): admission now takes OAuth tokens of scope events only; accounts and subject permissions are unchanged (a client still reaches only its own consumers' NEXT and ACK). New: resync publishing by lodge's hub client on lodge.<id>.>, which no app may publish (lodge is a reserved app ID); refilter keeps permissions and fails closed.
  • internal/events/** (L1, new, added to the list in this PR): the filter computation; cross-checked against hearth's events.ReadFilters in internal/hearthtest/events_test.go.
  • internal/gateway/{gateway,events}.go (L1): the new route runs the MCP gateway's checks in the same order (Host, no Origin, method, peer, bearer, scope, no upgrade); a test fails each.
  • internal/oauth/grants.go (L1): adds a read-only Client lookup of a live client.
  • internal/apps/apps.go (L1): reads and validates the manifest's events; a bad event disables only that app.
  • cmd/lodge/main.go, cmd/lodge/build_test.go (L1): wiring of the service, its hooks and its sweep; the development build test now expects the broker on by default.
  • .github/risk-paths.json (L2): adds internal/events/** and internal/gateway/events.go.

Verification

  • make check green (host).
  • make race and make cross green (run as part of make ci).
  • make client-check, ui-check, shell-check: not run locally (the nsl VM is not reachable from this session); this PR changes nothing under client/, ui/ or shell/, and CI runs them.
  • make mcp-e2e: not run (nsl). /gateway/mcp and internal/mcpgw are unchanged; the new route has its own tests.
  • Acceptance tests (internal/events/acceptance_test.go): TestSubscribeByTopic, TestOneFolderOfMany (100 events in 10 folders, a grant on 1 folder receives exactly its 10), TestNarrowing, TestRefilterAfterAnEmptyGrant, TestRevoke, TestStreamLimits, TestResync, TestSweepRevokesAGoneClient, TestTooManyFilters; route checks in internal/gateway/events_test.go.

Cross-review

Coder: deepseek/deepseek-flash (Go), docs by anthropic/claude-opus-5-5. Reviewer: openai/gpt-6.1-sol. Base 422dd8b.

Round Head Result Fixed in
Initial (5 batches, all 39 files) 1e6f745 5 blocking: a subscribe could miss a concurrent narrowing; a failed refilter left delivery on; concurrent resync checks published 2; GET reported computed filters; a bad DELETE name was 503 6ab694f
Re-review 1 6ab694f 3 blocking: a new consumer could deliver before the generation repair; a client lookup error skipped fail-closed; stopDelivery could recreate a revoked consumer b4caabd (activate-after-register replaces the generation design)
Re-review 2 b4caabd 2 blocking: a re-PUT could skip an authorized backlog; a concurrent unsubscribe made cleanup revoke the client cb92cf6
Re-review 3 cb92cf6 1 blocking: activation cleanup in a second lock could delete a replacement subscription 9f74d8f (Broker.Activate: activate and clean up under 1 lifecycle lock, cleanup with its own budget)
Re-review 4 (1 extra round, authorized) 9f74d8f 1 blocking: the lock is released between SubscribeWith and Activate, so a delete and a re-create of the same name in that gap lets a failed activation remove the replacement; Activate has no registration identity 1498766 (SubscribeWith registers, activates and cleans up under 1 lifecycle lock; the activation checks the OAuth client again)
Re-review 5 (1 extra round, authorized) 1498766 gap fixed; 2 blocking: an OAuth lookup failure in the activation answers 404 instead of 503; an earlier record's filled promoted_to was changed. 1 low: a test can hang on its failure path 896a882 (liveClient wraps ErrNotFound only for oauth.ErrNotFound; the record restored, a new record names the replacement tests; the test puts the value back)
Re-review 6 (last, authorized; the 1498766..896a882 diff) 896a882 Ready, Blocking: none —

Each blocking point has a guard test and a record in .memory/corrections/2026-11-16-pr-91-*.json.

Revert tests (scratch worktree from the PR head, fix files reverted, tests kept; go test -count=1 -run '<names>' ./internal/events/ ./internal/broker/):

  • Fixes of 6ab694f: TestSubscribeSeesAGrantChange, TestAFailedRefilterRevokesItsClient, TestListAnswersTheConsumersFilters, TestUnsubscribeRefusesABadName, TestResyncPublishesOneEventForConcurrentChecks, TestRefilterStopsDeliveryWhenTheGrantFails fail; TestAStoppedSweepRevokesNoClient fails with only its ctx.Err() check removed.
  • Fixes of b4caabd: TestANewSubscriptionDeliversNothingBeforeItsGrantIsRead (with Inactive forced false), TestAClientLookupFailureRevokesItsClient, TestAFailedRefilterAfterARevokeLeavesNoConsumer fail.
  • Fixes of cb92cf6: TestARePutKeepsTheBacklog, TestAnUnsubscribeDuringActivationKeepsTheOthers fail.
  • Fixes of 9f74d8f: TestAFailedActivationKeepsAReplacement (service reverted to 2 steps), TestActivateCleansUpAfterItsBudget (cleanup on the spent context) fail. TestActivateCleansUpUnderOneLock checks the outcome under concurrency; it does not tell the 2-step design apart.

Revert tests of the last 2 rounds (scratch worktree, fix reverted, tests kept):

  • 1498766: TestNoGapBetweenRegistrationAndActivation fails with the lock released and taken again around the activation point; TestARevokedClientGetsNoSubscription fails with the activation's client check removed.
  • 896a882: TestAClientLookupFailureDuringActivationIs503 fails with every lookup error wrapped as ErrNotFound.

Status: Ready at 896a882 (re-review 6).

… on by default

A client with an OAuth token of scope events subscribes on /gateway/events
by topic prefix. lodge gives its consumer the effective read prefixes:
the principal's grant read through the app's manifest events, narrowed to
the prefix, as hearth's events.ReadFilters derives them. A grant change
refilters the consumer in place, a revoke ends delivery, and a consumer
that retention overtook gets 1 org.frostyard.lodge.resync event. The
broker is on unless the configuration turns it off (ADR-0022).
@github-actions github-actions Bot added level:L1 Read every line risk:high Touches a path in .github/risk-paths.json labels Nov 16, 2026
… races

A subscription made while its grant changed refilters itself (a
generation per principal and app); a refilter that fails stops the
consumer's delivery and revokes its client, except in a sweep that lodge
stops; a consumer's resync check and publish run 1 at a time; a list
answers the consumer's installed filters; a bad name in DELETE is 400.
… closed on a lookup

A new consumer starts with its resync subject alone and is registered;
then lodge reads the grant inside the client's lock and gives it its
filters, so a grant change after that read finds it. A client lookup that
fails in a grant hook revokes the client, and a failed refilter that a
revoke overtook deletes the consumer it wrote.
…ation revokes nothing

Only a new subscription starts with its resync subject alone: a
registered one keeps its filters, so a pull between the 2 steps cannot
move its consumer past events its grant reads. An activation whose
subscription is already gone answers 404 and leaves the client's other
subscriptions.
Broker.Activate installs a new subscription's filters and, when that
fails, removes it under the same lock, with a budget of its own: the
cleanup can no longer remove a subscription that another request put in
its place.
SubscribeWith takes an Activate callback: a new subscription is made with
its resync subject alone, registered, activated and, on a failure,
removed, all before the client's lifecycle lock is released, so no other
request of the client can replace it in between. The activation checks
that the OAuth client is still there with scope events, so a client
revoked after the token check keeps no subscription (404).
Only a client that OAuth does not find is a revoked one; another lookup
error during a subscription's activation goes back as it is. An earlier
correction record is restored as it was, and a new one names the tests
that replace the one it names.
@frostyard-machines frostyard-machines added the ready-for-human Reviewed, CI green: ready for Brian to review and merge label Nov 16, 2026
@bketelsen
bketelsen merged commit 42388fb into main Nov 16, 2026
13 checks passed
@bketelsen
bketelsen deleted the irulan/t8-event-subscriptions branch November 16, 2026 16:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

level:L1 Read every line ready-for-human Reviewed, CI green: ready for Brian to review and merge risk:high Touches a path in .github/risk-paths.json

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants