Skip to content

fix(sql): correct signed ROUND and close speculative evaluation failures - #29546

Merged
XuPeng-SH merged 5 commits into
matrixorigin:mainfrom
XuPeng-SH:fix/28490-signed-round-boundaries
Oct 1, 2026
Merged

XuPeng-SH merged 5 commits into
matrixorigin:mainfrom
XuPeng-SH:fix/28490-signed-round-boundaries

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

Fixes #28490.

What this PR does / why we need it:

Signed ROUND mishandled negative remainders, and speculative expression evaluation could publish unsafe metadata or surface diagnostics from inactive branches. This change restores signed rounding and keeps failed or unproven metadata conservative, with residual row execution owning SQL results and selected diagnostics.

  • Keep checked signed/integer/Decimal64/128 precision arithmetic in the scalar owners. Preserve typed overflow diagnostics and selection masks.
  • Centralize metadata admission by resolved overload, physical domain and original constant controls. Reuse comparison/list codecs, checked index arithmetic and timezone interval proofs. A current point-valued divisor may bound division while a point-valued column remains FLAT. Arithmetic scale checks apply to decimal operands.
  • Publish only validated endpoints. Errors, panics, warnings, NULL/nonfinite endpoints and uncertified temporal ranges retain the residual expression. Consume current Fold payloads through their producer/adapter and preserve independent filters.
  • Separate runtime row independence from speculative fold eligibility in the existing function-owned walker. Constant CASE retains ordinary index access; CASE with row-dependent or volatile children remains ineligible. Folding and metadata keep their lazy CASE restrictions. Remove the redundant planner volatility walk.
  • Let local constant-input vectors keep one cleanup owner and remove their second copy. Refuse unavailable bounds/nonpoint division before allocating a speculative child. Keep the fresh isolated warning destination and existing result/kernel cleanup owners.

Design and overall review

The prior approved s1+d1+p1+a1 documents are archived in the formal design/review record. The bounded runtime-constness/ownership amendment and final overall review use actual gpt-6.1-sol / xhigh, session 01a0f822-7696-7662-8d51-ebe3e7561938; the accepted amendment and final overall PASS review confirm no unresolved material blocker.

Rebased onto main 32f54981401fd3888702f2dab8702d2e62c6997a as requested. Conflict reconciliation retains the current point-divisor proof and validator-aware publication helper alongside main's lifecycle changes.

Validation

Current candidate 5359b63d19b48d5e730f8c8815ecd0844fa0acec:

  • Full owning/consumer UT: function, planner, colexec, rule, readutil, disttae and compile pass. Focused race: 62 named tests/subtests, three terminal package passes.
  • Configured incremental vet/lint over all eight changed owning packages pass; lint reports 0 issues. Native prerequisites and CPU service build pass.
  • Real SQL validates forced-index versus base-scan NULL/range results, nested and reversed CASE, row dependence, prepared true/false/true rebinding, inactive versus selected overflow, and successful execution after a prepared error on flushed data.
  • Secondary-index BVT: two normal rounds on the same isolated instance, each 240/240 success, 0 failed/ignored/abnormal. Both constant CASE plans retain Index Table Scan and return (3,'below-95'), matching IGNORE INDEX. Teardown is empty and owned processes exit cleanly.
  • Historical scalar/domain evidence is retained where inputs are unchanged: exact legal-domain decimal oracle 15,300 cases; signed ROUND/selection, temporal/CHAR and pruning matrices; two original ROUND BVT rounds. These historical runtime runs used the earlier binary and are distinguished from current candidate evidence.

Performance and limits

Six alternating pairs of the same metadata microbench compare the pre-optimization and candidate binaries on the same machine:

Path Before ns/op After ns/op Before B/allocs After B/allocs
Native comparison 105.20 104.15 24 / 1 24 / 1
Generic ROUND 2448.0 2401.5 1920 / 16 1920 / 16
Constant ABS 1862.0 1486.5 1800 / 12 1312 / 10

The constant path removes 488 bytes and two allocations per invocation in this fixture. Timings are local measurements under shared-machine load. The diagnostic probe's measured 8-byte allocation remains in generic ROUND; the earlier main comparison had 1912 bytes/15 allocations. Numeric widening CAST and Decimal256 metadata retain conservative fallback. Whole-SQL throughput is not inferred from these microbenchmarks.

CI will run on the published revision; it is not awaited as requested.

@qodo-code-review

qodo-code-review Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

Sorry, something went wrong

We weren't able to complete the code review on our side. Please try again manually by commenting /agentic_review on this PR.

Grey Divider

Qodo Logo

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Fix signed ROUND boundaries and speculative evaluation cleanup

🐞 Bug fix 🧪 Tests 🕐 40+ Minutes

Grey Divider

AI Description

• Correct signed ROUND ties, exact multiples, and BIGINT overflow at coarse precisions.
• Release expression resources when speculative evaluation fails, without suppressing row-level
 errors.
• Preserve failing ROUND branches in CASE, IF, and COALESCE until runtime selection.
Diagram

graph TD
  P["SQL planner"] --> S["Speculative folding"] --> H["Expression helpers"] --> K["ROUND kernel"]
  Z["Zonemap evaluation"] --> H
  R["Row evaluation"] --> H
  S -->|"failed branch"| P
  Z -->|"unknown metadata"| R
Loading
High-Level Assessment

Keep the signed fix in the existing ROUND kernel and contain speculative failures at their existing evaluation boundaries. Globally converting kernel panics or disabling folding would obscure row-level error ownership or discard safe folding opportunities.

Files changed (12) +736 / -110

Bug fix (5) +81 / -66
evalExpression.goContain zonemap evaluation failures and free temporary results +54/-59

Contain zonemap evaluation failures and free temporary results

• Scopes generic zonemap evaluation so a panic resets its metadata instead of escaping. Defers function-result and cleanup callbacks, and evaluates constant arguments through the writable-result helper.

pkg/sql/colexec/evalExpression.go

evalExpressionOpt.goFree one-shot expression executors on failed exits +6/-2

Free one-shot expression executors on failed exits

• Defers executor cleanup for errors and panics in readonly and writable evaluation. Successful readonly callers retain the cleanup callback; successful writable results retain their transferred ownership.

pkg/sql/colexec/evalExpressionOpt.go

func_binary.goCorrect negative ROUND ties and precision-boundary overflow +10/-2

Correct negative ROUND ties and precision-boundary overflow

• Compares negative remainders against a negative half-scale so exact multiples and below-half values round correctly. Detects unrepresentable results at precision -19 while returning zero at coarser precisions.

pkg/sql/plan/function/func_binary.go

constant_fold.goReturn speculative kernel panics as folding errors +10/-2

Return speculative kernel panics as folding errors

• Converts recovered evaluation panics into the shared constant evaluator's typed error result. This lets callers defer errors in guarded branches without changing the parent process's warning destination.

pkg/sql/plan/rule/constant_fold.go

utils.goRetain failed IF and COALESCE branches during folding +1/-1

Retain failed IF and COALESCE branches during folding

• Extends CASE's existing failed-child retention behavior to canonical IFF and COALESCE. Other safe children can still fold while selection determines whether a retained error executes.

pkg/sql/plan/utils.go

Tests (7) +655 / -44
evalExpression_test.goTest one-shot ownership and nested zonemap failures +135/-39

Test one-shot ownership and nested zonemap failures

• Covers successful transfers, returned errors, typed panics, and native and on-heap cleanup. Expands constant zonemap tests to nested ROUND expressions, overflow, and subsequent reuse.

pkg/sql/colexec/evalExpression_test.go

evalExpression_zonemap_test.goTest zonemap admission and cleanup across ROUND overflow +33/-0

Test zonemap admission and cleanup across ROUND overflow

• Checks that overflowing metadata evaluation does not panic, admits row evaluation, and frees temporary native allocations across repeated checks.

pkg/sql/colexec/evalExpression_zonemap_test.go

constant_fold_serialized_test.goTest guarded constant folding through both planner paths +77/-0

Test guarded constant folding through both planner paths

• Verifies CASE, IF, and COALESCE retain failing ROUND subtrees while folding safe siblings. Confirms unselected branches succeed, selected branches raise typed overflow, and allocations return to baseline.

pkg/sql/plan/constant_fold_serialized_test.go

func_math_complex_test.goCover signed ROUND values and extreme precisions +82/-5

Cover signed ROUND values and extreme precisions

• Adds exact multiples, negative ties, BIGINT limits, precision -19 and below, dynamic precision, and NULL cases. Updates the prior expectation for negative rounding and checks allocation cleanup.

pkg/sql/plan/function/func_math_complex_test.go

constant_fold_test.goTest constant-evaluator failure and warning isolation +58/-0

Test constant-evaluator failure and warning isolation

• Checks panic conversion, returned errors, successful results, warning-sink preservation, and native and on-heap cleanup.

pkg/sql/plan/rule/constant_fold_test.go

func_math_round.resultRecord signed ROUND and guarded-error SQL results +162/-0

Record signed ROUND and guarded-error SQL results

• Adds expected values and typed overflow messages for signed integer widths, boundary precisions, prepared statements, CTAS, and selected versus unselected branches.

test/distributed/cases/function/func_math_round.result

func_math_round.testExercise signed ROUND across SQL execution paths +108/-0

Exercise signed ROUND across SQL execution paths

• Adds distributed queries for signed rounding, precision boundaries, NULLs, prepared-statement reuse, and guarded CASE, IF, and COALESCE expressions. Includes decimal, approximate, and truncation controls.

test/distributed/cases/function/func_math_round.test

@XuPeng-SH
XuPeng-SH force-pushed the fix/28490-signed-round-boundaries branch from 5dca4bd to 5359b63 Compare October 1, 2026 16:49

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Final overall review: PASS

Revision 5359b63d19b48d5e730f8c8815ecd0844fa0acec; requested rebase onto main 32f54981401fd3888702f2dab8702d2e62c6997a. Actual gpt-6.1-sol / xhigh, design and final review session 01a0f822-7696-7662-8d51-ebe3e7561938. This closes the constant CASE index regression raised in the earlier review.

The correction separates function-owned runtime row independence from speculative folding eligibility, removes the duplicate planner classifier, and preserves a single cleanup owner for constant inputs. No SQL-pattern special cases or new cache/state machine were added. Current UT, race, SQL, BVT, vet/lint and build evidence is distinguished from retained historical scalar/domain evidence. CI is not awaited; no merge performed.

Accepted design amendment — actual gpt-6.1-sol / xhigh

Recommend a bounded amendment to s1+d1+p1+a1: add a function-owned runtime-constness policy that accepts row-independent CASE, preserve the existing folding restrictions, and remove the redundant copy of owned constant-input vectors. Retain a fresh warning child and probe for speculative execution.

This is an implementable design recommendation. I made no edits, ran no experiments, changed no Git state, and spawned no agents.

Observed source and integration. The state record has advanced beyond the original prompt. The repair worktree is now at 22d4fde2c73cf5530c5d9d53d4b3660e8421a304, rebased onto 32f54981401fd3888702f2dab8702d2e62c6997a; no active conflict remains.

Its working-tree production content matches clean 5dca4bdf9753ec323e66d9c002a9750cf1bd6257 in the reviewed expression owners. The remaining tracked differences from that source are the 13 main-side pipeline/FIN files. Two local restorations are still necessary: the point-divisor admission in function/zonemap.go, and the two cleanup-test calls that supply the publication helper’s final validator argument. Those restorations are absent from committed 22d4…; they must survive delivery.

Comparing the historical first-commit hunk, main’s evaluator, and the complete final source gives this integration rule:

Boundary Required integrated behavior
Generic evaluation failure Preserve the PR’s outer speculative recovery: argument, kernel, validator, and cleanup panics reset the result to unknown.
Result and kernel cleanup Preserve main’s shared evaluateZoneMapFunction owner. It owns result cleanup and fnFree; callers own inputs.
Publication Retain the final six-argument helper, including validation before VectorToZM: warnings, any NULL endpoint, nonfinite output, or failed temporal proof refuse publication.
Division Preserve p1: typed candidate admission permits a row-dependent divisor; the evaluator requires its current block’s initialized range to be a point.
Operand provenance Preserve CONST conversion only for eligible original constants. A point-valued column remains FLAT.
Checked arithmetic Preserve the main-side checked index operations and a1’s decimal-only operand-scale restriction.
New main lifecycle changes Preserve pipeline/FIN termination changes. Metadata’s NewNoContextChildProc(0) creates no pipeline edges, so their stronger terminal ownership does not require a new metadata cleanup path.

This combines the owners and proofs involved in the conflict. Selecting either historical side wholesale would lose part of that contract.

E1 root cause and invariant. The confirmed failure is at the runtime predicate. It now delegates to function.IsConstant(expr, true), whose CASE exclusion exists to preserve lazy folding. Consequently, a stable runtime lookup key fails index admission.

The required invariant is:

A runtime lookup expression may determine one scan key when it is independent of input rows and contains no admitted volatile operation. That classification does not authorize speculative evaluation, folding, or metadata publication.

The negation is already demonstrated by E1: both constant CASE forms lose idx_a, while the literal and IF controls retain it and the row-dependent CASE remains excluded. The recorded base passes all five scenarios. No repeated baseline experiment is needed.

Selected E1 implementation. Keep the recursive semantics at the function owner. Extend its existing private walker with a small, explicit purpose distinguishing runtime invariance from fold eligibility. Add function.IsRuntimeConstant(expr) and make isRuntimeConstExpr delegate to it.

The wrappers should have these contracts:

Predicate Parameters/variables Statement-time functions CASE
IsConstant(expr, false) Excluded Excluded Excluded
IsConstant(expr, true) Existing binding promise Existing current-execution allowance Excluded
IsStatementConstant(expr) Excluded until materialized Existing snapshot allowance Excluded
New IsRuntimeConstant(expr) Existing runtime binding promise Existing snapshot allowance Accepted when every child qualifies

For the new runtime purpose:

  • Validate the registered overload through the existing canonical-ID lookup.
  • Reject CannotFold() overloads, aggregates, windows, columns, correlated references, subqueries, and unsupported expression variants.
  • Recursively inspect every CASE condition and value branch. Do not evaluate conditions or infer that a dependency is unreachable.
  • Preserve existing literal, target-type, vector, list, and scalar-Fold classification. Fold provenance does not establish payload availability.
  • Preserve nil-function, nil-list, invalid-overload, and nil-child refusal.
  • Use the same purpose throughout recursion, including nested CASE under casts, arithmetic, serialization, and lists.

Thus CASE … RAND() … remains ineligible even when the volatile branch appears unreachable. A constant CASE containing an overflow-producing branch can qualify structurally, but its execution and diagnostics remain with the lazy executor.

Keep IsConstant and IsStatementConstant behavior unchanged. Update the latter’s comment to describe its conservative role in speculative evaluation and endpoint CONST provenance; it is a sufficient condition, not an exhaustive row-independence test.

isScanInvariantRuntimeConstExpr can delegate directly to the new runtime predicate: its separate volatility traversal becomes redundant. Preserve containsVolatileFunction and its exported wrapper because other callers need a volatility-only query.

Reverse-consumer disposition. Changing the central runtime delegate repairs its complete consumer set without separate CASE exceptions:

Consumers inspected Effect and retained boundary
Ordinary/master index admission, leading-part matching, equality/range rewriting Stable CASE bounds become eligible; existing physical-key, float, decimal, and prefix restrictions remain.
Range direction, bound extraction, nullable residual decisions CASE bounds receive consistent classification on either operand side; SQL NULL residuals remain required.
Composite-key merging and block-filter construction CASE can supply a runtime bound; existing encoding, materialization, and metadata admission still decide whether pruning is available.
Spatial predicate/distance checks Stable geometry or distance bounds qualify through the same predicate; spatial-domain restrictions remain.
Vector-index equality-prefix checks Stable CASE equality can fix a prefix; algorithm and ordering guards remain.
DATETIME/TIMESTAMP binder normalization Column-versus-stable-CASE remains a constant-side comparison; row-dependent comparisons still use the common key type.
Correlated scalar-aggregate point-domain proof and pushdown Stable CASE can establish a point key; complete-key and correlation proofs remain necessary.

I also inspected the direct folding-policy consumers: binder and optimizer folding, exact decimal comparison normalization, IN cast checks, percentile/XML configuration, ASOF tolerance, vector placement/search gates, lock-row selection, and compile-time LIMIT/OFFSET evaluation. Their CASE restrictions predate this regression. Keep those callers on their existing policies; broadening them would introduce additional evaluation or configuration contracts.

IsStatementConstantInput also keeps its separate diagnostic contract: it permits EXECUTE parameters while excluding variables and real-time functions. It is not a substitute for either new runtime invariance or metadata eligibility.

In particular, do not replace the predicates in GetZoneMapEvaluation, generic isConst/isAllConst, or the no-column filter path with the new runtime predicate. This amendment restores index access without activating eager CASE metadata evaluation or relaxing fixed-precision provenance.

E2 root cause and bounded correction. The recorded benchmark establishes generic metadata overhead, not SQL latency: ROUND increased from approximately 2196.5 to 2378 ns/op, with 1912 B/15 allocations becoming 1920 B/16; constant ABS gained 72 B/op. E5 preserves the allocation counts after rebase, but its concurrent-load CPU results do not support a causal comparison.

Source inspection identifies fresh child/probe construction, input-pointer storage, executor/result work, and a redundant constant-vector copy. Aggregate benchmark deltas cannot assign exact bytes to each mechanism.

The concrete optimization is in the generic constant path:

  1. Continue obtaining inputs through GetWritableResultFromNoColumnExpression.
  2. Store each successful result directly in local ivecs[i].
  3. Remove the subsequent Dup.
  4. Retain the existing local deferred cleanup of those owned inputs.
  5. Stop publishing these local inputs into vecs[arg.AuxId].

The writable helper transfers fixed/function results or copies borrowed results when transfer is unavailable. Its returned success already belongs to the caller. The second copy supplies no additional lifetime or mutability requirement.

Keeping constant inputs solely in ivecs also handles repeated argument pointers or AuxIds: replacing a scratch slot cannot invalidate an earlier kernel input. If the existing branch releases an old scratch entry, clear that slot immediately after release. Endpoint inputs continue to belong to vecs, with ivecs borrowing them.

Two additional local deletions of redundant work are justified:

  • In each endpoint-adaptation iteration, compute isConst(arg) once and reuse that boolean for exact string-bound checking and CONST conversion.
  • Inside the existing recovery scope, perform mixed-input f() evaluation and the point-divisor rejection before constructing this function’s warning child/probe and input slice. Refused division or unavailable bounds need no speculative kernel destination.

Keep two-row execution, registered kernels, temporal validation, list decoding, and publication unchanged.

Allocation tradeoff. Retain the fresh NewNoContextChildProc(0) and WarningProbe for each actual speculative execution. The probe retains one presence bit and zero messages; the child borrows Base, context, session, and query attributes. It is not independently freed or cancelled.

A stack declaration does not guarantee elimination of the allocation: the probe’s address enters an interface, and the child reaches dynamically selected callbacks. The existing evidence does not establish a safe zero-allocation replacement.

Temporarily swapping the parent sink would violate immutable warning-destination ownership. Reusing a mutable probe across nested evaluations would change diagnostic boundaries and introduce reset/lifetime obligations. A pool, cache, Process layout change, or alternate constructor solely to eliminate this small object is disproportionate. Accept the remaining isolation cost and remove the proven duplicate work.

Ownership and failure invariants.

Resource/path Owner and terminal behavior
Owned constant input Writable helper retains ownership until successful return; local ivecs then owns it through deferred cleanup.
Endpoint input Existing scratch owner; local kernel-input slice borrows it.
Kernel state and output evaluateZoneMapFunction retains its existing result and fnFree defers.
Publication ZM receives copied bounds only after complete validation. No temporary vector escapes through metadata.
Error, warning, NULL, nonfinite result, invalid temporal proof Reset current result to unknown; residual execution retains diagnostics.
Argument/kernel/validator/cleanup panic Existing cleanup unwinds; outer metadata recovery resets to unknown. Ordinary row execution keeps its existing error behavior.
Subsequent block/execution Recompute current bounds and provenance; use a fresh probe. No exclusion or diagnostic state persists.

The repair adds no wait dependency, goroutine, channel, retry, or retained component. Numeric generic execution remains two rows; local inputs are bounded by expression arity. Removing the duplicate lowers live input storage rather than adding another owner.

Focused validation map. Extend existing fixtures; preserve archived evidence for unchanged contracts.

Risk/contract Focused fixture and acceptance
E1 classifier, R2 Extend TestZoneMapStatementConstantPolicy with runtime/folding expectations for nested CASE, parameters, scalar/list Fold, columns, invalid IDs, and nested volatility.
E1 public planner consumer, R2 Integrate the retained five-case probe into apply_indices_test.go, reusing addIndexHintChoiceTableForTest and its BIGINT column adjustment. Both constant CASE forms must select idx_a; row-dependent CASE must remain excluded. Include reversed equality and a nested CASE wrapper.
Laziness and diagnostics, R2 Extend TestConstantFoldDefersGuardedKernelFailure using constant CASE selectors. Planning must retain the selector; inactive overflow returns the safe value, selected overflow retains typed OutOfRange, and memory returns to baseline.
Reverse contracts, R2 Reuse composite-range, temporal-comparison, spatial, vector-prefix, force-index volatility, and issue_28158 point-domain fixtures. Add small CASE controls where they exercise a distinct boundary; use bound IDs for new function expressions.
E2 input ownership, R2 Extend TestGetExprZoneMapConstantFold: literal/nested success, later-argument failure after an earlier allocation, repeated argument/AuxId, and success after failure. Check native and on-heap baselines before process teardown.
Warning/publication isolation, R2 Extend TestEvaluateFilterByZoneMapConstantDiagnostics with warning → clean → warning reuse and a seeded parent count. Parent sink identity/count must remain unchanged; warning results remain unknown.
Partial construction and panic cleanup, R2 Reuse TestOneShotExpressionOwnership, TestEvaluateZoneMapFunctionCleanup, and scalar-overflow cleanup fixtures. Preserve the distinction between helper-level panic propagation and outer metadata recovery.
p1/a1 integration, R2 Preserve varying-denominator, point-division, decimal-precision, and arithmetic-scale controls, including point/nonpoint/point scratch reuse.
Public SQL access, R2 Extend existing secondary_index_range.sql before t11’s UPDATE, reusing k_bigint, idx_bigint, and six rows. For both constant CASE forms selecting 95, a noncovering SELECT id,payload … FORCE INDEX(idx_bigint) must retain index access and return (3,'below-95'), matching IGNORE INDEX.
Hot-path cost, R3 performance After implementation, run the existing benchmark on the new candidate only. Preserve pruning and zero residue; expect lower constant-ABS allocation from copy removal. ROUND/native allocation must not increase. Report retained probe cost and CPU comparison limits explicitly.

The existing ROUND BVT already covers constant dead/selected CASE, IF, COALESCE, and prepared rebinding. Reuse that coverage rather than adding another service fixture.

After implementation, run focused new/changed cases, then the affected owning packages once through the existing CGo workflow. Static checks cover the changed closure. Focused race validation should cover the changed ownership cases; the archived 189 race records remain evidence for unchanged paths, not proof of the new cleanup arrangement. Pipeline/FIN topology evidence belongs to the main-side changes and does not require rerunning the metadata experiments.

Compatibility and acceptance. This amendment changes planner admission and temporary metadata work. SQL values, lazy branch diagnostics, function IDs, overload identities, Fold/ZM encoding, protobuf, catalog, and on-disk formats retain their existing contracts. Metadata remains disposable and conservatively refuses unsupported cases.

Accept the repair when:

  • The final integration retains p1 and the validator-aware publication helper, including both local restorations.
  • The recorded CASE index regression is closed through the real planner and existing SQL fixture.
  • Nested volatility and row dependence remain excluded.
  • Folding and metadata retain their CASE restrictions and selected-diagnostic ownership.
  • Constant inputs have one cleanup owner, including partial failure and repeated-AuxId cases.
  • Warning isolation, unknown-on-failure publication, and scratch reuse remain valid.
  • New-candidate evidence demonstrates the bounded copy removal without claiming that the remaining probe allocation—or SQL latency overhead—has been eliminated.

The design is complete; implementation and repair-specific validation remain outstanding.

Final overall review — actual gpt-6.1-sol / xhigh

PASS — no unresolved material blocker. Final overall reviewer: gpt-6.1-sol / xhigh.

Reviewed clean commit 5359b63d19b48d5e730f8c8815ecd0844fa0acec, based on 32f54981401fd3888702f2dab8702d2e62c6997a.

The committed repair delta exactly matches final-delta.patch, SHA-256:
77258873f4b54d9f712ad71bc154a0f38752170d7311b421bfd4b39134d66828.

All 31 candidate source fingerprints match the recorded source/evidence manifest. I examined all 13 delta files and reconciled them with the prior complete change map and accepted design.

Closure Acceptance reconciliation
Runtime classification The function owner distinguishes scan independence from folding eligibility. Constant and nested CASE regain index access without evaluating branches during classification. Row dependence, volatility, invalid function identities, aggregates and windows remain rejected. Parameter binding promises retain their existing contract.
Folding and diagnostics Folding and metadata admission retain their conservative CASE policy. Dead diagnostic branches remain lazy; selected failures remain observable. Runtime classification does not authorize eager metadata evaluation.
Vector ownership Writable constant inputs have independent local owners and immediate deferred cleanup. Removing Dup is valid under the writable-result transfer contract. Partial construction, later argument failure, unavailable Fold and panic paths release prior inputs. Endpoint vectors retain their existing scratch owner.
Rebase integration Division admission and the current point-divisor guard restore the accepted paired-endpoint proof. Test validator arguments restore compatibility. These changes preserve the prior semantic domain.
Prior PR contracts Checked scalar arithmetic, typed admission, Fold payload availability, exact bytes, NULL/nonfinite handling, temporal proofs, native pruning and storage residual contracts remain reconciled. Unchanged evidence is reused by fingerprint. No new cache, pool, persistent state, execution parallelism or algorithm dispatch was introduced.

The required evidence is complete: seven owning packages passed, the final planner rerun passed, scoped race validation recorded 62 tests with three terminal package passes, public indexed/prepared CASE checks passed—including selected errors and persisted data—and both BVT rounds completed 240/240, with no skips. Vet and configured incremental lint passed. The runtime binary hash matches its recorded artifact; owned services exited successfully and their PIDs are absent.

The tests use existing fixtures and preserve independent plan, result, diagnostic and memory oracles. No material duplication or overengineering remains. Resource ownership closes on success and failure; the delta introduces no wait or generation protocol requiring additional liveness testing.

The performance tradeoff matches acceptance: constant ABS removes 488 bytes and two allocations per evaluation, with roughly 20% lower local median time. ROUND retains its allocation count and the accepted fresh warning probe. Those measurements support metadata-kernel claims only.

The complete final gate is satisfied. Public CI at 5dca remains historical; current approval rests on candidate validation and qualifying unchanged evidence. This review performed no mutations, tests, agent spawning or CI waiting.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep review / senior QA: PASS — no unresolved material blocker at 5359b63d19b48d5e730f8c8815ecd0844fa0acec.

No agent was spawned. I reconciled the unchanged 31 source fingerprints and prior complete change map with current comments and this additional consumer challenge. The existing actual gpt-6.1-sol/xhigh design and overall review remain valid for this unchanged commit; this is an additional current-agent QA review, not a newly claimed model run.

Design and ownership. Scalar/types own checked ROUND/CEIL/FLOOR arithmetic and typed diagnostics. The function owner admits metadata by resolved identity, physical domain and original controls; index codecs/arithmetic and temporal interval helpers own the proof. Generic evaluation owns publication, and residual execution owns SQL results and selected diagnostics. Runtime row independence is separate from speculative fold eligibility in the shared walker. Constant CASE regains index access without eager branch evaluation. The duplicate planner classifier and second constant-input copy are removed. No parallel validator, cache, persisted state, state machine or algorithm execution path was introduced.

Unhappy paths and useful optimization. Reviewed partial argument construction, later evaluation failure, panic, warning, NULL/nonfinite endpoints, unavailable Fold payloads, repeated input identity and scratch reuse. Constant inputs each have one local cleanup owner; endpoint scratch, result and kernel cleanup retain their existing owners. Borrowed child Process has zero pipeline edges; no new wait/generation protocol is added. Conservative metadata fallback keeps residual evaluation and independent safe filters. Both positive pruning and fail-open refusal are covered.

Additional executed QA. A review-only Go overlay reuses the regular-index catalogue and actual parser/BuildPlan: 8 cases, 16 paired literal/CASE plans. Lower ranges, reversed lower ranges, BETWEEN, composite equality-prefix plus range, composite unique lookup, and dead overflow branches in range/composite predicates preserve the expected index. An initial assertion that every reversed upper bound must select an index failed on the literal control. The clean old baseline 113d374b2e also produces the same literal/CASE fallback; the relevant planner owners are unchanged from that baseline to the frozen main base. That expectation was corrected using the baseline oracle, without product changes or weakening committed tests.

Comments. The only concrete inline finding was constant CASE losing its index. Commit 5359b63d19, its committed normal/reversed tests, public prepared SQL and the new range/composite matrix close it. The resolution reply cites the correction and evidence. Qodo's failed review notice contains no actionable finding and supplies no approval evidence.

Implementation, tests and documents assessed separately. The full PR changes 31 files: production +1019/-381, tests/results +2307/-55, tracked documentation 0. The production admission/publication code has an explicit correctness or ownership purpose. New tests cover separate value, plan, diagnostic, provenance, boundary and memory contracts; they reuse existing fixtures, small batches and the existing BVT table rather than add topology/data/sleeps. Historical approved design amendments are archived in the prior formal reviews; no duplicate design framework was added to source. Review-only probes remain outside tracked source.

Performance acceptance and limits. The constant metadata fixture removes 488 bytes and two allocations, with about 20% lower local median CPU time. The native fixture retains 24 bytes/one allocation. Generic ROUND retains the diagnostic probe and its measured 8-byte/one-allocation increment over old main; current before/after optimization timings do not establish zero overhead against main. Numeric widening CAST and Decimal256 metadata still use conservative fallback, which can reduce pruning for those SQL shapes. This tradeoff protects correctness; no claim of unchanged whole-SQL throughput is made.

Evidence and integration scope. Retained candidate evidence: seven owning UT packages, 62 scoped race tests/subtests, public indexed/prepared/error-recovery SQL, two secondary-index BVT rounds each 240/240, vet/lint (0 issues), native and service build. Historical scalar/domain evidence is reused only where its semantic inputs remain unchanged. Current main c2cad8af38 adds #29558 exact-integer/nullable-unique behavior; its overlapping hunks are outside this PR's edits and introduce no new caller of the removed classifier. No integration execution on that newer main is claimed and no new rebase/merge was performed. The CI snapshot has ongoing jobs and no terminal failure; skipped/pending jobs are not passes, and CI was not awaited.

@XuPeng-SH
XuPeng-SH merged commit a09f3a3 into matrixorigin:main Oct 1, 2026
2 of 5 checks passed
@XuPeng-SH
XuPeng-SH deleted the fix/28490-signed-round-boundaries branch October 1, 2026 18:11

This branch was previously deployed

1 inactive deployment
ci — d2b632e8 Deployed Oct 1, 2026 by XuPeng-SH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working kind/enhancement kind/refactor Code refactor kind/test-ci size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: ROUND misrounds negative signed integers at negative precision

2 participants