Skip to content

feat: show and filter by organization in AI Gateway sessions API - #32057

Merged
mollymaefraser merged 7 commits into
mainfrom
molly/aigov-754-sessions-org-backend
Nov 19, 2026
Merged

mollymaefraser merged 7 commits into
mainfrom
molly/aigov-754-sessions-org-backend

Conversation

@mollymaefraser

@mollymaefraser mollymaefraser commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Adds an organization filter to GET /api/v2/ai-gateway/sessions (and its /api/v2/aibridge/sessions alias) 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_id and organization_source already 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

  • Multi-org sessions (AIGOV-776): the filter is row-level, like provider and model. A session spanning two orgs is listed under each org's filter, and with the filter on, threads, started_at and ended_at only cover the matching interceptions, while providers, models, tokens and organizations cover the whole session. Is that the desired behavior?
  • Unknown org ID: an unknown org name returns 400, but an unknown org ID returns an empty page, because parseOrganization does not look up UUIDs. This matches workspaces and templates, but the spec says 400.

Notes for reviewers

  • aiBridgeSessionOrganizations returns 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.
  • A thread’s organization is taken from its root interception only. If later requests in the same thread were attributed to a different organization, that shows on each agentic action’s own organization field.
Implementation notes
  • coderd/database/queries/aibridge.sql:
    • @organization_id filter in CountAIBridgeSessions and the session_page CTE of ListAIBridgeSessions.
    • New sorg lateral in ListAIBridgeSessions that groups the session's interceptions by organization, collects distinct sources, joins organizations (deleted orgs still resolve) and returns a JSON array.
    • ListAIBridgeSessionThreads resolves the organization name, display name and icon through a LEFT JOIN LATERAL in the final SELECT. A plain join on organizations is not safe there: the query has two @authorize_filter placeholders, and the injected filter can reference a bare id, which would be ambiguous next to organizations.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-written ListAuthorizedAIBridgeSessions, CountAuthorizedAIBridgeSessions and ListAuthorizedAIBridgeSessionThreads gain the new argument and scan columns. The compiler does not catch a mismatch here; it fails at runtime.
  • enterprise/coderd/aibridge.go: pass OrganizationID into CountAIBridgeSessionsParams, which is built field by field, and list the organization key in @Param q.
  • coderd/searchquery/search.go: organization key via parseOrganization.
  • codersdk/aibridge.go: AIBridgeInterceptionOrganizationSource enum, AIBridgeInterceptionOrganization, AIBridgeSessionOrganization, new response fields and AIBridgeListSessionsFilter.Organization, per the proposed Go definitions.
  • coderd/database/db2sdk/db2sdk.go: decode the session organizations JSON, never returning nil; AIBridgeInterceptionOrganizationSource converter; build one organization per interception while grouping thread rows, and use it for the thread (root interception) and each agentic action.
  • site/: add organizations: [] to two frontend mocks, now that the field is required in the generated types.
  • docs/ai-governance/ai-gateway/monitoring.md: organization added to the sessions API query filters.
  • Tests: 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, session organizations on the detail endpoint), and TestAIBridgeInterceptionOrganizationSource (every database source maps to an SDK value).
  • Remaining files are generated by make gen.

Code written by @mollymaefraser, with Coder Agents used as a guide: explaining the existing code path, reviewing each step, and running tests.

@mollymaefraser
mollymaefraser temporarily deployed to main November 11, 2026 15:39 — with GitHub Actions Inactive
@mollymaefraser
mollymaefraser temporarily deployed to main November 11, 2026 15:39 — with GitHub Actions Inactive
@linear-code

linear-code Bot commented Nov 11, 2026

Copy link
Copy Markdown

AIGOV-754

@mollymaefraser
mollymaefraser temporarily deployed to main November 11, 2026 15:40 — with GitHub Actions Inactive
@mollymaefraser
mollymaefraser temporarily deployed to main November 12, 2026 10:19 — with GitHub Actions Inactive
@mollymaefraser
mollymaefraser temporarily deployed to main November 12, 2026 10:20 — with GitHub Actions Inactive
@mollymaefraser
mollymaefraser temporarily deployed to main November 12, 2026 10:21 — with GitHub Actions Inactive
@mollymaefraser
mollymaefraser temporarily deployed to main November 12, 2026 10:50 — with GitHub Actions Inactive
@mollymaefraser
mollymaefraser temporarily deployed to main November 12, 2026 10:53 — with GitHub Actions Inactive
@mollymaefraser
mollymaefraser temporarily deployed to main November 12, 2026 10:54 — with GitHub Actions Inactive
@mollymaefraser
mollymaefraser temporarily deployed to main November 12, 2026 11:10 — with GitHub Actions Inactive
@mollymaefraser
mollymaefraser temporarily deployed to main November 12, 2026 11:11 — with GitHub Actions Inactive
@mollymaefraser
mollymaefraser temporarily deployed to main November 12, 2026 11:13 — with GitHub Actions Inactive
@mollymaefraser
mollymaefraser temporarily deployed to main November 12, 2026 11:14 — with GitHub Actions Inactive
@mollymaefraser
mollymaefraser marked this pull request as ready for review November 16, 2026 08:22
@mollymaefraser
mollymaefraser temporarily deployed to main November 16, 2026 08:22 — with GitHub Actions Inactive

@mollymaefraser mollymaefraser left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Self-review

WHEN @session_id::text != '' THEN ai.session_id = @session_id::text
ELSE true
END
-- Filter organization_id

@mollymaefraser mollymaefraser Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 (

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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),

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 (

@mollymaefraser mollymaefraser Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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")

@mollymaefraser mollymaefraser Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Comment thread codersdk/aibridge.go
TokenUsageSummary AIBridgeSessionTokenUsageSummary `json:"token_usage_summary"`
// Organizations are the organizations this session's interceptions were
// attributed to.
Organizations []AIBridgeSessionOrganization `json:"organizations"`

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

“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{

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

child2 has no org on purpose, to cover a nil Organization on an agentic action.

Copy link
Copy Markdown
Collaborator Author

@SasSwart SasSwart left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Comment thread enterprise/coderd/aibridge_test.go Resolved
@mollymaefraser

Copy link
Copy Markdown
Collaborator Author

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?

@mollymaefraser
mollymaefraser force-pushed the molly/aigov-754-sessions-org-backend branch from 000e30f to 8dcefea Compare November 19, 2026 08:47
@mollymaefraser
mollymaefraser enabled auto-merge (squash) November 19, 2026 08:49
@mollymaefraser
mollymaefraser merged commit 4bccdc4 into main Nov 19, 2026
33 of 34 checks passed
@mollymaefraser
mollymaefraser deleted the molly/aigov-754-sessions-org-backend branch November 19, 2026 09:08
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 19, 2026

This branch had an error being deployed

1 failed and 1 inactive deployments
main — 8dcefeaf Deployed Nov 19, 2026 by mollymaefraser via cla #260120
docs-preview — 8dcefeaf Deployed Nov 19, 2026 by mollymaefraser via cleanup #249
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants