DacFx icon indicating copy to clipboard operation
DacFx copied to clipboard

BACPAC import fails (Msg 4002 / TDS stream ended unexpectedly) when a nullable JSON column is followed by another column and a row has NULL

Open Josh82934 opened this issue 6 months ago • 4 comments

  • SqlPackage or DacFx Version: SqlPackage 170.3.93.6 (DacFxVersion 170.3.93.6, ModelSchemaVersion 2.9, DataStreamVersion 2.0.0.0)
  • .NET Framework (Windows-only) or .NET Core: .NET Core 10.0.4 (sqlpackage as a dotnet global tool)
  • Environment (local platform and source/target platforms): Local: Linux (Arch). Source and target: SQL Server 2025 RTM-CU4 (build 17.0.4035.5) on Linux/Ubuntu 24.04, Docker image mcr.microsoft.com/mssql/server:2025-CU4-ubuntu-24.04. Same instance for both source and target databases, Azure SQL Database is not required to reproduce

Steps to Reproduce:

  1. Create a database with a single table containing a nullable JSON column followed by at least one other column, and insert one row whose JSON value is NULL:
CREATE DATABASE T;
GO
USE T;
GO
CREATE TABLE X (Json1 JSON NULL, Filler INT NOT NULL);
INSERT INTO X VALUES (NULL, 0);
GO
  1. Export the database (succeeds, produces a ~3 KB BACPAC):
sqlpackage /Action:Export /SourceServerName:"<server>" /SourceDatabaseName:T /SourceUser:SA /SourcePassword:"<pw>" /SourceTrustServerCertificate:True /TargetFile:T.bacpac
  1. Import the BACPAC to a new database:
sqlpackage /Action:Import /SourceFile:T.bacpac /TargetServerName:"<server>" /TargetDatabaseName:T2 /TargetUser:SA /TargetPassword:"<pw>" /TargetTrustServerCertificate:True

Expected: import succeeds. Actual: fails on dbo.X with Msg 4002: The incoming tabular data stream (TDS) protocol stream is incorrect. The stream ended unexpectedly. thrown from Microsoft.Data.SqlClient.SqlBulkCopy.CopyBatchesAsyncContinuedOnSuccess. SqlPackage then enters an indefinite exponential-backoff retry loop (delays 0.25s, 0.5s, 1s, 2s, 4s, 8s, 16s, 32s, then capped at 120s) and continues retrying past retry 8.

The trigger is narrow and verified by isolation testing. The bug fires if and only if BOTH: (a) the JSON-typed nullable column is followed by at least one other column in the table definition, AND (b) at least one row has NULL in that JSON column. Either condition alone passes. Both together fail deterministically, even on a single 1-row, 2-column table. The trailing column type does not matter (INT, JSON, etc. all trigger).

Possibly the same family as #8 (_BIN2_UTF8 BACPAC fails on import with "Unexpected end of stream") and #765 (sql_variant + UTF-8 collation export failure).

Did this occur in prior versions? If not - which version(s) did it work in?

(DacFx/SqlPackage/SSMS/Azure Data Studio) Tested only on SqlPackage 170.3.93.6, which is the current latest. I have not tested earlier SqlPackage versions. The first class JSON data type is new in SQL Server 2025, so any prior version comparison is constrained to SqlPackage versions released after JSON-type support was added to DacFx.

Josh82934 avatar May 08 '26 20:05 Josh82934

This was fixed and available in version 170.4.80-preview

allancascante avatar May 22 '26 16:05 allancascante

@allancascante Hello, I would like to signal that the issue that @Josh82934 has mentioned is still present. I replicated the same steps on version 170.4.83.3.

claudiocaldr avatar Jun 09 '26 14:06 claudiocaldr

I can confirm @claudiocaldr's report as well. When I had a nullable JSON column followed by a nullable column, I would get the error reported by the OP. If I read the output bcp file correctly that is packed inside the bacpac file, all of the data is exporting. This is an import problem. Through some troubleshooting, I eventually manipulated the table and moved the JSON column to the end of the table, and the import worked up through the first null value in the JSON column. (That is to say 3 rows had json values and the rest of the rows had null values in the JSON column. The import worked for 4 rows but not the rest.) As part of other troubleshooting, I updated all null JSON column values to an empty json value "{}", and all rows imported. I think the bug is still present for JSON columns followed by nullable columns and it is also related to if the JSON column has a value or not when the JSON column is at the end of a table.

Here is the stack with the /Diagnostics:True switch. This is when a nullable JSON column is followed by another nullable column (datetime2 in my case).

Error Number:4002,State:2,Class:16
Microsoft.Data.Tools.Diagnostics.Tracer Error: 19 : 2026-06-26T11:47:16 : Retry requested: Retry count = 6. Delay = 00:00:08, SQL Error Code = -2146232060, SQL Error Number = 4002, Can retry error = True, Will retry = True Microsoft.Data.SqlClient.SqlException (0x80131904): The incoming tabular data stream (TDS) protocol stream is incorrect. The stream ended unexpectedly.
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, SqlCommand command, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at Microsoft.Data.SqlClient.SqlBulkCopy.RunParser(BulkCopySimpleResultSet bulkCopyHandler)
   at Microsoft.Data.SqlClient.SqlBulkCopy.CopyBatchesAsyncContinuedOnSuccess(BulkCopySimpleResultSet internalResults, String updateBulkCommandText, CancellationToken cts, TaskCompletionSource`1 source)
   at Microsoft.Data.SqlClient.SqlBulkCopy.CopyBatchesAsyncContinued(BulkCopySimpleResultSet internalResults, String updateBulkCommandText, CancellationToken cts, TaskCompletionSource`1 source)
   at Microsoft.Data.SqlClient.SqlBulkCopy.CopyBatchesAsync(BulkCopySimpleResultSet internalResults, String updateBulkCommandText, CancellationToken cts, TaskCompletionSource`1 source)
   at Microsoft.Data.SqlClient.SqlBulkCopy.WriteToServerInternalRestContinuedAsync(BulkCopySimpleResultSet internalResults, CancellationToken cts, TaskCompletionSource`1 source)
   at Microsoft.Data.SqlClient.SqlBulkCopy.WriteToServerInternalRestAsync(CancellationToken cts, TaskCompletionSource`1 source)
   at Microsoft.Data.SqlClient.SqlBulkCopy.WriteToServerInternalAsync(CancellationToken ctoken)
   at Microsoft.Data.SqlClient.SqlBulkCopy.WriteRowSourceToServerAsync(Int32 columnCount, CancellationToken ctoken)
   at Microsoft.Data.SqlClient.SqlBulkCopy.WriteToServer(DbDataReader reader)
   at Microsoft.Data.Tools.Schema.Sql.Dac.Data.Import.ImportTableBatchHelper.WriteToServer(DataRowsBatch dataRowsBatch, SqlBulkCopyDataReader& bcpDataReader) in C:\__w\1\s\Source\SchemaSql\Dac\Data\Import\ImportTableBatchHelper.cs:line 217
   at Microsoft.Data.Tools.Schema.Sql.Dac.Data.Import.ImportTableBatchHelper.ImportRowsBatchWithRetryState(DataRowsBatch dataRowsBatch, RetryState retryState) in C:\__w\1\s\Source\SchemaSql\Dac\Data\Import\ImportTableBatchHelper.cs:line 108
   at Microsoft.Data.Tools.Schema.Sql.Dac.Data.Import.ImportTableBatchHelper.<>c__DisplayClass11_0.<ImportRowsBatch>b__0(RetryState retryState) in C:\__w\1\s\Source\SchemaSql\Dac\Data\Import\ImportTableBatchHelper.cs:line 97
   at Microsoft.Data.Tools.Schema.Common.SqlClient.RetryPolicy.<>c__DisplayClass26_0.<ExecuteAction>b__0(RetryState retryState) in C:\__w\1\s\Source\SchemaSql\Common\SqlClient\RetryPolicy.cs:line 144
   at Microsoft.Data.Tools.Schema.Common.SqlClient.RetryPolicy.ExecuteAction[R](Func`2 func, Nullable`1 token) in C:\__w\1\s\Source\SchemaSql\Common\SqlClient\RetryPolicy.cs:line 195

Here is my sqlpackage version.

C:\Users\PhilipWolfe>sqlpackage -version
170.4.83.3

philipwolfe avatar Jun 26 '26 16:06 philipwolfe

confirmed

z4urce-eset avatar Jul 01 '26 08:07 z4urce-eset

Yep, still having the same issue using 170.4.83.3 - I even tried the latest preview release just in the hope!!

markgr avatar Jul 30 '26 06:07 markgr

I have found a workaround - well for someone like me who just needs to install the BacPac locally....

  • Download 7-zip
  • Once installed - right click on the bacpac file and select 'Open Archive'
  • Right click on the model.xml file and select Edit (I think you can double click it as well to do the same thing)
  • Now search for all the JSON columns
  • Search for 'Name="[json]"'

You'll find entries like this

Image

Now replace the Relationship node and all its contents with this

<Property Name="IsNullable" Value="True" />
<Relationship Name="TypeSpecifier">
	<Entry>
		<Element Type="SqlTypeSpecifier">
			<Property Name="IsMax" Value="True" />
			<Relationship Name="Type">
				<Entry>
					<References ExternalSource="BuiltIns" Name="[nvarchar]" />
				</Entry>
			</Relationship>
		</Element>
	</Entry>
</Relationship>

Do this for all the JSON columns (Note if you see one like this)

Image

You can ignore these ones as they are NON Nullable :)

  • Ok so once you've done that for all the columns - make sure that it saves - make sure the Z-zip prompts you to update the archive - if you close the file (in say notepad) it should prompt you to do it

Now still in Z-Zip - copy the file to say c:\temp

Image

Then call this in a PowerShell terminal window

Get-FileHash -Path "model.xml" -Algorithm SHA256

That will give you a new File Hash

Image

Copy that HASH

  • Back in 7-Zip now edit the Origin.xml file

Update the Hash for the model.xml file

Image

Again make sure that 7-Zip updates the file in the Acrhive.....

Now when you run the import - it will create those columns as NVARCHAR(max) columns instead and will complete.....

I know it's not a perfect solution if you NEED the columns to be JSON ones - but for most people it will probably do for now until the SQLPackage / SSMS import is fixed

markgr avatar Jul 30 '26 07:07 markgr