Skip to content

to 3.0: fix non sys account cannot find the branch meta table. - #23220

Merged
1 commit merged into
matrixorigin:3.0-devfrom
gouhongshen:fix_nonsys_branch
Dec 5, 2025
Merged

1 commit merged into
matrixorigin:3.0-devfrom
gouhongshen:fix_nonsys_branch

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Dec 5, 2025 •

Copy link
Copy Markdown
Contributor

User description

What type of PR is this?

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

Which issue(s) this PR fixes:

issue ##21979

What this PR does / why we need it:

fix non sys account cannot find the branch meta table.


PR Type

Bug fix


Description

  • Pass BackgroundExec to branch metadata functions for non-sys account access

  • Fix constructBranchDAG to use runSql with system context for metadata queries

  • Add bh parameter to decideLCABranchTSFromBranchDAG function signature

  • Add comprehensive test cases for branch diff with NULL value handling


Diagram Walkthrough

flowchart LR
  A["diffMergeAgency"] -->|pass bh| B["decideLCABranchTSFromBranchDAG"]
  B -->|pass bh| C["constructBranchDAG"]
  C -->|use runSql with sysCtx| D["Query branch metadata"]
  D -->|system account context| E["Access MO_BRANCH_METADATA"]
Loading

File Walkthrough

Relevant files
Bug fix
data_branch.go
Add BackgroundExec parameter for metadata access                 

pkg/frontend/data_branch.go

  • Add bh BackgroundExec parameter to decideLCABranchTSFromBranchDAG
    function
  • Add bh BackgroundExec parameter to constructBranchDAG function
  • Replace sqlexec.RunSql with runSql call using system context for
    metadata queries
  • Pass bh parameter through call chain from diffMergeAgency to
    constructBranchDAG
+7/-4     
Tests
diff_6.sql
Add branch diff NULL value test cases                                       

test/distributed/cases/snapshot/branch/diff/diff_6.sql

  • Create test account acc1 with non-sys credentials
  • Test branch diff operations with NULL value toggling across multiple
    column types
  • Test case 1: Customer lifecycle table with wide column types and NULL
    transitions
  • Test case 2: Instrument positions table with composite primary key and
    NULL handling
+157/-0 
diff_6.result
Add expected results for branch diff tests                             

test/distributed/cases/snapshot/branch/diff/diff_6.result

  • Expected output for branch diff operations on customer lifecycle table
  • Expected output for branch diff operations on instrument positions
    table
  • Verify correct diff results with UPDATE, DELETE, and INSERT operations
  • Validate NULL value handling in diff output across different data
    types
+136/-0 

@qodo-code-review

Copy link
Copy Markdown

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
⚪
Privilege escalation context

Description: Switching the session process context to a system account (AttachAccountId to
System_Account) for running metadata queries broadens privileges and could be abused if
inputs to the query building path are not strictly controlled; verify that only static SQL
against system catalog is executed under elevated context and that the context is always
restored.
data_branch.go [4338-4345]

Referred Code
oldCtx = ses.proc.Ctx
sysCtx = defines.AttachAccountId(ctx, catalog.System_Account)
ses.proc.Ctx = sysCtx
defer func() {
	ses.proc.Ctx = oldCtx
	sqlRet.Close()
}()
Ticket Compliance
🟡
🎫 #21979
🟢 Add support for new data branching syntax so users can create, diff, and manage data
branches.
⚪ Ensure end-to-end behavior of the new syntax meets user expectations across permissions
and non-sys accounts in real deployments
Codebase Duplication Compliance
⚪
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

⚪
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status:
Missing Auditing: The new code performs privileged metadata queries via system context without any added
auditing of who initiated the action or its outcome.

Referred Code
oldCtx = ses.proc.Ctx
sysCtx = defines.AttachAccountId(ctx, catalog.System_Account)
ses.proc.Ctx = sysCtx
defer func() {
	ses.proc.Ctx = oldCtx
	sqlRet.Close()
}()

if sqlRet, err = runSql(
	sysCtx, ses, bh,
	fmt.Sprintf(scanBranchMetadataSql, catalog.MO_CATALOG, catalog.MO_BRANCH_METADATA),
	nil, nil,
); err != nil {
	return

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Error Context: Errors from privileged metadata query (runSql with sys context) are returned without added
contextual information about the operation, which may hinder debugging.

Referred Code
if sqlRet, err = runSql(
	sysCtx, ses, bh,
	fmt.Sprintf(scanBranchMetadataSql, catalog.MO_CATALOG, catalog.MO_BRANCH_METADATA),
	nil, nil,
); err != nil {
	return

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status:
Privilege Escalation: Switching to system account context to run metadata queries may bypass tenant scoping;
ensure authorization is explicitly validated for non-sys accounts.

Referred Code
oldCtx = ses.proc.Ctx
sysCtx = defines.AttachAccountId(ctx, catalog.System_Account)
ses.proc.Ctx = sysCtx
defer func() {
	ses.proc.Ctx = oldCtx
	sqlRet.Close()

Learn more about managing compliance generic rules or creating your own custom rules

Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent panic from nil pointer

Add a nil check for sqlRet before calling sqlRet.Close() in the deferred
function to prevent a panic on error.

pkg/frontend/data_branch.go [4341-4344]

 	defer func() {
 		ses.proc.Ctx = oldCtx
-		sqlRet.Close()
+		if sqlRet != nil {
+			sqlRet.Close()
+		}
 	}()

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a potential nil pointer dereference on sqlRet in an error path within the constructBranchDAG function, which would cause a panic. The proposed fix is correct and improves code robustness.

Medium
High-level
Refactor privilege escalation for safer context handling

To improve safety and isolation, refactor the privilege escalation mechanism.
Instead of mutating the shared session context (ses.proc.Ctx), pass a temporary
system context directly to the metadata query execution layer.

Examples:

pkg/frontend/data_branch.go [4338-4344]
	oldCtx = ses.proc.Ctx
	sysCtx = defines.AttachAccountId(ctx, catalog.System_Account)
	ses.proc.Ctx = sysCtx
	defer func() {
		ses.proc.Ctx = oldCtx
		sqlRet.Close()
	}()

Solution Walkthrough:

Before:

func constructBranchDAG(ctx context.Context, ses *Session, bh BackgroundExec) (*databranchutils.DataBranchDAG, error) {
    var oldCtx context.Context
    var sysCtx context.Context

    // Store original context
    oldCtx = ses.proc.Ctx
    
    // Create system context and overwrite the session's context
    sysCtx = defines.AttachAccountId(ctx, catalog.System_Account)
    ses.proc.Ctx = sysCtx
    defer func() {
        // Restore original context
        ses.proc.Ctx = oldCtx
    }()

    // Run SQL using the modified session, which implicitly uses the mutated context
    sqlRet, err := runSql(sysCtx, ses, bh, "SELECT ... FROM mo_branch_metadata", nil, nil)
    // ...
}

After:

func constructBranchDAG(ctx context.Context, ses *Session, bh BackgroundExec) (*databranchutils.DataBranchDAG, error) {
    // Create a system context for this specific operation
    sysCtx := defines.AttachAccountId(ctx, catalog.System_Account)

    // Pass the system context directly to the execution function.
    // This requires `runSql` or the underlying executor to use the
    // provided context for authorization instead of relying on `ses.proc.Ctx`.
    sqlRet, err := runSql(sysCtx, ses, bh, "SELECT ... FROM mo_branch_metadata", nil, nil)
    // ...
}

// The implementation of `runSql` and its callees should be adjusted
// to create execution options using the passed `sysCtx` for privilege checks,
// rather than relying on the context from `ses.proc`.
func runSql(ctx context.Context, ses *Session, ...) {
    // ...
    opts := executor.Options{}.
        // ...
        WithContext(ctx) // Explicitly use the passed context for the execution
    // ...
}
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a fragile design pattern where the shared session context (ses.proc.Ctx) is mutated for privilege escalation, which is a potential source of subtle bugs and race conditions.

Medium
  • More

@gouhongshen gouhongshen changed the title fix non sys account cannot find the branch meta table. to 3.0: fix non sys account cannot find the branch meta table. Dec 5, 2025
@mergify
mergify Bot requested a review from XuPeng-SH December 5, 2025 08:26
@mergify mergify Bot added the kind/bug Something isn't working label Dec 5, 2025
@ghost
ghost merged commit 3d75f10 into matrixorigin:3.0-dev Dec 5, 2025
This pull request was closed.

This branch was previously deployed

1 inactive deployment
ci — 63776d9b Deployed Dec 5, 2025 by ghost
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 Review effort 3/5 size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants