Skip to content

fix(core): let a lazy module load again after its first load() failed - #18183

Closed
maxymlyskov wants to merge 1 commit into
nestjs:masterfrom
maxymlyskov:fix/load-lazy-module-again-after-failure
Closed

maxymlyskov wants to merge 1 commit into
nestjs:masterfrom
maxymlyskov:fix/load-lazy-module-again-after-failure

Conversation

@maxymlyskov

Copy link
Copy Markdown
Contributor

PR Checklist

Please check if your PR fulfills the following requirements:

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Other... Please describe:

What is the current behavior?

When a provider factory in a lazy module rejects, LazyModuleLoader.load() rethrows but leaves the half-built modules in the container. createInstancesOfDependencies has already built the module class next to its providers, so Module#isInstantiated is true. The failed provider has no static instance, which reads as { instance: null, isResolved: true }, so the providers resolved next to it get null injected.

public async load(
loaderFn: () =>
Promise<Type<unknown> | DynamicModule> | Type<unknown> | DynamicModule,
loadOpts?: LazyModuleLoaderLoadOptions,
): Promise<ModuleRef> {
const originalLogger = (this.instanceLoader as any).logger;
try {
this.registerLoggerConfiguration(loadOpts);
const moduleClassOrDynamicDefinition = await loaderFn();
const moduleInstances = await this.dependenciesScanner.scanForModules({
moduleDefinition: moduleClassOrDynamicDefinition,
overrides: this.moduleOverrides,
lazy: true,
});
if (moduleInstances.length === 0) {
// The module has been loaded already. In this case, we must
// retrieve a module reference from the existing container.
const { token } = await this.moduleCompiler.compile(
moduleClassOrDynamicDefinition,
);
const moduleInstance = this.modulesContainer.get(token)!;
return moduleInstance && this.getTargetModuleRef(moduleInstance);
}
const lazyModulesContainer =
this.createLazyModulesContainer(moduleInstances);
await this.dependenciesScanner.scanModulesForDependencies(
lazyModulesContainer,
);
await this.instanceLoader.createInstancesOfDependencies(
lazyModulesContainer,
);
const [targetModule] = moduleInstances;
return this.getTargetModuleRef(targetModule);
} finally {
if (loadOpts?.logger === false) {
this.instanceLoader.setLogger(originalLogger);
}
}
}

On the next load(), scanForModules hits lazy && !moduleInserted && moduleInstance?.isInstantiated and returns [], so load() takes the "loaded already" branch and hands back the same broken ModuleRef. The factory is never called again.

{};
if (lazy && !moduleInserted && moduleInstance?.isInstantiated) {
return [];
}

A @Global module is worse. It also stays in globalModules, and lazy modules get globals bound through bindGlobalsToImports, so a module loaded later imports the dead copy. The failed modules also stay in dynamicModulesMetadata (for a DynamicModule definition) and in DiscoverableMetaHostCollection.

Reproduced on master with a real express app over HTTP (NestFactory + fetch). A route lazy loads a module whose "DB" is an async factory that throws on its first call. Same line on 3/3 runs:

PROBE failed first load: req1 -> 500 {"statusCode":500,"message":"Internal server error"} | req2 (db back) -> 500 {"statusCode":500,"message":"Internal server error"} | req3 -> 500 {"statusCode":500,"message":"Internal server error"} | DB factory calls=1

Issue Number: N/A

Steps to reproduce

  1. take the specs from this PR, revert the source files to master, and run the 3 new tests:
    npx vitest run packages/core/test/injector/lazy-module-loader/lazy-module-loader.spec.ts packages/core/test/injector/container.spec.ts -t "on the next load|discoverable entries"
  2. Expected: the next load() builds the module again and the provider gets 'connection'
  3. Actual (raw output, new specs on master's sources, trimmed):
 FAIL  packages/core/test/injector/container.spec.ts > NestContainer > removeModules > should remove the modules with their global, dynamic and discoverable entries
TypeError: container.removeModules is not a function

 FAIL  packages/core/test/injector/lazy-module-loader/lazy-module-loader.spec.ts > LazyModuleLoader > load > when the first load() fails > should build the module again on the next load()
AssertionError: expected null to be 'connection' // Object.is equality

 FAIL  packages/core/test/injector/lazy-module-loader/lazy-module-loader.spec.ts > LazyModuleLoader > load > when the first load() fails > should build a global module again on the next load()
AssertionError: expected null to be 'connection' // Object.is equality

 Test Files  2 failed (2)
      Tests  3 failed | 39 skipped (42)

What is the new behavior?

load() now runs scanModulesForDependencies and createInstancesOfDependencies in a try/catch. On a failure the catch removes the modules this call scanned and rethrows the original error, so the next load() scans and builds them from scratch. The logger restore in finally from #17631 is unchanged.

The removal is one container method, NestContainer.removeModules() next to clear(). The loader reaches it through a small DependenciesScanner.removeModules() forwarder, since it already talks to the container through the scanner. Per module it deletes the ModulesContainer entry, the globalModules and dynamicModulesMetadata entries, and the module's provider and controller wrappers in DiscoverableMetaHostCollection (new removeInstanceWrappers(), matched by wrapper id the way insertByMetaKey does).

What gets rebuilt and what doesn't:

  • providers built during the failed attempt (siblings of the one that threw) are built again on the next load()
  • modules built before the call, such as eager modules the lazy one imports, are left alone with their singletons. scanForModules returns [] for a module that's already instantiated, so they never end up in the batch
  • a load() that succeeds behaves as before

Same probe on this branch, 3/3:

PROBE failed first load: req1 -> 500 {"statusCode":500,"message":"Internal server error"} | req2 (db back) -> 200 report | req3 -> 200 report | DB factory calls=2

Does this PR introduce a breaking change?

  • Yes
  • No

The public API only gains NestContainer.removeModules, DependenciesScanner.removeModules and DiscoverableMetaHostCollection.removeInstanceWrappers.

Other information

Earlier fixes on the same loader: #17631 (logger restore in load()'s finally), #17430 (share eager singletons with lazy modules), #17464 (scan imports pre-registered by addDynamicMetadata) and #17667 (discovery of factory providers). This keeps #17631's finally as it is and puts the rollback in a catch beside it, and the eager singletons from #17430 aren't touched.

Validation on Node 22, Linux:

  • the 3 new tests fail on master's sources (above) and pass here, 42/42 across both specs. discovery specs 49/49
  • full unit suite: 4737 passed / 1 failed here, 4734 passed / 1 failed on master. The one failure is the colour assertion in packages/common/test/services/logger.service.spec.ts under NO_COLOR=1, same on both
  • integration suites lazy-modules, discovery, injector, inspector, scopes, repl, testing-module-override, module-utils and hello-world: 491 passed, 1 skipped
  • added lines are prettier 3.9.10 and oxlint clean. prettier also wants to reformat a few existing lines in container.ts and lazy-module-loader.spec.ts, I left those as master has them

When a provider of a lazily loaded module throws while load() builds it
(a database that is briefly down, say), load() rejects but the module
stays registered with its module class already instantiated. The next
load() finds it through scanForModules and returns the same ModuleRef:
the failed provider reads as null, the providers built next to it hold
null, and it stays that way until the process restarts.

On a failure while scanning or instantiating, remove the modules of this
load() from the container again, with their global module, dynamic
metadata and discovery entries, so the next load() builds them like a
first load. Like the logger restore of nestjs#17631, the cleanup stays inside
load().
@micalevisk
micalevisk self-requested a review October 17, 2026 22:41

@micalevisk micalevisk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the detailed write-up, it made this easy to verify.

I checked out 9b2f747 locally and traced the paths it touches. The diagnosis matches the code. Injector#loadInstance drops the failed static host in its catch, so the wrapper falls back to the { instance: null, isResolved: true } default. The module class wrapper is already built, so isInstantiated short-circuits every later load(). removeModules() undoes what setModule() / addDynamicMetadata() / addGlobalModule() register, plus the discovery entries.

What I ran:

  • npm run build, then npx vitest run packages/core: 1629 passed.
  • The 3 new specs fail on master's sources with the output from the description, and pass here.
  • npm run lint:ci: clean apart from one pre-existing warning in websockets. The prettier diffs in container.ts and lazy-module-loader.spec.ts are on master too.
  • Integration suites lazy-modules, discovery, injector, scopes and inspector: 204 passed.
  • An express app over HTTP against the built packages: req1=500 req2=200 req3=200, factory called twice.
  • Two concurrent failing load()s of a @Global lazy module, then a retry: globalModules is back to its original size and a later lazy module gets the working export.
  • A retry started from the first rejection while a second load() of the same module is still pending: it builds once and later loads return the same ref.

Blocking: the rollback evicts a module that a concurrent, successful load() is still using. Details and a failing spec are inline.

Non-blocking / follow-up:

  • Providers that were built during a failed attempt are dropped, and every retry builds new ones. Lazy modules never get shutdown hooks anyway, because getModulesToTriggerHooksOn() caches the module list at init(). So a sibling that opens a socket, such as a Redis client next to a failing DB provider, leaks one instance per failed retry. On master it leaks only once. A sentence about this in the docs would help.
  • The lazy-loading docs page says modules are "cached on the first LazyModuleLoader#load method invocation". It's worth a follow-up in nestjs/docs.nestjs.com stating that a load() that rejects is not cached and the next call builds the module again.

);
} catch (err) {
// Half-built modules would otherwise be returned by every later load().
this.dependenciesScanner.removeModules(lazyModulesContainer.values());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking. This removes every module in the batch, including a not-yet-instantiated module that a concurrent load() also picked up and is still building. After that load() succeeds, the module is gone from the container. The next load() of it, or of any new lazy module that imports it, builds a second set of singletons. Its providers also disappear from DiscoveryService.

Scenario: AModule and BModule both import a lazy SharedModule. They are loaded concurrently, A fails on its own provider, and B succeeds.

master this PR
SharedModule in the container after A fails yes no
later load(() => SharedModule) cached builds SharedService again

This spec passes on master (3/3) and fails here (3/3) with expected 3 to be 2:

it('should not evict a module that a concurrent load() still uses', async () => {
  const delay = (ms: number) => new Promise(r => setTimeout(r, ms));
  let sharedInstances = 0;

  @Injectable()
  class SharedService {
    constructor() {
      sharedInstances++;
    }
  }

  @Module({ providers: [SharedService], exports: [SharedService] })
  class SharedModule {}

  @Module({
    imports: [SharedModule],
    providers: [
      {
        provide: 'FAIL',
        useFactory: () =>
          delay(10).then(() => Promise.reject(new Error('A failed'))),
      },
    ],
  })
  class AModule {}

  @Module({
    imports: [SharedModule],
    providers: [{ provide: 'SLOW', useFactory: () => delay(30) }],
  })
  class BModule {}

  const [a, b] = await Promise.allSettled([
    lazyModuleLoader.load(() => AModule),
    lazyModuleLoader.load(() => BModule),
  ]);
  expect(a.status).toBe('rejected');
  expect(b.status).toBe('fulfilled');
  const instancesBefore = sharedInstances;

  await lazyModuleLoader.load(() => SharedModule);

  expect(sharedInstances).toBe(instancesBefore);
});

The naive fixes have a catch. I tried keeping modules that another in-flight load() still has in its batch, and keeping modules that a module outside the batch imports. Both make this spec pass, but both break a case this PR currently handles correctly:

  • load(() => X) fails while load(() => Z), where Z imports X, is still in flight.
  • A retry of X starts from the first rejection.

With the PR as it is, that retry gets a working X. With either variant, it gets the cached broken X, which stays broken after Z fails. Please add a spec for that race too, so whatever approach you take keeps it green.

DiscoverableMetaHostCollection.metaHostLinks.delete(DiscoverableProvider);
});

it('should remove the modules with their global, dynamic and discoverable entries', async () => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: removeInstanceWrappers() also walks controllersByMetaKey, but this spec only registers a discoverable provider. Adding a discoverable controller through container.addController() and asserting that getControllersByMetaKey() is empty would cover that branch.

@kamilmysliwiec

Copy link
Copy Markdown
Member

Thanks for working on this! Adding to @micalevisk's review, here are two more cases where the rollback removes a module that another load() still uses:

  1. Concurrent loads of the same module. p1 = load(X) and p2 = load(X) run while X's factory fails once. p1 fulfils and p2 rejects. p2's rollback then removes X from the container, so get('F') on the ModuleRef that p1 returned throws ("could not find F"), and the next load(X) builds a third instance. On master, p1's ref keeps working and later loads return it.
  2. Removal by token. removeModules() deletes by moduleRef.token without checking that the stored module is the one being rolled back. Suppose load(Z) and load(Y) both import X and both fail, Y later than Z, and a retry of load(X) starts after Z's rejection and succeeds. Y's late rollback then deletes the X that the retry just built.

The second one needs an identity check before each delete, e.g. if (this.modules.get(moduleRef.token) !== moduleRef) continue;, and the same for dynamicModulesMetadata. The first one, like the shared-module case micalevisk raised, needs the loader to know which modules other in-flight loads still hold, so a failed batch only removes modules that nothing else is using.

Two smaller points:

  • scanForModules() runs outside the new try, so a failure while scanning (e.g. an undefined import in a @Global() lazy module) still leaves the module registered.
  • Specs for both cases above, and for micalevisk's retry race, would help.

@thekhegay

Copy link
Copy Markdown
Contributor

Some numbers from master for case 1 in @kamilmysliwiec's comment (3a44abf, same harness as lazy-module-loader.spec.ts)

Master alredy builds X twice when two load(() => X) run at once: second call gets inserted Module without class instance yet, so scanner.ts:118 lets it through and providers run again. p2's build calls factory first:

  • first factory call fails: p2 gets error, p1 gets working F, later loads return it - case 1 holds
  • second factory call fails: p1 gets error, p2 fulfils but get('F') === null on its ref and on every later load() - same stuck state this PR fixes

Also load() that comes in mid-factory resolves right away with provider still null, isInstantiated only checks module class

So maybe start from one build per module - map of in-flight loads by token, concurrent load(X) share one promise and rollback runs once:

private readonly loadsInFlight = new Map<string, Promise<ModuleRef>>();

async load(loaderFn, loadOpts) {
  const definition = await loaderFn();
  const { token } = await this.moduleCompiler.compile(definition);
  let loading = this.loadsInFlight.get(token);
  if (!loading) {
    // loadModule = current body with your try/catch
    loading = this.loadModule(definition, loadOpts).finally(() =>
      this.loadsInFlight.delete(token),
    );
    this.loadsInFlight.set(token, loading);
  }
  return loading;
}

Entry is deleted before callers see rejection, so retry from catch starts fresh build. Map has to be per token, one global queue hangs when lazy module factory loads other lazy module

Tried it on 9b2f747 togehter with identity check from @kamilmysliwiec's comment: specs for same-time, mid-build, case 1 and case 2 fail on PR and pass with it, @micalevisk's retry race stays green. Can paste them

Not covered: two different lazy modules importing same new module (@micalevisk's AModule/BModule), and cycle where A's factory loads B and B's loads A now hangs instead of returning half built A

@kratos0722 kratos0722 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice fix — returning a half-built module from every subsequent load() after a failed first load is a genuinely confusing failure mode, and the two added tests (a regular module and a global module both rebuilding on the next load(), asserting factoryCalls === 2) pin the behavior down well.

A couple of notes from reading through it:

  1. In removeInstanceWrappers, deleting from the wrappers Set while iterating it with for...of is safe here since only the current element is removed — Set iteration won't skip the elements that follow — so no concern there.

  2. The one thing I wasn't sure about: does lazyModulesContainer.values() capture modules that scanModulesForDependencies discovers transitively? If scanning a lazy module pulls in a nested imported module that gets added to the main container but isn't part of lazyModulesContainer, would that nested module be left half-built on failure (i.e. not covered by removeModules)? If createLazyModulesContainer already scopes to exactly the modules that scanning can add, this is moot — I just wanted to confirm the cleanup set matches the set that scanning can grow.

Either way the core approach (clean up the partially-built modules, then rethrow) looks right.

@kamilmysliwiec

Copy link
Copy Markdown
Member

Thanks for working on this! Closing it for now, since the earlier review points are still open. A safe rollback first needs concurrent load() calls of the same module to share a single in-flight load, and the cleanup should only remove what the failed load itself added. Happy to look at a new PR that takes that route.

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.

5 participants