Skip to content

perf(sources,util): optimize row serialization and avoid speculative json parsing - #3660

Open
Deeven-Seru wants to merge 2 commits into
googleapis:mainfrom
Deeven-Seru:perf/optimize-row-serialization
Open

Deeven-Seru wants to merge 2 commits into
googleapis:mainfrom
Deeven-Seru:perf/optimize-row-serialization

Conversation

@Deeven-Seru

Copy link
Copy Markdown
Contributor

Description

Optimizes the core performance bottlenecks in the MCP toolbox during row serialization.

  1. Eliminates speculative JSON parsing in SQLite by introducing a fast-path heuristic filter (util.IsProbablyJSON), reducing OOM risks and CPU overhead on large text datasets.
  2. Refactors orderedmap.Row.MarshalJSON to stream output linearly into a single buffered json.Encoder, resulting in a ~2.5x speedup during row serialization.

PR Checklist

  • Make sure to open an issue as a bug/issue before writing your code!
  • Ensure the tests and linter pass
  • Code coverage does not decrease (if any source code was changed)
  • Appropriate docs were updated (if necessary)
  • Make sure to add ! if this involves a breaking change

Issue Reference

Fixes #3659 🦕

@Deeven-Seru
Deeven-Seru requested a review from a team as a code owner July 20, 2026 04:59
@Deeven-Seru
Deeven-Seru force-pushed the perf/optimize-row-serialization branch from d03f541 to 6ab36d0 Compare July 20, 2026 05:02

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request refactors the codebase by replacing the legacy toolset and promptset concepts with a unified group structure, introducing a new internal/group package and updating configuration parsing, resource management, and CLI commands accordingly. It also includes performance optimizations for SQLite JSON detection and ordered map JSON marshaling. Feedback suggests splitting the large-scale refactoring and performance optimizations into separate pull requests to reduce risk, and correcting several test failure messages that still refer to 'toolsets' instead of 'groups' for consistency.

I am having trouble creating individual review comments. Click here to see my feedback.

cmd/internal/config.go (39-41)

medium

This pull request mixes a large-scale refactoring (renaming toolset to group) with performance optimizations. According to our best practices, refactoring should be kept in separate PRs from functional changes to make reviews easier and reduce risk. Please consider splitting such changes into separate PRs in the future.

cmd/internal/config_test.go (868)

medium

The test failure message refers to "toolsets" but the code is checking configFile.Groups. This could be confusing if the test fails. Please update the message to refer to "groups" for consistency.

This issue also appears on lines 1119, 1461, and 2208. Please correct them as well.

				t.Fatalf("incorrect groups parse: diff %v", diff)

@Deeven-Seru

Copy link
Copy Markdown
Contributor Author

/gemini review

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request introduces performance optimizations for JSON handling, including a fast-path check IsProbablyJSON to avoid unnecessary json.Unmarshal calls on non-JSON strings in SQLite source processing, and refactoring orderedmap.MarshalJSON to use json.NewEncoder with byte-level buffer writes. The reviewer pointed out that the current implementation of IsProbablyJSON is too permissive because it triggers on common starting letters like 't', 'f', and 'n', which can degrade performance on normal text datasets, and provided a more robust implementation to check matching brackets, quotes, and strict boolean/null/number patterns.

Comment thread internal/util/util.go Resolved
@Deeven-Seru
Deeven-Seru force-pushed the perf/optimize-row-serialization branch from 6ab36d0 to bcf2fe6 Compare July 20, 2026 05:07
Comment thread internal/util/util.go Resolved
@Yuan325 Yuan325 added the priority: p1 Important issue which blocks shipping the next release. Will be fixed prior to next release. label Jul 21, 2026
Comment thread internal/sources/sqlite/sqlite.go Resolved
@Deeven-Seru
Deeven-Seru force-pushed the perf/optimize-row-serialization branch from bcf2fe6 to 71e9895 Compare July 22, 2026 07:44
@Deeven-Seru

Copy link
Copy Markdown
Contributor Author

Hi @Yuan325, thanks for the review!

  1. Unit Tests: I have just pushed comprehensive unit tests for IsProbablyJSON to the PR.

  2. json.Valid(): I did test json.Valid(), but unfortunately it defeats the purpose of this specific optimization.
    json.Valid() runs in O(N) time because it scans every single byte of the entire string to ensure full JSON correctness. If a normal text column contains a 10,000-character article, json.Valid() will still scan the entire 10,000 characters just to return false at the end. That is almost as CPU-intensive as json.Unmarshal().
    IsProbablyJSON is designed to run in O(1) time. It strictly checks the boundaries (first and last characters) to verify if the string even has a chance of being a JSON object ({}), array ([]), string (""), or matches exact primitive values. It immediately rejects 99.9% of normal text strings in under a nanosecond without ever scanning the middle of the string!

anubhav756 added a commit that referenced this pull request Nov 16, 2026
## Description

Fixes #4430. SQLite JSON results containing 64-bit IDs are rounded on
the server: `json_object('id', 9007199254740993)` reaches the tool
response as `9007199254740992`.

Keep valid JSON as `json.RawMessage` instead of decoding numbers through
`any`/`float64`. Both SQLite tools share this path; ordinary text
retains its existing fallback. Related #3660 optimizes JSON detection
and row serialization; it does not preserve numeric precision.

The real SQLite unit and public HTTP regression both fail on `06ea49d`
with the rounded ID and pass after the fix. SQLite source/tool unit
packages, all four `TestSQLiteExecuteSqlTool` cases, source-package vet,
scoped golangci-lint 2.15.0 and goimports formatting pass. Go 1.27.3;
module files unchanged.

## PR Checklist

- [x] Reviewed CONTRIBUTING.md.
- [x] Opened #4430 before implementing the fix; a local diagnostic case
first verified the report.
- [x] Reviewed the entire diff, including an independent agent review.
- [x] Relevant tests and linter pass.
- [ ] Code coverage does not decrease (numeric coverage comparison not
run locally).
- [x] Documentation assessed: this corrects existing JSON result
behavior; no configuration or documentation change is needed.
- [x] Breaking-change assessment completed; no API signature changes.

<details><summary>Validation scope</summary>

```sh
go test -mod=readonly -p=2 ./internal/sources/sqlite -count=1
go test -mod=readonly -p=2 ./internal/tools/sqlite/... -count=1
go test -mod=readonly -p=2 ./tests/sqlite \
  -run '^TestSQLiteExecuteSqlTool$' -count=1 -v -timeout=10m
go vet -mod=readonly -p=2 ./internal/sources/sqlite
golangci-lint run --timeout 10m ./internal/sources/sqlite/... \
  ./internal/tools/sqlite/... ./tests/sqlite/...
```

The existing HTTP fixture was temporarily pointed at a free local port
because 5000 was occupied; the port changes were restored. The
regression exercises the real temporary database and tool endpoint. No
external database or model service was used. The full repository
integration matrix and coverage comparison were not run.

</details>

Co-authored-by: Anubhav Dhawan <[email protected]>

This branch has not been deployed

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

Labels

priority: p1 Important issue which blocks shipping the next release. Will be fixed prior to next release.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Performance: Optimize Row Serialization and Avoid Speculative JSON Parsing

3 participants