Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: HA-compatible TaskRun session monitoring (#18706)

Danny Xu564f1e56183a
diff --git a/backend/api/v1/rollout_service.go b/backend/api/v1/rollout_service.go
index e9976b1dcf..9880d9fa9f 100644
--- a/backend/api/v1/rollout_service.go
+++ b/backend/api/v1/rollout_service.go
@@ -3,6 +3,7 @@ package v1
import (
"context"
"database/sql"
+ "fmt"
"slices"
"strings"
"time"
@@ -493,14 +494,6 @@ func (s *RolloutService) GetTaskRunSession(ctx context.Context, req *connect.Req
if err != nil {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "failed to get task run uid"))
}
- connIDAny, ok := s.stateCfg.TaskRunConnectionID.Load(taskRunUID)
- if !ok {
- return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("connection id not found for task run %d", taskRunUID))
- }
- connID, ok := connIDAny.(string)
- if !ok {
- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("expect connection id to be of type string but found %T", connIDAny))
- }
task, err := s.store.GetTaskByID(ctx, taskUID)
if err != nil {
@@ -518,7 +511,8 @@ func (s *RolloutService) GetTaskRunSession(ctx context.Context, req *connect.Req
}
defer driver.Close(ctx)
- session, err := getSession(ctx, instance.Metadata.GetEngine(), driver.GetDB(), connID)
+ appName := fmt.Sprintf("bytebase-taskrun-%d", taskRunUID)
+ session, err := getSession(ctx, instance.Metadata.GetEngine(), driver.GetDB(), appName)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get session"))
}
@@ -528,33 +522,36 @@ func (s *RolloutService) GetTaskRunSession(ctx context.Context, req *connect.Req
return connect.NewResponse(session), nil
}
-func getSession(ctx context.Context, engine storepb.Engine, db *sql.DB, connID string) (*v1pb.TaskRunSession, error) {
+func getSession(ctx context.Context, engine storepb.Engine, db *sql.DB, appName string) (*v1pb.TaskRunSession, error) {
switch engine {
- case storepb.Engine_POSTGRES:
+ case storepb.Engine_POSTGRES, storepb.Engine_COCKROACHDB:
query := `
+ WITH target_session AS (
+ SELECT pid FROM pg_catalog.pg_stat_activity WHERE application_name = $1 LIMIT 1
+ )
SELECT
- pid,
- pg_blocking_pids(pid) AS blocked_by_pids,
- query,
- state,
- wait_event_type,
- wait_event,
- datname,
- usename,
- application_name,
- client_addr,
- client_port,
- backend_start,
- xact_start,
- query_start
+ a.pid,
+ pg_blocking_pids(a.pid) AS blocked_by_pids,
+ a.query,
+ a.state,
+ a.wait_event_type,
+ a.wait_event,
+ a.datname,
+ a.usename,
+ a.application_name,
+ a.client_addr,
+ a.client_port,
+ a.backend_start,
+ a.xact_start,
+ a.query_start
FROM
- pg_catalog.pg_stat_activity
- WHERE pid = $1
- OR pid = ANY(pg_blocking_pids($1))
- OR $1 = ANY(pg_blocking_pids(pid))
- ORDER BY pid
+ pg_catalog.pg_stat_activity a
+ WHERE a.application_name = $1
+ OR (SELECT pid FROM target_session) = ANY(pg_blocking_pids(a.pid))
+ OR a.pid = ANY(pg_blocking_pids((SELECT pid FROM target_session)))
+ ORDER BY a.pid
`
- rows, err := db.QueryContext(ctx, query, connID)
+ rows, err := db.QueryContext(ctx, query, appName)
if err != nil {
return nil, errors.Wrapf(err, "failed to query rows")
}
@@ -599,12 +596,16 @@ func getSession(ctx context.Context, engine storepb.Engine, db *sql.DB, connID s
s.QueryStart = timestamppb.New(*qs)
}
- if s.Pid == connID {
+ if s.ApplicationName == appName {
ss.Session = &s
- } else if slices.Contains(s.BlockedByPids, connID) {
- ss.BlockedSessions = append(ss.BlockedSessions, &s)
- } else {
- ss.BlockingSessions = append(ss.BlockingSessions, &s)
+ } else if ss.Session != nil {
+ // For blocking/blocked sessions, we need to check if they're related to our main session
+ // We stored the main session, so check relationships with it
+ if slices.Contains(s.BlockedByPids, ss.Session.Pid) {
+ ss.BlockedSessions = append(ss.BlockedSessions, &s)
+ } else if slices.Contains(ss.Session.BlockedByPids, s.Pid) {
+ ss.BlockingSessions = append(ss.BlockingSessions, &s)
+ }
}
}
@@ -618,7 +619,7 @@ func getSession(ctx context.Context, engine storepb.Engine, db *sql.DB, connID s
},
}, nil
default:
- return nil, errors.Errorf("unsupported engine type %v", engine.String())
+ return nil, errors.Errorf("session monitoring is only supported for PostgreSQL and CockroachDB")
}
}
diff --git a/backend/component/state/state.go b/backend/component/state/state.go
index ed3c2634f9..931fe1b573 100644
--- a/backend/component/state/state.go
+++ b/backend/component/state/state.go
@@ -12,9 +12,6 @@ type State struct {
TaskRunSchedulerInfo sync.Map // map[taskRunID]*storepb.SchedulerInfo
- // TaskRunConnectionID is the map from task run ID to the connection id of the connection to the database.
- TaskRunConnectionID sync.Map // map[taskRunID]string
-
// RunningTaskRunsCancelFunc is the cancelFunc of running taskruns.
RunningTaskRunsCancelFunc sync.Map // map[taskRunID]context.CancelFunc
diff --git a/backend/plugin/db/cockroachdb/cockroachdb.go b/backend/plugin/db/cockroachdb/cockroachdb.go
index 32d5ae14ba..fb0ba56d6d 100644
--- a/backend/plugin/db/cockroachdb/cockroachdb.go
+++ b/backend/plugin/db/cockroachdb/cockroachdb.go
@@ -159,9 +159,13 @@ func getCockroachConnectionConfig(config db.ConnectionConfig) (*pgx.ConnConfig,
if tlscfg != nil {
connConfig.TLSConfig = tlscfg
}
+ appName := "bytebase"
+ if config.ConnectionContext.TaskRunUID != nil {
+ appName = fmt.Sprintf("bytebase-taskrun-%d", *config.ConnectionContext.TaskRunUID)
+ }
+ connConfig.RuntimeParams["application_name"] = appName
if config.ConnectionContext.ReadOnly {
connConfig.RuntimeParams["default_transaction_read_only"] = "true"
- connConfig.RuntimeParams["application_name"] = "bytebase"
}
return connConfig, nil
@@ -317,18 +321,6 @@ func (d *Driver) executeInTransactionMode(
}
defer conn.Close()
- if opts.SetConnectionID != nil {
- var pid string
- if err := conn.QueryRowContext(ctx, "SELECT pg_backend_pid()").Scan(&pid); err != nil {
- return 0, errors.Wrapf(err, "failed to get connection id")
- }
- opts.SetConnectionID(pid)
-
- if opts.DeleteConnectionID != nil {
- defer opts.DeleteConnectionID()
- }
- }
-
if isPlsql {
// USE SET SESSION ROLE to set the role for the current session.
if err := crdb.Execute(func() error {
@@ -463,18 +455,6 @@ func (d *Driver) executeInAutoCommitMode(
}
defer conn.Close()
- if opts.SetConnectionID != nil {
- var pid string
- if err := conn.QueryRowContext(ctx, "SELECT pg_backend_pid()").Scan(&pid); err != nil {
- return 0, errors.Wrapf(err, "failed to get connection id")
- }
- opts.SetConnectionID(pid)
-
- if opts.DeleteConnectionID != nil {
- defer opts.DeleteConnectionID()
- }
- }
-
if isPlsql {
// USE SET SESSION ROLE to set the role for the current session.
if err := crdb.Execute(func() error {
diff --git a/backend/plugin/db/driver.go b/backend/plugin/db/driver.go
index cdc47970db..c4d807678f 100644
--- a/backend/plugin/db/driver.go
+++ b/backend/plugin/db/driver.go
@@ -103,6 +103,8 @@ type ConnectionContext struct {
ReadOnly bool
// MessageBuffer is used for logging messages from the database server.
MessageBuffer []*v1pb.QueryResult_Message
+ // TaskRunUID is set when executing a task run, used to set application_name for connection identification.
+ TaskRunUID *int
}
// AppendMessage appends a message to the message buffer.
@@ -193,10 +195,6 @@ type ExecuteOptions struct {
// else only log the command index.
LogCommandStatement bool
- // Record the connection id first before executing.
- SetConnectionID func(id string)
- DeleteConnectionID func()
-
// The maximum number of retries for lock timeout statements.
MaximumRetries int
}
diff --git a/backend/plugin/db/pg/pg.go b/backend/plugin/db/pg/pg.go
index f3a79fe471..3154e0fa7b 100644
--- a/backend/plugin/db/pg/pg.go
+++ b/backend/plugin/db/pg/pg.go
@@ -76,7 +76,11 @@ func (d *Driver) Open(ctx context.Context, _ storepb.Engine, config db.Connectio
if err != nil {
return nil, err
}
- pgxConnConfig.RuntimeParams["application_name"] = "bytebase"
+ appName := "bytebase"
+ if config.ConnectionContext.TaskRunUID != nil {
+ appName = fmt.Sprintf("bytebase-taskrun-%d", *config.ConnectionContext.TaskRunUID)
+ }
+ pgxConnConfig.RuntimeParams["application_name"] = appName
if config.ConnectionContext.ReadOnly {
pgxConnConfig.RuntimeParams["default_transaction_read_only"] = "true"
}
@@ -489,18 +493,6 @@ func (d *Driver) executeInTransactionMode(
}
defer conn.Close()
- if opts.SetConnectionID != nil {
- var pid string
- if err := conn.QueryRowContext(ctx, "SELECT pg_backend_pid()").Scan(&pid); err != nil {
- return 0, errors.Wrapf(err, "failed to get connection id")
- }
- opts.SetConnectionID(pid)
-
- if opts.DeleteConnectionID != nil {
- defer opts.DeleteConnectionID()
- }
- }
-
if isPlsql {
if d.connectionCtx.TenantMode {
// USE SET SESSION ROLE to set the role for the current session.
@@ -634,18 +626,6 @@ func (d *Driver) executeInAutoCommitMode(
}
defer conn.Close()
- if opts.SetConnectionID != nil {
- var pid string
- if err := conn.QueryRowContext(ctx, "SELECT pg_backend_pid()").Scan(&pid); err != nil {
- return 0, errors.Wrapf(err, "failed to get connection id")
- }
- opts.SetConnectionID(pid)
-
- if opts.DeleteConnectionID != nil {
- defer opts.DeleteConnectionID()
- }
- }
-
if d.connectionCtx.TenantMode {
// USE SET SESSION ROLE to set the role for the current session.
if _, err := conn.ExecContext(ctx, fmt.Sprintf("SET SESSION ROLE '%s'", owner)); err != nil {
diff --git a/backend/runner/taskrun/database_migrate_executor.go b/backend/runner/taskrun/database_migrate_executor.go
index efa25c9dde..d9f5d293ac 100644
--- a/backend/runner/taskrun/database_migrate_executor.go
+++ b/backend/runner/taskrun/database_migrate_executor.go
@@ -123,7 +123,7 @@ func (exec *DatabaseMigrateExecutor) runMigrationWithPriorBackup(ctx context.Con
}
}
- terminated, result, err := runMigration(ctx, driverCtx, exec.store, exec.dbFactory, exec.stateCfg, exec.schemaSyncer, exec.profile, task, taskRunUID, sheet, task.Payload.GetSchemaVersion())
+ terminated, result, err := runMigration(ctx, driverCtx, exec.store, exec.dbFactory, exec.schemaSyncer, exec.profile, task, taskRunUID, sheet, task.Payload.GetSchemaVersion())
if result != nil {
// Save prior backup detail to task run result.
result.PriorBackupDetail = priorBackupDetail
@@ -230,7 +230,7 @@ func (exec *DatabaseMigrateExecutor) runGhostMigration(ctx context.Context, driv
}
}
- return runMigrationWithFunc(ctx, driverCtx, exec.store, exec.dbFactory, exec.stateCfg, exec.schemaSyncer, exec.profile, task, taskRunUID, sheet, task.Payload.GetSchemaVersion(), execFunc)
+ return runMigrationWithFunc(ctx, driverCtx, exec.store, exec.dbFactory, exec.schemaSyncer, exec.profile, task, taskRunUID, sheet, task.Payload.GetSchemaVersion(), execFunc)
}
func (exec *DatabaseMigrateExecutor) shouldSkipBackupError(ctx context.Context, task *store.TaskMessage) (bool, error) {
diff --git a/backend/runner/taskrun/executor.go b/backend/runner/taskrun/executor.go
index d01fc1bea3..b5c88b43bf 100644
--- a/backend/runner/taskrun/executor.go
+++ b/backend/runner/taskrun/executor.go
@@ -12,7 +12,6 @@ import (
"github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/component/config"
"github.com/bytebase/bytebase/backend/component/dbfactory"
- "github.com/bytebase/bytebase/backend/component/state"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/db"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
@@ -96,8 +95,8 @@ func getCreateTaskRunLog(ctx context.Context, taskRunUID int, s *store.Store, pr
}
}
-func runMigration(ctx context.Context, driverCtx context.Context, store *store.Store, dbFactory *dbfactory.DBFactory, stateCfg *state.State, syncer *schemasync.Syncer, profile *config.Profile, task *store.TaskMessage, taskRunUID int, sheet *store.SheetMessage, schemaVersion string) (terminated bool, result *storepb.TaskRunResult, err error) {
- return runMigrationWithFunc(ctx, driverCtx, store, dbFactory, stateCfg, syncer, profile, task, taskRunUID, sheet, schemaVersion, nil /* default */)
+func runMigration(ctx context.Context, driverCtx context.Context, store *store.Store, dbFactory *dbfactory.DBFactory, syncer *schemasync.Syncer, profile *config.Profile, task *store.TaskMessage, taskRunUID int, sheet *store.SheetMessage, schemaVersion string) (terminated bool, result *storepb.TaskRunResult, err error) {
+ return runMigrationWithFunc(ctx, driverCtx, store, dbFactory, syncer, profile, task, taskRunUID, sheet, schemaVersion, nil /* default */)
}
func runMigrationWithFunc(
@@ -105,7 +104,6 @@ func runMigrationWithFunc(
driverCtx context.Context,
store *store.Store,
dbFactory *dbfactory.DBFactory,
- stateCfg *state.State,
syncer *schemasync.Syncer,
profile *config.Profile,
task *store.TaskMessage,
@@ -123,7 +121,7 @@ func runMigrationWithFunc(
// Skip dump for pure DML statements (INSERT, UPDATE, DELETE) as they don't change schema.
mc.needDump = computeNeedDump(task.Type, mc.database.Engine, sheet.Statement)
- skipped, err := doMigrationWithFunc(ctx, driverCtx, store, stateCfg, profile, sheet.Statement, mc, execFunc)
+ skipped, err := doMigrationWithFunc(ctx, driverCtx, store, profile, sheet.Statement, mc, execFunc)
if err != nil {
return true, nil, err
}
@@ -194,7 +192,6 @@ func doMigrationWithFunc(
ctx context.Context,
driverCtx context.Context,
stores *store.Store,
- stateCfg *state.State,
profile *config.Profile,
statement string,
mc *migrateContext,
@@ -209,6 +206,7 @@ func doMigrationWithFunc(
}
driver, err := mc.dbFactory.GetAdminDatabaseDriver(ctx, instance, database, db.ConnectionContext{
TenantMode: project.Setting.GetPostgresDatabaseTenantMode(),
+ TaskRunUID: &mc.taskRunUID,
})
if err != nil {
return false, errors.Wrapf(err, "failed to get driver connection for instance %q", instance.ResourceID)
@@ -229,12 +227,6 @@ func doMigrationWithFunc(
opts.MaximumRetries = int(project.Setting.GetExecutionRetryPolicy().GetMaximumRetries())
}
- opts.SetConnectionID = func(id string) {
- stateCfg.TaskRunConnectionID.Store(mc.taskRunUID, id)
- }
- opts.DeleteConnectionID = func() {
- stateCfg.TaskRunConnectionID.Delete(mc.taskRunUID)
- }
opts.CreateTaskRunLog = getCreateTaskRunLog(ctx, mc.taskRunUID, stores, profile)
if execFunc == nil {
diff --git a/backend/runner/taskrun/schema_update_sdl_executor.go b/backend/runner/taskrun/schema_update_sdl_executor.go
index ac5e942798..afa7332554 100644
--- a/backend/runner/taskrun/schema_update_sdl_executor.go
+++ b/backend/runner/taskrun/schema_update_sdl_executor.go
@@ -73,7 +73,7 @@ func (exec *SchemaDeclareExecutor) RunOnce(ctx context.Context, driverCtx contex
return nil
}
- return runMigrationWithFunc(ctx, driverCtx, exec.store, exec.dbFactory, exec.stateCfg, exec.schemaSyncer, exec.profile, task, taskRunUID, sheet, task.Payload.GetSchemaVersion(), execFunc)
+ return runMigrationWithFunc(ctx, driverCtx, exec.store, exec.dbFactory, exec.schemaSyncer, exec.profile, task, taskRunUID, sheet, task.Payload.GetSchemaVersion(), execFunc)
}
func diff(ctx context.Context, s *store.Store, instance *store.InstanceMessage, database *store.DatabaseMessage, sheetContent string) (string, error) {
diff --git a/docs/plans/2025-12-30-taskrun-session-ha-design.md b/docs/plans/2025-12-30-taskrun-session-ha-design.md
new file mode 100644
index 0000000000..ae700ef0c9
--- /dev/null
+++ b/docs/plans/2025-12-30-taskrun-session-ha-design.md
@@ -0,0 +1,243 @@
+# TaskRun Session Monitoring - HA-Compatible Design
+
+## Overview
+
+Replace in-memory `TaskRunConnectionID` state with database-native connection identification using `application_name`. This makes session monitoring work in High Availability (HA) deployments where multiple Bytebase replicas run simultaneously.
+
+## Problem
+
+The current implementation stores connection IDs in `state.TaskRunConnectionID` (sync.Map), which breaks in HA:
+- Replica A executes a task and stores connection ID in its local memory
+- User requests session info, load balancer routes to Replica B
+- Replica B has no connection ID in its memory → request fails
+
+## Solution
+
+Use PostgreSQL's `application_name` parameter to make connections self-identifying. Query `pg_stat_activity` by `application_name` instead of connection ID.
+
+### Application Name Format
+
+```
+bytebase-taskrun-{taskRunUID}
+```
+
+Examples:
+- Task run execution: `bytebase-taskrun-12345`
+- Regular connections: `bytebase` (existing behavior)
+
+### Why This Works
+
+- PostgreSQL exposes `application_name` in `pg_stat_activity` view
+- No coordination needed between replicas - database is the source of truth
+- Auto-cleanup when connection closes
+- Fully stateless
+
+## Architecture Changes
+
+### 1. ConnectionContext Enhancement
+
+Add `TaskRunUID` to connection context (`backend/plugin/db/driver.go`):
+
+```go
+type ConnectionContext struct {
+ EnvironmentID string
+ InstanceID string
+ EngineVersion string
+ TenantMode bool
+ DatabaseName string
+ DataShare bool
+ ReadOnly bool
+ MessageBuffer []*v1pb.QueryResult_Message
+ TaskRunUID *int // NEW: Set when executing a task run
+}
+```
+
+### 2. PostgreSQL Driver Update
+
+Modify `backend/plugin/db/pg/pg.go` (line 79):
+
+```go
+// Current:
+pgxConnConfig.RuntimeParams["application_name"] = "bytebase"
+
+// New:
+appName := "bytebase"
+if config.ConnectionContext.TaskRunUID != nil {
+ appName = fmt.Sprintf("bytebase-taskrun-%d", *config.ConnectionContext.TaskRunUID)
+}
+pgxConnConfig.RuntimeParams["application_name"] = appName
+```
+
+### 3. Task Executor Changes
+
+Pass `TaskRunUID` when creating driver (`backend/runner/taskrun/executor.go`):
+
+```go
+driver, err := mc.dbFactory.GetAdminDatabaseDriver(ctx, mc.instance, mc.database, db.ConnectionContext{
+ EnvironmentID: mc.database.EnvironmentID,
+ InstanceID: mc.instance.ResourceID,
+ DatabaseName: mc.database.DatabaseName,
+ TaskRunUID: &mc.taskRunUID, // NEW
+})
+```
+
+### 4. GetTaskRunSession API Refactoring
+
+Update `backend/api/v1/rollout_service.go`:
+
+**Before:**
+1. Load connection ID from `stateCfg.TaskRunConnectionID.Load(taskRunUID)`
+2. Query `pg_stat_activity WHERE pid = $1`
+
+**After:**
+1. Construct `appName = fmt.Sprintf("bytebase-taskrun-%d", taskRunUID)`
+2. Query `pg_stat_activity WHERE application_name = $1`
+
+**Query Changes:**
+
+```sql
+-- Find main session and blocking/blocked sessions
+SELECT
+ pid,
+ pg_blocking_pids(pid) AS blocked_by_pids,
+ query,
+ state,
+ wait_event_type,
+ wait_event,
+ datname,
+ usename,
+ application_name,
+ client_addr,
+ client_port,
+ backend_start,
+ xact_start,
+ query_start
+FROM
+ pg_catalog.pg_stat_activity
+WHERE application_name = $1
+OR pid = ANY(pg_blocking_pids((SELECT pid FROM pg_stat_activity WHERE application_name = $1 LIMIT 1)))
+OR (SELECT pid FROM pg_stat_activity WHERE application_name = $1 LIMIT 1) = ANY(pg_blocking_pids(pid))
+ORDER BY pid
+```
+
+Identify main session by comparing `application_name` instead of `pid`.
+
+### 5. Cleanup - Remove In-Memory State
+
+**Delete from `backend/component/state/state.go`:**
+```go
+TaskRunConnectionID sync.Map // map[taskRunID]string
+```
+
+**Delete from `backend/plugin/db/driver.go` ExecuteOptions:**
+```go
+SetConnectionID func(id string)
+DeleteConnectionID func()
+```
+
+**Delete from `backend/runner/taskrun/executor.go`:**
+```go
+opts.SetConnectionID = func(id string) {
+ stateCfg.TaskRunConnectionID.Store(mc.taskRunUID, id)
+}
+opts.DeleteConnectionID = func() {
+ stateCfg.TaskRunConnectionID.Delete(mc.taskRunUID)
+}
+```
+
+**Delete from `backend/plugin/db/pg/pg.go` (2 occurrences):**
+```go
+if opts.SetConnectionID != nil {
+ var pid string
+ if err := conn.QueryRowContext(ctx, "SELECT pg_backend_pid()").Scan(&pid); err != nil {
+ return 0, errors.Wrapf(err, "failed to get connection id")
+ }
+ opts.SetConnectionID(pid)
+
+ if opts.DeleteConnectionID != nil {
+ defer opts.DeleteConnectionID()
+ }
+}
+```
+
+## Engine Support
+
+### Supported
+- **PostgreSQL**: Native `application_name` support
+- **CockroachDB**: PostgreSQL-compatible, uses same driver
+
+### Unsupported (for now)
+- MySQL, TiDB, MariaDB, OceanBase
+- Oracle
+- MSSQL (has `app name` but deferred to future work)
+- All other engines
+
+For unsupported engines, `GetTaskRunSession()` returns:
+```
+"session monitoring is only supported for PostgreSQL and CockroachDB"
+```
+
+## Implementation Plan
+
+### Files to Modify
+
+| File | Changes |
+|------|---------|
+| `backend/plugin/db/driver.go` | Add `TaskRunUID *int` to `ConnectionContext` |
+| `backend/plugin/db/pg/pg.go` | Set `application_name` based on `TaskRunUID` |
+| `backend/runner/taskrun/executor.go` | Pass `TaskRunUID` in `ConnectionContext` |
+| `backend/api/v1/rollout_service.go` | Query by `application_name` instead of loading from state |
+| `backend/component/state/state.go` | Remove `TaskRunConnectionID` field |
+
+### Implementation Order
+
+1. Add `TaskRunUID` to `ConnectionContext`
+2. Update PostgreSQL driver to set `application_name`
+3. Update task executor to pass `TaskRunUID`
+4. Update `GetTaskRunSession()` API to query by `application_name`
+5. Remove all in-memory state tracking code
+6. Test with PostgreSQL task execution
+
+### Testing Strategy
+
+**Manual Testing:**
+1. Execute task on PostgreSQL database
+2. Call `GetTaskRunSession()` during execution from any replica
+3. Verify session info shows correct query, state, blocking sessions
+4. Execute task on MySQL database
+5. Verify `GetTaskRunSession()` returns "not supported" error
+
+**Automated Testing:**
+1. Unit test: Verify `application_name` format matches `bytebase-taskrun-{uid}`
+2. Integration test: Execute task, query `pg_stat_activity`, verify app name appears
+
+## Benefits
+
+### HA Compatibility
+- No shared state between replicas
+- Any replica can serve `GetTaskRunSession()` requests
+- Database is the single source of truth
+
+### Simplification
+- Removes 5 code locations maintaining connection ID state
+- No cleanup logic needed (auto-cleanup when connection closes)
+- Fewer potential bugs (no stale connection IDs)
+
+### Observability
+- Connection purpose visible in `pg_stat_activity` without API calls
+- DBAs can identify Bytebase task executions directly
+- Easier debugging of long-running migrations
+
+## Future Work
+
+- Add MSSQL support using `app name` parameter and `sys.dm_exec_sessions`
+- Explore MySQL alternatives (CONNECTION_ID() with session variables)
+- Add Oracle support if equivalent feature exists
+
+## Compatibility
+
+No breaking changes:
+- New `TaskRunUID` field is optional (pointer)
+- Existing connections continue to use `application_name = "bytebase"`
+- Only affects PostgreSQL/CockroachDB task run connections
+- Other engines get clear "not supported" message