Skip to content

fix(factory): prevent stack overflow for cyclic existing relations - #768

Open
abdusco wants to merge 2 commits into
stephenafamo:mainfrom
abdusco:fix/factory-existing-relation-cycle
Open

abdusco wants to merge 2 commits into
stephenafamo:mainfrom
abdusco:fix/factory-existing-relation-cycle

Conversation

@abdusco

@abdusco abdusco commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Problem

Factories can accept an existing model as a relationship. If that model has its relationships loaded, and those relationships point back to it, factory construction can follow the circular graph indefinitely.

For example, an existing User containing loaded Videos, where each Video points back to that same User, causes a stack overflow when the user is supplied as an existing relationship for a new video.

Factory APIs should safely accept loaded bidirectional model graphs. They should preserve the existing relationship where needed, but stop following a model that has already been encountered during the same construction.

Fix

Track models encountered while converting existing relationship graphs, regardless of which factory API begins the conversion. Once a model has already been visited, stop traversing through its loaded relationships.

Regression Test

Adds a generated, no-database test using the existing users/videos fixture:

user := &models.User{}
video := &models.Video{}
user.R.Videos = models.VideoSlice{video}
video.R.User = user

_ = factory.New().NewVideo(factory.VideoMods.WithExistingUser(user))

The test builds a minimal in-memory relationship cycle and verifies that supplying the existing user relationship completes rather than crashing the test process.

Fixes #761.

@abdusco
abdusco force-pushed the fix/factory-existing-relation-cycle branch from cc1c2b6 to 0eb8740 Compare September 6, 2026 14:18
@abdusco
abdusco force-pushed the fix/factory-existing-relation-cycle branch from 1126047 to 9af65fe Compare September 6, 2026 14:51
@abdusco
abdusco marked this pull request as ready for review September 6, 2026 15:06
@abdusco abdusco changed the title fix(factory): guard cyclic existing relationships fix(factory): prevent stack overflow for cyclic existing relations Sep 6, 2026
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.

Factory: #584's cycle guard is not reached from WithExisting* / AddExisting*, still stack-overflows in v0.50.0

1 participant