Sub topic 15
Data-flow analysis with the graph engine
This chapter assumes you can already run sf code-analyzer run with a workspace and a rule selector. It also assumes you can read the severity levels in a results table. Basic Apex is enough for the examples.
What the graph engine is
Most Code Analyzer engines look at one file, or one pattern in one file, at a time. PMD matches syntax trees. ESLint checks JavaScript and Lightning Web Component files. Regex matches text. They are fast, but they cannot see a problem that only appears when two methods in different classes are combined.
The graph engine is called sfge (Salesforce Graph Engine). It parses your Apex into a graph and then walks the possible execution paths through it. It follows a method call into the class that defines the method and carries information along the path. This is called data-flow analysis. Because it sees paths, it can report problems that no single file contains.
Typical findings from sfge include:
- A database operation reached from an entry point without a preceding CRUD or field-level security check (rule
ApexFlsViolation). - A path where a variable that might be
nullis dereferenced (ruleApexNullPointerException). - Repeated, expensive schema lookups on one path (rule
AvoidMultipleMassSchemaLookups).
Rule names change between releases. Treat this list as examples and use sf code-analyzer rules --rule-selector sfge to see what your installed version provides.
Why a path-based rule needs a graph
Here is a case that a single-file engine cannot judge. The entry point and the DML live in different classes.
public with sharing class AccountController {
@AuraEnabled
public static void saveAccount(String name) {
Account acc = new Account(Name = name);
AccountService.persist(acc);
}
}public with sharing class AccountService {
public static void persist(Account acc) {
insert acc;
}
}Reading AccountService alone, insert acc; looks fine. The question that matters is whether any path from an entry point reaches it without a permission check. The AccountController.saveAccount method is callable from a Lightning component, and it reaches the insert with no check at all. sfge follows the call and reports a violation.
Running the engine
You select sfge the same way you select any engine: with a rule selector. The selector sfge picks every rule from that engine.
sf code-analyzer run --workspace force-app --rule-selector sfge --view tableTwo practical requirements apply:
- Java. The engine runs on Java. You need a Java runtime (version 11 or later) on your machine or CI runner.
- The whole workspace.
sfgecan only follow a call into code it has parsed. Point--workspaceat the full source folder, not a single class.
Your own scan may look different. Run the command on a project containing the two classes above and look for an ApexFlsViolation row that names AccountController.saveAccount as the starting point and AccountService.persist as the place where the operation happens.
Workspace and target with a graph
For other engines, --target narrows which files are examined. The graph engine behaves differently, because the files you target and the files it must read are not the same set. It builds its graph from the workspace and uses the target to decide which entry points to analyze.
sf code-analyzer run \
--workspace force-app \
--target force-app/main/default/classes/AccountController.cls \
--rule-selector sfge \
--view detailThis is a good way to check one controller quickly. If you shrink the workspace to just the controller, the engine can no longer follow the call into AccountService, so you may lose findings. Keep the workspace broad and narrow only the target.
Reading a graph-engine result
A path finding carries more location detail than a PMD finding. Expect to see two places: where the path starts and where the problematic operation happens. Use --view detail to see the full text of each violation, because the table view truncates long messages.
When you triage a finding, read it in this order:
- Find the entry point. Is it really reachable from outside, for example through
@AuraEnabled,@RestResource, aglobalmethod, or a Visualforce controller? - Follow the path to the flagged operation.
- Decide where the check belongs. Usually the best place is as close to the operation as possible, so every caller benefits.
A fix for the earlier example enforces object permissions in the service:
public with sharing class AccountService {
public static void persist(Account acc) {
if (!Schema.sObjectType.Account.isCreateable()) {
throw new System.NoAccessException();
}
insert acc;
}
}For field-level checks on many fields, Security.stripInaccessible is often cleaner. Whichever approach you choose, the rule recognizes recognized check patterns only. A custom wrapper method that does the check may not be recognized, and the engine will keep reporting the path.
Configuration
Engine settings live under engines.sfge in code-analyzer.yml, next to the rules block you used earlier.
# code-analyzer.yml
engines:
sfge:
java_max_heap_size: "4g"
java_thread_count: 4
disable_limit_reached_violations: falseThe options you are most likely to need are these:
| Setting | What it controls |
|---|---|
| `java_command` | Which Java executable to run, if the default one on your path is not suitable |
| `java_max_heap_size` | Memory given to the Java process, for large codebases |
| `java_thread_count` | How many analysis threads run in parallel |
| `disable_limit_reached_violations` | Whether to suppress the notices described below |
Check the documentation for your installed version, since option names and defaults can change.
Cost and failure modes
The graph engine trades speed for depth. Keep these points in mind when you plan its use.
- It is slow compared with PMD. The engine must parse the whole workspace and explore many paths. On a large org it can take minutes. Do not run it on every save.
- It needs memory. An out-of-memory error from the Java process usually means you should raise
java_max_heap_sizeor reduce the workspace. - It has limits. Some code has so many possible paths that the engine stops exploring. It then reports that a limit was reached for that entry point. That notice means the entry point was not fully analyzed. It does not mean the code is clean. Treat these notices as gaps to review, and do not silence them unless you have decided to accept those gaps.
- It can be wrong. Path analysis is conservative about what it cannot prove. A check done through a pattern the engine does not know looks like a missing check. Review each case and suppress it with a justified comment only when you have confirmed the code is safe.
Where it fits in a pipeline
A common split is to run the fast engines on every pull request and the graph engine less often. Pull requests get PMD, ESLint, and Regex through Recommended. A nightly or pre-release job runs --rule-selector sfge with a high --severity-threshold, so serious path findings fail the build while you still have time to fix them. Reuse the same code-analyzer.yml in both jobs, and the Java requirement then only affects the slower job.
Exercises
Exercise
You scan only AccountService.cls by setting both --workspace and --target to that single file, with --rule-selector sfge. The ApexFlsViolation that appeared in a full scan disappears. Why, and how do you fix the command?
Show answer
The graph engine builds its graph from the workspace. With only AccountService.cls in the workspace, it cannot see AccountController.saveAccount, the entry point that reaches the insert, so no unprotected path exists in its graph. Set --workspace force-app (the whole source folder) and keep --target pointed at the file or files you want to analyze.
Exercise
A scan reports that a limit was reached for one entry point and no other violations for it. A teammate says the entry point is therefore safe. What is wrong with that conclusion, and what are two reasonable responses?
Show answer
The notice means the engine stopped exploring paths before finishing, so the entry point was only partly analyzed and the lack of violations proves nothing. Reasonable responses include refactoring the method into smaller pieces so fewer paths exist, raising resources such as java_max_heap_size if memory was the issue, and reviewing the entry point manually. Disabling the notice with disable_limit_reached_violations hides the gap and should be done only as a deliberate decision.