Repository navigation
fix(governance): index workflow run history reads and add run retention - #35920
Conversation
The workflow instance states read filtered workflow_instance_state_time_series on entityFQNHash alone, which no index serves, so every call scanned the table and timed out on large installs. It now also filters on the indexed workflowInstanceId. The run list for an entity filtered on the unindexed entityLink TEXT column. The 2.0.7 migration adds idx_wf_instance_entity_link on (md5(entityLink), workflowDefinitionId, timestamp) and the list keys on it. Data Retention gains workflowInstanceRetentionPeriod (default 30 days): ended runs older than the period that have a newer run of the same workflow for the same entity are deleted with their states, in keyset pages.
❌ PR checklist incompleteThis PR cannot be merged until the following are addressed on its linked issue:
The fields live on the linked issue in the Shipping project (open the issue → right sidebar → Projects). After you set them, re-run this check (or push a commit) — issue/project changes do not re-trigger it automatically. Maintainers can bypass this check by adding the |
…d index-key contract
|
Addressed in eb31aa0: added |
✅ Generated Sources Auto-UpdatedThe generated TypeScript types ( |
…live A superseded or cancelled run is marked before its process is deleted, and that delete can fail, so the status alone does not prove the run stopped; an EXCEPTION run may still be retried. Retention now also requires that no ACT_RU_EXECUTION row carries the run id as its business key, checked through ACT_IDX_EXEC_BUSKEY.
…afe Java step The runner records each SQL statement once it succeeds and skips it on a retry, so a SET/PREPARE/EXECUTE guard whose EXECUTE failed or was interrupted reran in a fresh session without its PREPARE and failed on every retry. The entityLinkHash column and idx_wf_instance_entity_link are now added by the 2.0.7 MySQL Java migration, which checks information_schema before each DDL and is rerun until it completes.
The PostgreSQL half of idx_wf_instance_entity_link moves from schemaChanges.sql into the 2.0.7 Java migration next to the MySQL half. An interrupted CREATE INDEX CONCURRENTLY leaves an INVALID index that IF NOT EXISTS skips on every retry; the step now reads pg_index.indisvalid and drops and rebuilds an invalid index. The helper follows the per-version utils/v207/MigrationUtil convention, and the decision record is renamed to cover both databases.
Code Review ✅ Approved 2 closed / 2 findings🔴 High risk · Adding retention deletes expired governance runs and their stages when a newer same-entity run exists, potentially removing records needed for audits or debugging. Adds a shared md5(entityLink) index for the governance run list and stage reads, plus Data Retention for old workflow runs that keeps each entity's latest run per workflow. Two resolved findings: the retention rule and 30-day default now have a decision record, and the retry-safe Java DDL rule no longer cites an ADR that doesn't state it. No open issues found. ✅ 2 closed✅ Quality: Workflow-run retention rule and 30-day default have no decision record
✅ Quality: Retry-safe Java DDL rule is cited to an ADR that does not state it
VerificationRules No rules evaluated Functional validation Not enabledAuto-approval Not enabledFor more verification details, comment OptionsDisplay: compact → Showing compact verification results. Comment with these commands to change the behavior for this request:
Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source |
|
|
…on (2.0 backport #35920) (#36059) * fix(governance): index workflow run history reads and add run retention (#35920) Backport of #35920 to 2.0. The workflow instance states read also filters on the indexed workflowInstanceId; the run list for an entity keys on the new idx_wf_instance_entity_link (md5(entityLink), workflowDefinitionId, timestamp), built by the 2.0.7 Java migration on both engines; Data Retention gains workflowInstanceRetentionPeriod (default 30 days) and deletes an ended run with its states only when no Flowable process of it is alive, it is older than the period, and a newer run of the same workflow exists for the same entity. 2.0 differences: no automation-workflow retention or CANCELLED status; the workflow DAOs live in CollectionDAO. (cherry picked from commit feca176) * chore(governance): review follow-ups for workflow run retention (2.0 backport) - Charge a failed workflow-run retention page as at most one page of runs (WORKFLOW_RUN_PAGE_SIZE), not BATCH_SIZE, in the app run's failed count. - DataRetentionAppIT removes every run, state and live-process row it seeds, also when seeding or the app run fails. - nullOrEmpty over isEmpty(), final on unchanged locals, and named constants for the SQL fragments ListFilterTest asserts. (cherry picked from commit d73ef5f) * test(governance): pin the one-page failure charge for workflow run retention (2.0 backport) drainWorkflowRuns drains workflow-run pages with WORKFLOW_RUN_PAGE_SIZE as the per-page failure charge, and DataRetentionTest makes the run DAO throw and checks that exactly one page is charged. recordDrain holds the shared logging and stats; the new parameters are final. (cherry picked from commit edf56c8)



Describe your changes:
Fixes open-metadata/openmetadata-collate#7630
An entity's governance workflow history panel issues two list reads, and both scanned their table:
1. Run stages time out on large tables.
GET /v1/governance/workflowInstanceStates/{workflowDefinitionName}/{workflowInstanceId}filteredworkflow_instance_state_time_seriesonly onentityFQNHashplus a timestamp range. No index starts withentityFQNHash(the only one holding it isUNIQUE (id, entityFQNHash)), so every call scanned the table — twice, as the count query uses the same filter. With a few million state rows that runs past a 60 s load-balancer timeout. The read now also filters onworkflowInstanceId, which has always been indexed; the hash stays so a definition name that doesn't own the run still matches nothing. No migration is needed for this part.2. The run list for an entity scans every run.
GET /v1/governance/workflowInstances?entityLink=…filtered onentityLink, an unindexed TEXT column. The 2.0.7 migration addsidx_wf_instance_entity_linkon(md5(entityLink), workflowDefinitionId, timestamp)and the endpoint now also filters on the md5, so it is an index lookup.3. Governance workflow run history grows forever. Nothing deleted
workflow_instance_time_series/workflow_instance_state_time_seriesrows (workflowRetentionPeriodcovers automation workflows only). Data Retention getsworkflowInstanceRetentionPeriod(default 30 days, 0 = keep forever). A run is deleted, together with all of its states, only when all hold:ACT_RU_EXECUTIONrow whose business key is the run id, viaACT_IDX_EXEC_BUSKEY). Status alone is not proof: a superseded or cancelled run is marked before its process is deleted and that delete can fail, and an EXCEPTION run may still be retried;Flowable's own
ACT_*tables are not touched.Type of change:
High-level design:
One new index, shared.
idx_wf_instance_entity_link (md5(COALESCE(entityLink,'')), workflowDefinitionId, timestamp)serves both the run list (leading md5 equality) and the retention probe (md5 + workflow equality, timestamp range).entityLinkis unbounded TEXT, so the key is its md5: a Postgres expression index, and on MySQL aVIRTUALgenerated columnentityLinkHash(metadata-only add) with a secondary index.ListFilteremits the matching expression per dialect (entityLinkHashparam); a unit test pins both texts to the migration.A
(entityFQNHash, timestamp)index on the state table was considered and rejected: with theworkflowInstanceIdfilter in place the planner ANDed it with the instance-id index and got slower (see table), for 705 MB of index and a write on every stage transition.Retention — set-based keyset paging.
WorkflowRunRetentionwalks expired runs oldest-first with a(timestamp, id)cursor, 1,000 runs per page:SELECTper page picks the deletable runs; "a newer run of the same workflow for the same entity" is anEXISTSsemi-join probingidx_wf_instance_entity_link— one index probe per candidate, no window function or sort over the table;(timestamp > :afterTs OR (timestamp = :afterTs AND id > :afterId))tie-break and a plaintimestamp >= :afterTs. PostgreSQL cannot start an index range scan from the OR alone; without the plain bound every page walked the timestamp index from the oldest run (measured below);workflowInstanceId IN (…), then runs by primary key. States go first, so a failure between them leaves a run without states (deleted next pass), never orphaned states;BatchDraincap (1,000 pages) bounds one Data Retention run to 1M runs; a larger backlog finishes on the next weekly run.Migration 2.0.7 — one index, built by the 2.0.7 Java migrations (
migration/utils/v207/MigrationUtil, called frommysql/v207/Migrationandpostgres/v207/Migration); bothschemaChanges.sqlfiles only point there. Applied on databases already past 2.1.0 too — the runner applies any unexecuted version. Per ADR:2026-10-22-guarded-index-ddl-runs-from-a-java-data-migration, each step checks the catalog first and a Java data migration is recorded only once it completes, so an interrupted upgrade finishes on the nextmigrate:CREATE INDEX CONCURRENTLY IF NOT EXISTS(no write lock). Ifpg_index.indisvalidshows an INVALID index left by an interrupted concurrent build — whichIF NOT EXISTSalone would skip forever — it is droppedCONCURRENTLYand rebuilt.entityLinkHashVIRTUALcolumn (metadata-only) and the index (InnoDB in place, writes allowed), each only ifinformation_schemashows it missing. NotSET/PREPARE/EXECUTESQL: the runner skips recorded SQL statements on a retry, so a failedEXECUTEcould never be retried.migrateapplies it; after forcing the PostgreSQL index INVALID (or dropping the MySQL index with the column left) and removing the 2.0.7 records, a plainmigraterebuilds a valid index and records 2.0.7.Migration time (measured locally, Docker, warm cache; only
workflow_instance_time_seriesis touched, the states table is not):CREATE INDEX CONCURRENTLY)Build time grows about linearly; expect roughly 2–5× on a managed database with a cold cache (estimate). Writes are not blocked on either engine. The runner sets no statement timeout, so the build runs to completion.
If the step fails or is interrupted:
migrate(production compose files): the run stops, later versions are not applied, and 2.0.7 is not recorded; the nextmigratereruns the step, which carries on from where it stopped (an INVALID PostgreSQL index is dropped and rebuilt).migrate --force: the failure is logged and later versions still run; 2.0.7 is recorded, so on a database already on 2.1 the step is not retried and the index would have to be created by hand.Rollout note. The POJO default is 30, so on upgrade every install whose stored Data Retention config lacks the key starts deleting governance workflow runs older than 30 days (still keeping each entity's latest run per workflow). Set
workflowInstanceRetentionPeriod: 0to opt out.Tests:
Use cases covered
Unit tests
DataRetentionTest#workflowRunRetentionFallsBackToDefaultForConfigsSavedWithoutItListFilterTest#entityLinkHashCondition_matchesTheEntityLinkIndexKeyOnEachDialect,#entityLinkHashCondition_absentWhenNotRequested,#workflowInstanceIdCondition_appliedOnlyWhenRequestedIntegration tests
DataRetentionAppIT#test_retentionRun_deletesExpiredWorkflowRunsButKeepsEachEntitysLatest— seeds 1,202 expired runs (more than one page, kept runs interleaved so the cursor must step over them) and 8 runs that must survive, runs the app, then asserts the exact surviving run set, that each survivor keeps all 3 states and deleted runs leave none, that the states endpoint serves a kept run, nothing for a deleted run and nothing under a definition that doesn't own the run, and that the run list returns exactly the surviving runs for an entity, including one with a non-ASCII name.Results
ListFilterTest61/0 (58 → 61),DataRetentionTest4/0.DataRetentionAppIT, final revision: 5/0 on PostgreSQL + OpenSearch and 5/0 on MySQL + Elasticsearch (fresh failsafe reports, new test present in both).UI — Data Retention configuration
The only UI change is the new field in Settings → Applications → Data Retention → Configuration, rendered from the app's JSON schema, plus its help text. Captured against this branch (server revision
4f9003ef3f, UI from this branch via the Vite dev server) on a fresh MySQL 8.4 + Elasticsearch 9.3 migrated by the real runner (2.0.7 applied,idx_wf_instance_entity_linkpresent).New field with its default (30) and its highlighted help section:
Changed to 45 and saved —
PATCH /api/v1/apps→ 200; the API then returnsworkflowInstanceRetentionPeriod = 45:Query plans and timings
Local PostgreSQL 15 (Docker, warm cache), 7.02M state rows / 1.17M runs. A managed database with a cold cache will be slower; the shapes are what matter.
workflowInstanceStates/{wf}/{id}), dataUNIQUE(id, entityFQNHash), 4.7 sworkflowinstanceid_idx, 0.027 msworkflowInstances?entityLink=), datatimestamp >= :afterTs: 24 msThe run-list and retention rows were measured with the index columns ordered
(workflowDefinitionId, md5(entityLink), timestamp); the final order leads withmd5(entityLink)so the run list, which knows only the definition name, can use it without resolving an id. Both reads use equality on the leading column(s) under either order. On MySQL (200k runs) a retention page took 84 ms: ordered range on the timestamp index,refindex-only probe with a FirstMatch semi-join.The customer database that reported the timeout showed the same: cost 651,549 (Parallel Seq Scan) for the shipped states query against 40 (Index Scan
workflowinstanceid_idx) with theworkflowInstanceIdfilter.🤖 Generated with Claude Code


Confidence Score: 5/5
The PR appears safe to merge; no new blocking issue was found.Summary
The PR speeds up governance history reads and adds configurable cleanup of old runs.
No new actionable issues were found in the changes since the previous review.
Diagram
%%{init: {'theme': 'neutral'}}%% flowchart TD A[Run Java migration] --> B{PostgreSQL index state} B -->|Missing| C[Build index concurrently] B -->|Invalid| D[Drop index concurrently] D --> C B -->|Valid| E[Finish step] C --> E E --> F[Record completed step]Reviews (6) · Last reviewed commit: "refactor(migration): build the 2.0.7 ind..." · Reviewed by Greptile