Repository navigation
feat: show and filter by organization in AI Gateway sessions API - #32057
Conversation
mollymaefraser
left a comment
There was a problem hiding this comment.
Self-review
| WHEN @session_id::text != '' THEN ai.session_id = @session_id::text | ||
| ELSE true | ||
| END | ||
| -- Filter organization_id |
There was a problem hiding this comment.
Same rule as the filter in CountAIBridgeSessions (line 348), so the count and the page agree.
| AND ai.initiator_id = sp.initiator_id | ||
| AND ai.ended_at IS NOT NULL | ||
| ) sr ON true | ||
| LEFT JOIN LATERAL ( |
There was a problem hiding this comment.
This reads sr.interception_ids, so it only covers ended interceptions from the session’s initiator, same as the rest of the row. The inner JOIN to organizations is safe because organization_id is ON DELETE RESTRICT. sources never contains NULL because the migration’s CHECK ties organization_source NULL-ness to organization_id.
| SELECT | ||
| COALESCE(aibridge_interceptions.thread_root_id, aibridge_interceptions.id) AS thread_id, | ||
| sqlc.embed(aibridge_interceptions) | ||
| sqlc.embed(aibridge_interceptions), |
There was a problem hiding this comment.
The COALESCE and ::text casts keep sqlc from generating sql.NullString here. An empty string means no org. Callers should check OrganizationID.Valid instead.
| JOIN | ||
| paginated_threads pt | ||
| ON pt.thread_id = COALESCE(aibridge_interceptions.thread_root_id, aibridge_interceptions.id) | ||
| LEFT JOIN LATERAL ( |
There was a problem hiding this comment.
The LATERAL is deliberate: a plain LEFT JOIN organizations would add a second id column, and the injected @authorize_filter (which appears twice in this query) can reference a bare id, making it ambiguous. The lateral only exposes name, display name and icon.
| } | ||
|
|
||
| // AIBridgeInterceptionOrganizationSource converts a database organization source to its SDK value. | ||
| func AIBridgeInterceptionOrganizationSource(source database.AIBridgeInterceptionOrganizationSource) codersdk.AIBridgeInterceptionOrganizationSource { |
There was a problem hiding this comment.
This is a straight cast. It’s exported only so TestAIBridgeInterceptionOrganizationSource can check that every DB enum value has an SDK counterpart.
| // aiBridgeSessionOrganizations decodes the organizations JSON array built by | ||
| // ListAIBridgeSessions. It never returns nil, so the API sends [] rather | ||
| // than null. | ||
| func aiBridgeSessionOrganizations(raw json.RawMessage) []codersdk.AIBridgeSessionOrganization { |
There was a problem hiding this comment.
On an unmarshal error this returns [], so malformed data looks the same as “no orgs”. The JSON comes from our own query, so I don’t expect it to happen. Should this log the error, or is silent fallback fine here?
| filter.Model = parser.String(values, "", "model") | ||
| filter.Client = parser.String(values, "", "client") | ||
| filter.SessionID = parser.String(values, "", "session_id") | ||
| filter.OrganizationID = parseOrganization(ctx, db, parser, values, "organization") |
There was a problem hiding this comment.
This reuses parseOrganization, so an unknown or unauthorized org name returns a validation error. An unknown org ID isn't looked up and returns an empty page (see the open question in the description). UnknownOrganization in aibridge_test.go covers the name case.
| TokenUsageSummary AIBridgeSessionTokenUsageSummary `json:"token_usage_summary"` | ||
| // Organizations are the organizations this session's interceptions were | ||
| // attributed to. | ||
| Organizations []AIBridgeSessionOrganization `json:"organizations"` |
There was a problem hiding this comment.
Always non-nil. Sessions with no org return [], not null, and the generated TS type relies on that.
| }, &endedAt) | ||
| } | ||
|
|
||
| // One session across two orgs. aaa-org is reached through two sources. |
There was a problem hiding this comment.
“multi-org” is deliberately one session across two orgs, with two sources on aaa-org. The filter loop at the end checks that filtering by either org returns it once.
|
|
||
| // child2 has no stored org. | ||
| child2EndedAt := now.Add(3 * time.Minute) | ||
| dbgen.AIBridgeInterception(t, db, database.InsertAIBridgeInterceptionParams{ |
There was a problem hiding this comment.
child2 has no org on purpose, to cover a nil Organization on an agentic action.
This stack of pull requests is managed by Graphite. Learn more about stacking. |
SasSwart
left a comment
There was a problem hiding this comment.
Just one note on a test. Nothing to change. Let's get this in and deployed, but we should keep an eye on the grafana dashboards to check query performance.
Thanks Sas, in Slack can you point me in the direction of how I would observe this? |
…ay session queries
000e30f to
8dcefea
Compare

Adds an
organizationfilter toGET /api/v2/ai-gateway/sessions(and its/api/v2/aibridge/sessionsalias) and returns the organization an interception was attributed to, and how it was chosen, on sessions, threads and agentic actions, as proposed in the surface definitions on AIGOV-754. No migration:aibridge_interceptions.organization_idandorganization_sourcealready exist (000634).The filter accepts an organization name or ID and keeps sessions with at least one interception in that organization; the count uses the same rule so pagination totals match. Each session, on the list and detail responses, lists the organizations its interceptions were attributed to, ordered by name, with the distinct sources used for each, or
[]when none was stored. Each thread carries the organization of its root interception and each agentic action carries its own, or null when none was stored. The new filter is listed in the AI Gateway monitoring docs.Refs AIGOV-754
Open questions for reviewers
threads,started_atandended_atonly cover the matching interceptions, while providers, models, tokens andorganizationscover the whole session. Is that the desired behavior?parseOrganizationdoes not look up UUIDs. This matches workspaces and templates, but the spec says 400.Notes for reviewers
aiBridgeSessionOrganizationsreturns an empty list if the organizations JSON from the query can’t be decoded, rather than failing the whole request. The field is supplementary, so a decoding problem shouldn’t take down the sessions list, but it does mean a SQL bug here would show up as empty data rather than an error. The alternative is to log the error before returning the empty list.Implementation notes
coderd/database/queries/aibridge.sql:@organization_idfilter inCountAIBridgeSessionsand thesession_pageCTE ofListAIBridgeSessions.sorglateral inListAIBridgeSessionsthat groups the session's interceptions by organization, collects distinct sources, joinsorganizations(deleted orgs still resolve) and returns a JSON array.ListAIBridgeSessionThreadsresolves the organization name, display name and icon through aLEFT JOIN LATERALin the finalSELECT. A plain join onorganizationsis not safe there: the query has two@authorize_filterplaceholders, and the injected filter can reference a bareid, which would be ambiguous next toorganizations.id. The lateral only exposes the three selected columns. This answers the authorize-filter open question from the surface proposal.coderd/database/modelqueries.go: the hand-writtenListAuthorizedAIBridgeSessions,CountAuthorizedAIBridgeSessionsandListAuthorizedAIBridgeSessionThreadsgain the new argument and scan columns. The compiler does not catch a mismatch here; it fails at runtime.enterprise/coderd/aibridge.go: passOrganizationIDintoCountAIBridgeSessionsParams, which is built field by field, and list theorganizationkey in@Param q.coderd/searchquery/search.go:organizationkey viaparseOrganization.codersdk/aibridge.go:AIBridgeInterceptionOrganizationSourceenum,AIBridgeInterceptionOrganization,AIBridgeSessionOrganization, new response fields andAIBridgeListSessionsFilter.Organization, per the proposed Go definitions.coderd/database/db2sdk/db2sdk.go: decode the session organizations JSON, never returning nil;AIBridgeInterceptionOrganizationSourceconverter; build one organization per interception while grouping thread rows, and use it for the thread (root interception) and each agentic action.site/: addorganizations: []to two frontend mocks, now that the field is required in the generated types.docs/ai-governance/ai-gateway/monitoring.md:organizationadded to the sessions API query filters.TestAIBridgeSessions(name and ID parsing),TestAIBridgeListSessions/Filters(by name and ID, checks count and page),FilterErrors/UnknownOrganization,TestAIBridgeListSessions/Organizations(multi-org ordering and sources, no-org session returns[], filtering by either org returns the multi-org session and never the no-org one),TestAIBridgeGetSessionThreads/Organizations(thread uses the root's org, each action its own, null when none, sessionorganizationson the detail endpoint), andTestAIBridgeInterceptionOrganizationSource(every database source maps to an SDK value).make gen.Code written by @mollymaefraser, with Coder Agents used as a guide: explaining the existing code path, reviewing each step, and running tests.