Skip to content

Perf | Reduce SqlBulkCopy destination metadata query cost - #4988

Merged
paulmedynski merged 10 commits into
mainfrom
dev/cheena/sqlclient-performance-regression
Nov 11, 2026
Merged

paulmedynski merged 10 commits into
mainfrom
dev/cheena/sqlclient-performance-regression

Conversation

@cheenamalhotra

@cheenamalhotra cheenamalhotra commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Description

Reduces the destination-metadata query cost reported in #4985 by restoring the pre-6.0 SET FMTONLY ON; SELECT * query for Bulk Copy operations mapped by destination name.

Adds Switch.Microsoft.Data.SqlClient.UseBulkCopyCatalogMetadataDiscovery as a tri-state switch:

Setting Behavior
Unset (default) Destination-name mappings use the fast query, falling back once to sys.all_columns if a name is missing. Destination-ordinal mappings, implicit/default mappings, and SQL Graph aliases use catalog discovery directly.
true Always uses catalog discovery.
false Never uses catalog discovery. Uses visible-column positions without hidden-column or SQL Graph alias discovery.

Compatibility: Automatic mode preserves current destination positions and supports hidden-column names from #1854 and SQL Graph aliases. Explicit true avoids the extra metadata round trip for hidden-name workloads. Explicit false restores fast-only discovery and its limitations.

Fallback happens before any rows are sent; it does not retry the bulk write. The alias temp table is only created when mappings require it. Catalog metadata and alias capability are retained when the cache is reused. SQL Server restrictions on writing generated columns still apply. No public API changes. The switch is documented in the feature reference and API remarks.

Options considered

Option Why not use it as the default?
Keep catalog discovery for every copy Preserves current behavior, but keeps the catalog-query cost reported in #4985 for ordinary name-mapped copies.
Restore only the pre-6.0 query Removes the catalog cost, but loses hidden-column and graph-alias discovery added by #3590 and #3677. Hidden columns also disappear from destination positions.
Boolean switch, fast by default Lets customers restore catalog discovery, but existing hidden-column, graph-alias, and ordinal workloads could need a configuration change.
Probe the catalog before choosing a query Still adds catalog work to ordinary copies. A separate probe also adds a metadata round trip.
Try fast discovery for every automatic copy Adds an avoidable round trip for recognized graph aliases. Hidden columns can also shift ordinal mappings without a missing-name error, so fallback cannot reliably detect that problem.

Why this design

Automatic mode chooses the query from the destination mappings:

How columns are mapped Query used
By destination name, such as "Name" to "Name" Fast query; falls back once if a name is missing.
By destination position, such as 0 to 1 Catalog query directly.
No mappings supplied; positions are matched automatically Catalog query directly.
Graph aliases, such as $from_id Catalog query directly.

SELECT * omits hidden columns. For a table ordered as Id, ValidFrom (hidden), ValidTo (hidden), OtherDate, destination position 1 would become OtherDate instead of ValidFrom. Choosing catalog discovery upfront for ordinal/default mappings prevents values from going into the wrong column. A fast cache created by earlier named mappings is replaced before using ordinals. This choice adds no extra metadata round trip.

Who benefits when upgrading from 5.2?

Customers using explicit destination-name mappings avoid the catalog query for ordinary columns. The customer in #4985 uses name mappings, so this targets their reported regression.

Customers using destination ordinals or no explicit mappings retain catalog discovery, even for ordinary tables without hidden columns. They may therefore still see higher metadata-discovery CPU than 5.2; this does not restore 5.2 performance for every Bulk Copy workload. The cost matters most for frequent copies, many tables/databases, and small batches. Metadata caching helps when the same SqlBulkCopy instance is reused. These copies still avoid alias temp-table work when no graph aliases are mapped.

Only automatic name fallback adds one metadata batch round trip, including an invalid name that still fails after catalog discovery. Without metadata caching, the retry repeats on each copy. With caching, successful catalog discovery is reused. Each discovery query is one SQL batch; nested server-side EXEC calls do not add network round trips. Server CPU improvement still needs measurement against the customer workload.

Self-review notes

  • Ordinal/default mapping compatibility and cached alias capability are addressed.
  • Automatic name-fallback detection still adds a mapping-by-column scan on fast-metadata cache hits. This remains a driver CPU concern for wide-table workloads.
  • Collation rows are matched to destination metadata by position. Alignment when visible text columns follow hidden columns still needs SQL Server validation.

Validation

  • Tests added or updated
  • Public API changes documented (N/A; no API changes)

Issues

Fixes #4985

Testing

Added query-generation coverage for all three modes, automatic fallback decisions, alias resolution, destination-name escaping, and cache compatibility. Added sync/async integration coverage for ordinary copies, writable hidden columns, graph aliases, temporary tables, and metadata caching. Existing catalog-dependent tests explicitly enable the switch.

Added sync/async ordinal and default-mapping cases with a visible date column after writable hidden columns. Ordinal cases also cover replacing a fast cache after switching from names to ordinals. Added unit coverage for retaining cached alias capability.

  • dotnet test src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft.Data.SqlClient.UnitTests.csproj -f net10.0 --filter "FullyQualifiedName~SqlBulkCopyTests|FullyQualifiedName~LocalAppContextSwitchesTest|FullyQualifiedName~SqlBulkCopyCacheMetadataTest" -v q - passed, 70 tests, none skipped.
  • dotnet build src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTests.csproj -f net10.0 -v q - passed, no warnings.
  • dotnet build src/Microsoft.Data.SqlClient/src/Microsoft.Data.SqlClient.csproj -f net462 -v q - passed, no warnings.

Integration tests and customer CPU measurements were not run because no SQL Server is available. .NET Framework runtime tests were not run on macOS.

Guidelines

Please review the contribution guidelines before submitting a pull request:

cheenamalhotra and others added 2 commits November 3, 2026 18:46
- Skip the #Column_Aliases temp table and result set unless mappings use
  SQL Graph aliases.
- Add Switch.Microsoft.Data.SqlClient.UseLegacyBulkCopyMetadataDiscovery
  (default false) to restore the pre-6.0 SET FMTONLY ON / SELECT * query.
  Graph alias mappings still use the catalog-based query.
- Add unit tests for query generation and manual tests for the legacy path.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…ery (#4985)

Default false uses the pre-6.0 FMTONLY query. Setting it to true enables
the sys.all_columns query for hidden columns and SQL Graph aliases.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@cheenamalhotra
cheenamalhotra requested review from a team and a balanced review from Copilot November 4, 2026 01:53
@github-project-automation github-project-automation Bot moved this to To triage in SqlClient Board Nov 4, 2026
@cheenamalhotra cheenamalhotra added Public API 🆕 Issues/PRs that introduce new APIs to the driver. Breaking Change 🔨 Issues/PRs that are related with breaking API changes in the driver. labels Nov 4, 2026
@cheenamalhotra cheenamalhotra added this to the 8.0.0-preview1 milestone Nov 4, 2026

Copilot AI 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.

🟡 Changes recommended

The new constant is declared inside #if NET but referenced unconditionally, causing the net462 target to fail compilation with CS0103.

1 open issue
What changed in this PR

Restores the pre-6.0 SqlBulkCopy destination-metadata query to address the server CPU regression reported in #4985. Catalog discovery remains available through an opt-in switch for hidden-column and SQL Graph alias mappings.

Changes:

  • Uses SET FMTONLY ON; SELECT * by default.
  • Creates the alias temporary table only when catalog discovery requires alias resolution.
  • Documents the compatibility change and adds query-generation and integration tests.
File Description
src/​Microsoft.Data.SqlClient/​tests/​UnitTests/​Microsoft/​Data/​SqlClient/​SqlBulkCopyTests.cs Tests query selection, alias handling, and destination-name escaping.
src/​Microsoft.Data.SqlClient/​tests/​UnitTests/​Microsoft/​Data/​SqlClient/​LocalAppContextSwitchesTest.cs Checks the switch defaults to false.
src/​Microsoft.Data.SqlClient/​tests/​ManualTests/​BulkCopy/​UnprivilegedLogin.cs Enables catalog discovery for permission tests.
src/​Microsoft.Data.SqlClient/​tests/​ManualTests/​BulkCopy/​SqlGraphTables.cs Enables catalog discovery for graph tests.
src/​Microsoft.Data.SqlClient/​tests/​ManualTests/​BulkCopy/​LegacyMetadataDiscovery.cs Adds integration coverage for legacy discovery and mapping behavior.
src/​Microsoft.Data.SqlClient/​tests/​ManualTests/​BulkCopy/​HiddenTargetColumn.cs Enables catalog discovery for hidden-column tests.
src/​Microsoft.Data.SqlClient/​tests/​Common/​LocalAppContextSwitchesHelper.cs Saves, sets, and restores the new switch in tests.
src/​Microsoft.Data.SqlClient/​src/​Microsoft/​Data/​SqlClient/​SqlBulkCopy.cs Selects the metadata query and handles optional alias results.
src/​Microsoft.Data.SqlClient/​src/​Microsoft/​Data/​SqlClient/​LocalAppContextSwitches.cs Defines the catalog-discovery switch and cached value.
.github/​instructions/​features.instructions.md Documents the switch, default, and mapping implications.

Review effort: Balanced

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 4, 2026 02:00

Copilot AI 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.

🔵 Needs a closer look

SQL Server metadata-shape and hidden-column/graph compatibility changes remain unverified, with current-head CI pending and trusted copies of the review policies missing.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@cheenamalhotra
cheenamalhotra marked this pull request as draft November 4, 2026 02:10
@cheenamalhotra cheenamalhotra removed the Breaking Change 🔨 Issues/PRs that are related with breaking API changes in the driver. label Nov 4, 2026
Use a tri-state switch to preserve hidden-column and graph-alias support while keeping ordinary copies on the fast metadata path.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 4, 2026 02:13
@cheenamalhotra
cheenamalhotra marked this pull request as ready for review November 4, 2026 02:18
@cheenamalhotra cheenamalhotra moved this from To triage to In review in SqlClient Board Nov 4, 2026

Copilot AI 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.

🟡 Changes recommended

Skipping hidden columns shifts ordinal and default destination mappings, potentially causing silent writes to the wrong column.

2 open issues

Review effort: Balanced

@cheenamalhotra cheenamalhotra modified the milestones: 8.0.0-preview1, 8.0.0 Nov 4, 2026
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 4, 2026 02:29
This was referenced Dec 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Hotfix 8.0.1 PRs that must be backported to release/8.0 Public API 🆕 Issues/PRs that introduce new APIs to the driver.

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

A major performance regression from when you upgraded 5.2.2 to 7.1.1

5 participants