Skip to content

*: support logging session connect attrs to slow query log (test split experiment)#67115

Open
jiong-nba wants to merge 10 commits intopingcap:masterfrom
jiong-nba:jiong-nba/ci-noop-same-files-66617
Open

*: support logging session connect attrs to slow query log (test split experiment)#67115
jiong-nba wants to merge 10 commits intopingcap:masterfrom
jiong-nba:jiong-nba/ci-noop-same-files-66617

Conversation

@jiong-nba
Copy link
Copy Markdown
Contributor

@jiong-nba jiong-nba commented Mar 18, 2026

What problem does this PR solve?

Issue Number: ref #66616

Problem Summary:
In a Kubernetes deployment environment, container IPs change frequently. The current slow query log records only IP information, which is insufficient to trace the real source or application of SQL statements. Recording SESSION_CONNECT_ATTRS in the slow log provides critical client metadata (such as app_name, _os, _client_name, etc.) injected during the connection handshake.

This PR is used as a CI isolation experiment for #66617. Other code changes are kept aligned with #66617. The only intentional difference is that TestInitStatsSessionBlockGC and TestInitStatsSessionBlockGCCanBeCanceled are moved out of pkg/server into an isolated test package pkg/server/tests/initstats.

What changed and how does it work?

This PR introduces the same feature changes as #66617:

  1. Slow Query Log Enhancement:

    • Added a Session_connect_attrs field in JSON format to the slow query file (pkg/sessionctx/variable/slow_log.go).
    • Added a new SESSION_CONNECT_ATTRS JSON column to both the SLOW_QUERY and CLUSTER_SLOW_QUERY system tables (pkg/infoschema/tables.go).
    • Updated the slow log parser to correctly parse and deserialize this JSON field (pkg/executor/slow_query.go).
  2. System Variables:

    • Converted performance_schema_session_connect_attrs_size from a noop variable to a functional GLOBAL variable (pkg/sessionctx/variable/sysvar.go), controlling the maximum total byte size of attributes per connection (default: 4096).
  3. Status Variables & Truncation Logic:

    • Implemented a two-tier restriction approach during the handshake: a hard limit of 1 MiB to reject unusually large data, and a soft limit driven by performance_schema_session_connect_attrs_size (pkg/server/internal/parse/parse.go).
    • Added two new GLOBAL status variables: Performance_schema_session_connect_attrs_longest_seen and Performance_schema_session_connect_attrs_lost to monitor attribute size and truncation stats.
    • For truncated lists, it cleanly discards exceeded properties and injects _truncated to record discarded bytes.
  4. Test Isolation Difference From *: support logging session connect attrs to slow query log #66617:

    • Moved TestInitStatsSessionBlockGC and TestInitStatsSessionBlockGCCanBeCanceled from pkg/server/stat_test.go to a dedicated package pkg/server/tests/initstats.
    • The purpose is to validate whether fast_test_tiprow instability is related to same-binary test interaction inside pkg/server.

Check List

Tests

  • Unit test
  • Integration test
  • Manual test (add detailed scripts or steps below)
  • No need to test

Side effects

  • Performance regression: Consumes more CPU
  • Performance regression: Consumes more Memory
  • Breaking backward compatibility

Documentation

  • Affects user behaviors
  • Contains syntax changes
  • Contains variable changes
  • Contains experimental features
  • Changes MySQL compatibility

Release note

None

Summary by CodeRabbit

  • New Features

    • Session connection attributes are captured, JSON-encoded in slow query logs, and exposed as a JSON column in information_schema.slow_query and cluster_slow_query.
    • New GLOBAL variable performance_schema_session_connect_attrs_size controls max captured size (default 4 KB, range -1, 0–65536). Metrics report largest-seen and truncation counts; long/oversize attributes are truncated with metadata.
  • Tests

    • Added coverage for capture, parsing, truncation, sysvar validation, and slow-log serialization.

@ti-chi-bot
Copy link
Copy Markdown

ti-chi-bot Bot commented Mar 18, 2026

Skipping CI for Draft Pull Request.
If you want CI signal for your change, please convert it to an actual PR.
You can still manually trigger a test run with /test all

@ti-chi-bot ti-chi-bot Bot added do-not-merge/needs-triage-completed do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. release-note-none Denotes a PR that doesn't merit a release note. do-not-merge/needs-linked-issue labels Mar 18, 2026
@ti-chi-bot
Copy link
Copy Markdown

ti-chi-bot Bot commented Mar 18, 2026

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign benjamin2037, yudongusa for approval. For more information see the Code Review Process.
Please ensure that each of them provides their approval before proceeding.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 18, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 5c13004a-ea9d-4f08-99a3-c39a9bcf04ad

📥 Commits

Reviewing files that changed from the base of the PR and between 78ea5b3 and 0b8fc58.

📒 Files selected for processing (10)
  • pkg/executor/BUILD.bazel
  • pkg/executor/adapter_slow_log.go
  • pkg/executor/cluster_table_test.go
  • pkg/executor/slow_query.go
  • pkg/executor/slow_query_sql_test.go
  • pkg/executor/slow_query_test.go
  • pkg/infoschema/tables.go
  • pkg/infoschema/test/clustertablestest/BUILD.bazel
  • pkg/infoschema/test/clustertablestest/cluster_tables_test.go
  • pkg/infoschema/test/clustertablestest/tables_test.go
✅ Files skipped from review due to trivial changes (4)
  • pkg/infoschema/test/clustertablestest/BUILD.bazel
  • pkg/executor/BUILD.bazel
  • pkg/executor/cluster_table_test.go
  • pkg/executor/slow_query_test.go
🚧 Files skipped from review as they are similar to previous changes (4)
  • pkg/infoschema/tables.go
  • pkg/executor/adapter_slow_log.go
  • pkg/infoschema/test/clustertablestest/tables_test.go
  • pkg/executor/slow_query_sql_test.go

📝 Walkthrough

Walkthrough

Adds end-to-end session connection attributes: new vardef/sysvar state and metrics, handshake parsing with truncation/limits and warnings, slow-log serialization and slow-query ingestion of Session_connect_attrs, tests across parsing, slow-query, cluster table, server, and initstats, plus test/build adjustments.

Changes

Cohort / File(s) Summary
Session vardef & sysvar
pkg/sessionctx/vardef/tidb_vars.go, pkg/sessionctx/vardef/sysvar.go, pkg/sessionctx/variable/sysvar.go, pkg/sessionctx/variable/statusvar.go, pkg/sessionctx/variable/noop.go
Add DefConnectAttrsSize and atomic counters (ConnectAttrsSize, ConnectAttrsLongestSeen, ConnectAttrsLost); expose GLOBAL sysvar performance_schema_session_connect_attrs_size; wire status vars to atomics and remove noop entry.
Handshake parsing & policy
pkg/server/internal/parse/parse.go, pkg/server/internal/parse/parse_test.go, pkg/server/internal/parse/BUILD.bazel
Replace parseAttrs with policy pipeline enforcing size limits, truncation behavior (including _truncated metadata), deprecation warnings for custom leading-underscore keys, longest-seen/lost counters, add 1MiB hard-reject and bounds checks, and add tests/build deps.
Slow-log, slow-query ingestion & infoschema
pkg/sessionctx/variable/slow_log.go, pkg/executor/adapter_slow_log.go, pkg/executor/slow_query.go, pkg/executor/slow_query_test.go, pkg/executor/slow_query_sql_test.go, pkg/infoschema/tables.go
Add SessionConnectAttrs field and slow-log line emission; parse Session_connect_attrs in slow-query retriever as JSON column; add column to SLOW_QUERY schema and tests for present/missing/truncated cases.
Cluster slow-query tests & testkit helpers
pkg/infoschema/test/clustertablestest/cluster_tables_test.go, pkg/infoschema/test/clustertablestest/tables_test.go, pkg/testkit/testutil/require.go, pkg/infoschema/test/clustertablestest/BUILD.bazel, pkg/executor/cluster_table_test.go
Add cluster slow-query tests asserting Session_connect_attrs, add testkit fixture JSON and helper assertions, update expected rows to include new column, and add test deps.
Server connection tests & conn parsing helpers
pkg/server/conn_test.go, pkg/server/BUILD.bazel, pkg/server/stat_test.go
Add handshake packet helpers and extensive tests for connect-attrs parsing/truncation/limits; remove an unused Bazel dep and delete two removed stat tests.
InitStats test suite (new)
pkg/server/tests/initstats/BUILD.bazel, pkg/server/tests/initstats/initstats_test.go, pkg/server/tests/initstats/main_test.go
Introduce new initstats test package, TestMain, two tests for InitStats blocking via failpoints, and a new Bazel test target.
Session variable tests & sharding
pkg/sessionctx/variable/tests/session_test.go, pkg/sessionctx/variable/tests/variable_test.go, pkg/sessionctx/variable/tests/BUILD.bazel
Extend slow-log format tests, add sysvar validation/global SQL tests for the new sysvar, and adjust shard_count.
Minor BUILD/test deps
pkg/executor/BUILD.bazel, pkg/infoschema/test/clustertablestest/BUILD.bazel, pkg/sessionctx/variable/tests/BUILD.bazel
Add or adjust test dependencies and shard counts to include pkg/testkit/testutil and align test sharding.

Sequence Diagram(s)

sequenceDiagram
  participant Client as Client
  participant Server as Server(parse.go)
  participant Vardef as vardef (atomics)
  participant Logger as Logger

  Client->>Server: send HandshakeResponse (length-encoded attrs)
  Server->>Server: read length, check bounds (malformed -> ErrMalformPacket)
  Server->>Vardef: Load ConnectAttrsSize
  alt ConnectAttrsSize == 0
    Server->>Vardef: return empty attrs, no warnings
  else
    Server->>Server: decode k/v pairs, accumulate total size
    alt total size > effective limit
      Server->>Vardef: increment ConnectAttrsLost (first truncation)
      Server->>Server: set `_truncated` metadata with discarded bytes
      Server->>Vardef: maybe update ConnectAttrsLongestSeen
      Server->>Logger: emit truncation warning
    end
    alt contains leading-underscore custom keys not allowed
      Server->>Logger: emit deprecation warning
    end
    Server->>Server: return attrs, warningsText
  end
  Server->>Logger: log warningsText at debug (if non-empty)
  alt declared length > 1MiB
    Server->>Client: refuse connection (error)
  else
    Server->>Client: accept connection with packet.Attrs set
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • yudongusa
  • XuHuaiyu
  • zyguan
  • winoros

Poem

🐇 I parsed each attr with careful hops and care,
Truncated bytes tucked into a secret lair.
Logs now whisper client tales in JSON art,
Metrics keep watch — a tidy little chart.
Hop, test, and build — a carrot for the heart!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.75% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'support logging session connect attrs to slow query log (test split experiment)' accurately describes the main functional change: adding session connection attributes to slow query logs, with a note about the test reorganization experiment.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
📝 Coding Plan
  • Generate coding plan for human review comments

Warning

Tools execution failed with the following error:

Failed to run tools: 13 INTERNAL: Received RST_STREAM with code 2 (Internal server error)


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@ti-chi-bot ti-chi-bot Bot added the size/M Denotes a PR that changes 30-99 lines, ignoring generated files. label Mar 18, 2026
@tiprow
Copy link
Copy Markdown

tiprow Bot commented Mar 18, 2026

Hi @jiong-nba. Thanks for your PR.

PRs from untrusted users cannot be marked as trusted with /ok-to-test in this repo meaning untrusted PR authors can never trigger tests themselves. Collaborators can still trigger tests on the PR using /test all.

I understand the commands that are listed here.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@jiong-nba jiong-nba marked this pull request as ready for review March 18, 2026 09:58
Copilot AI review requested due to automatic review settings March 18, 2026 09:58
@ti-chi-bot ti-chi-bot Bot removed the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Mar 18, 2026
@pantheon-ai
Copy link
Copy Markdown

pantheon-ai Bot commented Mar 18, 2026

Review Complete

Findings: 0 issues
Posted: 0
Duplicates/Skipped: 0

ℹ️ Learn more details on Pantheon AI.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR is a comment-only, no-op experiment to reproduce CI behavior by touching the same file set as #66617, helping isolate whether failures (e.g. fast_test_tiprow / TestInitStatsSessionBlockGC) correlate with the touched targets rather than code logic.

Changes:

  • Added a trailing no-op comment line to the same Go source and test files touched by #66617.
  • Added a trailing no-op comment line to the same Bazel BUILD.bazel targets touched by #66617.

Reviewed changes

Copilot reviewed 24 out of 24 changed files in this pull request and generated no comments.

Show a summary per file
File Description
pkg/testkit/testutil/require.go Add trailing no-op comment to touch file for CI investigation.
pkg/sessionctx/variable/tests/variable_test.go Add trailing no-op comment to touch file for CI investigation.
pkg/sessionctx/variable/tests/session_test.go Add trailing no-op comment to touch file for CI investigation.
pkg/sessionctx/variable/tests/BUILD.bazel Add trailing no-op comment to touch Bazel target for CI investigation.
pkg/sessionctx/variable/sysvar.go Add trailing no-op comment to touch file for CI investigation.
pkg/sessionctx/variable/statusvar.go Add trailing no-op comment to touch file for CI investigation.
pkg/sessionctx/variable/slow_log.go Add trailing no-op comment to touch file for CI investigation.
pkg/sessionctx/variable/noop.go Add trailing no-op comment to touch file for CI investigation.
pkg/sessionctx/vardef/tidb_vars.go Add trailing no-op comment to touch file for CI investigation.
pkg/sessionctx/vardef/sysvar.go Add trailing no-op comment to touch file for CI investigation.
pkg/server/internal/parse/parse_test.go Add trailing no-op comment to touch file for CI investigation.
pkg/server/internal/parse/parse.go Add trailing no-op comment to touch file for CI investigation.
pkg/server/internal/parse/BUILD.bazel Add trailing no-op comment to touch Bazel target for CI investigation.
pkg/server/conn_test.go Add trailing no-op comment to touch file for CI investigation.
pkg/infoschema/test/clustertablestest/tables_test.go Add trailing no-op comment to touch file for CI investigation.
pkg/infoschema/test/clustertablestest/cluster_tables_test.go Add trailing no-op comment to touch file for CI investigation.
pkg/infoschema/test/clustertablestest/BUILD.bazel Add trailing no-op comment to touch Bazel target for CI investigation.
pkg/infoschema/tables.go Add trailing no-op comment to touch file for CI investigation.
pkg/executor/slow_query_test.go Add trailing no-op comment to touch file for CI investigation.
pkg/executor/slow_query_sql_test.go Add trailing no-op comment to touch file for CI investigation.
pkg/executor/slow_query.go Add trailing no-op comment to touch file for CI investigation.
pkg/executor/cluster_table_test.go Add trailing no-op comment to touch file for CI investigation.
pkg/executor/adapter_slow_log.go Add trailing no-op comment to touch file for CI investigation.
pkg/executor/BUILD.bazel Add trailing no-op comment to touch Bazel target for CI investigation.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@jiong-nba
Copy link
Copy Markdown
Contributor Author

/test fast_test_tiprow

@ti-chi-bot
Copy link
Copy Markdown

ti-chi-bot Bot commented Mar 18, 2026

@jiong-nba: The specified target(s) for /test were not found.
The following commands are available to trigger required jobs:

/test build
/test check-dev
/test check-dev2
/test mysql-test
/test pull-br-integration-test
/test pull-build-next-gen
/test pull-integration-e2e-test
/test pull-integration-realcluster-test-next-gen
/test pull-lightning-integration-test
/test pull-mysql-client-test
/test pull-mysql-client-test-next-gen
/test pull-unit-test-ddlv1
/test pull-unit-test-next-gen
/test unit-test

The following commands are available to trigger optional jobs:

/test pingcap/tidb/canary_ghpr_unit_test
/test pull-br-integration-test-next-gen
/test pull-check-deps
/test pull-common-test
/test pull-e2e-test
/test pull-error-log-review
/test pull-integration-common-test
/test pull-integration-copr-test
/test pull-integration-ddl-test
/test pull-integration-ddl-test-next-gen
/test pull-integration-e2e-test-next-gen
/test pull-integration-jdbc-test
/test pull-integration-mysql-test
/test pull-integration-nodejs-test
/test pull-integration-python-orm-test
/test pull-mysql-test-next-gen
/test pull-sqllogic-test
/test pull-tiflash-integration-test

Use /test all to run the following jobs that were automatically triggered:

pingcap/tidb/ghpr_build
pingcap/tidb/ghpr_check
pingcap/tidb/ghpr_check2
pingcap/tidb/ghpr_mysql_test
pingcap/tidb/ghpr_unit_test
pingcap/tidb/pull_br_integration_test
pingcap/tidb/pull_build_next_gen
pingcap/tidb/pull_integration_e2e_test
pingcap/tidb/pull_integration_realcluster_test_next_gen
pingcap/tidb/pull_lightning_integration_test
pingcap/tidb/pull_mysql_client_test
pingcap/tidb/pull_mysql_client_test_next_gen
pingcap/tidb/pull_unit_test_next_gen
pull-check-deps
pull-error-log-review
Details

In response to this:

/test fast_test_tiprow

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@tiprow
Copy link
Copy Markdown

tiprow Bot commented Mar 18, 2026

@jiong-nba: PRs from untrusted users cannot be marked as trusted with /ok-to-test in this repo meaning untrusted PR authors can never trigger tests themselves. Collaborators can still trigger tests on the PR using /test.

Details

In response to this:

/test fast_test_tiprow

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@jiong-nba
Copy link
Copy Markdown
Contributor Author

/test all

@tiprow
Copy link
Copy Markdown

tiprow Bot commented Mar 18, 2026

@jiong-nba: PRs from untrusted users cannot be marked as trusted with /ok-to-test in this repo meaning untrusted PR authors can never trigger tests themselves. Collaborators can still trigger tests on the PR using /test.

Details

In response to this:

/test all

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@jiong-nba
Copy link
Copy Markdown
Contributor Author

/ok-to-test

@ti-chi-bot ti-chi-bot Bot added the ok-to-test Indicates a PR is ready to be tested. label Mar 18, 2026
@jiong-nba
Copy link
Copy Markdown
Contributor Author

/test fast_test_tiprow

@ti-chi-bot
Copy link
Copy Markdown

ti-chi-bot Bot commented Mar 18, 2026

@jiong-nba: The specified target(s) for /test were not found.
The following commands are available to trigger required jobs:

/test build
/test check-dev
/test check-dev2
/test mysql-test
/test pull-br-integration-test
/test pull-build-next-gen
/test pull-integration-e2e-test
/test pull-integration-realcluster-test-next-gen
/test pull-lightning-integration-test
/test pull-mysql-client-test
/test pull-mysql-client-test-next-gen
/test pull-unit-test-ddlv1
/test pull-unit-test-next-gen
/test unit-test

The following commands are available to trigger optional jobs:

/test pingcap/tidb/canary_ghpr_unit_test
/test pull-br-integration-test-next-gen
/test pull-check-deps
/test pull-common-test
/test pull-e2e-test
/test pull-error-log-review
/test pull-integration-common-test
/test pull-integration-copr-test
/test pull-integration-ddl-test
/test pull-integration-ddl-test-next-gen
/test pull-integration-e2e-test-next-gen
/test pull-integration-jdbc-test
/test pull-integration-mysql-test
/test pull-integration-nodejs-test
/test pull-integration-python-orm-test
/test pull-mysql-test-next-gen
/test pull-sqllogic-test
/test pull-tiflash-integration-test

Use /test all to run the following jobs that were automatically triggered:

pingcap/tidb/ghpr_build
pingcap/tidb/ghpr_check
pingcap/tidb/ghpr_check2
pingcap/tidb/ghpr_mysql_test
pingcap/tidb/ghpr_unit_test
pingcap/tidb/pull_br_integration_test
pingcap/tidb/pull_build_next_gen
pingcap/tidb/pull_integration_e2e_test
pingcap/tidb/pull_integration_realcluster_test_next_gen
pingcap/tidb/pull_lightning_integration_test
pingcap/tidb/pull_mysql_client_test
pingcap/tidb/pull_mysql_client_test_next_gen
pingcap/tidb/pull_unit_test_next_gen
pull-check-deps
pull-error-log-review
Details

In response to this:

/test fast_test_tiprow

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@jiong-nba
Copy link
Copy Markdown
Contributor Author

/test all

@codecov
Copy link
Copy Markdown

codecov Bot commented Mar 18, 2026

Codecov Report

❌ Patch coverage is 92.90780% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.3992%. Comparing base (485bd4b) to head (0b8fc58).
⚠️ Report is 161 commits behind head on master.

Additional details and impacted files
@@               Coverage Diff                @@
##             master     #67115        +/-   ##
================================================
+ Coverage   77.7126%   79.3992%   +1.6866%     
================================================
  Files          2016       1962        -54     
  Lines        552501     539534     -12967     
================================================
- Hits         429363     428386       -977     
+ Misses       121396     109697     -11699     
+ Partials       1742       1451       -291     
Flag Coverage Δ
integration 47.0958% <4.9645%> (-1.0273%) ⬇️
unit 76.5782% <92.9078%> (+0.3370%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Components Coverage Δ
dumpling 57.0098% <ø> (ø)
parser ∅ <ø> (∅)
br 66.2227% <ø> (+5.3570%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Copy Markdown

@pantheon-ai pantheon-ai Bot left a comment

Choose a reason for hiding this comment

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

✅ Code looks good. No issues found.

@jiong-nba jiong-nba changed the title *: add no-op touches for CI investigation *: support logging session connect attrs to slow query log (test split experiment) Mar 19, 2026
@jiong-nba jiong-nba force-pushed the jiong-nba/ci-noop-same-files-66617 branch from ece611a to 78ea5b3 Compare March 19, 2026 07:15
@ti-chi-bot ti-chi-bot Bot added size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. and removed size/M Denotes a PR that changes 30-99 lines, ignoring generated files. labels Mar 19, 2026
@jiong-nba
Copy link
Copy Markdown
Contributor Author

/retest

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
pkg/server/tests/initstats/initstats_test.go (1)

86-92: Context is already canceled before InitStatsLite is called.

After h.InitStats(ctx, dom.InfoSchema()) returns due to cancellation (line 91), the ctx is already in a canceled state. The subsequent h.InitStatsLite(ctx) call (line 92) will immediately see ctx.Err() == context.Canceled rather than experiencing an active cancellation while blocked.

If the intent is to verify that InitStatsLite can be actively canceled mid-execution (matching the test name), consider using a fresh context:

♻️ Suggested fix to test active cancellation for both functions
-	ctx, cancel := context.WithCancel(context.Background())
-	go func() {
-		time.Sleep(time.Second)
-		cancel()
-	}()
-	require.ErrorIs(t, h.InitStats(ctx, dom.InfoSchema()), context.Canceled)
-	require.ErrorIs(t, h.InitStatsLite(ctx), context.Canceled)
+	ctx1, cancel1 := context.WithCancel(context.Background())
+	go func() {
+		time.Sleep(time.Second)
+		cancel1()
+	}()
+	require.ErrorIs(t, h.InitStats(ctx1, dom.InfoSchema()), context.Canceled)
+
+	ctx2, cancel2 := context.WithCancel(context.Background())
+	go func() {
+		time.Sleep(time.Second)
+		cancel2()
+	}()
+	require.ErrorIs(t, h.InitStatsLite(ctx2), context.Canceled)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/server/tests/initstats/initstats_test.go` around lines 86 - 92, The test
uses the same canceled ctx for both calls so InitStatsLite sees ctx already
canceled; create a fresh cancellable context (e.g., ctx2, cancel2 :=
context.WithCancel(context.Background())) and a separate goroutine to cancel it
after a delay before calling h.InitStatsLite(ctx2) so that InitStats and
InitStatsLite each experience an active mid-execution cancellation; ensure you
call the matching cancel functions or defer cancels to avoid leaks and assert
ErrorIs(..., context.Canceled) for both InitStats and InitStatsLite.
pkg/sessionctx/vardef/tidb_vars.go (1)

1775-1777: Align these exported comments with the actual normalization rules.

pkg/server/internal/parse/parse.go normalizes -1 to a 64 KiB cap, and ConnectAttrsLongestSeen deliberately ignores payloads >= 64 KiB. The new comments read a bit broader than that, so spelling those constraints out here would keep the vardef contract accurate for future readers.

As per coding guidelines, comments SHOULD explain non-obvious intent, constraints, invariants, concurrency guarantees, SQL/compatibility contracts, or important performance trade-offs.

Also applies to: 1914-1918

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/sessionctx/vardef/tidb_vars.go` around lines 1775 - 1777, Update the
exported comment for DefConnectAttrsSize (and the similar comment around lines
1914-1918) to precisely state the normalization and caps: note that a configured
value of -1 is normalized to a 64 KiB cap by pkg/server/internal/parse/parse.go
and that ConnectAttrsLongestSeen intentionally ignores payloads >= 64 KiB, so
the effective maximum tracked/used size is 64 KiB; mention these constraints and
the SQL/compatibility semantics in the comment so readers know the invariant and
where normalization occurs.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@pkg/server/internal/parse/parse.go`:
- Around line 195-205: The helper parseAttrs should preserve a nil map to
represent “no attrs”: change the early-return when
vardef.ConnectAttrsSize.Load() == 0 to return nil, "", nil instead of an
allocated map, and likewise update the other similar helper later in the file
(the helper in the 241-282 region that currently returns map[string]string{} for
no-attrs cases) to return nil, "", nil; ensure any call sites that copy
resp.Attrs (e.g., conn.go logic referenced in the review) still handle a nil map
as “absent” and keep other error-return paths unchanged.

---

Nitpick comments:
In `@pkg/server/tests/initstats/initstats_test.go`:
- Around line 86-92: The test uses the same canceled ctx for both calls so
InitStatsLite sees ctx already canceled; create a fresh cancellable context
(e.g., ctx2, cancel2 := context.WithCancel(context.Background())) and a separate
goroutine to cancel it after a delay before calling h.InitStatsLite(ctx2) so
that InitStats and InitStatsLite each experience an active mid-execution
cancellation; ensure you call the matching cancel functions or defer cancels to
avoid leaks and assert ErrorIs(..., context.Canceled) for both InitStats and
InitStatsLite.

In `@pkg/sessionctx/vardef/tidb_vars.go`:
- Around line 1775-1777: Update the exported comment for DefConnectAttrsSize
(and the similar comment around lines 1914-1918) to precisely state the
normalization and caps: note that a configured value of -1 is normalized to a 64
KiB cap by pkg/server/internal/parse/parse.go and that ConnectAttrsLongestSeen
intentionally ignores payloads >= 64 KiB, so the effective maximum tracked/used
size is 64 KiB; mention these constraints and the SQL/compatibility semantics in
the comment so readers know the invariant and where normalization occurs.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 06f2618e-6d2e-4d3e-86fe-7fa5004f69a4

📥 Commits

Reviewing files that changed from the base of the PR and between ece611a and 78ea5b3.

📒 Files selected for processing (29)
  • pkg/executor/BUILD.bazel
  • pkg/executor/adapter_slow_log.go
  • pkg/executor/cluster_table_test.go
  • pkg/executor/slow_query.go
  • pkg/executor/slow_query_sql_test.go
  • pkg/executor/slow_query_test.go
  • pkg/infoschema/tables.go
  • pkg/infoschema/test/clustertablestest/BUILD.bazel
  • pkg/infoschema/test/clustertablestest/cluster_tables_test.go
  • pkg/infoschema/test/clustertablestest/tables_test.go
  • pkg/server/BUILD.bazel
  • pkg/server/conn_test.go
  • pkg/server/internal/parse/BUILD.bazel
  • pkg/server/internal/parse/parse.go
  • pkg/server/internal/parse/parse_test.go
  • pkg/server/stat_test.go
  • pkg/server/tests/initstats/BUILD.bazel
  • pkg/server/tests/initstats/initstats_test.go
  • pkg/server/tests/initstats/main_test.go
  • pkg/sessionctx/vardef/sysvar.go
  • pkg/sessionctx/vardef/tidb_vars.go
  • pkg/sessionctx/variable/noop.go
  • pkg/sessionctx/variable/slow_log.go
  • pkg/sessionctx/variable/statusvar.go
  • pkg/sessionctx/variable/sysvar.go
  • pkg/sessionctx/variable/tests/BUILD.bazel
  • pkg/sessionctx/variable/tests/session_test.go
  • pkg/sessionctx/variable/tests/variable_test.go
  • pkg/testkit/testutil/require.go
💤 Files with no reviewable changes (3)
  • pkg/server/BUILD.bazel
  • pkg/server/stat_test.go
  • pkg/sessionctx/variable/noop.go
✅ Files skipped from review due to trivial changes (5)
  • pkg/sessionctx/variable/tests/BUILD.bazel
  • pkg/infoschema/test/clustertablestest/BUILD.bazel
  • pkg/executor/BUILD.bazel
  • pkg/server/tests/initstats/BUILD.bazel
  • pkg/server/internal/parse/BUILD.bazel
🚧 Files skipped from review as they are similar to previous changes (12)
  • pkg/executor/adapter_slow_log.go
  • pkg/sessionctx/vardef/sysvar.go
  • pkg/sessionctx/variable/statusvar.go
  • pkg/executor/slow_query.go
  • pkg/infoschema/test/clustertablestest/tables_test.go
  • pkg/server/internal/parse/parse_test.go
  • pkg/infoschema/tables.go
  • pkg/testkit/testutil/require.go
  • pkg/sessionctx/variable/slow_log.go
  • pkg/sessionctx/variable/sysvar.go
  • pkg/server/conn_test.go
  • pkg/sessionctx/variable/tests/variable_test.go

Comment on lines +195 to +205
func parseAttrs(data []byte) (map[string]string, string, error) {
if vardef.ConnectAttrsSize.Load() == 0 {
return map[string]string{}, "", nil
}

decoded, err := decodeConnAttrs(data)
if err != nil {
return map[string]string{}, "", err
}
attrs, warningsText := applyConnAttrsPolicyAndMetrics(decoded, vardef.ConnectAttrsSize.Load())
return attrs, warningsText, nil
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Preserve nil for the “no attrs” cases.

These helpers always return an allocated map. pkg/server/conn.go:642-646 copies resp.Attrs straight into cc.attrs, so performance_schema_session_connect_attrs_size = 0 stops meaning “no attrs” downstream and starts meaning “present but empty”. That loses the missing-vs-empty distinction and can surface as {} instead of omitted/null in later JSON consumers.

💡 Suggested fix
 func parseAttrs(data []byte) (map[string]string, string, error) {
 	if vardef.ConnectAttrsSize.Load() == 0 {
-		return map[string]string{}, "", nil
+		return nil, "", nil
 	}
 
 	decoded, err := decodeConnAttrs(data)
 	if err != nil {
-		return map[string]string{}, "", err
+		return nil, "", err
 	}
 	attrs, warningsText := applyConnAttrsPolicyAndMetrics(decoded, vardef.ConnectAttrsSize.Load())
 	return attrs, warningsText, nil
 }
 
 func applyConnAttrsPolicyAndMetrics(decoded decodedConnAttrs, limit int64) (map[string]string, string) {
-	attrs := make(map[string]string)
+	var attrs map[string]string
 	effectiveLimit := normalizeConnectAttrsLimit(limit)
 
 	var totalSize int64
 	var acceptedSize int64
 	truncated := false
@@
 		if totalSize > effectiveLimit {
 			if !truncated {
 				truncated = true
 				vardef.ConnectAttrsLost.Add(1)
 			}
 			continue
 		}
 		if !truncated {
+			if attrs == nil {
+				attrs = make(map[string]string)
+			}
 			attrs[item.key] = item.value
 			acceptedSize += kvSize
 		}
 	}
@@
 	if truncated {
 		truncatedBytes := decoded.totalSize - acceptedSize
+		if attrs == nil {
+			attrs = make(map[string]string)
+		}
 		attrs[reservedConnAttrTruncated] = strconv.FormatInt(truncatedBytes, 10)
 		warnings = append(warnings, fmt.Sprintf(
 			"session connection attributes truncated: total size %d bytes exceeds "+
 				"performance_schema_session_connect_attrs_size (%d), %d bytes were discarded",
 			decoded.totalSize, effectiveLimit, truncatedBytes))
 	}

Also applies to: 241-282

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/server/internal/parse/parse.go` around lines 195 - 205, The helper
parseAttrs should preserve a nil map to represent “no attrs”: change the
early-return when vardef.ConnectAttrsSize.Load() == 0 to return nil, "", nil
instead of an allocated map, and likewise update the other similar helper later
in the file (the helper in the 241-282 region that currently returns
map[string]string{} for no-attrs cases) to return nil, "", nil; ensure any call
sites that copy resp.Attrs (e.g., conn.go logic referenced in the review) still
handle a nil map as “absent” and keep other error-return paths unchanged.

@jiong-nba jiong-nba force-pushed the jiong-nba/ci-noop-same-files-66617 branch from 78ea5b3 to 0b8fc58 Compare March 19, 2026 07:40
@ti-chi-bot ti-chi-bot Bot added the needs-cherry-pick-release-8.5 Should cherry pick this PR to release-8.5 branch. label Mar 26, 2026
@ti-chi-bot ti-chi-bot Bot added needs-cherry-pick-release-8.5 Should cherry pick this PR to release-8.5 branch. and removed needs-cherry-pick-release-8.5 Should cherry pick this PR to release-8.5 branch. labels Apr 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-cherry-pick-release-8.5 Should cherry pick this PR to release-8.5 branch. ok-to-test Indicates a PR is ready to be tested. release-note-none Denotes a PR that doesn't merit a release note. size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants