Skip to content

Realm import: JSON representation migration fails with LazyInitializationException when a users file is present (regression in 26.3) #52870

Closed

Description

@chrizmaster

Before reporting an issue

  • I have read and understood the above terms for submitting issues, and I understand that my issue may be closed without action if I do not follow them.

Area

import-export

Describe the bug

When a realm is imported with kc.sh import (DirImportProvider) from a directory that contains both -realm.json and -users-0.json, and the realm representation declares a keycloakVersion lower than 24.0.0, the migration of the JSON representation fails:

ERROR [org.keycloak.storage.datastore.DefaultMigrationManager] (main) Failed to migrate json
representation for version: 24.0.0: org.hibernate.LazyInitializationException: Cannot lazily
initialize collection of role 'org.keycloak.models.jpa.entities.RealmEntity.components'
with key '7915f19e-5a3b-488d-82e5-29ff709f0aae' (no session)
The import afterwards reports success (Realm 'migbug' imported, KC-SERVICES0032: Import finished successfully), so the failure is easy to miss — but MigrateTo24_0_0 has been skipped and its effects are missing from the imported realm.

Comparing the same import on 26.1.2 and on 26.7.3, the imported realm differs in:

unmanagedAttributePolicy is not set to ENABLED (MigrateTo24_0_0.updateUserProfileSettings)
the hmac-generated-hs512 key provider component is not created (MigrateTo24_0_0.createHS512ComponentModelKey)
The remaining migration steps of the chain are applied correctly.

Version

26.7.3

Regression

  • The issue is a regression

Expected behavior

The migration chain of the imported representation is applied completely and no error is logged — as in 26.2.5 and earlier.

Also reproduced on 26.3.5 and 26.4.6. Not reproducible on 26.1.2 and 26.2.5 (same two files, same command).

Actual behavior

MigrateTo24_0_0 aborts with a LazyInitializationException; the import continues and reports success.

How to Reproduce?

Two files in an otherwise empty directory:

migbug-realm.json

{
  "realm": "migbug",
  "enabled": true,
  "keycloakVersion": "18.0.0"
}
migbug-users-0.json

{
  "realm": "migbug",
  "users": [
    {
      "username": "alice",
      "enabled": true
    }
  ]
}

Run the import (any database, dev-file is enough):

docker run --rm -v "$PWD:/tmp/imp" keycloak/keycloak:26.7.3 import --dir /tmp/imp --db dev-file
Two things make the import clean again, which isolates the two conditions:

  • delete migbug-users-0.json — the migration then runs inside the still-open session
  • set "keycloakVersion": "24.0.0" or higher — MigrateTo24_0_0 is then not part of the chain

The change in log order between versions is the give-away:

26.2.5    Realm 'migbug' imported
          Imported users from /tmp/imp/migbug-users-0.json
26.3.5+   Imported users from /tmp/imp/migbug-users-0.json
          Failed to migrate json representation for version: 24.0.0 ...
          Realm 'migbug' imported

Importing the same representation through the Admin REST API (POST /admin/realms) is not affected, regardless of the keycloakVersion value.

Anything else?

The cause appears to be the refactoring of the user import in DirImportProvider.

26.2.5 imported the users in a separate transaction after ImportUtils.importRealm had returned:

KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {
    protected void runExportImportTask(KeycloakSession session) throws IOException {
        boolean imported = ImportUtils.importRealm(session, realmRep, strategy, true);
        realmImported.set(imported);
    }
});

if (realmImported.get()) {
    // Import users
    for (final File userFile : userFiles) { ... }
}

26.3.5 passes the user import as a Runnable into ImportUtils.importRealm:

ImportUtils.importRealm(session, realmRep, strategy, () -> {
    importUsers(realmName, userFiles, false);
    importUsers(realmName, federatedUserFiles, true);
});

and DirImportProvider additionally flushes the entity manager:

Optional.ofNullable(KeycloakSessionUtil.getKeycloakSession())
        .ifPresent(session -> EntityManagers.flush(session, true));

In RealmManager.importRealm(RealmRepresentation, Runnable) the callback is therefore invoked before the migration event is fired (line numbers from 26.3.5; in 26.7.3 the fire(...) call is at RealmManager.java:724, as in the stack trace below):

  • RealmManager.java:629 — RepresentationToModel.importRealm(session, rep, realm, userImport), which hands the callback down via RepresentationToModel.java:144 → DatastoreProvider.getExportImportManager().importRealm(rep, newRealm, userImport), where the users are imported
  • RealmManager.java:680 — StoreMigrateRepresentationEvent.fire(session, realm, rep, skipUserDependent), i.e. the migration runs after the user import has completed
  • By then the RealmEntity is no longer associated with a persistence context, so DeclarativeUserProfileProvider.getComponentModel cannot initialize the lazy RealmEntity.components collection.

Full stack trace

ERROR [org.keycloak.storage.datastore.DefaultMigrationManager] (main) Failed to migrate json representation for version: 24.0.0: org.hibernate.LazyInitializationException: Cannot lazily initialize collection of role 'org.keycloak.models.jpa.entities.RealmEntity.components' with key '7915f19e-5a3b-488d-82e5-29ff709f0aae' (no session)
	at org.hibernate.collection.spi.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:647)
	at org.hibernate.collection.spi.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:232)
	at org.hibernate.collection.spi.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:620)
	at org.hibernate.collection.spi.AbstractPersistentCollection.read(AbstractPersistentCollection.java:142)
	at org.hibernate.collection.spi.PersistentSet.iterator(PersistentSet.java:164)
	at java.base/java.util.Spliterators$IteratorSpliterator.estimateSize(Spliterators.java:1959)
	at java.base/java.util.Spliterator.getExactSizeIfKnown(Spliterator.java:414)
	at java.base/java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:526)
	at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:513)
	at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
	at java.base/java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:150)
	at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.base/java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:647)
	at org.keycloak.userprofile.DeclarativeUserProfileProvider.getComponentModel(DeclarativeUserProfileProvider.java:243)
	at org.keycloak.userprofile.DeclarativeUserProfileProvider.getConfiguration(DeclarativeUserProfileProvider.java:198)
	at org.keycloak.migration.migrators.MigrateTo24_0_0.updateUserProfileSettings(MigrateTo24_0_0.java:72)
	at org.keycloak.migration.migrators.MigrateTo24_0_0.migrateRealm(MigrateTo24_0_0.java:50)
	at org.keycloak.migration.migrators.RealmMigration.migrateImport(RealmMigration.java:57)
	at org.keycloak.storage.datastore.DefaultMigrationManager.migrate(DefaultMigrationManager.java:227)
	at org.keycloak.migration.MigrationModelManager.migrateImport(MigrationModelManager.java:37)
	at org.keycloak.storage.datastore.DefaultDatastoreProviderFactory.onEvent(DefaultDatastoreProviderFactory.java:129)
	at org.keycloak.services.DefaultKeycloakSessionFactory.publish(DefaultKeycloakSessionFactory.java:87)
	at org.keycloak.storage.StoreMigrateRepresentationEvent.fire(StoreMigrateRepresentationEvent.java:44)
	at org.keycloak.services.managers.RealmManager.importRealm(RealmManager.java:724)
	at org.keycloak.exportimport.util.ImportUtils.importRealm(ImportUtils.java:128)
	at org.keycloak.exportimport.dir.DirImportProvider$1.runExportImportTask(DirImportProvider.java:154)
	at org.keycloak.exportimport.util.ExportImportSessionTask.lambda$run$1(ExportImportSessionTask.java:58)
	at org.keycloak.exportimport.util.ExportImportSessionTask.run(ExportImportSessionTask.java:66)
	at org.keycloak.exportimport.util.ExportImportSessionTask.runTask(ExportImportSessionTask.java:49)
	at org.keycloak.exportimport.util.ExportImportSessionTask.runTask(ExportImportSessionTask.java:42)
	at org.keycloak.exportimport.dir.DirImportProvider.importRealm(DirImportProvider.java:160)
	at org.keycloak.exportimport.dir.DirImportProvider.importModel(DirImportProvider.java:103)
	at org.keycloak.exportimport.ExportImportManager.lambda$runImport$1(ExportImportManager.java:105)
	at java.base/java.lang.Iterable.forEach(Iterable.java:75)
	at org.keycloak.exportimport.ExportImportManager.runImport(ExportImportManager.java:103)
	at org.keycloak.services.resources.KeycloakApplication.bootstrap(KeycloakApplication.java:154)
	at org.keycloak.services.resources.KeycloakApplication.lambda$runBootstrap$1(KeycloakApplication.java:102)
	at org.keycloak.models.utils.KeycloakModelUtils.runJobInTransactionWithResult(KeycloakModelUtils.java:480)
	at org.keycloak.models.utils.KeycloakModelUtils.runJobInTransactionWithResult(KeycloakModelUtils.java:458)

Practical impact
Containerized setups that provision a realm on first start from a directory holding a realm export plus a users file are affected on every fresh installation, as long as the export carries a keycloakVersion below 24.0.0 — which is common for exports that have been carried along for a while. In-place upgrades of existing installations are not affected, because the realm in the database is migrated through migrateModel instead.

Activity

  1. added
    kind/bug
    on Sep 16, 2026
  2. added theissue type on Sep 16, 2026
  3. added
    area/import-export
    on Sep 16, 2026
  4. added 4 commits that reference this issue on Sep 17, 2026
    4fb51ca
    d4d100d
    52772ae
    7b03dcd
  5. mposolda commented on Sep 21, 2026

    @mposolda
    Contributor

    Moving to cloud-native team as it looks like a regression of #37926 (CC @shawkins )

  6. added a commit that references this issue on Sep 27, 2026
    7c919b4
  7. 15 remaining items

  8. added a commit that references this issue on Oct 15, 2026
    f6ba89e
  9. added 2 commits that reference this issue on Oct 22, 2026
    a966151
    c2a046a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    Fields

    No fields configured for bug.

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions