Record agent versions and last sync time for external agent sessions
What does this MR do and why?
This MR is part of GitLab AI Agent Governance (GAIG). GAIG records sessions from external AI coding agents (Claude Code, OpenCode, Codex, Cursor). The glab CLI uploads those sessions.
This MR does two things:
POST /api/v4/projects/:id/ai_agent/sessionsaccepts two new optional parameters:glab_versionandagent_version. Both are strings, up to 255 characters. They are stored on the new row inai_governance_sessionswhen the session is created. The session API response returns them.ai_agent_identitiesgets a new nullable column,last_synced_at(timestamp with time zone). It is set byAi::ExternalAgents::AgentIdentity.record_sync(id).
Why
- Versions: they let us trace a problem to a specific glab or agent release. Later stages can also use the agent version, for example for model allowlisting or cost attribution.
last_synced_at: the fallback sync runs on developer machines, and its failures are otherwise invisible to admins. This column lets admins later see which machines have stopped syncing.
How record_sync works
- It is a single primary-key UPDATE.
- It writes only when
last_synced_atis empty or older than 5 minutes. - It writes only for active (non-revoked) identities.
- It does not change
updated_at. - It runs after a successful identity registration, session creation, session completion, or audit event upload.
Why
glab calls several of these endpoints on every sync. The 5-minute throttle keeps this from causing a write on every call.
Not in this MR
Showing last_synced_at to admins (API, GraphQL or the governance UI) is not part of this MR. It is follow-up work on https://gitlab.com/gitlab-org/gitlab/-/work_items/633649. This MR does not close that work item.
Database
- Two regular migrations (
Gitlab::Database::Migration[2.4], milestone 19.5). Both tables are small. - The new text columns get 255-character limits with
add_text_limit. ai_governance_sessionsis replicated to ClickHouse by Siphon. A ClickHouse migration addsglab_versionandagent_versionasNullable(String)tosiphon_ai_governance_sessions. This matches the existing nullable text columns there.db/structure.sqlwas generated withscripts/regenerate-schema.db/click_house/main.sql, the Siphon schema cache file and the ClickHouse schema migration marker were updated by hand. This follows the same pattern as the earlier commit that addedagent_identity_idto that table.- The ClickHouse up and down SQL were checked against a temporary table.
Why
The ClickHouse files were edited by hand because the local ClickHouse could not run all master migrations.
Tests
- Model, service and request specs. They include checks that no sync is recorded when a request fails or the identity is revoked.
ee/spec/requests/api/ai/external_agents/audit_events_spec.rbnow uses:clean_gitlab_redis_rate_limiting.
Why
The examples in that spec share one rate-limit counter in Redis. Adding an example pushed a later example over the limit.
The OpenAPI v3 document is regenerated.
References
- Resolves https://gitlab.com/gitlab-org/gitlab/-/work_items/633646
- Related: https://gitlab.com/gitlab-org/gitlab/-/work_items/633649
- Related client change in glab, which sends the correct sync_type: cli!4105 (merged)
Screenshots or screen recordings
Not applicable. There is no UI change.
How to set up and validate locally
You need a license that includes the ai_catalog licensed feature. Use a user with the developer role on a project.
-
Register an identity.
machine_fingerprintcan be any 64-character hex string.curl --request POST \ --header "PRIVATE-TOKEN: <token>" \ --data "agent_type=claude-code" \ --data "machine_fingerprint=$(printf 'a%.0s' {1..64})" \ "http://gdk.test:3000/api/v4/projects/:id/ai_agent/identities" -
Create a session with the
agent_identity_idfrom step 1. The response includesglab_versionandagent_version.curl --request POST \ --header "PRIVATE-TOKEN: <token>" \ --data "agent_type=claude-code" \ --data "agent_identity_id=<agent_identity_id>" \ --data "sync_type=hook" \ --data "glab_version=glab 1.121.0" \ --data "agent_version=2.1.295" \ "http://gdk.test:3000/api/v4/projects/:id/ai_agent/sessions" -
In the Rails console, check that
last_synced_atis set:Ai::ExternalAgents::AgentIdentity.find(<id>).last_synced_at
Database review
Migrations
This MR adds three migrations. It adds no new indexes.
AddVersionsToAiGovernanceSessionsadds two nullabletextcolumns toai_governance_sessions:glab_versionandagent_version. Each has a 255-character limit, added withadd_text_limit.AddLastSyncedAtToAiAgentIdentitiesadds a nullablelast_synced_atcolumn (timestamp with time zone) toai_agent_identities.- A ClickHouse migration adds the two version columns as
Nullable(String)tosiphon_ai_governance_sessions.
Both PostgreSQL migrations were run up and down on the test database, main only.
Migration up output
main: == 20261013233001 AddVersionsToAiGovernanceSessions: migrating ================
main: -- add_column(:ai_governance_sessions, :glab_version, :text, {:if_not_exists=>true})
main: -> 0.0318s
main: -- add_column(:ai_governance_sessions, :agent_version, :text, {:if_not_exists=>true})
main: -> 0.0010s
main: -- transaction_open?(nil)
main: -> 0.0000s
main: -- transaction_open?(nil)
main: -> 0.0000s
main: -- execute("ALTER TABLE ai_governance_sessions\nADD CONSTRAINT check_e5536276dc\nCHECK ( char_length(glab_version) <= 255 )\nNOT VALID;\n")
main: -> 0.0013s
main: -- execute("SET statement_timeout TO 0")
main: -> 0.0002s
main: -- execute("ALTER TABLE ai_governance_sessions VALIDATE CONSTRAINT check_e5536276dc;")
main: -> 0.0005s
main: -- execute("RESET statement_timeout")
main: -> 0.0002s
main: -- transaction_open?(nil)
main: -> 0.0000s
main: -- transaction_open?(nil)
main: -> 0.0000s
main: -- execute("ALTER TABLE ai_governance_sessions\nADD CONSTRAINT check_41f35a4745\nCHECK ( char_length(agent_version) <= 255 )\nNOT VALID;\n")
main: -> 0.0003s
main: -- execute("ALTER TABLE ai_governance_sessions VALIDATE CONSTRAINT check_41f35a4745;")
main: -> 0.0003s
main: == 20261013233001 AddVersionsToAiGovernanceSessions: migrated (0.0529s) =======
main: == 20261013233002 AddLastSyncedAtToAiAgentIdentities: migrating ===============
main: -- add_column(:ai_agent_identities, :last_synced_at, :datetime_with_timezone)
main: -> 0.0183s
main: == 20261013233002 AddLastSyncedAtToAiAgentIdentities: migrated (0.0225s) ======Migration down output
main: == 20261013233002 AddLastSyncedAtToAiAgentIdentities: reverting ===============
main: -- remove_column(:ai_agent_identities, :last_synced_at, :datetime_with_timezone)
main: -> 0.0183s
main: == 20261013233002 AddLastSyncedAtToAiAgentIdentities: reverted (0.0245s) ======
main: == 20261013233001 AddVersionsToAiGovernanceSessions: reverting ================
main: -- remove_column(:ai_governance_sessions, :glab_version, {:if_exists=>true})
main: -> 0.0190s
main: -- remove_column(:ai_governance_sessions, :agent_version, {:if_exists=>true})
main: -> 0.0010s
main: == 20261013233001 AddVersionsToAiGovernanceSessions: reverted (0.0240s) =======Queries
Query plans were captured with EXPLAIN (ANALYZE, BUFFERS) in a local GDK development database, inside a transaction that was rolled back. The local tables have only a handful of rows, so the timings are not representative of GitLab.com. The plans still answer the question. Every query is a single-row lookup by primary key or by a unique-indexed column, so its cost does not depend on table size. All tables involved are marked table_size: small in their db/docs dictionary entries and are in the gitlab_main_org schema.
One new query is added: Ai::ExternalAgents::AgentIdentity.record_sync.
- It is an
update_all. It runs after a successful identity registration, session creation, session completion, or audit event upload. - It updates at most one row, by primary key.
- It only touches an active identity, and only when
last_synced_atis empty or older than 5 minutes. Repeated calls within 5 minutes write nothing. - It does not change
updated_at. - The literal values in the SQL (id and timestamps) come from the local run.
The only other changed write is the existing session INSERT into ai_governance_sessions. It now also sets the two new version columns. It is not a new query.
`record_sync` UPDATE: SQL
UPDATE "ai_agent_identities" SET "last_synced_at" = '2026-10-14 02:30:34.163385' WHERE "ai_agent_identities"."revoked_at" IS NULL AND "ai_agent_identities"."id" = 1 AND (last_synced_at IS NULL OR last_synced_at < '2026-10-14 02:25:34.163334')`record_sync` UPDATE: query plan
Update on ai_agent_identities (cost=0.15..2.17 rows=0 width=0) (actual time=0.020..0.020 rows=0 loops=1)
Buffers: shared hit=5
-> Index Scan using ai_agent_identities_pkey on ai_agent_identities (cost=0.15..2.17 rows=1 width=14) (actual time=0.004..0.005 rows=1 loops=1)
Index Cond: (id = 1)
Filter: ((revoked_at IS NULL) AND ((last_synced_at IS NULL) OR (last_synced_at < '2026-10-14 02:25:34.163334+00'::timestamp with time zone)))
Buffers: shared hit=2
Planning Time: 0.021 ms
Execution Time: 0.028 msNew model validations
Ai::Governance::Session gets length: { maximum: 255 } on glab_version and agent_version.
The columns are new and nullable, so all existing rows are NULL and stay valid. The database enforces the same limit.
Before database review
- The
db:gitlabcom-database-testingpipeline has not run yet. This MR is a draft with[skip ci]in its title. - Run that pipeline before requesting database review.
- A database reviewer can be assigned after the pipeline has run.
MR acceptance checklist
Evaluate this MR against the MR acceptance checklist. It helps you analyze changes to reduce risks in quality, performance, reliability, security, and maintainability.