[sergo] Sergo Report: Regex Duplication & Goroutine Context Analysis - 2026-04-01 #23946
Closed
Replies: 1 comment
-
|
This discussion has been marked as outdated by Sergo - Serena Go Expert. A newer discussion is available at Discussion #24168. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Date: 2026-04-01
Strategy: regex-duplication-and-goroutine-context
Success Score: 9/10
Run ID: §23869084025
Executive Summary
Today's analysis combined a concurrency/goroutine review (extending last run's mutex-safety findings) with a brand-new regex duplication audit. The concurrency review confirmed that signal handling, atomic operations, and spinner goroutines are all correct — a reassuring negative result. The regex audit uncovered a systematic pattern of centralization violations: the
workflowpackage's dedicatedexpression_patterns.gofile was created precisely to be a single source of truth for regex patterns, yetexpression_safety_validation.goignores it entirely with 9 duplicate package-level variables, andtemplate.gorecompilesTemplateIfPatternevery time it's called. In theclipackage, three functions compile static patterns inline, andincludes.goduplicates a pattern already defined in the same package.Three actionable tasks follow: (1) migrate
expression_safety_validation.goandtemplate_injection_validation.goto use the centralized exports, (2) hoist staticregexp.MustCompilecalls to package-level vars in theclipackage, and (3) fixincludes.goto use the existingincludePattern.🛠️ Serena Tools Update
Tools Snapshot
Tool Capabilities Used Today
search_for_pattern— regex pattern search across Go files forregexp.MustCompile,go func(,make(chan,signal.Notify,atomic.,sync.Mapfind_referencing_symbols— verified call frequency ofparseIssueSpecandsanitizeBranchNamefind_symbol— locatedTemplateIfPattern,InlineExpressionPattern,ExpressionPatternDotAllin centralized fileget_symbols_overview— scoped searches to relevant filesread_file— verified full context of findings before categorizing📊 Strategy Selection
Cached Reuse Component (50%)
Previous Strategy Adapted: mutex-safety-and-compile-time-checks (2026-03-31, score: 8/10)
expression_patterns.go's centralized exports are consistently used vs. re-declared. Also extended the goroutine/concurrency scope from mutex to goroutine lifecycle.New Exploration Component (50%)
Novel Approach: Regex Duplication Audit
search_for_patternwithregexp.MustCompile\(pattern, cross-referenced against known centralized exportsexpression_patterns.go) likely has drift — older files that predate centralization still declare their own copiespkg/workflow/(focused onexpression_patterns.goconsumers) andpkg/cli/(inline compilation in helper functions)Combined Strategy Rationale
The cached component validated the concurrency picture (no new issues), freeing focus for the new exploration. The regex duplication angle was chosen because prior runs hadn't examined it, the codebase has an explicit centralization artifact (
expression_patterns.go), and duplication here creates real risk: if a pattern inexpression_patterns.gois refined for security/correctness, the duplicates silently diverge.🔍 Analysis Execution
Codebase Context
pkg/workflow,pkg/cli,pkg/parserexpression_patterns.goconsumers, function-levelregexp.MustCompilecallsFindings Summary
📋 Detailed Findings
High Priority Issues
Finding 1:
expression_safety_validation.gore-declares 9 centralized regex patternspkg/workflow/expression_safety_validation.godeclares 9 package-level regex variables that are exact duplicates of exports inpkg/workflow/expression_patterns.go. Theexpression_patterns.gofile was explicitly created as a "single source of truth" (per its file-level comment), yet this file predates or ignores that centralization.Duplicated pairs (local var → centralized export):
expressionRegex((?s)\$\{\{(.*?)\}\})ExpressionPatternDotAllexpression_safety_validation.go:26needsStepsRegexNeedsStepsPattern:27inputsRegexInputsPattern:28workflowCallInputsRegexWorkflowCallInputsPattern:29awInputsRegexAWInputsPattern:30awImportInputsRegexAWImportInputsPattern:31envRegexEnvPattern:32comparisonExtractionRegexComparisonExtractionPattern:35orExpressionPatternOrPattern:37Risk: If any centralized pattern is updated (e.g., for a new expression syntax or security fix),
expression_safety_validation.gosilently keeps the old version. Two separate regex objects also consume extra memory.Medium Priority Issues
Finding 2:
template_injection_validation.goduplicates 2 centralized patternspkg/workflow/template_injection_validation.godeclares:inlineExpressionRegex(\$\{\{[^}]+\}\}) at line 63 → duplicatesInlineExpressionPatternunsafeContextRegexat line 67 → duplicatesUnsafeContextPatternSame risk as Finding 1 — these files are in the same
workflowpackage and should reference the centralized exports directly.Finding 3:
template.go:24recompilesTemplateIfPatterninside a functionpkg/workflow/template.gofunctionwrapExpressionsInTemplateConditionalscompiles this at runtime:This is byte-for-byte identical to
TemplateIfPatterninexpression_patterns.go:142, which is in the same package. The function usesretwice (once forReplaceAllStringFunc, once inside the closure), so it's called on every invocation. This should simply beTemplateIfPattern.Finding 4:
includes.go:358duplicatesincludePatternfrompackages.gopkg/cli/includes.go:358(insidefetchAndSaveRemoteIncludes) compiles:pkg/cli/packages.go:20already declares a package-level variable with the same name and pattern:Both files are in package
cli. Theincludes.gofunction shadows the package-level variable with a local one, missing the existing optimization and creating a duplication risk. The local variable should simply be removed — the function already has access to the package-levelincludePattern.Low Priority Issues
Finding 5: Static regex compiled inside functions in
clipackageThree
clifunctions compile static, unchanging patterns on every call:pkg/cli/trial_helpers.go:234,240,246(parseIssueSpec) — 3 patternspkg/cli/add_workflow_pr.go:29,33(sanitizeBranchName) — 2 patternspkg/cli/generate_action_metadata_command.go:180,206,238,268— 4 patterns across 3 functionsThese functions are not called in tight loops (call-site analysis via
find_referencing_symbolsconfirmed once-per-command invocation), so the performance impact is minimal. However, hoisting them to package-level follows Go best practice and makes intent clear.Concurrency Audit (Negative Result)
The cached component scanned the following — all patterns were found correct:
signal.Notify): 3 locations incompile_watch.go,signal_aware_poll.go,retry.go— all usedefer signal.Stop()correctlyspinner.gousessync.WaitGroupwith properwg.Add(1)before goroutine launch andwg.Wait()inStop()/StopWithMessage()mcp_inspect_inspector.go:200-215uses adonechannel +time.After(5s)select — correct patternlogs_orchestrator.go:637,841useatomic.AddInt64correctlysync.Mapusage:yaml.go:105,repository_features_validation.go:75-76— appropriate use for concurrent read-heavy workloadsCheckForUpdatesAsync(update_check.go:242): Goroutine does not propagate context intocheckForUpdates, but this is intentional fire-and-forget behavior with a panic recovery guard✅ Improvement Tasks Generated
Task 1: Migrate
expression_safety_validation.goto use centralized regex exportsIssue Type: Code Duplication / Centralization Violation
Problem:
expression_safety_validation.godeclares 9 package-level regex variables that are exact duplicates of exports inexpression_patterns.go. The centralized file's own header comment states it is the "single source of truth" for expression matching logic. Having 9 stale copies creates a maintenance hazard: any future fix or refinement to the centralized patterns silently leaves the safety validation using an older version.Locations:
pkg/workflow/expression_safety_validation.go:26-37— 9 local declarations to removepkg/workflow/template_injection_validation.go:63,67— 2 local declarations to removepkg/workflow/template.go:24— local compilation to replace withTemplateIfPatternImpact:
UnsafeContextPattern) would not take effect intemplate_injection_validation.goRecommendation:
Remove the 11 local declarations and replace all usages with the corresponding centralized exports:
Validation:
regexpimport from files where it's no longer neededEstimated Effort: Small
Task 2: Remove shadowed
includePatterninincludes.goIssue Type: Package-Level Variable Shadowing
Problem:
pkg/cli/includes.go:358declares a local variableincludePatternthat shadows the package-levelincludePatternfrompackages.go:20. Both are in packagecliand compile the identical pattern^@include(\?)?\s+(.+)$. The local variable compiles a new regex object on every call tofetchAndSaveRemoteIncludesinstead of reusing the pre-compiled package-level one.Location:
pkg/cli/includes.go:358— line to removepkg/cli/packages.go:20— the canonical declaration (no change needed)Impact:
packages.gois updated (e.g., to support@importdirective unification),includes.gosilently keeps the old patternRecommendation:
Validation:
fetchAndSaveRemoteIncludesstill compiles (the package-levelincludePatternis in scope)go vet ./pkg/cli/...to confirm no shadowing warningsEstimated Effort: Small (single line deletion)
Task 3: Hoist static
regexp.MustCompilecalls to package-level inclipackageIssue Type: Performance / Go Best Practice
Problem:
Three functions in
pkg/cli/compile static regex patterns on every call. While none are in tight loops (confirmed via reference analysis), Go best practice requires package-level pre-compilation for any reusable pattern. This ensures the pattern is compiled exactly once at startup, the variable name documents intent, and the pattern is testable in isolation.Locations:
pkg/cli/trial_helpers.go:234,240,246—parseIssueSpec: 3 patternspkg/cli/add_workflow_pr.go:29,33—sanitizeBranchName: 2 patternspkg/cli/generate_action_metadata_command.go:180,206,238,268— 4 patterns acrossextractDescription,extractInputs,extractOutputs,extractDependenciesRecommendation:
Validation:
go vet ./pkg/cli/...cleanEstimated Effort: Small
📈 Success Metrics
This Run
Reasoning for Score
expression_patterns.go. Finding 1 (9 duplicated patterns) carries real maintenance risk.📊 Historical Context
Strategy Performance
Cumulative Statistics
🎯 Recommendations
Immediate Actions
expression_safety_validation.go+template.go— Remove 11 regex duplicates and use centralized exports. Zero behavior change, eliminates silent drift risk.includePatterninincludes.go— One line deletion, uses already-present package-level variable.regexp.MustCompileincli— 9 patterns across 3 files; low urgency but consistent with Go idiom.Long-term Improvements
go vetorgolangci-lintcustom rule to flagregexp.MustCompileinside functions (e.g., viabodycloseor a custom analyzer)expression_safety_validation.gopointing toexpression_patterns.goas a migration note until cleaned up🔄 Next Run Preview
Suggested Focus Areas
fmt.Errorfcalls using%wfor wrappable errors? Previous run 1 found%santi-patterns; a systematic audit may find more.context.Contextpropagation completeness: Run 2 found 15context.Background()misuses. Verify if those were addressed and check for new ones in recently-added files.find_referencing_symbolstool, scan for exported functions/types inpkg/that have zero callers outside their own package.Strategy Evolution
References:
Beta Was this translation helpful? Give feedback.
All reactions