Skip to content

Consolidate attribute and trait resolution in Compiler - #1853

Merged
neilvcarvalho merged 1 commit into
nc/single-evaluatorfrom
nc/compiler
Nov 27, 2026
Merged

neilvcarvalho merged 1 commit into
nc/single-evaluatorfrom
nc/compiler

Conversation

@neilvcarvalho

@neilvcarvalho neilvcarvalho commented Oct 6, 2026 •

Copy link
Copy Markdown
Member

Fifth step of the sequence of refactors toward a compiled, non-cloning core. Stacked on #1852 (step 4), #1851, #1848 and #1847; merge those first.

What changed

Resolving a definition was spread across Declaration::Implicit#build (which mutated the definition by appending base traits), DeclarationList and AttributeList (duplicate and self-reference errors), Definition#compile (enum expansion into the definition, and registering the factory's traits into every trait it used), Factory#inherit_parent_traits (cloning the parent's traits so trait bodies resolved names per factory) and Internal.trait_by_name (setting klass on global traits).

  • Compiler (new) does all of it in one place and reads definitions without changing them. Factory#compile_with_traits is now one line that delegates to it, so the snapshot cache from step 3 is unchanged.
  • A bare word becomes an association, a global sequence attribute, or a reference to a trait. Trait names are resolved in the scope of the factory being built: its own traits, then the parent chain, then enum traits, then global traits. That is the order the clone-based inheritance produced, and it is what lets Trait#clone go: a parent or global trait that names another trait now resolves it against the factory being built rather than against whichever factory registered its traits into the shared definition first.
  • Enum traits are built from the model's defined_enums and the registered traits_for_enum during compilation instead of being expanded into the definition once. The per-factory automatically_define_enum_traits option from Add per model automatically_define_enum_traits option #1598 stays on Definition as data; the compiler resolves it as the factory's own setting, else the nearest ancestor's, else the global one, which replaces the inheritance step that Factory#compile performed.
  • AttributeDefinitionError, AssociationDefinitionError, TraitDefinitionError, the association ArgumentError hints and the "Referenced within" suffix on trait KeyErrors (with the did_you_mean receiver handling) are raised from the compiler. The messages are byte for byte the ones the acceptance suite pins.
  • The factory_bot.compile_factory notification fires from the compiler for each definition it resolves, wrapping the resolution work as Measure factory compilation in compile_factory span #1850 made Definition#compile do, with the same payload as main: name, class, attributes as an AttributeList of the definition's own attributes (so associations, names, transient and non_transient keep working for subscribers such as config.factory_bot.validator in factory_bot_rails), and traits as the traits in the factory's scope, including inherited and enum traits. The global configuration still reports itself once as :configuration, now from a cached root snapshot (Internal.compiled_configuration). Three new examples in spec/acceptance/activesupport_instrumentation_spec.rb pin the payload. Events fire when a snapshot is computed, so they repeat after a later define or modify clears the cache; on main they repeat on every build that passes traits.
  • Definition is plain data: declarations, callbacks, constructor, to_create, defined traits, registered enums and base traits, plus the overridable replace-on-redeclare rule that modify needs. Declaration and its subclasses keep only their data and equality.
  • Inline sequences are registered once at declaration time; DefinitionProxy#sequence no longer looks for an existing sequence by URI. Internal.trait_by_name no longer takes a class. The linter asks the compiler for the trait names a factory can use, which keeps linting inherited and enum traits of child factories as before. Enum traits need the factory's class, so when the class does not exist the linter falls back to the declared and inherited trait names and reports each one, as main does, instead of letting the NameError escape FactoryBot.lint(traits: true). A new example in spec/acceptance/lint_spec.rb pins it; found by running Forem against the stack.

Deleted

  • lib/factory_bot/declaration_list.rb, its require and its spec. AttributeList is reduced to the read-only enumerable the notification payload exposes; its define_attribute, apply_attributes and error checks are gone.
  • Trait#clone, Trait#klass, the Trait delegations, DefinitionProxy#__fetch_or_register_sequence, Factory#compile, Factory#inherit_parent_traits, NullFactory#compile, and everything on Definition that resolved rather than stored: compile, attributes, callbacks aggregation, constructor and to_create aggregation, lookup_traits, inherit_traits, enum expansion, klass, and the error decoration, all of which moved to Compiler.
  • Declaration#to_attributes and the build methods on the three subclasses.

The Declaration classes stay as records because the association argument hints must be raised at compile time, when the declaration still holds the raw arguments, and the custom spec matchers compare declarations by equality.

Behavior

No existing acceptance spec or feature was edited; three payload examples were added. Beyond the suite, I reran the behavior scripts from steps 2, 3 and 4 on this branch with identical results, and compared this branch with main on a global trait that names a factory trait when two factories define that trait differently, the same through a child factory, shared inline sequences of an inherited trait, the sequence URI of an inherited trait, the error for a missing trait on a child, and linting a child factory's traits. All match except the first two, which are the scoping fix: on main a global trait titled that references fancy resolved to the first factory's fancy for every factory, and now each factory gets its own.

Benchmarks

Baseline is main at 0d06d64, which includes #1857 (the fix for the Set growth that building with traits caused). Each cell is a fresh process on Ruby 4.0.10: a factory with N traits, each setting one attribute on a plain Ruby class, built with build. "Retained" is the growth in ObjectSpace.memsize_of_all after the suite and four full GCs. "Allocated" is GC.stat(:total_allocated_objects) per build.

Random suite: 2,000 builds, each with 0 to 3 random traits.

traits retained (main / this stack) allocated objects per build (main / this stack) time (main / this stack)
10 148 KB / 422 KB 301 / 102 55 / 17 ms
100 180 KB / 897 KB 308 / 210 83 / 35 ms
1000 401 KB / 1.1 MB 323 / 917 368 / 119 ms

Repeat suite: 2,000 examples, each ten builds with the same two traits (create_list style), 20,000 builds in total.

traits retained (main / this stack) allocated objects per build (main / this stack) time (main / this stack)
10 1.8 MB / 1.3 MB 375 / 74 0.65 / 0.13 s
100 1.9 MB / 3.0 MB 379 / 96 1.03 / 0.17 s
1000 2.2 MB / 3.1 MB 381 / 189 4.45 / 0.28 s

Many distinct combinations: 100 traits, 20,000 builds touching 8,038 distinct trait combinations.

main this stack
retained 1.6 MB 7.9 MB
time 0.84 s 0.35 s

A factory and trait combination is resolved once and the snapshot is reused, so repeated builds cost the same regardless of the trait count. main recompiles a clone on every build with traits, so its time per build grows with the trait count. The cost of the stack is the snapshot cache: about 1 KB per distinct factory and trait combination, held until define, modify or reload, which is the 6 MB gap in the last table. Resolving a new combination walks the factory's trait list, which is why allocations per build in the random suite grow with the trait count (most of those builds are a first use); step 4 does less work there than this step.

Where each change lands, same suites, each step measured on its own rebased branch:

main step 1 (#1847) step 2 (#1848) step 3 (#1851) step 4 (#1852) step 5 (this PR)
random, 1000 traits, retained 401 KB 401 KB 402 KB 3.5 MB 986 KB 1.1 MB
random, 1000 traits, time 0.37 s 0.37 s 0.37 s 0.10 s 0.06 s 0.12 s
repeat, 1000 traits, retained 2.2 MB 2.2 MB 2.2 MB 6.7 MB 2.5 MB 3.2 MB
repeat, 1000 traits, time 4.45 s 4.39 s 4.43 s 0.33 s 0.21 s 0.28 s
8,038 combos, retained 1.6 MB 1.6 MB 1.6 MB 23.5 MB 6.4 MB 7.9 MB
8,038 combos, retained classes 2 2 2 17,820 0 0
8,038 combos, time 0.84 s 0.85 s 0.93 s 0.62 s 0.34 s 0.35 s

Steps 1 and 2 match main. Step 3 removes the per-build compile but keeps two anonymous classes per cached combination, and step 4 removes the classes.

Verification

All on Ruby 4.0.10.

  • bundle exec standardrb: no offenses.
  • bundle exec rake all_specs (default Gemfile): 312 unit examples, 457 acceptance examples, 4 Cucumber scenarios, all passing.
  • BUNDLE_GEMFILE=gemfiles/7.0.gemfile bundle exec rake all_specs: same counts, all passing.
  • BUNDLE_GEMFILE=gemfiles/main.gemfile bundle exec rake all_specs: same counts, all passing.

Unit spec changes: a new Compiler spec covers bare word resolution (which the deleted Implicit examples covered), requested trait precedence, and the trait names in scope. The Definition spec covers the overridable rule directly instead of through a DeclarationList double, and the Factory, Internal and NullFactory specs drop examples for removed methods.

Resolving a definition was spread across Declaration::Implicit#build,
which mutated the definition by appending base traits, DeclarationList
and AttributeList, which raised the duplicate and self-reference
errors, Definition#compile, which expanded enum traits into the
definition and registered the factory's traits into every trait it
used, Factory#inherit_parent_traits, which cloned the parent's traits
so that trait bodies resolved names per factory, and
Internal.trait_by_name, which set klass on global traits. The URI
based reuse of inline sequences existed only because cloned traits
re-ran their blocks.

Compiler now does all of it in one place and reads definitions without
changing them. A bare word becomes an association, a global sequence
attribute, or a reference to a trait; trait names are resolved in the
scope of the factory being built, its own traits first, then the
parent chain, then enum traits, then global traits, so a parent or
global trait that names another trait picks up the current factory's
definition of it. Enum traits are built from the model and the
registered enums during compilation. AttributeDefinitionError,
AssociationDefinitionError, TraitDefinitionError, the association
ArgumentError hints and the "Referenced within" suffix on trait
KeyErrors are raised from the compiler. The compile_factory
notification fires from the compiler for each definition it resolves.

Definition becomes plain data: the declarations, callbacks,
constructor, to_create, defined traits, registered enums and base
traits as the block declared them. Declaration and its subclasses keep
only their data and equality. Trait loses clone and its delegations,
inline sequences are registered once at declaration time, and
Internal.trait_by_name no longer takes a class. The linter asks the
compiler for the trait names a factory can use, which keeps linting
inherited and enum traits of child factories.

Deletes declaration_list.rb and attribute_list.rb with their specs,
Factory#compile and NullFactory#compile, and the resolution methods on
Definition and Declaration. Adds a Compiler spec for the bare word
resolution that the Implicit declaration spec covered.

Behavior is unchanged for every acceptance example. The one visible
difference is a global or parent trait that names a trait which two
factories define differently: before, the first factory to use it won
for both; now each factory gets its own definition.
@neilvcarvalho
neilvcarvalho marked this pull request as ready for review November 27, 2026 18:36
@neilvcarvalho
neilvcarvalho merged commit 6310dd3 into main Nov 27, 2026
39 checks passed
@neilvcarvalho
neilvcarvalho deleted the nc/compiler branch November 27, 2026 18:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant