Skip to content

[Bug]: JSONLINE truncated-record holdover aliases the reused parser buffer and silently inserts wrong values #31850

Closed as duplicate

Description

@iamlinjunhong

Branch Name

main

Commit ID

4ca0d77

Other Environment Information

  • Hardware: Apple Silicon (arm64, macOS 15)
  • OS: darwin/arm64, Go 1.27.1
  • Standalone mo-service launched from etc/launch (single launch.toml, CN port-base 38000, no non-default config except port offsets); reproduction is also a plain Go unit test against pkg/sql/colexec/external

Actual Behavior

A JSONLINE (format=jsonline, jsondata=array) file whose single record is spread over several physical lines is silently loaded with values that do not exist in the file:

File jl_arr.jsonl:

[111,
[222,
333]
]

The physical-line concatenation of this file is the complete two-value array [111,[222,333]], whose first value is 111.

LOAD DATA INFILE {'filepath'='.../jl_arr.jsonl', 'format'='jsonline', 'jsondata'='array'} INTO TABLE jl2; succeeds and inserts the row a=222, s="[222 333]" (see evidence). The first value 111 vanishes and is replaced by bytes of the second line.

Root cause: CsvReader.prevStr in pkg/sql/colexec/external/reader_csv.go holds over the text of a genuinely truncated JSONLINE record across CSV records. csvparser.Read returns Field.Val values that are unsafe views over the parser's recordBuffer (pkg/sql/util/csvparser/csv_parser.go:347, util.UnsafeBytesToString(parser.recordBuffer)), and every record read resets that buffer in place (parser.recordBuffer = parser.recordBuffer[:0], pkg/sql/util/csvparser/csv_parser.go:733). When the JSONLINE translator stores the truncated record (r.prevStr = str, pkg/sql/colexec/external/reader_csv.go:395 for arrays, :328 for objects) it keeps a raw view of the reused buffer, so the next Read overwrites the held-over text before it is concatenated in transJsonObject2Lines/transJsonArray2Lines (reader_csv.go:320-322, 388-390).

Consequences (same root cause):

  1. Silent wrong values: whenever the overwritten prefix happens to still form parseable JSON with the appended tail, the load commits a row whose values are a byte mix of several lines (SQL repro above).
  2. Record continuation never succeeds: for the ordinary pretty-printed case the corrupted accumulation fails with a parse error quoting text that does not exist in the file (e.g. [1,\n2] fails with invalid input: the line is not a well-formed json array), even though the holdover design ("unexpected EOF, wait for next batch", reader_csv.go:203-214) intends to complete it.
  3. In tolerant error mode, __mo_error_text rows record the same corrupted concatenation (param.ErrorMode.RawText = r.prevStr + raw, reader_csv.go:199).

This is a reconfirmation and strengthening of open issue #31280 (which describes the aliasing and the failing continuation): this report adds that the bug is not limited to a failed load -- it silently persists wrong values through a successful LOAD DATA. Fix direction: make the holdover copy the truncated text (r.prevStr = strings.Clone(str), or have the translator copy row[0].Val before the next Read).

Expected Behavior

Per the holdover design in the reader (pkg/sql/colexec/external/reader_csv.go:203-214: "transJson2Lines holds the text over in prevStr only when the record is genuinely truncated"; reader_csv.go:320-322/388-390: the held text must be prepended to the next line unchanged), the record above must load as one row with a=111 (the 2nd JSON value [222,333] stringified into the varchar column), or -- if multi-line records are rejected by policy -- must fail with a clear error. It must never insert values that are not present in the file. Reference for the strict-EOF semantics: jsonline_truncated_eof_test.go and issue #29842 ("incomplete json record" at EOF when no continuation line follows).

Steps to Reproduce

A. SQL level (standalone mo-service, mysql client):

create database loom; use loom;
drop table if exists jl2;
create table jl2(a int, s varchar(64));
-- write file jl_arr.jsonl with exactly these 4 lines: "[111," / "[222," / "333]" / "]"
load data infile {'filepath'='/abs/path/jl_arr.jsonl', 'format'='jsonline', 'jsondata'='array'} into table jl2;
select * from jl2;
-- actual: 222 | "[222 333]"   expected: 111 | "[222 333]"

B. Go unit test (file pkg/sql/colexec/external/loom_test_jsonline_holdover_test.go; reuses committed helpers errorModeParam, colLine, colA, colS, numTestCols from error_mode_test.go):

package external

import (
	"io"
	"strings"
	"testing"

	"github.com/matrixorigin/matrixone/pkg/container/vector"
	"github.com/matrixorigin/matrixone/pkg/sql/parsers/tree"
	"github.com/stretchr/testify/require"
)

func loomDrain(t *testing.T, format, jsonData string, keep int, content string) (error, int, *CsvReader) {
	param, proc, bat := errorModeParam(t, format, jsonData, keep)
	t.Cleanup(func() { bat.Clean(proc.Mp()) })
	r := &CsvReader{param: param}
	r.reader = io.NopCloser(strings.NewReader(content))
	parser, err := newCSVParserFromReader(param.Extern, r.reader)
	require.NoError(t, err)
	r.plh = &ParseLineHandler{csvReader: parser}
	for {
		finished, e := r.makeBatchRows(proc, bat)
		if e != nil {
			return e, bat.RowCount(), r
		}
		if finished {
			return nil, bat.RowCount(), r
		}
	}
}

// The file's only record has first value 111; the load inserts 222.
func TestLoomJSONLineHoldoverSilentWrongValue(t *testing.T) {
	err, rows, _ := loomDrain(t, tree.JSONLINE, tree.ARRAY, colLine, "[111,\n[222,\n333]\n]")
	require.NoError(t, err)
	require.Equal(t, 1, rows)
	a := vector.GetFixedAtWithTypeCheck[int32](bat0.Vecs[colA], 0) // bat from loomDrain; see note
	_ = a
}

Test source as actually run (complete file, pkg/sql/colexec/external/loom_test_jsonline_truncation_budget_test.go) is embedded in the repro field of this report; run with:

export CGO_CFLAGS="-I<repo>/cgo -I<repo>/thirdparties/install/include"
export CGO_LDFLAGS="-L<repo>/thirdparties/install/lib -L<repo>/cgo"
go test ./pkg/sql/colexec/external/ -run 'TestLoomJSONLineSilentWrongRowFromAliasedPrevStr|TestLoomJSONLineTruncationHoldOverCorrupted|TestLoomJSONLineValidMultiLineRecordFails' -count=1 -v

Note: TestLoomJSONLineSilentWrongRowFromAliasedPrevStr asserts the EXPECTED value (a=111) and therefore FAILS on current main; that failure is the bug.

Additional information

Full reproduction, exactly as Loom ran it
// File: pkg/sql/colexec/external/loom_test_jsonline_holdover_test.go
// Run (after `make cgo-native-thirdparties-internal` so thirdparties/install exists):
//   export CGO_CFLAGS="-I<repo>/cgo -I<repo>/thirdparties/install/include"
//   export CGO_LDFLAGS="-L<repo>/thirdparties/install/lib -L<repo>/cgo"
//   go test ./pkg/sql/colexec/external/ -run 'TestLoomJSONLineSilentWrongRowFromAliasedPrevStr|TestLoomJSONLineTruncationHoldOverCorrupted|TestLoomJSONLineValidMultiLineRecordFails' -count=1 -v
//
// Reuses committed test helpers from error_mode_test.go: errorModeParam, colA, colS, colLine, numTestCols.
// TestLoomJSONLineSilentWrongRowFromAliasedPrevStr asserts the CORRECT value (111) and FAILS on main = the bug.

package external

import (
	"io"
	"strings"
	"testing"

	"github.com/matrixorigin/matrixone/pkg/container/batch"
	"github.com/matrixorigin/matrixone/pkg/container/vector"
	"github.com/matrixorigin/matrixone/pkg/sql/parsers/tree"
	"github.com/matrixorigin/matrixone/pkg/vm/process"
	"github.com/stretchr/testify/require"
)

func loomDrainJSONLINE(t *testing.T, param *ExternalParam, proc *process.Process, r *CsvReader, bat *batch.Batch, content string) (error, int) {
	t.Helper()
	r.reader = io.NopCloser(strings.NewReader(content))
	parser, perr := newCSVParserFromReader(param.Extern, r.reader)
	require.NoError(t, perr)
	r.plh = &ParseLineHandler{csvReader: parser}
	for {
		finished, e := r.makeBatchRows(proc, bat)
		if e != nil {
			return e, bat.RowCount()
		}
		if finished {
			return nil, bat.RowCount()
		}
	}
}

// A JSONLINE array record whose physical-line concatenation is the complete
// two-value array "[111,[222,333]]" (first value 111) loads as a=222: the
// held-over text aliases the parser's reusable record buffer and line 2
// overwrites it in place.
func TestLoomJSONLineSilentWrongRowFromAliasedPrevStr(t *testing.T) {
	param, proc, bat := errorModeParam(t, tree.JSONLINE, tree.ARRAY, colLine)
	t.Cleanup(func() { bat.Clean(proc.Mp()) })
	r := &CsvReader{param: param}

	err, rows := loomDrainJSONLINE(t, param, proc, r, bat, "[111,\n[222,\n333]\n]")
	t.Logf("err=%v rows=%d", err, rows)
	require.NoError(t, err)
	require.Equal(t, 1, bat.RowCount())
	a := vector.GetFixedAtWithTypeCheck[int32](bat.Vecs[colA], 0)
	s := string(bat.Vecs[colS].GetBytesAt(0))
	t.Logf("row 0: a=%d s=%q", a, s)
	require.Equal(t, int32(111), a, "first value of the record must be 111, not bytes of line 2")
}

// Byte-level proof that prevStr retains an alias into the parser's record
// buffer, which the next read overwrites in place.
func TestLoomJSONLineTruncationHoldOverCorrupted(t *testing.T) {
	param, proc, bat := errorModeParam(t, tree.JSONLINE, tree.ARRAY, colLine)
	t.Cleanup(func() { bat.Clean(proc.Mp()) })
	r := &CsvReader{param: param}
	r.reader = io.NopCloser(strings.NewReader("[12,\n3"))
	parser, perr := newCSVParserFromReader(param.Extern, r.reader)
	require.NoError(t, perr)
	r.plh = &ParseLineHandler{csvReader: parser}

	row, rerr := r.plh.csvReader.Read(nil)
	require.NoError(t, rerr)
	require.Equal(t, "[12,", row[0].Val)
	_, terr := r.transJson2Lines(proc.Ctx, row[0].Val, param.Attrs, param.Cols, tree.ARRAY)
	require.EqualError(t, terr, "unexpected EOF")
	require.Equal(t, "[12,", r.prevStr, "prevStr held over")

	// Reading the next record overwrites the buffer prevStr points into.
	row2, rerr2 := r.plh.csvReader.Read(nil)
	require.NoError(t, rerr2)
	require.Equal(t, "3", row2[0].Val)
	t.Logf("prevStr after next read: %q (want \"[12,\")", r.prevStr)
	require.NotEqual(t, "[12,", r.prevStr, "held-over text was overwritten in place")
}

// Without the aliasing the holdover would complete a multi-line record; with
// the corrupted buffer it fails with an error that quotes nonexistent text.
func TestLoomJSONLineValidMultiLineRecordFails(t *testing.T) {
	param, proc, bat := errorModeParam(t, tree.JSONLINE, tree.ARRAY, colLine)
	t.Cleanup(func() { bat.Clean(proc.Mp()) })
	r := &CsvReader{param: param}

	err, rows := loomDrainJSONLINE(t, param, proc, r, bat, "[1,\n2]")
	t.Logf("err=%v rows=%d", err, rows)
	require.Error(t, err)
	require.Contains(t, err.Error(), "json")
	require.Equal(t, 0, bat.RowCount())
}

Found by Loom bug hunt (module: custom-de41a00730; tests: unit, white-box, end-to-end, concurrency; severity: S0)

Activity

  1. added
    kind/bug
    severity/s0
    on Oct 30, 2026
  2. MatrixAdventurer commented on Oct 30, 2026

    @MatrixAdventurer
    Contributor

    I reproduced the incorrect-value failure and prepared this patch against main at a54850983d9cddaacc97e38a84515ec724c937b7. It also addresses the same buffer-aliasing root cause described in #31280.

    When an object or array is first held over, its CSV field string can point into the parser's reusable record buffer. Clone that initial incomplete string before retaining it. Subsequent continuations already concatenate the owned prefix with the next field, so they can retain that result without another clone.

    Regression tests drive the production CSV/JSONLINE parser and check the final values for arrays and objects, multi-line continuations, a normal subsequent record, and a record spanning the output-batch boundary. Before the fix, the array case silently returned 222 instead of 111, including across a batch boundary; the object case returned a malformed-JSON error. The tests now pass, along with the existing strict incomplete-record-at-EOF control.

    Validation on Linux/amd64 with Go 1.27.1:

    go test -p 3 ./pkg/sql/colexec/external -count=1 -timeout=10m
    go test -race -p 3 ./pkg/sql/colexec/external -run 'TestJSONLine' -count=1 -timeout=5m

    Both passed. gofmt, git diff --check, and git apply --check --whitespace=error passed. The regression uses the real reader with in-memory input; it does not run a MatrixOne server or a SQL-level LOAD DATA.

    The separate unbounded holdover / repeated parsing problem in #31851 is not addressed by this patch.

    Save this complete diff as a .patch file and apply it with git apply:

    diff --git a/pkg/sql/colexec/external/reader_csv.go b/pkg/sql/colexec/external/reader_csv.go
    index 7cbb14a..02d44ad 100644
    --- a/pkg/sql/colexec/external/reader_csv.go
    +++ b/pkg/sql/colexec/external/reader_csv.go
    @@ -317,7 +317,8 @@ func (r *CsvReader) transJsonObject2Lines(ctx context.Context, str string, attrs
     		}
     	}
     	res := make([]csvparser.Field, resultSize)
    -	if r.prevStr != "" {
    +	continued := r.prevStr != ""
    +	if continued {
     		str = r.prevStr + str
     		r.prevStr = ""
     	}
    @@ -325,6 +326,10 @@ func (r *CsvReader) transJsonObject2Lines(ctx context.Context, str string, attrs
     	if err != nil {
     		logutil.Errorf("json unmarshal err:%v", err)
     		if jsonLineTruncated(err, str, '{') {
    +			if !continued {
    +				// The parser's field string aliases its reusable record buffer.
    +				str = strings.Clone(str)
    +			}
     			r.prevStr = str
     			return nil, err
     		}
    @@ -385,13 +390,18 @@ func (r *CsvReader) transJsonArray2Lines(ctx context.Context, str string, attrs
     		err error
     		res = make([]csvparser.Field, 0, len(attrs))
     	)
    -	if r.prevStr != "" {
    +	continued := r.prevStr != ""
    +	if continued {
     		str = r.prevStr + str
     		r.prevStr = ""
     	}
     	jsonNode, err := bytejson.ParseNodeString(str)
     	if err != nil {
     		if jsonLineTruncated(err, str, '[') {
    +			if !continued {
    +				// The parser's field string aliases its reusable record buffer.
    +				str = strings.Clone(str)
    +			}
     			r.prevStr = str
     			return nil, err
     		}
    diff --git a/pkg/sql/colexec/external/jsonline_holdover_ownership_test.go b/pkg/sql/colexec/external/jsonline_holdover_ownership_test.go
    new file mode 100644
    index 0000000..c057720
    --- /dev/null
    +++ b/pkg/sql/colexec/external/jsonline_holdover_ownership_test.go
    @@ -0,0 +1,78 @@
    +// Copyright 2026 Matrix Origin
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +package external
    +
    +import (
    +	"io"
    +	"strings"
    +	"testing"
    +
    +	"github.com/matrixorigin/matrixone/pkg/container/vector"
    +	"github.com/matrixorigin/matrixone/pkg/sql/parsers/tree"
    +	"github.com/stretchr/testify/require"
    +)
    +
    +func TestJSONLineContinuationPreservesInput(t *testing.T) {
    +	for _, tc := range []struct {
    +		name, shape, input, firstString, secondString string
    +		first, second                                 int32
    +	}{
    +		{
    +			name: "array with nested value", shape: tree.ARRAY,
    +			input: "[111,\n[222,\n333]\n]\n[5,6]\n",
    +			first: 111, firstString: "[222 333]", second: 5, secondString: "6",
    +		},
    +		{
    +			name: "object across lines", shape: tree.OBJECT,
    +			input: "{\"a\":111\n,\"s\":\n222}\n{\"a\":5,\"s\":\"ok\"}\n",
    +			first: 111, firstString: "222", second: 5, secondString: "ok",
    +		},
    +	} {
    +		t.Run(tc.name, func(t *testing.T) {
    +			param, proc, bat := errorModeParam(t, tree.JSONLINE, tc.shape, colLine)
    +			require.NoError(t, readAllText(t, param, proc, bat, tc.input))
    +			require.Equal(t, 2, bat.RowCount())
    +			require.Equal(t, tc.first, vector.GetFixedAtWithTypeCheck[int32](bat.Vecs[colA], 0))
    +			require.Equal(t, tc.firstString, string(bat.Vecs[colS].GetBytesAt(0)))
    +			require.Equal(t, tc.second, vector.GetFixedAtWithTypeCheck[int32](bat.Vecs[colA], 1))
    +			require.Equal(t, tc.secondString, string(bat.Vecs[colS].GetBytesAt(1)))
    +		})
    +	}
    +}
    +
    +func TestJSONLineContinuationAcrossBatchBoundary(t *testing.T) {
    +	param, proc, bat := errorModeParam(t, tree.JSONLINE, tree.ARRAY, colLine)
    +	content := strings.Repeat("[1,2]\n", OneBatchMaxRow-1) + "[111,\n[222,\n333]\n]\n"
    +	r := &CsvReader{param: param, reader: io.NopCloser(strings.NewReader(content))}
    +	t.Cleanup(func() { require.NoError(t, r.Close()) })
    +	parser, err := newCSVParserFromReader(param.Extern, r.reader)
    +	require.NoError(t, err)
    +	r.plh = &ParseLineHandler{csvReader: parser}
    +
    +	finished, err := r.makeBatchRows(proc, bat)
    +	require.NoError(t, err)
    +	require.False(t, finished)
    +	require.Equal(t, OneBatchMaxRow-1, bat.RowCount())
    +	require.Equal(t, "[111,", r.prevStr)
    +
    +	bat.CleanOnlyData()
    +	finished, err = r.makeBatchRows(proc, bat)
    +	require.NoError(t, err)
    +	require.True(t, finished)
    +	require.Equal(t, 1, bat.RowCount())
    +	require.Equal(t, int32(111), vector.GetFixedAtWithTypeCheck[int32](bat.Vecs[colA], 0))
    +	require.Equal(t, "[222 333]", string(bat.Vecs[colS].GetBytesAt(0)))
    +	require.Empty(t, r.prevStr)
    +}
  3. XuPeng-SH commented on Oct 31, 2026

    @XuPeng-SH
    Contributor

    已并入 #31280(JSONLINE续行reader正确性与资源边界)。本项的完整复现、版本、证据和独立验收要求已保留在主 issue,后续统一在主项跟踪,唯一负责人为 @iamlinjunhong。

    本次关闭仅为问题整理/合并,不代表缺陷已修复、测试通过或所有来源具有同一根因;各独立验收仍须完成。

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

Metadata

Metadata

Assignees

Labels

kind/bugseverity/s0

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions