-
Notifications
You must be signed in to change notification settings - Fork 8
fix: optimize queries with leading unbounded expansion BED-8779 #116
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
urangel
wants to merge
3
commits into
main
Choose a base branch
from
BED-8779
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+480
−29
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,167 @@ | ||
| package optimize | ||
|
|
||
| import ( | ||
| "github.com/specterops/dawgs/cypher/models/cypher" | ||
| "github.com/specterops/dawgs/graph" | ||
| ) | ||
|
|
||
| // InboundTraversalReversalRule reverses a qualifying multi-step traversal pattern so that the | ||
| // search is driven from the more selective terminal endpoint inward, rather than expanding | ||
| // outward from an unconstrained source through a leading unbounded variable-length expansion. | ||
| // | ||
| // A pattern such as: | ||
| // | ||
| // MATCH p = (s:User)-[:MemberOf*0..]->(:Group)-[:AdminTo]->(d:Computer) | ||
| // WHERE s.samaccountname =~ '(?i).*[ge]$' AND d.operatingsystem CONTAINS "WINDOWS SERVER" | ||
| // RETURN p | ||
| // | ||
| // is rewritten to drive from d:Computer inbound toward s:User by reversing the pattern element | ||
| // order and each relationship direction. The reversed pattern is flagged via | ||
| // PatternPart.PathDirectionReversed so path materialization can restore the original | ||
| // left-to-right order for RETURN p. | ||
| type InboundTraversalReversalRule struct{} | ||
|
|
||
| func (s InboundTraversalReversalRule) Name() string { | ||
| return "InboundTraversalReversal" | ||
| } | ||
|
|
||
| func (s InboundTraversalReversalRule) Apply(plan *Plan) (bool, error) { | ||
| if plan == nil || plan.Query == nil || plan.Query.SingleQuery == nil || plan.Query.SingleQuery.SinglePartQuery == nil { | ||
| return false, nil | ||
| } | ||
|
|
||
| return reverseInboundTraversalSinglePartQuery(plan.Query.SingleQuery.SinglePartQuery), nil | ||
| } | ||
|
|
||
| func reverseInboundTraversalSinglePartQuery(query *cypher.SinglePartQuery) bool { | ||
| var ( | ||
| applied bool | ||
| declaredSymbols = map[string]struct{}{} | ||
| ) | ||
|
|
||
| for _, readingClause := range query.ReadingClauses { | ||
| if readingClause == nil || readingClause.Match == nil { | ||
| continue | ||
| } | ||
|
|
||
| match := readingClause.Match | ||
| if !match.Optional { | ||
| searchSymbols := whereSearchPredicateSymbols(match) | ||
|
|
||
| for _, patternPart := range match.Pattern { | ||
| if reverseInboundTraversalPatternPart(patternPart, declaredSymbols, searchSymbols) { | ||
| applied = true | ||
| } | ||
| } | ||
| } | ||
|
|
||
| declareMatchSymbols(declaredSymbols, match) | ||
| } | ||
|
|
||
| return applied | ||
| } | ||
|
|
||
| // reverseInboundTraversalPatternPart reverses a single pattern part if it qualifies. A pattern | ||
| // qualifies when it is a non-shortest-path traversal with more than one step, a leading | ||
| // unbounded variable-length expansion with a concrete direction whose source endpoint is neither | ||
| // externally bound nor more selective than the constrained terminal endpoint. | ||
| func reverseInboundTraversalPatternPart(patternPart *cypher.PatternPart, declaredSymbols, searchSymbols map[string]struct{}) bool { | ||
| if !inboundTraversalReversalCandidate(patternPart, declaredSymbols, searchSymbols) { | ||
| return false | ||
| } | ||
|
|
||
| reversePatternElements(patternPart) | ||
| patternPart.PathDirectionReversed = !patternPart.PathDirectionReversed | ||
| return true | ||
| } | ||
|
|
||
| func inboundTraversalReversalCandidate(patternPart *cypher.PatternPart, declaredSymbols, searchSymbols map[string]struct{}) bool { | ||
| if patternPart == nil || | ||
| patternPart.ShortestPathPattern || | ||
| patternPart.AllShortestPathsPattern { | ||
| return false | ||
| } | ||
|
|
||
| steps := traversalStepsForPattern(patternPart) | ||
| if len(steps) < 2 { | ||
| return false | ||
| } | ||
|
|
||
| leadingStep := steps[0] | ||
| if leadingStep.Relationship == nil || | ||
| leadingStep.Relationship.Range == nil || | ||
| leadingStep.Relationship.Range.EndIndex != nil || | ||
| leadingStep.Relationship.Direction == graph.DirectionBoth || | ||
| leadingStep.Relationship.Variable != nil { | ||
| return false | ||
| } | ||
|
|
||
| var ( | ||
| sourceNode = steps[0].LeftNode | ||
| terminalNode = steps[len(steps)-1].RightNode | ||
| sourceSymbol = variableSymbol(sourceNode.Variable) | ||
| terminalSym = variableSymbol(terminalNode.Variable) | ||
| ) | ||
|
|
||
| // The source endpoint must not be bound by a prior clause; reversing would break the | ||
| // established drive order for an externally provided source. | ||
| if sourceSymbol != "" { | ||
| if _, bound := declaredSymbols[sourceSymbol]; bound { | ||
| return false | ||
| } | ||
| } | ||
|
|
||
| // The terminal endpoint must carry a search constraint to make anchoring there worthwhile. | ||
| if !endpointHasSearchConstraint(terminalNode, terminalSym, searchSymbols) { | ||
| return false | ||
| } | ||
|
|
||
| var ( | ||
| sourceSelectivity = endpointSelectivity(sourceNode, sourceSymbol, searchSymbols) | ||
| terminalSelectivity = endpointSelectivity(terminalNode, terminalSym, searchSymbols) | ||
| ) | ||
|
|
||
| // Only reverse when the terminal endpoint is at least as selective as the source. This keeps | ||
| // the drive anchored at the endpoint expected to prune the recursive expansion earliest. | ||
| return terminalSelectivity >= sourceSelectivity | ||
| } | ||
|
|
||
| func endpointSelectivity(nodePattern *cypher.NodePattern, symbol string, searchSymbols map[string]struct{}) boundSourceSelectivity { | ||
| selectivity := nodePatternSelectivity(nodePattern, false) | ||
| if _, constrained := searchSymbols[symbol]; constrained && symbol != "" { | ||
| mergeSelectivityValue(&selectivity, boundSourceSelectivityPredicate) | ||
| } | ||
|
|
||
| return selectivity | ||
| } | ||
|
|
||
| // whereSearchPredicateSymbols collects the set of symbols referenced by a search-operator | ||
| // predicate (equality, regex, comparison, STARTS/ENDS WITH, CONTAINS, IN) within a match's WHERE | ||
| // clause. These indicate a filter that can anchor a traversal at the referenced endpoint. | ||
| func whereSearchPredicateSymbols(match *cypher.Match) map[string]struct{} { | ||
| symbols := map[string]struct{}{} | ||
|
|
||
| if match == nil || match.Where == nil { | ||
| return symbols | ||
| } | ||
|
|
||
| for _, expression := range match.Where.Expressions { | ||
| addShortestPathSearchPredicateSymbols(symbols, expression) | ||
| } | ||
|
|
||
| return symbols | ||
| } | ||
|
|
||
| func reversePatternElements(patternPart *cypher.PatternPart) { | ||
| elements := patternPart.PatternElements | ||
|
|
||
| for left, right := 0, len(elements)-1; left < right; left, right = left+1, right-1 { | ||
| elements[left], elements[right] = elements[right], elements[left] | ||
| } | ||
|
|
||
| for _, element := range elements { | ||
| if relationshipPattern, ok := element.AsRelationshipPattern(); ok { | ||
| relationshipPattern.Direction = relationshipPattern.Direction.Reverse() | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
Repository: SpecterOps/DAWGS
Length of output: 50372
🏁 Script executed:
Repository: SpecterOps/DAWGS
Length of output: 50372
🏁 Script executed:
Repository: SpecterOps/DAWGS
Length of output: 41979
🏁 Script executed:
Repository: SpecterOps/DAWGS
Length of output: 45186
🏁 Script executed:
Repository: SpecterOps/DAWGS
Length of output: 6531
Process qualifying traversals in
MultiPartQuery.InboundTraversalReversalRule.Applyreturns whenMultiPartQueryis present, so it skips qualifying traversals afterWITH. Process each eligible segment and preserve bindings carried throughWITH. Add a regression test for this case.🤖 Prompt for AI Agents