Internal architecture
Rule Graph Construction
Overview
Build logic in Pants is declared using collections of @rules with recursively memoized and invalidated results. This framework (known as Pants's "Engine") has similar goals to Bazel's Skyframe and the Salsa framework: users define logic using a particular API, and the framework manages tracking the dependencies between nodes in a runtime graph.
In order to maximize the amount of work that can be reused at runtime, Pants statically computes the memoization keys for the nodes of the runtime graph from the user specified @rules during startup: this process is known as "rule graph construction". See the Goals section for more information on the strategy and reasoning for this.
Concepts used in compilers, including live variable analysis and monomorphization, can also be useful in rule graph construction to minimize rule identities and pre-decide which versions of their dependencies they will use.
Concepts
A successfully constructed RuleGraph contains a graph where nodes have one of three types, Rules, Querys, and Params, which map fairly closely to what a Pants @rule author consumes. The edges between nodes represent dependencies: Querys are always roots of the graph, Params are always leaves, and Rules represent the end user logic making up all of the internal nodes of the graph.
Rules
A Rule is a function or coroutine with all of its inputs declared as part of its type signature. The end user type signature is made up of:
- the return type of the 
Rule - the positional arguments to the 
Rule - a set of 
Calls which declare the runtime requirements of a coroutine, of the formrule_name(output_type, (*input_types)) 
In the RuleGraph, these are encoded in a Rule trait, with a DependencyKey trait representing both the positional arguments (which have no provided Param) and the Calls (which provide their input types as Params).
Queries
The roots/entrypoints of a RuleGraph are Querys, which should correspond one-to-one to external callsites that use the engine to request that values are computed. A Query has an output type, and a series of input types: Query(output_type, (*input_types)).
If a user makes a request to the engine that does not have a corresponding Query declared, the engine fails rather than attempting to dynamically determine which Rules to use to answer the Query: how a RuleGraph is constructed should show why that is the case.
Params
Params are typed, comparable (eq/hash) values that represent both the inputs to Rules, and the building block of the runtime memoization key for a Rule. The set of Params (unique by type) that are consumed to create a Rule's inputs (plus the Rule's own identity) make up the memoization key for a runtime instance of the Rule.
Params are eventually used as positional args to Rules, but it's important to note that the Params in a Rule instance's identity/memoization-key will not always become the positional arguments to that Rule: in many cases, a Param will be used by a Rule's transitive dependencies in order to produce an output value that becomes either a positional argument to the Rule as it starts, or the result of a Call while a coroutine Rule runs.
The Params that are available to a Rule are made available by the Rule's dependents (its "callers"), but Params need not be passed explicitly at each use site. A Rule will be used to compute the output value for a DependencyKey: i.e., a positional argument, Call result, or Query result. Of these usage sites, only Query specifies the complete set of Params that will be available: the other two usages (positional arguments and Calls) are able to use any Param that will be "in scope" at the use site.
Params flow down the graph from Querys and the provided Params of Calls: their presence does not need to be re-declared at each intermediate callsite. When a Rule consumes a Param as a positional argument, that Param will no longer be available to that Rule's dependencies (but it might still be present in other subgraphs adjacent to that Rule).
Goals
The goal of RuleGraph construction is to determine the minimum set of Param inputs needed to satisfy the Rules below those Querys.
As explained above, usage sites need not explicitly declare all Params that their dependencies might consume.  The rule graph is used to "fill in the blanks" and figure out how to provide implicit inputs by (transitively) computing them from Params via Rules.
Because the identity of a Rule is computed from its transitive input Params rather than from its positional arguments, Rules can accept arbitrarily-many large input values (which don't need to implement hash) with no impact on its memoization hit rate.
Constraints
There are a few constraints that decide which Rules are able to provide dependencies for one another:
param_consumption- When aRuledirectly uses aParamas a positional argument, thatParamis removed from scope for any of thatRule's dependencies.- For example, for a 
Ruleywith a positional argumentAand aCall(B, C): if there is aParamAin scope atyand it is used to satisfy the positional argument, it cannot also be used to (transitively) to satisfy theCall(B, C)(i.e., a hypothetical rule that consumes bothAandCwould not be eligible in that position). - On the other hand, for a 
RulewwithCall(B, C)andCall(D, E), if there is aParamAin scope atw, two dependencyRules that consumeA(transitively) can be used to satisfy thoseCalls. Only consuming aParamas a positional argument removes it from scope. 
- For example, for a 
 provided_params- When deciding whether oneRulecan use anotherRuleto provide the output type of aCall, a constraint is applied that the candidate dependency must (transitively) consume theParamthat is provided by theCall.- For example: if a 
Rulezhas aCall(A, B), onlyRules that compute anAand (transitively) consume aBare eligible to be used. This also means that aParamAwhich is already in scope forRulezis not eligible to be used, because it would trivially not consumeB. 
- For example: if a 
 
Implementation
As of 3a188a1e06, we construct a RuleGraph using a combination of data flow analysis and some homegrown (and likely problematic: see the "Issue Overview") node splitting on the call graph of Rules.
The construction algorithm is broken up into phases:
- initial_polymorphic - Builds a polymorphic graph while computing an "out-set" for each node in the graph by accounting for which 
Params are available at each use site. During this phase, nodes may have multiple dependency edges perDependencyKey, which is what makes them "polymorphic". Each of the possible ways to compute a dependency will likely have different inputParamrequirements, and each node in this phase represents all of those possibilities. - live_param_labeled - Run live variable analysis on the polymorphic graph to compute the initial "in-set" of 
Paramsused by each node in the graph. Because nodes in the polymorphic graph have references to all possible sources of a particular dependency type, the computed set is conservative (i.e., overly large).- For example: if a 
Rulexhas exactly oneDependencyKey, but there are two potential dependencies to provide thatDependencyKeywith inputParams{A,B}and{B,C}(respectively), then at this phase the inputParams forxmust be the union of all possibilities:{A,B,C}. - If we were to stop 
RuleGraphconstruction at this phase, it would be necessary to do a form of dynamic dispatch at runtime to decide which source of a dependency to use based on theParams that were currently in scope. And the sets ofParams used in the memoization key for eachRulewould still be overly large, causing excess invalidation. 
 - For example: if a 
 - monomorphize - "Monomorphize" the polymorphic graph by using the out-set of available 
Params (initialized duringinitial_polymorphic) and the in-set of consumedParams (computed duringlive_param_labeled) to partition nodes (and their dependents) for each valid combination of their dependencies. Combinations of dependencies that would be invalid (see the Constraints section) are not generated, which causes some pruning of the graph to happen during this phase.- Continuing the example from above: the goal of monomorphize is to create one copy of 
Rulexper legal combination of itsDependencyKey. Assuming that both ofx's dependencies remain legal (i.e. that all of{A,B,C}are still in scope in the dependents ofx, etc), then two copies ofxwill be created: one that uses the first dependency and has an in-set of{A,B}, and another that uses the second dependency and has an in-set of{B,C}. 
 - Continuing the example from above: the goal of monomorphize is to create one copy of 
 - prune_edges - Once the monomorphic graph has converged, each node in the graph will ideally have exactly one source of each 
DependencyKey(except forQuerys, which are not monomorphized). This phase validates that, and chooses the smallest inputParamset to use for eachQuery. In cases where a node has more than one dependency perDependencyKey, it is because given a particular set of inputParamsthere was more than one valid way to compute a dependency. This can happen either because there were too manyParams in scope, or because there were multipleRules with the sameParamrequirements.- This phase is the only phase that renders errors: all of the other phases mark nodes and edges "deleted" for particular reasons, and this phase consumes that record. A node that has been deleted indicates that that node is unsatisfiable for some reason, while an edge that has been deleted indicates that the source node was not able to consume the target node for some reason.
 - If a node has too many sources of a 
DependencyKey, this phase will recurse to attempt to locate the node in theRulegraph where the ambiguity was introduced. Likewise, if a node has no source of aDependencyKey, this phase will recurse on deleted nodes (which are preserved by the other phases) to attempt to locate the bottom-mostRulethat was missing aDependencyKey. 
 - finalize - After 
prune_edgesthe graph is known to be valid, and this phase generates the final staticRuleGraphfor allRules reachable fromQuerys.