Skip to content

dxf: avoid exposing sensitive task error messages in history API - #69863

Merged
ti-chi-bot[bot] merged 4 commits into
pingcap:masterfrom
D3Hunter:avoid-expose-error
Jul 17, 2026
Merged

ti-chi-bot[bot] merged 4 commits into
pingcap:masterfrom
D3Hunter:avoid-expose-error

Conversation

@D3Hunter

@D3Hunter D3Hunter commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Issue Number: ref #67640

Problem Summary:

PR #69739 exposed persisted DXF task error messages through the task history HTTP API so operators could diagnose failed history tasks. However, some task errors can contain sensitive information that is not covered by tidb_redact_log. Returning the complete error message from an HTTP API can therefore disclose that information.

What changed and how does it work?

The task history response no longer exposes the raw task error message. HistoryTaskSummary.Error is replaced by:

  • ErrorCode, populated on a best-effort basis from the effective RFC code of a *errors.Error.
  • ErrorCategory, a coarse failed, cancelled, or data-error category.

The categorization reuses the logic previously used by DXF finished-task metrics. The data-error and cancellation helpers are moved to dxfutil so the metrics and HTTP history response use the same behavior.

The storage and HTTP tests verify named, wrapped, legacy, numeric, code-less, cancelled, data, and ordinary errors. The HTTP regression test also verifies that the sensitive error message and the old Error field are absent from the response.

Check List

Tests

  • Unit test
    • ./tools/check/failpoint-go-test.sh pkg/dxf/framework/dxfutil -run '^(TestAcquireTaskRuntime|TestCheckTaskRuntime|TestTaskErrorCategory)$' -count=1
    • ./tools/check/failpoint-go-test.sh pkg/dxf/framework/storage -run '^TestTaskHistoryTable$' -count=1
    • ./tools/check/failpoint-go-test.sh pkg/dxf/framework/scheduler -run '^(TestBaseSchedulerInitChecksTaskRuntime|TestOnTaskFinished)$' -count=1
    • ./tools/check/failpoint-go-test.sh pkg/dxf/framework/taskexecutor -run '^TestBaseTaskExecutorInitChecksTaskRuntime$' -count=1
    • ./tools/check/failpoint-go-test.sh pkg/dxf/importinto -run '^TestSchedulerExtLocalSort$' -count=1
    • ./tools/check/failpoint-go-test.sh pkg/dxf/importinto -tags=intest,deadlock,nextgen -run '^(TestSchedulerExtLocalSort|TestSchedulerPrepareEnabledJobTransitionsFromPreparingToFirstBusinessPhase)$' -count=1
    • ./tools/check/failpoint-go-test.sh pkg/server/handler/tests -run '^TestDXFAPI$/^task_history_api$' -count=1
    • ./tools/check/failpoint-go-test.sh pkg/server/handler/tests -tags=intest,deadlock,nextgen -run '^TestDXFAPI$/^task_history_api$' -count=1
    • make lint
  • Integration test
  • Manual test (add detailed scripts or steps below)
  • No need to test
    • I checked and no code files have been changed.

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

Please refer to Release Notes Language Style Guide to write a quality release note.

The DXF task history HTTP API no longer returns raw task error messages. It now returns the error code and a coarse error category to prevent sensitive information exposure.

Summary by CodeRabbit

  • New Features

    • DXF task history responses now provide structured error codes and categories instead of raw error messages.
    • Sensitive task error details are no longer exposed through the history API.
    • Cancellation and data-error conditions are classified consistently across task processing.
  • Documentation

    • Updated API examples and explanations to reflect structured error metadata and reverted task states.
  • Tests

    • Added coverage for history error classification, cancellation handling, and updated API response behavior.

@ti-chi-bot

ti-chi-bot Bot commented Jul 15, 2026

Copy link
Copy Markdown

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/work-in-progress Indicates that a PR should not merge because it is a work in progress. release-note Denotes a PR that will be considered when it comes time to generate release notes. size/XL Denotes a PR that changes 500-999 lines, ignoring generated files. labels Jul 15, 2026
@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

Review Change Stack

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: 53127754-759b-4f78-a0be-700b1ceff67c

📥 Commits

Reviewing files that changed from the base of the PR and between d2a4beb and 0bba899.

📒 Files selected for processing (6)
  • .agents/skills/tidb-test-guidelines/references/dxf-case-map.md
  • pkg/dxf/framework/scheduler/scheduler.go
  • pkg/dxf/framework/scheduler/scheduler_nokit_test.go
  • pkg/dxf/framework/storage/BUILD.bazel
  • pkg/dxf/framework/storage/history.go
  • pkg/dxf/framework/storage/task_state.go
💤 Files with no reviewable changes (2)
  • pkg/dxf/framework/storage/BUILD.bazel
  • .agents/skills/tidb-test-guidelines/references/dxf-case-map.md
🚧 Files skipped from review as they are similar to previous changes (3)
  • pkg/dxf/framework/storage/task_state.go
  • pkg/dxf/framework/scheduler/scheduler.go
  • pkg/dxf/framework/storage/history.go

📝 Walkthrough

Walkthrough

DXF history task errors are now represented by structured codes and categories instead of raw messages. Cancellation and data-error classification move into storage helpers, with scheduler integrations, API tests, documentation, Bazel updates, and test mappings updated accordingly.

Changes

DXF error reporting and classification

Layer / File(s) Summary
Error classification and history summaries
pkg/dxf/framework/storage/..., .agents/skills/tidb-test-guidelines/references/dxf-case-map.md
History summaries derive ErrorCode and ErrorCategory; shared cancellation and classification helpers and their tests are added.
Scheduler cancellation and metrics integration
pkg/dxf/framework/scheduler/..., pkg/dxf/importinto/...
Scheduler metrics and import completion routing use storage-based error classification and cancellation detection.
API contract, examples, and validation
pkg/server/handler/tests/dxf_test.go, docs/tidb_http_api.md
History API tests and examples use structured error metadata and verify raw error messages are omitted.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant DXFHistoryAPI
  participant HistoryStorage
  participant ClassifyTaskError
  DXFHistoryAPI->>HistoryStorage: list history tasks
  HistoryStorage->>ClassifyTaskError: classify stored task state and error
  ClassifyTaskError->>HistoryStorage: error category and normalized code
  HistoryStorage->>DXFHistoryAPI: structured task summary
Loading

Possibly related PRs

Suggested reviewers: wjhuang2016, gmhdbjd, joechenrh

Poem

I’m a rabbit with errors neatly spun,
Codes and categories now hop in the sun.
Raw messages hide in their burrow below,
While cancelled and failed paths clearly show.
The scheduler thumps a tidy beat—
DXF history is crisp and sweet!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: hiding sensitive task error messages in the DXF history API.
Description check ✅ Passed The description follows the template well, includes an issue reference, change summary, checklist items, and a release note.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

}

// IsCancelledErr checks if the error is a cancelled error.
func IsCancelledErr(err error) bool {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

moved to task_state.go

@D3Hunter
D3Hunter marked this pull request as ready for review July 15, 2026 08:37
@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 Jul 15, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (3)
pkg/dxf/bizutil/error_test.go (1)

24-28: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use table-driven tests for better coverage.

IsDataError implements multiple conditional string matches for different types of data errors (e.g., constraints, partitions, duplicate keys). It's recommended to use a table-driven test to easily cover all these distinct patterns and ensure none regress over time.

♻️ Proposed refactor
-func TestIsDataError(t *testing.T) {
-	dataErr := errors.New("[Lightning:Restore:ErrEncodeKV]Value conversion failed for column 'a'")
-	require.True(t, IsDataError(dataErr))
-	require.False(t, IsDataError(errors.New("Value conversion failed for column 'a'")))
-}
+func TestIsDataError(t *testing.T) {
+	tests := []struct {
+		err  error
+		want bool
+	}{
+		{errors.New("[Lightning:Restore:ErrEncodeKV]Value conversion failed for column 'a'"), true},
+		{errors.New("[Lightning:Restore:ErrEncodeKV]Check constraint 'c' is violated"), true},
+		{errors.New("[Lightning:Restore:ErrEncodeKV]Table has no partition for value 1"), true},
+		{errors.New("[executor:8167]Duplicate key conflict found"), true},
+		{errors.New("ErrFoundDataConflictRecords found data conflict records"), true},
+		{errors.New("ErrFoundIndexConflictRecords found index conflict records"), true},
+		{errors.New("[kv:1062]Duplicate entry '1' for key 't.idx'"), true},
+		{errors.New("Value conversion failed for column 'a'"), false},
+		{errors.New("some random error"), false},
+		{nil, false},
+	}
+	for _, tt := range tests {
+		require.Equal(t, tt.want, IsDataError(tt.err))
+	}
+}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/dxf/bizutil/error_test.go` around lines 24 - 28, Refactor TestIsDataError
into a table-driven test covering each conditional error pattern handled by
IsDataError, including constraints, partitions, duplicate keys, and the existing
encode-value case. Include negative cases for unrelated messages, then iterate
through the cases and assert the expected result.
pkg/dxf/framework/scheduler/BUILD.bazel (1)

70-70: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Revert cosmetic test-target tweak.

Based on learnings, running make bazel_prepare is only required when making structural Bazel changes. For cosmetic changes or test-target tweaks that do not affect generated metadata (such as changing the shard_count attribute of a go_test rule in an otherwise structurally unmodified package), do not run or commit the make bazel_prepare output. Please consider reverting this line.

♻️ Proposed refactor
-    shard_count = 45,
+    shard_count = 46,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/dxf/framework/scheduler/BUILD.bazel` at line 70, Revert the shard_count
change in the affected go_test rule, restoring the prior test-target
configuration. Do not include any generated metadata changes from bazel_prepare,
since this cosmetic adjustment does not require them.

Source: Learnings

pkg/dxf/framework/storage/history.go (1)

237-247: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Prevent potential nil-pointer dereference.

Protect against a nil-pointer dereference in the rare event that errors.As matches a typed nil in the error chain (which causes As to return true while assigning nil to normalizedErr).

🛡️ Proposed defensive check
 func taskErrorCode(taskErr error) string {
 	var normalizedErr *errors.Error
-	if !goerrors.As(taskErr, &normalizedErr) {
+	if !goerrors.As(taskErr, &normalizedErr) || normalizedErr == nil {
 		return ""
 	}
 	code := string(normalizedErr.RFCCode())
 	if code == "0" {
 		return ""
 	}
 	return code
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/dxf/framework/storage/history.go` around lines 237 - 247, Update
taskErrorCode to check whether normalizedErr is nil immediately after
goerrors.As succeeds, returning an empty string before calling RFCCode. Preserve
the existing handling for unmatched errors and RFC code "0".
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@pkg/dxf/bizutil/error_test.go`:
- Around line 24-28: Refactor TestIsDataError into a table-driven test covering
each conditional error pattern handled by IsDataError, including constraints,
partitions, duplicate keys, and the existing encode-value case. Include negative
cases for unrelated messages, then iterate through the cases and assert the
expected result.

In `@pkg/dxf/framework/scheduler/BUILD.bazel`:
- Line 70: Revert the shard_count change in the affected go_test rule, restoring
the prior test-target configuration. Do not include any generated metadata
changes from bazel_prepare, since this cosmetic adjustment does not require
them.

In `@pkg/dxf/framework/storage/history.go`:
- Around line 237-247: Update taskErrorCode to check whether normalizedErr is
nil immediately after goerrors.As succeeds, returning an empty string before
calling RFCCode. Preserve the existing handling for unmatched errors and RFC
code "0".

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: e0c13e4c-a152-4c81-8e95-ef2113511194

📥 Commits

Reviewing files that changed from the base of the PR and between 92fc143 and 06c857f.

📒 Files selected for processing (18)
  • .agents/skills/tidb-test-guidelines/references/dxf-case-map.md
  • docs/tidb_http_api.md
  • pkg/dxf/bizutil/BUILD.bazel
  • pkg/dxf/bizutil/error.go
  • pkg/dxf/bizutil/error_test.go
  • pkg/dxf/framework/scheduler/BUILD.bazel
  • pkg/dxf/framework/scheduler/scheduler.go
  • pkg/dxf/framework/scheduler/scheduler_nokit_test.go
  • pkg/dxf/framework/scheduler/scheduler_test.go
  • pkg/dxf/framework/storage/BUILD.bazel
  • pkg/dxf/framework/storage/history.go
  • pkg/dxf/framework/storage/history_test.go
  • pkg/dxf/framework/storage/table_test.go
  • pkg/dxf/framework/storage/task_state.go
  • pkg/dxf/framework/storage/task_state_test.go
  • pkg/dxf/importinto/scheduler.go
  • pkg/dxf/importinto/scheduler_testkit_test.go
  • pkg/server/handler/tests/dxf_test.go
💤 Files with no reviewable changes (1)
  • pkg/dxf/framework/scheduler/scheduler_test.go

@codecov

codecov Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 64 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.0222%. Comparing base (7ab6def) to head (0bba899).
⚠️ Report is 6 commits behind head on master.

Additional details and impacted files
@@               Coverage Diff                @@
##             master     #69863        +/-   ##
================================================
- Coverage   76.3207%   74.0222%   -2.2985%     
================================================
  Files          2041       2057        +16     
  Lines        559980     580128     +20148     
================================================
+ Hits         427381     429424      +2043     
- Misses       131698     150213     +18515     
+ Partials        901        491       -410     
Flag Coverage Δ
integration 41.1689% <0.0000%> (+1.4636%) ⬆️

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

Components Coverage Δ
dumpling 60.4471% <ø> (ø)
parser ∅ <ø> (∅)
br 47.4060% <ø> (-15.3154%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

# Conflicts:
#	.agents/skills/tidb-test-guidelines/references/dxf-case-map.md
#	pkg/server/handler/tests/dxf_test.go
@ingress-bot

Copy link
Copy Markdown

🔍 Starting code review for this PR...

@ingress-bot ingress-bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This review was generated by AI and should be verified by a human reviewer.
Manual follow-up is recommended before merge.

Summary

  • Total findings: 8
  • Inline comments: 7
  • Summary-only findings (no inline anchor): 1
Findings (highest risk first)

🟡 [Minor] (7)

  1. New bizutil package created for a single caller inside storage (pkg/dxf/bizutil/error.go:21, pkg/dxf/framework/storage/history.go:245)
  2. ErrorCategory value "failed" is ambiguous between real Failed state and uncategorized Reverted errors (pkg/dxf/framework/storage/history.go:248, docs/tidb_http_api.md:66, pkg/dxf/framework/storage/table_test.go:601)
  3. getMetricState re-implements ClassifyTaskError's Failed case instead of delegating for all terminal states (pkg/dxf/framework/scheduler/scheduler.go:830, pkg/dxf/framework/storage/history.go:234)
  4. Classification label strings duplicated across scheduler and storage packages (pkg/dxf/framework/scheduler/scheduler.go:48, pkg/dxf/framework/scheduler/scheduler.go:49, pkg/dxf/framework/storage/history.go:42)
  5. New taskErrorCategoryCancelled/DataError constants duplicate scheduler.go's metricStateCancelled/DataError under a different name with no shared source (pkg/dxf/framework/storage/history.go:42, pkg/dxf/framework/scheduler/scheduler.go:48, pkg/dxf/framework/scheduler/scheduler.go:837)
  6. ClassifyTaskError's doc comment calls the result "safe" without saying what it's safe from (pkg/dxf/framework/storage/history.go:233)
  7. taskErrorCode's "0" sentinel check has no rationale comment (pkg/dxf/framework/storage/history.go:260)

🧹 [Nit] (1)

  1. Exported TaskCancelMessage/IsCancelledErr lost their design-rationale comment and don't disclose substring matching (pkg/dxf/framework/storage/task_state.go:30, pkg/dxf/framework/storage/task_state.go:34)

Unanchored findings

🟡 [Minor] (1)

  1. getMetricState re-implements ClassifyTaskError's Failed case instead of delegating for all terminal states
    • Request: Have getMetricState call storage.ClassifyTaskError(state, taskErr) for both TaskStateFailed and TaskStateReverted (or any state ClassifyTaskError already covers) instead of re-implementing the Failed branch locally, and drop the now-unreachable proto.TaskStateFailed.String() fallback after the delegation.

Comment thread pkg/dxf/bizutil/error.go Resolved
Comment thread pkg/dxf/framework/storage/history.go Resolved
Comment thread pkg/dxf/framework/storage/history.go Resolved
Comment thread pkg/dxf/framework/storage/history.go Resolved
Comment thread pkg/dxf/framework/storage/history.go Resolved
Comment thread pkg/dxf/framework/storage/task_state.go Resolved
@ti-chi-bot ti-chi-bot Bot added approved needs-1-more-lgtm Indicates a PR needs 1 more LGTM. labels Jul 15, 2026

@OliverS929 OliverS929 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM overall.

Non-blocking: please update the PR description to match the current implementation.

@ti-chi-bot

ti-chi-bot Bot commented Jul 16, 2026

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: OliverS929, wjhuang2016

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

The pull request process is described 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

@ti-chi-bot ti-chi-bot Bot added lgtm and removed needs-1-more-lgtm Indicates a PR needs 1 more LGTM. labels Jul 16, 2026
@ti-chi-bot

ti-chi-bot Bot commented Jul 16, 2026

Copy link
Copy Markdown

[LGTM Timeline notifier]

Timeline:

  • 2026-07-15 13:24:19.129335422 +0000 UTC m=+806445.165430479: ☑️ agreed by wjhuang2016.
  • 2026-07-16 15:06:16.234392465 +0000 UTC m=+898962.270487521: ☑️ agreed by OliverS929.

@D3Hunter

Copy link
Copy Markdown
Contributor Author

/retest

@ti-chi-bot
ti-chi-bot Bot merged commit 57b5f22 into pingcap:master Jul 17, 2026
34 checks passed
@D3Hunter
D3Hunter deleted the avoid-expose-error branch July 17, 2026 02:51
@D3Hunter

Copy link
Copy Markdown
Contributor Author

/cherry-pick release-nextgen-202603

@ti-chi-bot

Copy link
Copy Markdown
Member

@D3Hunter: new pull request created to branch release-nextgen-202603: #69898.
But this PR has conflicts, please resolve them!

Details

In response to this:

/cherry-pick release-nextgen-202603

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 ti-community-infra/tichi repository.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved lgtm release-note Denotes a PR that will be considered when it comes time to generate release notes. size/XL Denotes a PR that changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants