Repository navigation
Consolidate attribute and trait resolution in Compiler - #1853
Merged
Merged
Conversation
neilvcarvalho
force-pushed
the
nc/compiler
branch
2 times, most recently
from
October 13, 2026 13:15
219a76c to
a47f9cf
Compare
neilvcarvalho
force-pushed
the
nc/compiler
branch
2 times, most recently
from
October 30, 2026 15:55
0fa5793 to
11b1054
Compare
This was referenced Nov 3, 2026
neilvcarvalho
force-pushed
the
nc/compiler
branch
from
November 27, 2026 14:23
11b1054 to
56f41a7
Compare
neilvcarvalho
force-pushed
the
nc/compiler
branch
2 times, most recently
from
November 27, 2026 17:26
4be0605 to
56d20b1
Compare
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
force-pushed
the
nc/compiler
branch
from
November 27, 2026 17:35
56d20b1 to
15ca85a
Compare
neilvcarvalho
marked this pull request as ready for review
November 27, 2026 18:36
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
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),DeclarationListandAttributeList(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) andInternal.trait_by_name(settingklasson global traits).Compiler(new) does all of it in one place and reads definitions without changing them.Factory#compile_with_traitsis now one line that delegates to it, so the snapshot cache from step 3 is unchanged.Trait#clonego: 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.defined_enumsand the registeredtraits_for_enumduring compilation instead of being expanded into the definition once. The per-factoryautomatically_define_enum_traitsoption from Add per model automatically_define_enum_traits option #1598 stays onDefinitionas 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 thatFactory#compileperformed.AttributeDefinitionError,AssociationDefinitionError,TraitDefinitionError, the associationArgumentErrorhints and the "Referenced within" suffix on traitKeyErrors (with the did_you_mean receiver handling) are raised from the compiler. The messages are byte for byte the ones the acceptance suite pins.factory_bot.compile_factorynotification fires from the compiler for each definition it resolves, wrapping the resolution work as Measure factory compilation in compile_factory span #1850 madeDefinition#compiledo, with the same payload asmain:name,class,attributesas anAttributeListof the definition's own attributes (soassociations,names,transientandnon_transientkeep working for subscribers such asconfig.factory_bot.validatorin factory_bot_rails), andtraitsas 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 inspec/acceptance/activesupport_instrumentation_spec.rbpin the payload. Events fire when a snapshot is computed, so they repeat after a laterdefineormodifyclears the cache; onmainthey repeat on every build that passes traits.Definitionis plain data: declarations, callbacks, constructor,to_create, defined traits, registered enums and base traits, plus theoverridablereplace-on-redeclare rule thatmodifyneeds.Declarationand its subclasses keep only their data and equality.DefinitionProxy#sequenceno longer looks for an existing sequence by URI.Internal.trait_by_nameno 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, asmaindoes, instead of letting theNameErrorescapeFactoryBot.lint(traits: true). A new example inspec/acceptance/lint_spec.rbpins it; found by running Forem against the stack.Deleted
lib/factory_bot/declaration_list.rb, its require and its spec.AttributeListis reduced to the read-only enumerable the notification payload exposes; itsdefine_attribute,apply_attributesand error checks are gone.Trait#clone,Trait#klass, theTraitdelegations,DefinitionProxy#__fetch_or_register_sequence,Factory#compile,Factory#inherit_parent_traits,NullFactory#compile, and everything onDefinitionthat resolved rather than stored:compile,attributes,callbacksaggregation,constructorandto_createaggregation,lookup_traits,inherit_traits, enum expansion,klass, and the error decoration, all of which moved toCompiler.Declaration#to_attributesand thebuildmethods on the three subclasses.The
Declarationclasses 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
mainon 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: onmaina global traittitledthat referencesfancyresolved to the first factory'sfancyfor every factory, and now each factory gets its own.Benchmarks
Baseline is
mainat 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 withbuild. "Retained" is the growth inObjectSpace.memsize_of_allafter the suite and four full GCs. "Allocated" isGC.stat(:total_allocated_objects)per build.Random suite: 2,000 builds, each with 0 to 3 random traits.
main/ this stack)main/ this stack)main/ this stack)Repeat suite: 2,000 examples, each ten builds with the same two traits (
create_liststyle), 20,000 builds in total.main/ this stack)main/ this stack)main/ this stack)Many distinct combinations: 100 traits, 20,000 builds touching 8,038 distinct trait combinations.
mainA factory and trait combination is resolved once and the snapshot is reused, so repeated builds cost the same regardless of the trait count.
mainrecompiles 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 untildefine,modifyorreload, 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:
mainSteps 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
Compilerspec covers bare word resolution (which the deletedImplicitexamples covered), requested trait precedence, and the trait names in scope. TheDefinitionspec covers the overridable rule directly instead of through aDeclarationListdouble, and theFactory,InternalandNullFactoryspecs drop examples for removed methods.