Skip to content

Fixes #31782: stop pipeline alerts firing for historical and re-ingested executions - #32181

Merged
manerow merged 17 commits into
mainfrom
fix/pipeline-alerts-historical-executions
Sep 3, 2026
Merged

manerow merged 17 commits into
mainfrom
fix/pipeline-alerts-historical-executions

Conversation

@manerow

@manerow manerow commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Describe your changes:

Fixes #31782

An alert on Pipeline filtered to Failed is unusable today. Two symptoms, both reproduced end to end:

  1. Repeat storm. The metadata agent re-sends the same numberOfStatus runs every cycle. addPipelineStatus upserted and returned ENTITY_UPDATED unconditionally, so an identical re-send still emitted a change event and the same failure re-notified forever.
  2. Backfill burst. The first ingestion after an alert is created emits a change event per historical run, and matchPipelineState matched on executionStatus alone, so a run from 40 days ago was indistinguishable from one 40 seconds ago.

Investigating the bulk variant surfaced a third, unfiled defect:

  1. Silent under-alerting on /status/bulk. The endpoint accepts up to 1000 statuses but emitted exactly one change event describing only the newest, so any failure that was not the newest run in a batch never alerted at all.

Type of change:

  • Bug fix

High-level design:

Context. The metadata agent never says what changed: every cycle it re-sends the last numberOfStatus runs of every pipeline. The server turned each PUT into a change event, and the alert engine notified on any event whose executionStatus was Failed. Nothing ever asked "have I seen this?" or "did this run recently?", so one old failure notifies forever. The fix adds those two questions as two gates.

flowchart LR
  A["Metadata agent<br/>re-sends the last N runs<br/>every cycle"] --> B["PUT /pipelines/.../status<br/>PUT /pipelines/.../status/bulk"]
  B --> G1{"Gate 1<br/>identical to what<br/>we already stored?"}
  G1 -- yes --> X1["ENTITY_NO_CHANGE<br/>nothing written, no event"]
  G1 -- no --> W["store status<br/>emit 1 change event per status"]
  W --> G2{"Gate 2<br/>did it execute before<br/>this alert existed?"}
  G2 -- yes --> X2["drop"]
  G2 -- no --> R["evaluate alert rules, notify"]
Loading

Gate 1, stop re-notifying on re-sends (PipelineRepository). Both endpoints compare the incoming status against the stored row and return UNCHANGED / CREATED / UPDATED. UNCHANGED returns ENTITY_NO_CHANGE, which ChangeEventHandler never inserts, so the storm stops at the source. The comparison canonicalises taskStatus order first: the Airflow connector builds that list from a query with no ORDER BY, so a plain List.equals would read a reordered run as "changed" and re-open the storm.

Gate 2, stop notifying on history (AlertUtil). A subscription records a startingTimestamp watermark at creation, and anything that executed earlier is dropped before the rules run.

Why not compare pipelineStatus.timestamp? It is not a clock. For Airflow it is logical_date, the start of the data interval: a @daily DAG running at 03:00 today carries timestamp = yesterday 00:00. Filtering on it would silence that DAG for 24h after you enable the alert, and a monthly one for a month. Across 25 connectors the field means at least six different things, so it is a per-execution key, not a comparable time. Gate 2 therefore derives an effective execution time from real wall clocks:

flowchart TD
  S["PipelineStatus"] --> A{"endTime set?"}
  A -- yes --> U1["use endTime"]
  A -- no --> B{"any task endTime?"}
  B -- yes --> U2["use max task endTime"]
  B -- no --> C{"any task startTime?"}
  C -- yes --> U3["use max task startTime"]
  C -- no --> U4["unknown: fail open, deliver"]
Loading

Failing open is deliberate: a suppression rule that cannot decide must not suppress. Airflow/Composer resolves on the second branch, since that connector never sets a top-level endTime.

Why it is a pre-filter, not a rule. EXCLUDE rules compile to !(condition), so a cut-off inside matchPipelineState would make an EXCLUDE alert fire on exactly the executions it should suppress. It sits in the consumer instead, scoped to Notification and Observability so Custom and GovernanceWorkflowChangeEvent integrations still see everything.

The bulk endpoint was losing failures outright. /status/bulk accepts up to 1000 statuses but emitted one event describing only the newest, so a failure that was not the newest never alerted:

flowchart LR
  subgraph Before
    B1["bulk PUT<br/>Failed, Failed, Success"] --> B2["1 change event<br/>newest only = Success"] --> B3["0 alerts"]
  end
  subgraph After
    A1["bulk PUT<br/>Failed, Failed, Success"] --> A2["3 change events"] --> A3["2 alerts"]
  end
Loading

It now follows one rule: a bulk PUT of N statuses is observationally equivalent to N sequential single PUTs, batching only the DB writes and indexing. Events go through buildChangeEventJsonForBulkOperation + insertChangeEventsBatch, as CSV import and every other bulk operation already do, and the response returns ENTITY_NO_CHANGE so the response filter adds no N+1th event. Offsets stay safe for AbstractEventConsumer.planCursor because insertBatchRows is @Transaction-annotated and commits contiguous offsets in one short transaction, chunked at 100, while the response filter's own insert runs later on a ForkJoinPool and takes a higher offset. Worst case is 1000 events instead of 1, which is the cost of the equivalence rule; after Gate 1 the steady state is zero or one.

Migration. Existing subscriptions are stamped so the fix applies without recreating alerts. It goes in 2.0.2, the next unreleased folder on the 2.0 line. Idempotent (WHERE … startingTimestamp IS NULL), measured at 0 rows on re-run against both engines.

Rejected. Comparing timestamp directly, above. Alerting only on the latest execution (the reporter's third request), because the Before/After diagram is what it would lose. Capping bulk events, because it breaks the equivalence rule.

One coupling worth flagging. The storm removed here had been incidentally rewriting every pipeline execution search document on every ingestion cycle, which masked that index having no reindex coverage. Nothing in the alerting path reads it, so nothing here regresses, but the staleness stops being self-healing once this merges.

Tests:

Use cases covered

  • Identical re-send of a status emits no change event and no notification.
  • Historical backfill after enabling an alert delivers nothing.
  • A run whose logical_date is stale but which just failed still alerts.
  • Bulk emits one event per status, so non-newest failures alert.
  • A status with no taskStatus returns 200 rather than 500 (pre-existing NPE).

Unit tests

mvn -pl openmetadata-service test → 7657 run, 0 failures, 0 errors.

  • PipelineStatusComparisonTest (new, 4): reordered taskStatus, explicit-null inputs, changed status, changed task endTime.
  • StalePipelineExecutionTest (new, 9): stale dropped, recent delivered, the logical-date guard, top-level endTime precedence, fail-open, null watermark, non-pipeline events, EXCLUDE-rule guard, unreadable payload delivered rather than thrown out of the batch.
  • SearchRepositoryBehaviorTest, AlertUtilTest, AbstractEventConsumerTest updated and green.

Each assertion was selected by mutation testing: seven bugs were injected (drop the sort, remove canonicalisation, always-same, always-different, drop the entity-type guard, suppress everything, suppress nothing, drop the alert-type scoping) and only tests that uniquely caught one were kept. Three earlier assertions that caught nothing were deleted.

Backend integration tests

Not applicable: no new REST endpoints. PipelineResource changes only thread the caller's principal through so bulk-emitted events carry the right userName.

Ingestion integration tests

Not applicable: no connector changes.

Playwright (UI) tests

Not applicable: the only UI diff is regenerated types under generated/.

Manual testing performed

On a local deploy of this branch, with an Observability alert on Pipeline filtered to Failed and a webhook destination. Payloads match the Airflow connector's exact field population (timestamp = logical_date, no top-level endTime, per-task startTime/endTime).

Scenario Before After
Backfill 5 failures aged 5-40 days 5 notifications 0
Re-send the identical 5 5 more 0, and no change events
Failure with 24h-old logical_date, just executed 1 1
Bulk [Failed(t-3h), Failed(t-2h), Success(t-1h)] 1 event, 0 alerts 3 events, 2 alerts
Re-send the identical batch 3 events 0
Status without taskStatus HTTP 500 200

Rows 1-3 are the reporter's first two requirements: no alerts for historical failures already in the source, alerts for new failures after monitoring starts. The migration was verified against a live MySQL and a throwaway Postgres 15: it stamps only eventSubscription.Offset rows, leaves the NOT NULL generated timestamp column intact, and touches 0 rows on a second run.

UI screen recording / screenshots:

Not applicable.

Checklist:

  • I have read the CONTRIBUTING document.
  • My PR title is Fixes <issue-number>: <short explanation>
  • My PR is linked to a GitHub issue via Fixes #31782 above.
  • I have commented on my code, particularly in hard-to-understand areas.
  • For JSON Schema changes: I updated the migration scripts or explained why it is not needed.
  • I have added tests (unit / integration / Playwright as applicable) and listed them above.
  • I have added a test that covers the exact scenario we are fixing.

Greptile Summary

The PR suppresses duplicate pipeline-status events and historical execution alerts while changing bulk status ingestion to emit one event per changed execution.

  • Adds subscription-start watermarks and filters pipeline executions using available wall-clock completion times.
  • Compares incoming statuses with stored canonical representations to avoid events for unchanged re-ingestion.
  • Persists and indexes changed bulk statuses and emits their change events in bounded batches.
  • Adds schema documentation, upgrade migrations, and focused tests for comparison and stale-execution behavior.

Confidence Score: 4/5

The PR is not yet safe to merge because a bulk event-insertion failure can permanently suppress alerts for statuses that were already committed.

Pipeline statuses commit before change-event insertion, insertion failures are logged without propagation, and subsequent identical ingestion skips event regeneration as unchanged.

Files Needing Attention: openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/PipelineRepository.java; openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java

Important Files Changed

Filename Overview
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/PipelineRepository.java Adds canonical status comparison, changed-only persistence, bulk event generation, and staged-index routing.
openmetadata-service/src/main/java/org/openmetadata/service/events/subscription/AlertUtil.java Adds alert-type-scoped historical pipeline execution filtering using effective wall-clock execution times.
openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/changeEvent/AbstractEventConsumer.java Loads, preserves, and applies the subscription starting timestamp during event filtering.
openmetadata-service/src/main/java/org/openmetadata/service/events/scheduled/EventSubscriptionScheduler.java Applies the same subscription watermark when counting and listing relevant unprocessed events.
bootstrap/sql/migrations/native/2.0.0/mysql/schemaChanges.sql Backfills missing subscription starting timestamps for existing MySQL offset records.
bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql Backfills missing subscription starting timestamps for existing PostgreSQL offset records.
openmetadata-spec/src/main/resources/json/schema/events/eventSubscriptionOffset.json Adds the optional subscription starting-timestamp contract used by historical-event filtering.

Sequence Diagram

sequenceDiagram
    participant Agent as Metadata Agent
    participant API as Pipeline Status API
    participant Repo as PipelineRepository
    participant DB as Status Store
    participant Events as Change Event Store
    participant Alerts as Alert Consumer
    Agent->>API: PUT status or status/bulk
    API->>Repo: Authorized status update
    Repo->>DB: Compare with stored execution
    alt Identical status
        Repo-->>API: ENTITY_NO_CHANGE
    else New or changed status
        Repo->>DB: Upsert status
        Repo->>Events: Insert one event per status
        Events->>Alerts: Consume event
        Alerts->>Alerts: Drop execution older than subscription watermark
    end
Loading

Reviews (3): Last reviewed commit: "docs(pipeline): tighten the wall-clock n..." | Re-trigger Greptile

@manerow
manerow requested a review from a team as a code owner August 27, 2026 13:04
@github-actions github-actions Bot added backend safe to test Add this label to run secure Github workflows on PRs labels Aug 27, 2026
@manerow manerow self-assigned this Aug 27, 2026
@manerow
manerow force-pushed the fix/pipeline-alerts-historical-executions branch from fe37abb to 2f2bae7 Compare August 27, 2026 13:32
@github-actions

github-actions Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Jest test Coverage

UI tests summary

Lines Statements Branches Functions
Coverage: 67%
67.93% (88459/130206) 52% (54441/104683) 53.63% (16657/31056)

@gitar-bot

gitar-bot Bot commented Sep 2, 2026

Copy link
Copy Markdown
Code Review 👍 Approved with suggestions 2 resolved / 3 findings

Stops pipeline alerts from firing on historical and re-ingested executions by adding comparison gates and execution time filters. Consider optimizing the bulk status serializer to avoid redundant deep copies and documenting the side effect in getStartingOffset.

💡 Quality: getStartingOffset now performs a DB write from a read-style method

📄 openmetadata-service/src/main/java/org/openmetadata/service/events/subscription/AlertUtil.java:320-334

getStartingOffset was previously a pure computation; it now upserts a new offset row (with startingTimestamp=now) when none exists. It is invoked from multiple callers including AbstractEventConsumer.loadInitialOffset and EventSubscriptionScheduler paths. Concurrent first-time calls can race to upsert (idempotent, so tolerable) but the hidden write is surprising for a getter and can persist a watermark from whichever caller hits it first. Consider renaming/documenting the side effect, or ensuring the watermark is only ever established at subscription creation (syncEventSubscriptionOffset already stamps it).

✅ 2 resolved
✅ Edge Case: Stale-check adds a new throw site inside the batch filter stream

📄 openmetadata-service/src/main/java/org/openmetadata/service/events/subscription/AlertUtil.java:353-367 📄 openmetadata-service/src/main/java/org/openmetadata/service/events/subscription/AlertUtil.java:297-311
checkIfChangeEventIsAllowed now runs isStalePipelineExecution first, which calls JsonUtils.convertValue(fieldChange.getNewValue(), PipelineStatus.class). This executes inside the getFilteredEvents stream — the exact stream AlertsRuleEvaluatorDeletedEntityIT protects because a throw there drops the whole delivery batch. A malformed/unexpected pipelineStatus payload would now abort delivery of every event in the batch rather than just failing to match. Consider wrapping the conversion in a try/catch that fails open (returns false → not stale) so a single bad payload cannot silence an entire batch.

✅ Performance: Bulk status emits a full-entity deep copy per status (up to 1000x)

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/PipelineRepository.java:423-436 📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/PipelineRepository.java:353-361
buildStatusChangeEvent runs JsonUtils.deepCopy(pipeline, Pipeline.class) for every changed status in the batch. A 1000-record bulk request performs up to 1000 serialize+parse round-trips of the entire pipeline entity (including all tasks), and each resulting change event stores the full entity payload. For pipelines with many tasks this is a notable per-request cost. Consider serializing the pipeline once and reusing/cloning the base JSON, or only copying the fields the change event needs.

🤖 Prompt for agents
Code Review: Stops pipeline alerts from firing on historical and re-ingested executions by adding comparison gates and execution time filters. Consider optimizing the bulk status serializer to avoid redundant deep copies and documenting the side effect in `getStartingOffset`.

1. 💡 Quality: getStartingOffset now performs a DB write from a read-style method
   Files: openmetadata-service/src/main/java/org/openmetadata/service/events/subscription/AlertUtil.java:320-334

   getStartingOffset was previously a pure computation; it now upserts a new offset row (with startingTimestamp=now) when none exists. It is invoked from multiple callers including AbstractEventConsumer.loadInitialOffset and EventSubscriptionScheduler paths. Concurrent first-time calls can race to upsert (idempotent, so tolerable) but the hidden write is surprising for a getter and can persist a watermark from whichever caller hits it first. Consider renaming/documenting the side effect, or ensuring the watermark is only ever established at subscription creation (syncEventSubscriptionOffset already stamps it).

Options

Display: compact → Showing less information.

Comment with these commands to change the behavior for this request:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source

@sonarqubecloud

sonarqubecloud Bot commented Sep 2, 2026

Copy link
Copy Markdown

@sonarqubecloud

sonarqubecloud Bot commented Sep 2, 2026

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

🚦 Removed from the merge queue — failed_checks (2026-09-02T14:58:20Z)

Blocked the queue: playwright-summary

@github-actions

github-actions Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

🚦 Removed from the merge queue — failed_checks (2026-09-03T02:04:19Z)

Blocked the queue: py-tests-status

  • py-tests-postgres — python / Integration Tests (shard-2), python / Integration Tests (shard-2)
  • py-tests — py-tests-status, python / Verify Expected Jobs, python / Integration Tests (shard-2), python / Integration Tests (shard-2), python / Integration Tests (shard-2)

@github-actions

github-actions Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Failed to cherry-pick changes to the 1.13 branch.
Please cherry-pick the changes manually.
You can find more details here.

@github-actions

github-actions Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Failed to cherry-pick changes to the 2.0 branch.
Please cherry-pick the changes manually.
You can find more details here.

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend safe to test Add this label to run secure Github workflows on PRs To release Will cherry-pick this PR into the release branch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Pipeline alerts fire for historical executions ingested by the metadata agent

2 participants