Skip to content

SQLAlchemy: let database do work where it can - #68108

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

mattp- wants to merge 20 commits into
saltstack:masterfrom
mattp-:sqla-opt

Conversation

@mattp-

@mattp- mattp- commented Jun 24, 2025 •

Copy link
Copy Markdown
Contributor

What does this PR do?

provide subclasses for salt.utils.minions.CkMinions and salt.key.Key that use sqlalchemy to make things go fast that would otherwise require a full fetch of the entire minion data cache. the larger your installation the bigger the improvement will be. The CkMinions optimization heavily relies on GIN indexing with @> contains queries, so is postgresql speciific. mysql/sqlite unfortunately don't offer anything equivalent to translate to.

NOTE: This PR, depends on #68068, which in turn has dependencies. please make sure they're landed first. thanks!

Previous Behavior

naive iteration of entire cache in multiple critical spots interacting with minion data cache / pki key list.

New Behavior

database now in use where possible.

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 24, 2025 17:28
@twangboy twangboy added the test:full Run the full test suite label Jun 26, 2025
@twangboy twangboy added this to the Argon v3008.0 milestone Jun 26, 2025
twangboy
twangboy previously approved these changes Sep 16, 2025
twangboy
twangboy previously approved these changes Oct 1, 2025
@twangboy

Copy link
Copy Markdown
Contributor

Please address conflicts and rebase once master is green again

@mattp-

mattp- commented Jan 16, 2026

Copy link
Copy Markdown
Contributor Author

@twangboy will do 👍

twangboy
twangboy previously approved these changes Feb 11, 2026
@twangboy

Copy link
Copy Markdown
Contributor

Please rebase and resolve conflicts

twangboy
twangboy previously approved these changes Mar 23, 2026
@dwoz

dwoz commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

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

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.
previously, for the given grains

"services": {
    "running": [
        {"name": "nginx", "ports": [80, 443]},
        {"name": "redis", "ports": [6379]},
    ],
    "stopped": [],
}

it was impossible to grain match something like services:running:*:443
this allows it to.
Add SQLAlchemy key and minion matcher subclasses to avoid per-minion
cache reads, chosen by CkMinions.factory. Route authentication,
publication, clients, runners, and cache consumers through the factory
so the SQLAlchemy implementations are used consistently. Other cache
drivers keep the base implementation.

PostgreSQL selects a superset of candidate cache rows and always applies
subdict_match in Python, preserving case folding, regex, glob, and
serialized-value behavior used by target ACLs. Other dialects retain the
base cache matcher.

Keep key glob matching consistent with Python, including local keys and
display ordering. Ignore invalid key states and expired rows. Preserve
greedy candidate selection and the first connected address per family.
Log and match nothing for PCRE targets that do not compile, rather than
raising.

Provide shared database fixtures and functional matcher coverage across
PostgreSQL, MySQL, SQLite, and the filesystem cache.
Keep full key-glob filtering in PostgreSQL, MySQL, MariaDB and SQLite.
Translate shell wildcards to case-sensitive LIKE plus native regular
expressions, or SQLite GLOB, instead of returning broad prefix candidates
for Python matching.

Batch glob queries with UNION ALL to preserve overlapping and duplicate
matches without dropping SQL filters on large inputs. Batch exact-name
lookups on MySQL, MariaDB and SQLite while keeping PostgreSQL's array
lookup. Include local master keys with full=True and preserve Windows'
native glob normalization. On MySQL and MariaDB, match LIKE under a NO
PAD collation: utf8mb4_bin pads with spaces, so its prefix range skips
keys continuing with a control character.

Delete denied keys from their own bank when deleting all keys, and let
the localfs_key driver flush every key bank rather than stopping at the
first missing one.

Add functional salt.key coverage across the database backends: suffixes,
character classes, case sensitivity, duplicate matches, local keys, large
lists, malformed states, and managed keys filtered by the database. Wire
the database-aware master options into key and matcher tests so each
database parameter exercises the SQLAlchemy implementations, compare
compound targets with direct matching, and centralize driver and Docker
availability skips in the database helper.
Grain and pillar targets on the SQL cache read every cached document and
ran subdict_match in Python, so a target cost the same whether it
matched one minion or the whole fleet.

When Salt stores grains or pillar on PostgreSQL, a Python flattener now
records what subdict_match can match in the document as an array of
terms: values and list members at each path, dictionary keys, and
markers for lists and for data the terms cannot describe, including
floats and sets, which can read back differently from JSONB. A GIN index
over array_to_tsvector(terms) on each bank partition treats every term
as one lexeme, so it answers exact terms and prefix searches of any
length.

A target compiles into certain terms, whose rows match without further
work, and candidate terms, whose rows are rechecked with subdict_match on
only the top-level subtrees it can read. A glob or regular expression
that is a literal followed by a trailing wildcard is answered by the
index alone. Targets the terms cannot restrict, such as wildcard path
segments, scan the cached data, fetching the same subtrees, or whole
documents for targets starting with *. Each fallback is logged and
counted by the salt.targeting.sql.fallback metric.

Lookups query the bank partition directly and disable sequential and
plain index scans, so the planner cannot choose to build every row's
tsvector when most rows match. Rows stream in batches, and results are
returned unsorted. Documents whose terms would pass the tsvector size
limit keep only a recheck marker. Revision 0002 adds the column and
indexes and computes terms for existing rows; rows without terms are
always rechecked through a partial index.

Because the flattener and compiler are Python, property tests check them
against subdict_match directly, with targets derived from paths in the
generated documents. PostgreSQL tests compare targets against the
matcher reading documents back from the database.
Indexing every leaf of large grain documents costs about 145 KB of index
per minion on prod-shaped data, mostly from per-host values nobody
targets. sqlalchemy.term_paths limits terms to listed subtrees and
sqlalchemy.term_exclude leaves subtrees out; by default every path is
indexed. Excluding one inventory subtree cut the cost to about 24 KB per
minion, 23 GB at one million minions.

Targets that read a path without terms are matched by scanning, so
results never change. Ancestors of listed subtrees keep terms for their
own keys and values, because Salt also reads a:b:c as a = "b:c".

Each row records a fingerprint of the configuration its terms were built
with. Lookups only trust certain matches from rows with the current
fingerprint and recheck every other row, through an index on the
fingerprint, so changing the configuration stays correct before the
terms are rebuilt.
During a rolling upgrade, masters without term support keep writing
grains and pillar. Their upserts replace the data but leave the terms
describing the old data, which lookups would trust and so return wrong
minions.

Writers that maintain terms now set salt.cache_terms for their
transaction. A BEFORE UPDATE OF data trigger on the grains and pillar
partitions clears terms and their fingerprint when data changes in a
transaction without that setting, so lookups recheck the row until a
term-aware master stores it again. Downgrade removes the trigger before
the columns it refers to.
Computing terms for every existing grains and pillar row inside the
migration's transaction, then building the indexes with a lock, rewrites
the whole cache in one transaction and blocks writes for the whole index
build, which took 71 minutes at one million minions.

Terms are now computed in committed batches and the indexes are built
afterwards with CREATE INDEX CONCURRENTLY, dropping indexes a previous
interrupted build left invalid. A batch update only applies when the
row's created_at is unchanged since it was read, so a row a master stores
meanwhile keeps the terms that master wrote. Because those steps commit
before the revision is recorded, an interrupted upgrade runs revision
0002 again from the start; the columns are added with IF NOT EXISTS and
the rebuild skips rows whose terms are current, so the rerun completes.

salt-run sqlalchemy.rebuild_terms runs the same rebuild, by default only
for rows whose terms were built for another configuration. It is needed
after changing sqlalchemy.term_paths or term_exclude, and after an
offline upgrade, which cannot compute terms.
The master stores grains and pillar again on every refresh, and the
document is usually unchanged. Each store still wrote a new row version
with new GIN entries for every term.

Cache upserts now keep the stored data when it is not distinct from the
new value, on every supported database, and keep the stored terms when
the new terms are not distinct from them. Data outside the indexed paths,
such as an excluded inventory subtree, can then change without rewriting
the terms. On PostgreSQL the unchanged values are reused and, when no
indexed column changes, the update can be HOT and skip index
maintenance. The cache timestamp still refreshes, so updated() keeps its
semantics.

HOT updates need free space on the row's page, so the grains and pillar
partitions get a fill factor of 80; downgrade resets it. Tests check HOT
updates for an unchanged store and for a change confined to excluded
data with terms large enough to be stored out of line. Ported from the
match-term index branch; comparing terms suggested by Codex review.
A target the terms cannot answer scans every minion that has the path's
first key. At 50,000 prod-shaped minions a target on an excluded
inventory subtree took 88 seconds, roughly half an hour at one million,
holding a master worker the whole time.

sqlalchemy.targeting_timeout (30000 ms by default, 0 to disable) bounds
each grain or pillar target. The database statements get the remaining
time as statement_timeout, and the master checks the deadline every 500
streamed rows, for each recheck, after the stream ends and around the
accepted-minion check. Timeouts are logged as errors and counted by the
salt.targeting.sql.timeout metric.

A timed-out or failed lookup must not match nothing. CkMinions turns
errors into an empty result, and an empty grain or pillar result is
unsafe: a compound "not" built on it matches every minion, validate_tgt
treats an empty requested set as a subset of any ACL, and with syndics
the master publishes even when nothing matched. Minions match grain
targets themselves, so such a publish can run on minions the ACL never
allowed. The SQL matcher therefore wraps any lookup failure in
TargetingError, TargetingTimeout for timeouts, and check_minions lets
that type through ahead of its catch-all, so publishes, compound
targets, auth_check and validate_tgt that need the target fail with an
error. Found by Codex review.
Greedy grain and pillar targets listed every accepted key before
intersecting with the matches, so a target matching 5,000 of a million
minions spent 6 seconds listing keys after a 19 ms lookup, and a compound
target or ACL with several grain terms listed the whole key set once per
term.

The SQL matcher now looks up matches first and asks the key backend which
of them are accepted, through Key.list_match: one query with the SQL key
cache, a read per key with the PKI directory. That makes the cost follow
the number of matches, whichever key backend is configured. Past 10,000
matches for per-key backends, or 250,000 for the SQL key cache, listing
every key once is cheaper and is used instead. A listing is memoized for
the rest of a check_minions or auth_check call, per thread, so it is
made at most once per request. Key lookup errors propagate and fail the
target. Explicit minion lists and non-greedy targets are unchanged.

At one million minions, a target matching 5,000 now takes 224 ms instead
of 5.9 s and one matching 100,000 takes 1.4 s instead of 6.0 s; targets
matching most of the fleet cost what they did.
The compound matcher maps and/or/not onto Python set operators and lets
eval handle precedence and parentheses. Each operand's minion set was
written into the expression as a set literal, so Python serialized and
then parsed every minion id again: for two 100,000-minion operands, about
1.2 seconds and 174 MiB of temporary memory, against 20 ms and 10 MiB
with the sets bound as variables.

Operands are now bound to generated names that eval receives along with
all_minions. The expression's operators, parentheses and validation are
unchanged, and minion ids are no longer spliced into evaluated source. A
test pins compound results for ids containing quotes and braces.
Suggested by Codex review.
The grain trie and the resource id key list rebuild when the bank's
generation changes, read from the mmap_cache header or the mtime of
<cachedir>/<bank>. The cache wrapper exposes a cachedir for every
driver, so with SQL, Redis, Consul or etcd caches the trie was built
under that directory, which the driver never writes. After its first
build the directory mtime stays fixed, the generation matches, and the
trie keeps answering from that first build. Its results are final, so
grain targets on MySQL, MariaDB and SQLite, and resource grain targets
on every SQL backend, returned minions as of the first query.

Report an unknown generation for drivers that do not store banks under
cachedir, so the key list is listed afresh, and skip the trie for them
with a warning when enable_grain_trie_index is set.
salt.key and salt.utils.minions imported salt.sqlalchemy, which loads
SQLAlchemy and the storage models, so every master process spent about
0.2 seconds on those imports even with the localfs cache and key
drivers. Windows starts each master process afresh, so the cost repeats
for every process during master startup.

Move SqlAlchemyKey to salt.sqlalchemy.key and SQLAlchemyCkMinions to
salt.sqlalchemy.minions. salt.key.get_key and CkMinions.factory import
them only when keys.cache_driver or the minion data cache is sqlalchemy.
TargetingError and TargetingTimeout stay in salt.utils.minions, which
raises them through check_minions for every cache driver.
Drop the module-level salt.key import from salt.utils.minions again:
CkMinions imports it in __init__ to avoid an import cycle.
@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 — 2e2eebae Deployed Nov 28, 2026 by mattp- via Build Onedir Packages / DEB (x86_64) #29753
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.

4 participants