Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

13.7 KB
Raw Blame
"""Opening the database a config names, and what a server database is checked for before the app uses it."""

import logging
import time
from pathlib import Path
from typing import Optional

import pytest
from sqlalchemy import URL, create_engine, delete, insert, select

from invokeai.app.services.config.config_default import DefaultInvokeAIAppConfig, InvokeAIAppConfig
from invokeai.app.services.shared.database import database as database_module
from invokeai.app.services.shared.database import startup
from invokeai.app.services.shared.database.database import Database
from invokeai.app.services.shared.database.errors import DatabaseInUseError
from invokeai.app.services.shared.database.schema.migrator import applied_migrations
from invokeai.app.services.shared.database.session_lock import InstanceLock, SessionLock
from invokeai.app.services.shared.database.startup import (
    DatabaseSetupError,
    init_database,
    open_database,
    open_migrated_database,
    redacted_database_url,
)
from invokeai.app.services.shared.sqlite_migrator.migration_loader import (
    PORTABLE_CUTOVER,
    MigrationBuildContext,
    build_migrations,
)
from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import (
    MigrationBase,
    MigrationError,
    PortableMigration,
)
from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_impl import UPGRADE_DOCS_URL, NoImageFiles
from invokeai.backend.util.logging import InvokeAILogger
from tests.fixtures.database import external_test_db_url

server_only = pytest.mark.skipif(
    external_test_db_url() is None, reason="needs a MySQL or MariaDB server (INVOKEAI_TEST_DB_URL)"
)
LOGGER = InvokeAILogger.get_logger("test_startup")


def _config(root: Path, **values: object) -> InvokeAIAppConfig:
    # Read from no file and no environment: the migrations clean up files under the root.
    config = DefaultInvokeAIAppConfig(**values)
    config._root = root
    return config


def test_a_memory_database_and_a_url_exclude_each_other(tmp_path: Path) -> None:
    config = _config(tmp_path, use_memory_db=True, db_url="mariadb+pymysql://invokeai:secret@db/invokeai")
    with pytest.raises(DatabaseSetupError, match="exclude each other"):
        open_database(config, LOGGER)


def test_a_url_is_shown_without_its_password() -> None:
    assert redacted_database_url("mariadb+pymysql://invokeai:s3cret@db/invokeai") == (
        "mariadb+pymysql://invokeai:***@db/invokeai"
    )
    assert redacted_database_url(None) is None
    assert redacted_database_url("no url at all") == "***"


@pytest.mark.parametrize(
    ("url", "shown"),
    [
        (
            "mariadb+pymysql://invokeai@db/invokeai?password=s3cret",
            "mariadb+pymysql://invokeai@db/invokeai?password=***",
        ),
        (
            "mysql+pymysql://invokeai:s3cret@db/invokeai?charset=utf8mb4&passwd=0ther",
            "mysql+pymysql://invokeai:***@db/invokeai?charset=utf8mb4&passwd=***",
        ),
    ],
)
def test_a_password_in_the_query_is_masked_too(
    url: str, shown: str, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch
) -> None:
    # PyMySQL takes `password` and `passwd` from the query as the password.
    assert redacted_database_url(url) == shown

    logger = logging.getLogger("test_startup_redaction")
    # Exercise the real URL parsing and logging without requiring the optional MySQL driver.
    monkeypatch.setattr(database_module, "create_mysql_engine", lambda _url: create_engine("sqlite:///:memory:"))
    with caplog.at_level(logging.INFO, logger=logger.name):
        Database.open_url(url, logger).dispose()
    [message] = [record.getMessage() for record in caplog.records if record.name == logger.name]
    assert message == f"Connecting to database {shown}"
    assert "s3cret" not in caplog.text and "0ther" not in caplog.text


@pytest.mark.parametrize(
    ("reported", "version"),
    [("8.4.3", (8, 4)), ("10.11.6-MariaDB-1:10.11.6+maria~ubu2204", (10, 11)), ("11.4.2-MariaDB-log", (11, 4))],
)
def test_server_versions_are_read_from_what_the_server_reports(reported: str, version: tuple[int, int]) -> None:
    assert startup._version_of(reported) == version


def test_a_tool_refuses_a_database_the_app_has_not_updated(tmp_path: Path) -> None:
    config = _config(tmp_path)
    database = init_database(config, LOGGER, NoImageFiles())
    with database.begin(write=True) as conn:
        conn.execute(
            delete(applied_migrations).where(applied_migrations.c.migration_id == "2026_10_07_drop_sqlite_triggers")
        )
    database.dispose()

    with pytest.raises(DatabaseSetupError, match="start InvokeAI once"):
        open_migrated_database(config, LOGGER)

    # As the app does when it starts.
    init_database(config, LOGGER, NoImageFiles()).dispose()
    open_migrated_database(config, LOGGER).dispose()


def test_a_tool_creates_no_database_where_there_is_none(tmp_path: Path) -> None:
    config = _config(tmp_path)

    with pytest.raises(DatabaseSetupError, match="no database at"):
        open_migrated_database(config, LOGGER)

    assert not config.db_path.exists()


@server_only
def test_one_process_at_a_time_holds_a_server_database(_external_test_schema: Optional[URL]) -> None:
    assert _external_test_schema is not None
    url = _external_test_schema.render_as_string(hide_password=False)
    first = Database.open_url(url, LOGGER)
    second = Database.open_url(url, LOGGER)
    try:
        first.hold_instance_lock()
        with pytest.raises(DatabaseInUseError, match="Another InvokeAI process"):
            second.hold_instance_lock()

        # The lock ends with the process that holds it, or, as here, when its database is closed.
        first.dispose()
        second.hold_instance_lock()
    finally:
        first.dispose()
        second.dispose()


@server_only
def test_a_server_without_room_for_large_projects_or_too_old_is_refused(
    empty_database: Database, monkeypatch: pytest.MonkeyPatch
) -> None:
    with empty_database.begin(write=False) as conn:
        packet = int(conn.exec_driver_sql("SELECT @@max_allowed_packet").scalar_one())

    monkeypatch.setattr(startup, "MINIMUM_MAX_ALLOWED_PACKET", packet)
    monkeypatch.setitem(startup.MINIMUM_SERVER_VERSIONS, empty_database.dialect_name, (8, 0))
    startup.check_server(empty_database)

    monkeypatch.setattr(startup, "MINIMUM_MAX_ALLOWED_PACKET", packet + 1)
    with pytest.raises(DatabaseSetupError, match="max_allowed_packet"):
        startup.check_server(empty_database)

    monkeypatch.setattr(startup, "MINIMUM_MAX_ALLOWED_PACKET", packet)
    monkeypatch.setitem(startup.MINIMUM_SERVER_VERSIONS, empty_database.dialect_name, (99, 0))
    with pytest.raises(DatabaseSetupError, match="too old"):
        startup.check_server(empty_database)


@server_only
def test_a_new_server_database_beside_a_sqlite_one_is_pointed_out(
    empty_database: Database, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
    config = _config(tmp_path, db_url="mariadb+pymysql://invokeai:secret@db/invokeai")
    config.db_path.parent.mkdir(parents=True)
    config.db_path.write_bytes(b"")

    with caplog.at_level(logging.WARNING):
        startup._warn_when_new_beside_sqlite(empty_database, config, LOGGER)

    [warning] = [record.getMessage() for record in caplog.records if record.levelno == logging.WARNING]
    assert "invoke-db-copy" in warning
    assert "secret" not in warning


def test_a_url_that_cannot_be_read_is_refused_without_repeating_its_password() -> None:
    # An `@` in the password that is not percent-encoded.
    url = "mariadb+pymysql://invokeai:se@[email protected]/invokeai"

    assert redacted_database_url(url) == "***"
    with pytest.raises(ValueError, match="Percent-encode") as refused:
        Database.open_url(url, LOGGER)
    assert "cret" not in str(refused.value)


def test_a_missing_driver_is_named_with_the_extra_that_installs_it(monkeypatch: pytest.MonkeyPatch) -> None:
    def no_driver(_url: object) -> None:
        raise ModuleNotFoundError("No module named 'pymysql'", name="pymysql")

    monkeypatch.setattr(database_module, "create_mysql_engine", no_driver)

    with pytest.raises(ValueError, match=r"invokeai\[mysql\]"):
        Database.open_url("mariadb+pymysql://invokeai:[email protected]/invokeai", LOGGER)


@server_only
def test_the_app_refuses_a_server_database_another_process_holds(
    _external_test_schema: Optional[URL], tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    assert _external_test_schema is not None
    # The test servers keep their own defaults; what is checked here is the lock.
    monkeypatch.setattr(startup, "MINIMUM_MAX_ALLOWED_PACKET", 1)
    url = _external_test_schema.render_as_string(hide_password=False)
    holder = Database.open_url(url, LOGGER)
    try:
        holder.hold_instance_lock()
        with pytest.raises(DatabaseInUseError, match="IS_USED_LOCK"):
            init_database(_config(tmp_path, db_url=url), LOGGER, NoImageFiles())
    finally:
        holder.dispose()


@server_only
def test_a_lock_the_server_released_is_taken_again(
    _external_test_schema: Optional[URL], caplog: pytest.LogCaptureFixture
) -> None:
    assert _external_test_schema is not None
    url = _external_test_schema.render_as_string(hide_password=False)
    database, other = Database.open_url(url, LOGGER), Database.open_url(url, LOGGER)
    lock = InstanceLock(database.engine, LOGGER)
    try:
        # The server ends the session that holds the lock, as after an idle timeout or a network failure.
        probe = SessionLock(other.engine, "instance")
        probe.close()
        with other.begin(write=False) as conn:
            holder = conn.exec_driver_sql("SELECT IS_USED_LOCK(%s)", (probe.name,)).scalar_one()
            conn.exec_driver_sql(f"KILL {int(holder)}")

        # Another process takes it meanwhile: two serve the database, which is reported.
        rival = _take_when_free(other)
        with caplog.at_level(logging.ERROR):
            lock.check()
        assert any("two processes now serve it" in record.getMessage() for record in caplog.records)

        rival.close()
        lock.check()
        with pytest.raises(DatabaseInUseError):
            InstanceLock(other.engine, LOGGER)
    finally:
        lock.close()
        database.dispose()
        other.dispose()


@server_only
def test_updating_an_existing_server_database_warns_that_no_backup_was_made(
    empty_database: Database,
    _external_test_schema: Optional[URL],
    tmp_path: Path,
    monkeypatch: pytest.MonkeyPatch,
    caplog: pytest.LogCaptureFixture,
) -> None:
    assert _external_test_schema is not None
    # The test servers keep their own defaults; what is checked here is the warning.
    monkeypatch.setattr(startup, "MINIMUM_MAX_ALLOWED_PACKET", 1)
    config = _config(tmp_path, db_url=_external_test_schema.render_as_string(hide_password=False))

    with caplog.at_level(logging.WARNING):
        init_database(config, LOGGER, NoImageFiles()).dispose()
    assert [record for record in caplog.records if record.levelno == logging.WARNING] == []

    # A newer version, with a migration this database has not had.
    def with_one_more(context: MigrationBuildContext) -> list[MigrationBase]:
        probe = PortableMigration(id="2099_01_01_probe", depends_on=PORTABLE_CUTOVER, callback=lambda context: None)
        return [*build_migrations(context), probe]

    monkeypatch.setattr(startup, "build_migrations", with_one_more)
    caplog.clear()
    with caplog.at_level(logging.WARNING):
        init_database(config, LOGGER, NoImageFiles()).dispose()

    [warning] = [record.getMessage() for record in caplog.records if record.levelno == logging.WARNING]
    assert _external_test_schema.render_as_string(hide_password=True) in warning
    if _external_test_schema.password:
        # The password may also spell the database name (CI uses "invokeai" for both), so look for it where the URL
        # writes it, after the user name.
        credentials = _external_test_schema.render_as_string(hide_password=False).split("://", 1)[1].rpartition("@")[0]
        assert credentials not in warning
    assert "makes no backup of a server database" in warning
    assert UPGRADE_DOCS_URL in warning


@server_only
def test_a_server_database_a_newer_version_updated_is_refused_with_how_to_go_back(
    empty_database: Database,
    _external_test_schema: Optional[URL],
    tmp_path: Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    assert _external_test_schema is not None
    monkeypatch.setattr(startup, "MINIMUM_MAX_ALLOWED_PACKET", 1)
    config = _config(tmp_path, db_url=_external_test_schema.render_as_string(hide_password=False))
    init_database(config, LOGGER, NoImageFiles()).dispose()
    with empty_database.begin(write=True) as conn:
        conn.execute(insert(applied_migrations).values(migration_id="2999_01_01_from_a_newer_version"))
    with empty_database.begin(write=False) as conn:
        applied_before = set(conn.execute(select(applied_migrations.c.migration_id)).scalars())

    with pytest.raises(
        MigrationError, match="unknown applied migration IDs: 2999_01_01_from_a_newer_version"
    ) as refused:
        init_database(config, LOGGER, NoImageFiles())

    message = str(refused.value)
    assert "restore the backup you made before upgrading" in message
    assert "InvokeAI does not back up server databases" in message
    assert UPGRADE_DOCS_URL in message
    with empty_database.begin(write=False) as conn:
        assert set(conn.execute(select(applied_migrations.c.migration_id)).scalars()) == applied_before


def _take_when_free(database: Database) -> InstanceLock:
    # A killed session releases its locks as the server gets to it.
    deadline = time.monotonic() + 5
    while True:
        try:
            return InstanceLock(database.engine, LOGGER)
        except DatabaseInUseError:
            if time.monotonic() > deadline:
                raise
            time.sleep(0.05)