Skip to content

[Bug]: strict JSONLINE load holds an unbounded truncated record in prevStr, growing past LargestEntryLimit #32055

Closed

Description

@iamlinjunhong

Is there an existing issue for the same bug?

Branch Name

main

Commit ID

8ff3c0d

Other Environment Information

  • Hardware parameters: Apple Silicon (arm64, macOS); Go unit test only, no server needed
  • OS type: darwin/arm64, go1.27.1
  • Others: workspace build of main; test reuses the committed helpers errorModeParam / colLine from pkg/sql/colexec/external/error_mode_test.go

Actual Behavior

A strict-mode JSONLINE scan of a file whose first record opens a string value it never closes is classified as truncated on every following physical line. CsvReader.prevStr (pkg/sql/colexec/external/reader_csv.go) then concatenates each new line onto the whole tail:

  • transJsonObject2Lines (:320-322): str = r.prevStr + str — never measured. When the parse reports unexpected EOF and the text still opens an object (jsonLineTruncated, :267-273), the entire accumulated text is stored back as the new holdover (:327-329). transJsonArray2Lines has the same pattern (:388-390, :394-396).
  • The caller makeBatchRows treats a truncated record as "held over for the next line" and does continue (:213-214) — which skips the batch budget check at :252 (curBatchSize >= param.maxBatchSize), so a run of continuation lines never hands the batch on.
  • Each line alone obeys the CSV parser's per-record cap config.LargestEntryLimit (64 MiB, pkg/config/configuration.go:213, largest-entry-limit), but the assembled holdover record has no cap of any kind, and the whole growing buffer is re-allocated and re-scanned on every new line (O(file^2)).
  • The scan only fails at EOF with invalid input: incomplete json record (:165-171), after the whole remaining file has been absorbed.

Measured on the commit above (default LargestEntryLimit = 67108864, fixture maxBatchSize = 1048576):

  1. White-box: an opening {"a":1,"s":" continued with 2 MiB x-only lines grows prevStr to 67,108,876 bytes — already past the 64 MiB record cap — with no error, and it keeps growing line after line.
  2. End-to-end: a 9,830,562-byte truncated file (150 pad lines) is scanned by ONE makeBatchRows in 0.09s while allocating 746,696,376 bytes (76x the file size) before finally failing with incomplete json record. Nothing loads.

A corrupted or partially uploaded JSONLINE file therefore makes the CN buffer the remainder of the file in one Go-heap string (invisible to mpool accounting and to largest-entry-limit) and burn quadratic parse CPU — the class of load memory-exhaustion the per-record cap exists to prevent.

Expected Behavior

The hold-over record is one row of the load. A single physical line larger than config.LargestEntryLimit is already rejected by the CSV parser precisely so one record cannot exhaust parse memory; the same cap must apply to the assembled record: once the concatenation at reader_csv.go:321 (and :389) would grow past config.LargestEntryLimit, the reader must fail the record immediately with an invalid-input error instead of holding and re-parsing it. The truncated-line continuation must also not bypass the batch byte budget (curBatchSize >= param.maxBatchSize).

Steps to Reproduce

Save the test below as pkg/sql/colexec/external/loom_jsonline_prevstr_growth_test.go and run from the repo root (helpers errorModeParam/colLine/newCSVParserFromReader are committed in the package):

CGO_CFLAGS="-I$(pwd)/cgo -I$(pwd)/thirdparties/install/include" \
go test ./pkg/sql/colexec/external -run TestLoomJSONLineTruncated -count=1 -v

Both TestLoomJSONLineTruncatedPrevStrGrowsUncapped and TestLoomJSONLineTruncatedScanBuffersWholeFile fail on main (kept failing across repeated runs, deterministic).

// 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"
	"runtime"
	"strings"
	"testing"

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

// A JSONLINE object whose string value is never closed is classified as
// "truncated" on every physical line that continues it, so strict-mode
// scanning (reader_csv.go) holds the whole tail over in CsvReader.prevStr and
// re-copies/re-parses it on each following line. The CSV parser caps a single
// record at config.LargestEntryLimit, but this hold-over record is assembled
// outside the parser and has no cap at all: a corrupted or truncated JSONLINE
// file makes the scan buffer the whole remaining file and spend O(file^2)
// work before failing at EOF.

// Expected: a held-over JSONLINE record must obey the load parser's per-record
// cap (config.LargestEntryLimit, `largest-entry-limit` in the CN toml), just
// like any record the CSV parser reads directly.
func TestLoomJSONLineTruncatedPrevStrGrowsUncapped(t *testing.T) {
	param, proc, _ := errorModeParam(t, tree.JSONLINE, tree.OBJECT, colLine)
	require.False(t, param.ErrorMode.Tolerate, "strict scan for declared columns only")
	ctx := proc.Ctx

	r := &CsvReader{param: param}
	first := `{"a":1,"s":"`
	_, err := r.transJsonObject2Lines(ctx, first, param.Attrs, param.Cols)
	require.Error(t, err)
	require.True(t, jsonLineTruncated(err, first, '{'),
		"unterminated string must be classified as truncated, got %v", err)
	require.Equal(t, first, r.prevStr)

	// Continue the record with 2 MiB physical lines, the same way
	// makeBatchRows drives it (transJson2Lines error -> truncated -> continue).
	chunk := strings.Repeat("x", 2<<20)
	for i := 0; len(r.prevStr) <= int(config.LargestEntryLimit); i++ {
		require.Less(t, i, 64, "did not expect the record to grow so long")
		_, err := r.transJsonObject2Lines(ctx, chunk, param.Attrs, param.Cols)
		require.Error(t, err)
	}
	t.Logf("held-over record after %d continuation lines: %d bytes (record cap %d, batch budget %d)",
		int(len(r.prevStr)/(2<<20)), len(r.prevStr), config.LargestEntryLimit, param.maxBatchSize)
	require.LessOrEqual(t, len(r.prevStr), int(config.LargestEntryLimit),
		"the held-over JSONLINE record must be capped by largest-entry-limit like every other record")
}

// Expected: a strict scan of a truncated JSONLINE file must not buffer the
// whole file and re-copy it once per line before failing at EOF.
func TestLoomJSONLineTruncatedScanBuffersWholeFile(t *testing.T) {
	param, proc, bat := errorModeParam(t, tree.JSONLINE, tree.OBJECT, colLine)

	var content strings.Builder
	content.WriteString(`{"a":1,"s":"`)
	pad := strings.Repeat("x", 64<<10) // 64 KiB continuation lines
	const padLines = 150
	for i := 0; i < padLines; i++ {
		content.WriteByte('\n')
		content.WriteString(pad)
	}
	fileSize := content.Len()

	r := &CsvReader{param: param}
	r.reader = io.NopCloser(strings.NewReader(content.String()))
	parser, err := newCSVParserFromReader(param.Extern, r.reader)
	require.NoError(t, err)
	r.plh = &ParseLineHandler{csvReader: parser}

	var before, after runtime.MemStats
	runtime.GC()
	runtime.ReadMemStats(&before)
	_, err = r.makeBatchRows(proc, bat)
	runtime.ReadMemStats(&after)
	require.Error(t, err)
	require.Contains(t, err.Error(), "incomplete json record")

	allocated := after.TotalAlloc - before.TotalAlloc
	t.Logf("%d-byte truncated file (%d pad lines) scanned: %d bytes allocated before failing",
		fileSize, padLines, allocated)
	require.LessOrEqual(t, allocated, uint64(10*fileSize),
		"scanning a truncated record must not copy the held tail once per line")
}

// One short truncated record still fails cleanly at EOF, for contrast.
func TestLoomJSONLineTruncatedRecordEOFStillFails(t *testing.T) {
	param, proc, _ := errorModeParam(t, tree.JSONLINE, tree.OBJECT, colLine)
	r := &CsvReader{param: param}
	_, err := r.transJsonObject2Lines(proc.Ctx, `{"a":1,"s":"x`, param.Attrs, param.Cols)
	require.Error(t, err)
	require.True(t, jsonLineTruncated(err, r.prevStr, '{'))
	require.LessOrEqual(t, len(r.prevStr), int(config.LargestEntryLimit))
}

Additional information

Full reproduction, exactly as Loom ran it
Save as pkg/sql/colexec/external/loom_jsonline_prevstr_growth_test.go (helpers errorModeParam/colLine/newCSVParserFromReader are committed in the package), then run from the repo root:

CGO_CFLAGS="-I$(pwd)/cgo -I$(pwd)/thirdparties/install/include" go test ./pkg/sql/colexec/external -run TestLoomJSONLineTruncated -count=1 -v

Both TestLoomJSONLineTruncatedPrevStrGrowsUncapped and TestLoomJSONLineTruncatedScanBuffersWholeFile fail on main at 8ff3c0d81da; the contrast subtest TestLoomJSONLineTruncatedRecordEOFStillFails passes.

// 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"
	"runtime"
	"strings"
	"testing"

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

func TestLoomJSONLineTruncatedPrevStrGrowsUncapped(t *testing.T) {
	param, proc, _ := errorModeParam(t, tree.JSONLINE, tree.OBJECT, colLine)
	require.False(t, param.ErrorMode.Tolerate, "strict scan for declared columns only")
	ctx := proc.Ctx
	r := &CsvReader{param: param}
	first := `{"a":1,"s":"`
	_, err := r.transJsonObject2Lines(ctx, first, param.Attrs, param.Cols)
	require.Error(t, err)
	require.True(t, jsonLineTruncated(err, first, '{'), "unterminated string must be classified as truncated, got %v", err)
	require.Equal(t, first, r.prevStr)
	chunk := strings.Repeat("x", 2<<20)
	for i := 0; len(r.prevStr) <= int(config.LargestEntryLimit); i++ {
		require.Less(t, i, 64, "did not expect the record to grow so long")
		_, err := r.transJsonObject2Lines(ctx, chunk, param.Attrs, param.Cols)
		require.Error(t, err)
	}
	t.Logf("held-over record after %d continuation lines: %d bytes (record cap %d, batch budget %d)", int(len(r.prevStr)/(2<<20)), len(r.prevStr), config.LargestEntryLimit, param.maxBatchSize)
	require.LessOrEqual(t, len(r.prevStr), int(config.LargestEntryLimit), "the held-over JSONLINE record must be capped by largest-entry-limit like every other record")
}

func TestLoomJSONLineTruncatedScanBuffersWholeFile(t *testing.T) {
	param, proc, bat := errorModeParam(t, tree.JSONLINE, tree.OBJECT, colLine)
	var content strings.Builder
	content.WriteString(`{"a":1,"s":"`)
	pad := strings.Repeat("x", 64<<10)
	const padLines = 150
	for i := 0; i < padLines; i++ {
		content.WriteByte('\n')
		content.WriteString(pad)
	}
	fileSize := content.Len()
	r := &CsvReader{param: param}
	r.reader = io.NopCloser(strings.NewReader(content.String()))
	parser, err := newCSVParserFromReader(param.Extern, r.reader)
	require.NoError(t, err)
	r.plh = &ParseLineHandler{csvReader: parser}
	var before, after runtime.MemStats
	runtime.GC()
	runtime.ReadMemStats(&before)
	_, err = r.makeBatchRows(proc, bat)
	runtime.ReadMemStats(&after)
	require.Error(t, err)
	require.Contains(t, err.Error(), "incomplete json record")
	allocated := after.TotalAlloc - before.TotalAlloc
	t.Logf("%d-byte truncated file (%d pad lines) scanned: %d bytes allocated before failing", fileSize, padLines, allocated)
	require.LessOrEqual(t, allocated, uint64(10*fileSize), "scanning a truncated record must not copy the held tail once per line")
}

func TestLoomJSONLineTruncatedRecordEOFStillFails(t *testing.T) {
	param, proc, _ := errorModeParam(t, tree.JSONLINE, tree.OBJECT, colLine)
	r := &CsvReader{param: param}
	_, err := r.transJsonObject2Lines(proc.Ctx, `{"a":1,"s":"x`, param.Attrs, param.Cols)
	require.Error(t, err)
	require.True(t, jsonLineTruncated(err, r.prevStr, '{'))
	require.LessOrEqual(t, len(r.prevStr), int(config.LargestEntryLimit))
}

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

Activity

  1. self-assigned this
    on Nov 3, 2026
  2. added
    kind/bug
    severity/s1
    on Nov 3, 2026
  3. added
    ai-easy
    on Nov 9, 2026
  4. slyunnn commented on Nov 17, 2026

    @slyunnn

    Regression and extended verification for #32055 (2026-11-17)

    Verification Environment

    MatrixOne origin/main commit e765c5fd44e842167d4271c37af6d25586511e16 — fix: correct temporal numeric coercion for bit consumers (#32642) — freshly built and confirmed via git_version() on Proxy 6001, CN1 16001, CN2 16002. Native 2 CN / 1 TN / 1 Log service / Proxy. MySQL text protocol via PyMySQL; checks were serial.

    What Was Covered

    • OK — Original strict JSONLINE truncated object spanning physical lines: a 68,157,518-byte input exceeded the default 67,108,864-byte record limit through Proxy. The server returned 20301 with the cumulative-record limit error, committed 0 rows and subsequently answered SELECT 1.
    • OK — Truncated object and array inputs returned incomplete-record errors with 0 rows; a valid object file loaded 2 rows. These controls ran separately through Proxy, CN1 and CN2.
    • OK — Existing focused external reader tests covered pending-buffer size and growth, budget/resumption, cancellation, error cleanup and EOF handling on the verified source commit.
    • Not covered — The 65 MiB boundary test was executed through Proxy only; production-scale concurrency, RSS/GC and full SQL throughput were not measured. 4.2-dev and released-server compatibility were not tested.

    Findings

    PR #32366, commit 374ad5847f5ca2c57e355487bb375380bd8b57e3 — Bound JSONLINE continuation and respect batch budget — is included in the verified main commit. The default-size boundary requires a multi-line file slightly above 64 MiB; this focused local boundary test used the minimum relevant scale, with no production-scale performance claim. Existing product reader tests and JSONLINE BVT cover the same contract, so no redundant MOTR case was added.

    MOTR / BVT Coverage

    Existing product tests: pkg/sql/colexec/external/jsonline_pending_test.go and jsonline_qa_test.go; existing SQL regression: test/distributed/cases/load_data/issue_29842_jsonline_strict_eof.sql. This run executed the focused Go tests and direct SQL fixtures; it did not rerun the complete BVT group or a Nightly workflow.

    Final Conclusion

    Fixed on the verified main commit for the reported cumulative JSONLINE record limit and budget handling.

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

Metadata

Metadata

Assignees

Labels

ai-easykind/bugseverity/s1

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions