Skip to content

salt.sqlalchemy base implementation (+ returner & cache) - #68068

Open
mattp- wants to merge 7 commits into
saltstack:masterfrom
mattp-:sqla
Open

mattp- wants to merge 7 commits into
saltstack:masterfrom
mattp-:sqla

Conversation

@mattp-

@mattp- mattp- commented Jun 12, 2025 •

Copy link
Copy Markdown
Contributor

What does this PR do?

this is the foundation for a shared sqlalchemy model that can be used across (at least, from current testing) postgresql, mysql, sqlite. The eventual goal would be to deprecate the redundant mysql, pgjsonb, postgres returners & cache implementations. In the longer future, possibly defaulting to sqlite and removing file based cache &
returner mechanisms could lead to simplifying the salt codebase, but thats a much larger discussion.

NOTE: this PR is rebased on #68039 and #68030 , please merge them first, thanks 👍

NOTE: this pr only runs against sqlite and pymysql at the moment; I can't figure out how to get psycopg installing with the static reqs. I'll try to work with someone from salt-co to get that added. once psycopg gets installed the pg tests should run automatically.

I've got a separate changeset that implements sql optimizations for salt.key/salt.utils.minions, I'll be working on that next

Merge requirements satisfied?

[NOTICE] Bug fixes or features added to Salt require tests.

Commits signed with GPG?

Yes

@mattp-
mattp- requested a review from a team as a code owner June 12, 2025 18:55
@mattp- mattp- changed the title new: salt.sqlalchemy base implementation new: salt.sqlalchemy base implementation (+ returner & cache) Jun 12, 2025
@mattp- mattp- changed the title new: salt.sqlalchemy base implementation (+ returner & cache) WIP: new: salt.sqlalchemy base implementation (+ returner & cache) Jun 12, 2025
@mattp-
mattp- force-pushed the sqla branch 2 times, most recently from e0c1ccb to 9b8f4df Compare June 13, 2025 00:54
@whytewolf whytewolf added the test:full Run the full test suite label Jun 17, 2025
@mattp-

mattp- commented Jun 24, 2025

Copy link
Copy Markdown
Contributor Author

I can't figure out how to get psycopg installing with the static reqs.

try adding psycopg-binary that will bypass the compile steps and let you add tests for it

tried that, unfortunately it craps out for reasons I can't figure out where it cannot find the right wheel (I'm pretty sure are related to the hacks https://github.com/saltstack/pip-tools-compile-impersonate are doing but couldn't figure it out / wasted enough time on it)

@twangboy

Copy link
Copy Markdown
Contributor

Got some pre-commit and lint failures

twangboy
twangboy previously approved these changes Sep 15, 2025
@twangboy

Copy link
Copy Markdown
Contributor

Looks like there are some Lint failures

@mattp-

mattp- commented Sep 16, 2025

Copy link
Copy Markdown
Contributor Author

@twangboy should be fixed now 👍 remaining fails are from the new release / master missing mergeforward thing again.

twangboy
twangboy previously approved these changes Sep 16, 2025
twangboy
twangboy previously approved these changes Oct 1, 2025
twangboy
twangboy previously approved these changes Feb 11, 2026
@mdschmitt

Copy link
Copy Markdown
Contributor

@twangboy do you think #68039 can get some 👀 as well since it's mentioned in the description? Seems like #68030 is already merged.

@twangboy

Copy link
Copy Markdown
Contributor

Please rebase and resolve conflicts

twangboy
twangboy previously approved these changes Mar 19, 2026
@a76yyyy

a76yyyy commented May 12, 2026

Copy link
Copy Markdown
Contributor

Is there a plan to merge this into version 3008?

@mattp-

mattp- commented May 12, 2026

Copy link
Copy Markdown
Contributor Author

hi @a76yyyy , I would like to see it landed, but I don't think the core team is open to it at this time.

@a76yyyy

a76yyyy commented May 12, 2026

Copy link
Copy Markdown
Contributor

hi @a76yyyy , I would like to see it landed, but I don't think the core team is open to it at this time.

Is it because the branches cannot be merged cleanly yet?

@mattp-

mattp- commented May 12, 2026

Copy link
Copy Markdown
Contributor Author

@a76yyyy will defer to @dwoz but I believe there are concerns about maintenance burden
the conflicts are fixable easily

@dwoz

dwoz commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@mattp- I'd like to merge these, can you please rebase?

@twangboy

twangboy commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

please rebase and fix conflicts

twangboy
twangboy previously approved these changes Nov 6, 2026

@twangboy twangboy left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Here are the main potential issues, edge cases, and performance bottlenecks identified in the implementation:


1. Inefficient Fallback Upsert in salt/cache/sqlalchemy.py

  • Location: salt/cache/sqlalchemy.py (Lines 131–152)
  • Code:
else:
    # the default path is racy, so any implementation specific upsert is preferred
    try:
        stmt = insert(Cache).values(key=key, bank=bank, cluster=cluster_id, data=data)
        session.execute(stmt)
        session.commit()
    except sqlalchemy.exc.IntegrityError:
        session.rollback()
        stmt = update(Cache)...
  • Issue:
  1. Missing expires_at on Initial Insert: Line 134 inserts Cache without passing expires_at=expires_at. If a key with an expiration is stored on a non-PostgreSQL backend (e.g., MySQL, SQLite), the expiration date is silently dropped on the initial insert.
  2. High Exception/Rollback Overhead: Relying on IntegrityError catch-and-retry on non-PostgreSQL databases forces transaction rollbacks during routine key updates, causing unnecessary database locking and overhead under high minion cache concurrency.

2. Performance Bottleneck in clean_expired Delete Strategy

  • Location: [salt/cache/sqlalchemy.py (Lines 265–279)
  • Code:
subq = select(Cache.bank, Cache.key, Cache.cluster).where(...)
stmt = delete(Cache).where(tuple_(Cache.bank, Cache.key, Cache.cluster).in_(subq)).returning(Cache.key)
  • Issue:
  1. Tuple In-Clause Support: Tuple comparison via tuple_().in_(subq) is unsupported or poorly optimized in several standard SQL engines (including standard SQLite versions and MariaDB configurations).
  2. RETURNING Clause Compatibility: .returning(Cache.key) is not supported natively across all dialects (e.g., standard MySQL/MariaDB). Calling this directly on standard MySQL engines will raise an execution error during cache maintenance runs.

3. Missing expires_at Update on SQLite / Generic Engine Fallback

  • Location: salt/cache/sqlalchemy.py (Lines 142–150)
  • Code:
stmt = update(Cache).where(...).values(data=data)
  • Issue: During a fallback update path (when an entry already exists and raises IntegrityError), update() updates data=data but omits updating expires_at or updating created_at = now(). Updating an existing cached key will retain its old expiration timestamp.

4. Overly Permissive Typings in Configuration Schema

  • Location: salt/config/__init__.py (Lines 1196–1211)
  • Code:
"sqlalchemy.port": (type(None), str),
  • Issue: sqlalchemy.port and sqlalchemy.ro_port are typed strictly as str (or None). If a user passes an integer in their master/minion configuration file (sqlalchemy.port: 5432), configuration validation will flag it or fail depending on how strict config parsing is invoked.

Take these for what they're worth...

@mattp-

mattp- commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

@twangboy thanks for review 👍 this pr is rebased, but I'll have to see the CI fallout and address later

twangboy
twangboy previously approved these changes Nov 17, 2026
Provide shared engines, sessions, schema runners, and models for cache,
job loads, returns, and events across PostgreSQL, MySQL, MariaDB, and SQLite.
Support explicit named-engine selection without an unused default engine,
and explain the default connection required by built-in consumers.

Allow separate read connections to inherit PostgreSQL SSL settings with
explicit overrides. Reject libpq-specific options for other dialects.

Preserve ordinary JSON paths for database queries while reversibly encoding
Salt values that JSON cannot represent. Normalize timestamps to UTC and
retain microsecond precision on MySQL and MariaDB. Store function metadata
as text with MySQL index prefixes so long compound jobs can be saved.

Give job loads a partition-compatible identity tied to the JID timestamp.
Support native partitions with pg_partman 4.7.x and 5.x and register schema
callbacks per table so configuring another engine does not duplicate them.
Explicitly type interval arguments to avoid psycopg 3 parameter ambiguity.
the mysql fixture was useful as a base, but making it database agnostic
required some changes. now it supports postgres, and easily others in
the future if desired. reworked the way versions work as well so it can
be consumed from different tests more easily.
Store cache data for PostgreSQL, MySQL, MariaDB, and SQLite using shared
models and atomic native upserts. Support relative TTLs and numeric absolute
expirations, compare timestamps in UTC, and refresh cache ages on overwrite.
Replace or clear expiry on overwrite without routine duplicate-key errors.

Check affected rows in the generic update/insert fallback and bound retries
for competing key creation. Preserve constraint failures when no conflicting
key exists and never report success after silently losing a cache write.

Expose immediate sub-banks for discovery and migration, and flush complete
bank hierarchies. Keep SQLite prefix comparisons case-sensitive to avoid
removing another bank. Preserve case and accents in MySQL and MariaDB
identifiers and retain queryable JSON without losing Salt value types.

Delete expired entries without returning unused keys. Apply native MySQL
and MariaDB limits and retain bounded cleanup on PostgreSQL and SQLite.
Document default and named connection usage. Add regressions for expiry,
timestamp refresh, bank/cluster isolation, concurrent writes, cleanup races,
constraint failures, and retry exhaustion.

Verify with 53 unit tests and 70 functional tests across PostgreSQL 13/17,
MySQL 8, MariaDB 10.4/10.5, Percona 8, and SQLite. Run Ruff format/check.
Store job loads, returns, and events using shared SQLAlchemy models. Scope
lookups and cleanup by cluster, preserve multi-function return payloads,
and allow minions to use the returner without master-only defaults.
Document the default connection required for built-in returner usage.

Make repeated job-load saves idempotent so minion returns cannot replace
the publish load or its minion list. Derive created_at from the JID for
partition-compatible uniqueness and skip saves beyond configured retention.

Generate JIDs from microsecond UTC database timestamps and advisory locks.
Evaluate the PostgreSQL candidate once and honor unique_jid. Locks reduce
concurrent collisions without reserving identifiers after release.

Log and raise exhausted database retries. Add regression coverage for load
identity, cluster isolation, retention, long multi-function returns, and
retry exhaustion.
Require SQLAlchemy 2.1.8 on Python 3.11 and newer, and 2.0.57 on older
Python versions. Both support the MySQL delete limit used by cache cleanup.

Update the shared CI input and generated platform lockfiles together so
test environments install SQLAlchemy and its required dependencies. Use the
lockfile changes generated by upstream pre-commit to preserve its pins and
platform markers.
Add salt.sqlalchemy.migrations, an Alembic environment configured from the
running engine and its Salt settings instead of an ini file. Revision 0001
recreates the current cache and job schema with its own frozen table
definitions, including PostgreSQL cache partitions, GIN indexes, JID CHECK
constraints and optional pg_partman setup, so later model changes cannot
alter it.

Migrations run only through the sqlalchemy runner, never at startup. The
runner gains upgrade, downgrade, current, history and stamp, and upgrade
sql=True emits reviewable SQL without connecting. create_all and drop_all
now run upgrade head and downgrade base, so operators have one schema path.

Online runs hold a PostgreSQL advisory lock or a MySQL/MariaDB named lock,
so masters upgrading at the same time apply each revision once. The schema
records structural settings at creation, and upgrades refuse to proceed
when pg_partman has since been switched on PostgreSQL, because converting
tables to or from partitions requires a manual data migration.

configure_orm keeps each engine's resolved settings in the registry so
migrations can read the schema and partman options. Alembic is optional at
runtime, like SQLAlchemy itself, and is added to the CI requirements and
locks.

Functional tests cover every supported database: the migrated schema
matches the models, upgrades are idempotent, downgrades remove the schema,
offline SQL keeps the MySQL JID format literal intact, configured schemas
hold every table, and a second process waits on the migration lock.
The cache table carried a GIN index over every key and value of every
cached document. No Salt query uses it: cache reads and writes go through
the primary key. On grains shaped like a large production fleet it cost
about 65 KB per minion, around 65 GB at one million minions, and added
index maintenance to every changed grains and pillar store.

Leave it out of the model and of revision 0001, which has not been
released, so no migration has to drop it. The events table keeps its
data index.
@mattp-

mattp- commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

@twangboy @dwoz should be rebased/clean now

This branch was previously deployed

1 inactive deployment
ci — aebf2c30 Deployed Nov 27, 2026 by mattp- via Build Onedir Packages / RPM (x86_64) #29728
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

test:full Run the full test suite

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants