Skip to content

Fix ANSI parameter MAX promotion for multibyte encodings - #4824

Closed
jtheisen wants to merge 1 commit into
dotnet:mainfrom
jtheisen:dev/automation/fix-utf8-parameter-promotion
Closed

jtheisen wants to merge 1 commit into
dotnet:mainfrom
jtheisen:dev/automation/fix-utf8-parameter-promotion

Conversation

@jtheisen

Copy link
Copy Markdown

AI Disclaimer

I'm the original reporter of this issue and the test case 3 years ago. AI (Codex/6.1-Sol) now helped me create this PR which apparently fixes this issue, but I can't say that I properly understand it. However, I thought it could be at least a helpful starting point.

Description

ANSI parameter metadata can be invalid when a value fits within 8,000 characters but exceeds 8,000 bytes in the connection encoding. For example, 4,001 é characters occupy 8,002 UTF-8 bytes. The driver currently selects non-MAX metadata using the character count, causing SQL Server to reject the RPC with an invalid data length or metadata length error.

This change counts transmitted ANSI bytes using the connection’s negotiated encoding before selecting MAX metadata. The calculation respects parameter size and offset. Public APIs and the character-based semantics of SqlParameter.Size remain unchanged.

Adds unit regression coverage and SQL Server round-trip tests. Database tests use unique database names and clean up their resources.

Issues

Fixes #2035.

Testing

  • Added 14 unit cases covering encoded byte boundaries, explicit and inferred sizes, truncation, offsets, nulls, and SqlString values.
  • Added six SQL Server regression cases covering text, stored procedure, and prepared commands with synchronous and asynchronous execution.
  • Validated against SQL Server 2022 on GitHub’s Ubuntu runner:
    • Without the fix: all six cases reproduced the expected SQL Server TDS metadata error.
    • With the fix: all six cases passed, with no skips.

Both comparison workflows report success when their expected outcomes are verified; the baseline’s green status means the expected failures were confirmed.

Additional local validation:

  • 1,502 unit tests and 206 parameter functional tests passed. The Windows-only integrated authentication test was excluded on Linux.
  • All 19 wire-protocol scenarios passed, including replay of the original EF-generated command and parameters.
  • Driver builds passed for net10.0 and net462.

The fork-specific comparison workflows are separate from this PR. Windows runtime validation remains for upstream CI.

Use the connection encoding to count transmitted ANSI bytes before selecting MAX metadata. This prevents UTF-8 values below 8000 characters but above 8000 bytes from producing invalid VARCHAR declarations and RPC framing.

Cover encoded byte boundaries, inferred sizes, truncation, offsets and SqlString values with unit regressions. Add SQL Server round-trip tests for text, stored procedure and prepared commands with sync and async execution.

Validation: 1502 unit tests and 206 parameter functional tests passed; the Windows-only integrated authentication test was excluded on Linux. All 19 wire scenarios passed, including replay of the original EF command. Driver builds passed for net10.0 and net462. Live SQL Server tests compile but remain unverified locally.

Fixes dotnet#2035
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

@jtheisen

Copy link
Copy Markdown
Author

@dotnet-policy-service agree

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

Fix mirrors the serializer's byte-count logic correctly, but the rollout is incomplete.

  • SqlParameter.MetaDataForSmi (SqlParameter.cs:1741) still calls ValidateTypeLengths() with no parser, so the Always Encrypted type_info path keeps the old character-based promotion and can disagree with the RPC metadata for the same parameter.
  • No test covers Always Encrypted or Offset-with-unset-Size for the new path.

// func will change type to that with a 4 byte length if the type has a two
// byte length and a parameter length > than that expressible in 2 bytes
internal MetaType ValidateTypeLengths()
internal MetaType ValidateTypeLengths(TdsParser parser = null)

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.

Defaulting parser to null silently preserves the old character-based behaviour at any call site that misses it — and one already does (MetaDataForSmi, line 1741). Make it a required argument so the compiler flags every caller.

object value = GetCoercedValue();
string text = value is SqlString sqlString ? sqlString.Value :
value is SqlChars sqlChars ? new string(sqlChars.Value) : (string)value;
actualSizeInBytes = parser.GetEncodingCharLength(text, (int)actualSizeInBytes, Offset, null);

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.

GetActualSize() returns min(Size, value.Length), not value.Length - Offset, so with a non-zero Offset and unset Size this resolves to GetByteCount(text, Offset, text.Length) and throws ArgumentOutOfRangeException. Clamp numChars to text.Length - Offset.

@github-project-automation github-project-automation Bot moved this from To triage to Waiting for customer in SqlClient Board Oct 22, 2026
@paulmedynski
paulmedynski self-requested a review October 23, 2026 17:43
@paulmedynski

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 2 pipeline(s).
1 pipeline(s) were filtered out due to trigger conditions.

@paulmedynski paulmedynski added this to the 8.0.0 milestone Oct 23, 2026
@codecov

codecov Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 66.08%. Comparing base (332e17f) to head (4c2ddd4).
⚠️ Report is 44 commits behind head on main.

❗ There is a different number of reports uploaded between BASE (332e17f) and HEAD (4c2ddd4). Click for more details.

HEAD has 2 uploads less than BASE
Flag BASE (332e17f) HEAD (4c2ddd4)
CI-SqlClient 2 0
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4824      +/-   ##
==========================================
- Coverage   72.43%   66.08%   -6.35%     
==========================================
  Files         292      289       -3     
  Lines       45471    68690   +23219     
==========================================
+ Hits        32937    45394   +12457     
- Misses      12534    23296   +10762     
Flag Coverage Δ
CI-SqlClient ?
PR-SqlClient-Project 66.08% <100.00%> (?)

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

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@paulmedynski paulmedynski added the Author attention needed PRs that require author to respond or make updates to PR. label Oct 26, 2026
@github-actions

Copy link
Copy Markdown

@jtheisen This pull request has been marked as Author attention needed.

When you have addressed the reviewer feedback and are ready for another review, please post a comment with /ready to remove the label and re-engage reviewers.

@jtheisen jtheisen closed this Oct 26, 2026
@github-project-automation github-project-automation Bot moved this from Waiting for customer to Done in SqlClient Board Oct 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Author attention needed PRs that require author to respond or make updates to PR.

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Bug in SQL Server provider when using UTF8 collations

3 participants