Skip to content

fix(export): discard incompatible statement info CSV - #28503

Merged
XuPeng-SH merged 5 commits into
matrixorigin:mainfrom
jiangxinmeng1:fix/issue-28379-etlmerge-statement-info
Sep 11, 2026
Merged

XuPeng-SH merged 5 commits into
matrixorigin:mainfrom
jiangxinmeng1:fix/issue-28379-etlmerge-statement-info

Conversation

@jiangxinmeng1

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #28379

What this PR does / why we need it:

Fix ETLMerge retry storms caused by legacy system.statement_info CSV files whose schema
predates the account_id column.

  • Detects records where account_id cannot be parsed as an unsigned integer (for example,
    legacy rows where user=admin occupies that position).

  • Marks them as permanently incompatible instead of treating them as transient database
    failures.

  • Logs the cause and deletes the incompatible ETL file, preventing repeated merge retries and
    error-log storms.

  • Keeps normal retry behavior for temporary database connection failures.

  • Adds unit coverage for incompatible-record detection and file cleanup.

Validated remotely with build, go vet, and CGo-enabled tests for pkg/util/export/etl/db and
pkg/util/export.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@matrix-meow matrix-meow added the size/S Denotes a PR that changes [10,99] lines label Sep 9, 2026
@mergify mergify Bot added the kind/bug Something isn't working label Sep 9, 2026
@jiangxinmeng1
jiangxinmeng1 force-pushed the fix/issue-28379-etlmerge-statement-info branch from 7532920 to 8d70c2f Compare September 9, 2026 07:31
@matrix-meow matrix-meow added size/M Denotes a PR that changes [100,499] lines and removed size/S Denotes a PR that changes [10,99] lines labels Sep 9, 2026

@gouhongshen gouhongshen 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.

Codex automated review

Scope: git diff origin/main...HEAD touches 4 files (pkg/util/export/etl/db/db_holder.go, pkg/util/export/merge.go + their tests); no unrelated files.

Prior behavior: IsRecordExisted (db_holder.go:409) hardcodes the post-#23149 statement_info layout (account_id at index 4) and returned the raw strconv.ParseUint error for pre-account_id CSVs. Commit e3fd7fe inserted accountIdCol between account and user, so in legacy rows index 4 holds user ("admin" in issue #28379). doMergeFiles classified that permanent parse failure as a transient DB error: log + 10s sleep per file + retry every merge interval — exactly the reported storm.

The fix is directionally correct, and I verified the invariants that matter:

  • Only the statement_info branch can emit the new sentinel, so rawlog/metric merges are unaffected. Moving getDBConn after the parse is safe: Flush -> WriteRowRecords obtains its own connection (db_holder.go:246), so the removed pre-fetch was not a warm-up dependency.
  • Transient failures still retry: connection/query errors are returned unwrapped; only the parse failure routes to deletion.
  • Deletion cannot destroy currently-loadable data: producers always set account_id via table.Uint32Field and Row.ToStrings() renders it with fmt.Sprintf("%d", uint32(...)) (pkg/util/export/table/table.go:798), so index 4 of a current-layout record is always a base-10 uint32 (never empty). Deleting rather than quarantining is a reasonable documented tradeoff — a 30-field legacy CSV is unloadable into the 31-column table by any version after the v4.0.0 upgrade.
  • Merge is only constructed by NewMerge (no struct literals outside it), so the new isRecordExisted seam cannot be nil in production; it is written before publication, so no race with concurrent doMergeFiles.
  • gofmt -l clean.

Blocking: the second new test fails deterministically, so pkg/util/export UT is red and the merge-level discard path is unverified. Ran locally with CGO enabled: go test ./pkg/util/export/ -> only --- FAIL: TestMergeDiscardsIncompatibleStatementInfoFile (reported at merge_test.go:219, "file size does not match"); go test ./pkg/util/export/etl/db/ -> ok. The rest of that test is sound: NewCSVReader reads with Size: -1 and ContentReader.ReadLine returns the single record, so once the IOEntry size matches the data the discard branch is genuinely exercised. The canceled-context assertion in TestDiscardIncompatibleFile also passes for the right reason (MemoryFS.Delete checks ctx.Done() first, pkg/fileservice/memory_fs.go:330).

The PR has no existing reviews and no inline review comments (only a paused-qodo bot notice), so nothing here duplicates another reviewer and there was no author explanation to weigh.

P1 - New test TestMergeDiscardsIncompatibleStatementInfoFile fails deterministically: IOEntry Size (9) does not match Data (10 bytes) (pkg/util/export/merge_test.go:221)

The fixture declares Size: int64(len("statement")) = 9 but Data: []byte("statement\n") = 10 bytes. fileservice enforces the declared size on every backend (moerr ErrSizeNotMatch, "file %s size does not match", reached via MemoryFS.write -> newIOEntriesReader, pkg/fileservice/memory_fs.go:176), so fs.Write fails and require.NoError at merge_test.go:219 aborts the test before any discard logic runs.

Verified locally with CGO enabled (third-party headers from a sibling checkout, no repo modification):

  • go test -count=1 ./pkg/util/export/ -> FAIL, exactly one failing test: --- FAIL: TestMergeDiscardsIncompatibleStatementInfoFile, merge_test.go:219: Received unexpected error: file size does not match.
  • go test -count=1 ./pkg/util/export/etl/db/ -> ok.

Impact: the package UT gate is red, and the merge-level behavior this PR exists to add (doMergeFiles -> sentinel -> discardIncompatibleFile -> file removed, task returns success instead of looping) has no passing coverage. Note the sibling test TestDiscardIncompatibleFile uses matching sizes (len("legacy") vs "legacy") and passes, which is why only this one is broken.

Fix: make the declared size match the payload, e.g. {Size: int64(len("statement\n")), Data: []byte("statement\n")} (or drop the trailing newline). No other change is needed — I traced the remainder and it exercises the new branch: newETLReader ignores FileMeta.FileSize for .csv, NewCSVReader reads with Size: -1 (merge.go:656), ContentReader.ReadLine returns ["statement"], Row.ParseRow only assigns, then the stubbed isRecordExisted returns the sentinel and the file is deleted; &table.Table{Table: "statement_info"} is safe through GetRow/GetIdentify.

P2 - Incompatibility is inferred from the value at hardcoded index 4 instead of the record schema, so some legacy files keep the retry storm (pkg/util/export/etl/db/db_holder.go:419)

Non-blocking, but it bounds how completely the PR fixes issue #28379. In the legacy layout index 4 is user (e3fd7fe inserted accountIdCol between account and user), so the sentinel fires only while that value is not a base-10 uint32. If a legacy row's user name is numeric (digit-only MySQL/MO user names are legal), ParseUint succeeds, isStatementExisted runs with a bogus account_id and returns false, the file is not discarded, and it then fails in LOAD DATA INLINE (30 fields vs the current 31 columns) — reproducing the same permanent per-interval failure plus the 10s sleep per file in doMergeFiles (merge.go:463). The same blind spot applies to any other layout whose index 4 happens to be numeric.

A deterministic discriminator is available: ETL CSVs are written by encoding/csv from Row.ToStrings() (pkg/util/export/etl/csv.go:82, pkg/util/export/table/table.go:789), which always emits exactly len(tbl.Columns) fields with proper quoting, so a record whose field count differs from the table's column count is by definition written against a different schema. Comparing len(record) with len(tbl.Columns) (and resolving the account_id index from tbl.Columns by name rather than the hardcoded 4 with its "Replace with actual index" comment at db_holder.go:412) catches every pre-account_id file regardless of data values. Care needed: the new merge_test fixtures build &table.Table{Table: "statement_info"} with no columns, so a count-based check requires the test table to carry the real column list.

The reported production data ("admin") is handled by the current heuristic, so this is a robustness gap rather than a regression.

P2 - Destructive discard path increments no metric, unlike every other outcome in the merge flow (pkg/util/export/merge.go:486)

Non-blocking observability gap. discardIncompatibleFile permanently deletes observability data, but on success it emits only a WARN log and no counter; the delete-error case reuses v2.TraceETLMergeDeleteFailedCounter, which is indistinguishable from a normal post-upload delete failure. Every other outcome in this flow is metered (TraceETLMergeOpenFailedCounter, ReadFailed, ParseFailed, ExistFailed, WriteFailed, DeleteFailed, ExistCounter, SuccessCounter), so operators lose the only signal that distinguishes "data merged" from "data silently destroyed". Since the issue being fixed is explicitly about log noise, a dashboard-visible counter (e.g. a dedicated discard-incompatible counter in pkg/util/metric/v2) is a better long-term signal than grepping WARN lines. The WARN message itself is well formed (table, path, cause).

@mergify

mergify Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Queued — the merge queue status continues in this comment ↓.

@XuPeng-SH XuPeng-SH 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.

Reviewed exact head 5c79e38 against base 7013fbb and reconciled both earlier reviews. No concrete blocker remains. The fixture byte-count failure is fixed; schema-length validation now precedes the fallback index guard, and tests cover length mismatch and named-column lookup.

Current-layout statement_info writers emit the expected field count and canonical uint32 account ID. The permanent sentinel is produced before DB access only for incompatible records; connection/query errors still follow the existing retry path. At merge level the sentinel exits the per-file upload closure, deletes only that exact file and continues the outer file loop. Reader/row/cache cleanup still runs, failed deletion propagates, and compatible files retain normal flush-before-delete semantics. The earlier Row.ParseRow call only assigns CSV data, so it does not shadow the new validation. This intentionally discards unloadable observability files rather than migrating/quarantining them, consistent with the documented policy; the remaining dedicated-discard-metric suggestion is non-blocking.

Evidence: full diff/history, record producer/parser, DB/flush and per-file merge/error/cleanup paths and test assertions. Prior native package results and the current PR's remote build/vet/tests are author/prior-review evidence, not new runs by me. No CI wait or live deletion was performed. Head/base rechecked before submission.

@mergify

mergify Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-09-11 07:59 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🚫 Left the queue — 2026-09-11 07:59 UTC · at 5c79e384c34c288fd7be80056a0e7ad244a318b5

This pull request spent 30 seconds in the queue, with no time running CI.

Reason

The pull request can't be updated

For security reasons, Mergify can't update this pull request. Try updating locally.
GitHub response: refusing to allow a GitHub App to create or update workflow .github/workflows/entrypoint.yaml without workflows permission

Hint

You should update or rebase your pull request manually. If you do, this pull request will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

This branch was previously deployed

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

Labels

kind/bug Something isn't working size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants