Skip to content

[AI-4467] Session controllers get their dependencies as a plain struct - #2803

Draft
kanat wants to merge 4 commits into
mainfrom
feature/ai-4467-session-deps
Draft

kanat wants to merge 4 commits into
mainfrom
feature/ai-4467-session-deps

Conversation

@kanat

@kanat kanat commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Do not merge yet: ship-feature is in progress.

createSession is a controller since #2728, but it still reaches back into Server through ten proxy methods. This branch gives session controllers a plain struct of six layers instead, and moves the helpers they share with other operations into their own packages. The API and openapi.yaml do not change.

internal/api (Server, legacy routes, one-line delegates)
 ├── sessions ── sessions/controller (Deps struct, CreateSession, session-only helpers)
 ├── agentconfig   find an agent config, floor control checks
 ├── callapp       the Stream app of a call
 ├── userteams     a user's teams, cached
 ├── refusal       from a failed session to an answer
 ├── apierr        API errors
 └── reqctx        who is asking

It lands as 12 small PRs, one after another, into this branch. Tracking: AI-4467.

Gates for the merge into main

none (no migration, no flag, no behaviour change)

🤖 Generated with Claude Code

kanat and others added 2 commits November 30, 2026 20:28
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The customer, organization, caller kind, server side mark and request id
of a request were stored under keys that only the API package could see,
so a controller in another package had to go through `Server` to read
them. This PR moves those keys, with their setters and readers, into a
package of their own that any controller can import. Nothing changes at
run time and the API spec does not change.

## How it works

```
request
  │
  ├─ withRequestID ───────────> reqctx.WithRequestID
  ├─ auth middleware ─────────> reqctx.WithCustomer, WithOrganization,
  │                             WithServerSide, WithKind
  └─ scheduled delivery ──────> reqctx.WithCustomer, WithServerSide, WithKind
                                          │
                                          v
                                   context of the request
                                          │
     ┌────────────────────────────────────┴───────────────┐
     v                                                    v
 api.CustomerFrom, KindFrom, ...                 reqctx.IdentityFrom
 (one-line delegates, every caller               nil without a customer, else
  in internal/api is unchanged)                  AppID, Caller, Kind, ServerSide
```

The new package has an `AGENTS.md` (its rules, each with a command that
shows when it is broken) and a `CLAUDE.md` that only links it. `reqctx`
imports only `auth` and `routing`. `IdentityFrom` has no production
caller yet: the session controllers read it in a later PR of this
series.

## What differs from the base

| Base in `internal/api` | Now | What differs |
| --- | --- | --- |
| `customerContextKey`, `organizationContextKey`,
`serverSideContextKey`, `kindContextKey`, `requestIDContextKey` |
`customerKey`, `organizationKey`, `serverSideKey`, `kindKey`,
`requestIDKey` in `reqctx` | The names |
| `CustomerFrom`, `OrganizationFrom`, `ServerSideFrom`, `KindFrom`,
`RequestIDFrom` | Same names in `reqctx`, delegates in `api` | The body
differs only in the key name |
| `CallerFrom` | `reqctx.CallerFrom`, delegate in `api` | Nothing |
| `context.WithValue(ctx, <key>{}, v)` in `server.go`, `requestid.go`,
`scheduled_delivery.go` | `reqctx.With*(ctx, v)` | Same value, same
order |
| `context.WithValue` and `huma.WithValue` on these keys in 18 test
files | `reqctx.With*` | Assertions are unchanged |

The keys for the request's public key, the actor, the logged app and the
request failure stay in `internal/api`, since this PR does not need them
elsewhere.

## Tests

| Test | Defect it catches |
| --- | --- |
| `TestIdentityFromIsNilWhenCustomerIsMissingOrEmpty` | A request with
no customer gets an empty identity instead of none |
| `TestIdentityFromReadsAllRequestIdentityFields` | A setter and a
reader use different keys, or a field of `Identity` is not filled |
| `TestServerSideFromReadsBackFalse` | A setter ignores its argument, so
a device passes for a backend |
| `TestRequestIDFromRoundTrips` | The request id is stored under one key
and read under another |
| `TestOrganizationFromRoundTripsIndependently` | The organization
shares a key with the customer or the request id |
| `ScheduledTasksSuite/TestADeliveryRunsAsItsTasksOwnerServerSide`
(integration) | A scheduled delivery runs as the user's device. Before
this PR no test in that suite failed when the mark was false. |

<details><summary>Mutations and commands</summary>

Each mutant was applied, tested and restored in turn, and a test failed
for every one:

- Each of the five setters writes under another key, or ignores its
value.
- Each reader returns nothing, or the opposite. `CustomerFrom` accepts
an empty customer.
- The guard of `IdentityFrom` is off, or always on. Each field of
`Identity` is dropped, and `ServerSide` is read from the caller.
- Each delegate in `internal/api` calls another reader, or returns the
zero value.
- Each argument in the auth middleware, `withRequestID` and
`scheduledOwnerContext` is swapped or emptied.

Two mutants needed more than the first run: an empty organization in the
middleware is caught by `TestAccountSuite`, and a false server side mark
in `scheduledOwnerContext` is caught only by the new test.

```
go test ./internal/api/reqctx ./internal/api
go build ./... && go vet ./... && go vet -tags integration ./internal/... ./cmd/...
go run ./cmd/openapi && git diff --exit-code api/openapi.yaml
go test -tags integration ./internal/api -run '^(TestActivitySuite|TestAuditSuite|TestAuthorizationsSuite|TestFloorControlSuite|TestOAuthClientDataKeysSuite|TestAgentTeamsSuite|TestUsageIdentitySuite|TestProxiedUsageSuite|TestShippedUsageSuite|TestKnowledgeFilesSuite|TestScheduledTasksSuite)$'
```

`gofmt -l` names `dispatch_channel_test.go` and
`session_create_unit_test.go`, as it does on the base.

The whole integration run is not done here.

</details>

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added the docs label Dec 1, 2026
kanat and others added 2 commits November 30, 2026 22:40
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The session controllers need to return API errors, but the error types
live in a package they cannot import. This PR moves the types to a small
package of their own and leaves aliases behind, so existing code keeps
working. Nothing changes for a caller: statuses, codes, messages and the
API spec are the same.

## How it works

```text
internal/api                              internal/api/apierr (new)
  type APIError = apierr.APIError  ---->    APIError, ErrorType,
  (alias: the same type)                    ErrorResponse, ErrorDetail,
  newAPIError, notFound, ...                the type/status/code table
  (constructors stay for now)               Of

an error or a response body
  │
  ├─ refusalText (session socket)  ─┐
  └─ noteRefusals (activity count) ─┴─> apierr.Of(v)
                                          ├─ APIError            -> it, true
                                          ├─ type embedding one  -> it, true
                                          │  (moneyAnswer)
                                          └─ anything else       -> false
```

| Change | Result | Test |
| --- | --- | --- |
| `refusalText` uses `apierr.Of` | a socket frame keeps the refusal's
own words, also for a refusal with headers |
`TestRefusalTextReturnsTheMessageOfARefusalWithHeaders`,
`TestRefusalTextReturnsTheMessageOfAPlainRefusal` |
| `noteRefusals` uses `apierr.Of` | a refusal an operation returns is
still counted with its code |
`TestARefusalAnOperationReturnedIsCountedWithItsCode` (integration) |
| `Of` in `apierr` | matches an `APIError` and a type embedding one,
nothing else | `TestOfReturnsTheFailureATypeEmbeds`,
`TestOfReturnsFalseForAnythingElse` |
| Aliased `ErrorType*` constants | each type keeps its wire name |
`TestEveryErrorTypeIsSentUnderItsOwnName` |
| Types moved | `api/openapi.yaml` has no diff | `go run ./cmd/openapi`
|

## Why every match changes in this PR

The moved type has an unexported method that three places matched on. Go
treats an unexported method as a different one in each package, so a
match left behind would compile and never succeed. All three now call
`apierr.Of`.

## What differs from the moved code

| Symbol | Difference from the base |
| --- | --- |
| `ErrorType`, its constants, `errorTypes`, `errorDocs`, `APIError` and
its other methods, `ErrorDetail` | none |
| `(ErrorType).Schema` | calls `schema.NamedEnum`, which `namedEnum`
delegates to |
| `SomethingWentWrong`, `(*ErrorResponse).TransformSchema` | the
constant is exported; `api` keeps `somethingWentWrong` with its value |
| `apiError()` | its comment names `Of` instead of `noteRefusals` |
| `newAPIError`, `statusError` (stay in `api`) | read the moved table
through `ErrorType.Code` and `TypeOfStatus` instead of looping over it |
| `TestEveryErrorTypeIsAnsweredWithItsOwnStatus` | moved to `apierr`
with its assertions, in a suite; it builds the `APIError` directly |
| `authorizations_test.go` | expects the full documentation URL as text,
since `errorDocs` is now unexported in another package |

## Why `Code` and `TypeOfStatus` are exported

The constructors move in the next piece, so for now two of them need to
read a table that has already moved. These two lookups keep one copy of
the table. The next piece can unexport them.

<details><summary>Mutations and commands</summary>

A left-over `interface{ apiError() APIError }` match in `internal/api`,
tried before the switch to `Of`: it compiles and answers false for both
`APIError` and `moneyAnswer`, and both refusal text tests fail.

45 mutations, all caught:

- `Of` (5): matching `APIError()` instead of `apiError()` fails both
refusal text tests; matching only the `APIError` type fails the one with
headers; the wrong answer, value or ok fails
`TestOfReturnsTheFailureATypeEmbeds` or the stream socket tests.
- `ErrorType.Code` (3), `TypeOfStatus` (3), `newAPIError` (2),
`statusError` (2): inverted match, wrong row, wrong answer for an
unknown value, dropped message.
- `Status` (2), `DocURL`, `MarshalJSON`, `Error`.
- The spec (3): the `ErrorType` and `APIError` schemas and the 500 text
each change `openapi.yaml`.
- `refusalText` (4) and `noteRefusals` (3, with `TestActivitySuite`),
the old assertion included.
- Each of the 15 aliased constants, pointed at another type.

Commands, from `acceleration/`: `go build ./...`, `go vet ./...`, `go
vet -tags integration ./internal/... ./cmd/...`, `go run ./cmd/openapi
&& git diff --exit-code api/openapi.yaml`, `go test ./internal/api
./internal/api/...`, and `TestActivitySuite`, `TestAuthorizationsSuite`
and `TestAdmissionSuite` with `-tags integration`. All pass.

The integration suites not named here were not run locally.

</details>

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant