Repository navigation
Conversation
e0c1ccb to
9b8f4df
Compare
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) |
|
Got some pre-commit and lint failures |
|
Looks like there are some Lint failures |
|
@twangboy should be fixed now 👍 remaining fails are from the new release / master missing mergeforward thing again. |
|
Please rebase and resolve conflicts |
|
Is there a plan to merge this into version 3008? |
|
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- I'd like to merge these, can you please rebase? |
|
please rebase and fix conflicts |
twangboy
left a comment
There was a problem hiding this comment.
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:
- Missing
expires_aton Initial Insert: Line 134 insertsCachewithout passingexpires_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. - High Exception/Rollback Overhead: Relying on
IntegrityErrorcatch-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:
- 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). RETURNINGClause 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()updatesdata=databut omits updatingexpires_ator updatingcreated_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.portandsqlalchemy.ro_portare typed strictly asstr(orNone). 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...
|
@twangboy thanks for review 👍 this pr is rebased, but I'll have to see the CI fallout and address later |
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.
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