Skip to content

fix(alerts): read change events up to a byte budget, not only a row count - #36268

Closed
manerow wants to merge 1 commit into
mainfrom
fix/alerts-byte-bounded-reads
Closed

manerow wants to merge 1 commit into
mainfrom
fix/alerts-byte-bounded-reads

Conversation

@manerow

@manerow manerow commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

What was wrong

Alerts, the audit log consumer and the alert diagnostics read change events with ChangeEventDAO.listWithOffset(limit, afterOffset). That read was bounded only by its row count:

  • An alert's stored batchSize is passed straight through as the SQL LIMIT, and nothing bounds it.
  • Every change event embeds the whole entity that changed. So even 100 rows can be hundreds of megabytes when the entities are large, and one read can fill the heap.

What this changes

listWithOffset itself now enforces two limits, so every caller gets them from one place:

  • At most 1000 rows (MAX_ROWS_PER_READ), whatever the caller asks for.
  • At most 8 MB of event JSON (MAX_BYTES_PER_READ), except that it always returns at least one event, so a single very large event is still delivered.

It reads in two steps:

  1. The offsets and stored sizes of the next events (LENGTH(json) on MySQL, octet_length(json::text) on Postgres), without loading the JSON.
  2. The JSON of the leading events that fit the budget, by their exact offsets.

The events left out are simply the first ones of the next read. The consumer's position only moves across events it has read, so nothing is skipped. Fetching by exact offsets, rather than by range, keeps the bound even when new events appear between the two steps. An event deleted between the two steps shows up as a gap, which the existing gap handling already covers.

pollEvents no longer casts the stored batchSize to int, so an out-of-range value is clamped instead of wrapping around.

What users see

Nothing for normal alerts. With the default batchSize of 100, a read only stops early when the next events average more than 80 KB each. Then those events are delivered over a few more ticks instead of one, still in order and all of them.

Tests

  • ChangeEventReadBudgetTest (unit): the cut keeps a prefix, always keeps the first event, stops before the event that would pass the budget, and the read never asks for more than 1000 rows.
  • ChangeEventReadBudgetIT (new, failed on main): three 5 MB events are delivered one per tick, in order (main delivered all three in the first tick).
  • DispatchOrderTest and DiagnosticsTest now stub the read with anyLong(), because the limit is a long.
  • Passing on MySQL and Postgres: the alert tick, dispatch, delivery, running-tick, time-budget and resource integration tests.

A backport to 2.0 follows in a separate PR.

RetriggerView in GreptileConfidence Score: 4/5

Fix the audit consumer’s short-page handling before merging; it now stops catch-up while events remain.

Findings

  1. P1 Audit catch-up stops early ▶
  2. P2 Test alert remains enabled ▶

Summary

Adds a shared byte budget to change-event reads.

  • Change-event reads stop at a row and byte budget.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Caller requests events after an offset] --> B[Clamp row limit to 1 through 1000]
  B --> C[Read offsets and JSON sizes]
  C --> D[Keep leading events within 8 MiB]
  D --> E[Always keep the first event]
  E --> F[Fetch JSON by exact offsets]
  F --> G[Return events in offset order]
Loading

Reviews (1) · Last reviewed commit: "fix(alerts): read change events up to a ..." · Reviewed by Greptile

@manerow
manerow requested a review from a team as a code owner October 26, 2026 14:39
@manerow
manerow requested a review from mohityadav766 October 26, 2026 14:39
@manerow manerow added safe to test Add this label to run secure Github workflows on PRs backend labels Oct 26, 2026
@github-actions

Copy link
Copy Markdown
Contributor

❌ PR checklist incomplete

This PR cannot be merged until the following are addressed on its linked issue:

  • No GitHub issue is linked. Link an issue in the Development section of the PR (or add Fixes #12345 to the description). For a same-org cross-repo issue, add Fixes open-metadata/<repo>#123 to the description.

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 skip-pr-checks label.

Comment on lines +1278 to +1292
/** The most change events one read returns, whatever the caller asks for. */
int MAX_ROWS_PER_READ = 1000;

/** The most bytes of change event JSON one read loads, except that it always loads one. */
long MAX_BYTES_PER_READ = 8L * 1024 * 1024;

/**
* Returns the change events after {@code afterOffset} in offset order, with their offsets for
* cursor tracking. A read stops at {@link #MAX_ROWS_PER_READ} events and at {@link
* #MAX_BYTES_PER_READ} bytes, because each event embeds a whole entity: the events it leaves
* out are the first ones the next read returns.
*/
default List<ChangeEventRecord> listWithOffset(long limit, long afterOffset) {
int rows = Math.clamp(limit, 1, MAX_ROWS_PER_READ);
List<Long> offsets =

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Quality: New 1000-row / 8 MB change-event read limits are not recorded

This PR adds limits that other code depends on and that were chosen by judgment: MAX_ROWS_PER_READ = 1000 and MAX_BYTES_PER_READ = 8 MB, with a rule that a read always returns at least one event. Every caller of ChangeEventDAO.listWithOffset (alerts, AuditLogConsumer, UnprocessedEvents) now runs under them. No record in docs/decisions/ covers change-event read limits; the alert records there are about consumer ids and UI widgets. The rule only appears in the PR description ("At most 1000 rows ... At most 8 MB of event JSON, except that it always returns at least one event"), and that description is lost when the PR is squash-merged.

The record should say: "A change-event read (ChangeEventDAO.listWithOffset) returns at most 1000 rows and at most 8 MB of stored event JSON, measured as LENGTH(json) / octet_length(json::text). It always returns at least the first event. The events it leaves out are the first ones of the next read, so callers must not treat a short read as being caught up."

Was this helpful? React with 👍 / 👎

Comment on lines +1290 to +1295
default List<ChangeEventRecord> listWithOffset(long limit, long afterOffset) {
int rows = Math.clamp(limit, 1, MAX_ROWS_PER_READ);
List<Long> offsets =
offsetsWithinBudget(listSizesAfter(rows, afterOffset), MAX_BYTES_PER_READ);
return offsets.isEmpty() ? List.of() : listByOffsets(offsets);
}

@gitar-bot gitar-bot Bot Oct 26, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Bug: AuditLogConsumer reads a byte-truncated batch as "caught up"

AuditLogConsumer.execute stops its catch-up loop when processed < BATCH_SIZE ("If we processed less than a full batch, we're caught up"). listWithOffset can now return fewer than 100 rows while there is still a backlog, whenever the next events add up to more than 8 MB. So with a backlog of large events, each run reads roughly 8 MB, breaks out of the loop, and waits a full schedule interval instead of using its 10 batches. Audit-log lag then grows while large entities are being changed.

Fix: decide "caught up" from the offset rather than the row count. For example, stop when nothing was processed or when the stored offset has reached changeEventDAO().getLatestOffset(). Or have processBatch report whether its read was cut short by the byte budget.

Stop the loop on an empty read or once the latest offset is reached, not on a short batch:

if (processed == 0
    || loadOffsetFromDatabase(collectionDAO).currentOffset()
        >= collectionDAO.changeEventDAO().getLatestOffset()) {
  break;
}

Was this helpful? React with 👍 / 👎

@gitar-bot

gitar-bot Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Code Review ⚠️ Changes requested 0 closed / 2 findings

🟡 Medium risk · Capping event reads by rows and bytes may delay alert and audit-event processing when large payloads require additional ticks.

Caps change-event reads at 1000 rows and 8 MB of event JSON so large entities can't exhaust the heap during alert and audit-log reads. Changes requested: the new read limits are not recorded in docs/decisions/, and AuditLogConsumer treats a byte-truncated batch under 100 rows as caught up, so it can stall for a full schedule interval while a backlog of large events remains.

⚠️ Quality: New 1000-row / 8 MB change-event read limits are not recorded

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/AccessControlDAOs.java:1278-1292

This PR adds limits that other code depends on and that were chosen by judgment: MAX_ROWS_PER_READ = 1000 and MAX_BYTES_PER_READ = 8 MB, with a rule that a read always returns at least one event. Every caller of ChangeEventDAO.listWithOffset (alerts, AuditLogConsumer, UnprocessedEvents) now runs under them. No record in docs/decisions/ covers change-event read limits; the alert records there are about consumer ids and UI widgets. The rule only appears in the PR description ("At most 1000 rows ... At most 8 MB of event JSON, except that it always returns at least one event"), and that description is lost when the PR is squash-merged.

The record should say: "A change-event read (ChangeEventDAO.listWithOffset) returns at most 1000 rows and at most 8 MB of stored event JSON, measured as LENGTH(json) / octet_length(json::text). It always returns at least the first event. The events it leaves out are the first ones of the next read, so callers must not treat a short read as being caught up."

💡 Bug: AuditLogConsumer reads a byte-truncated batch as "caught up"

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/AccessControlDAOs.java:1290-1295

AuditLogConsumer.execute stops its catch-up loop when processed < BATCH_SIZE ("If we processed less than a full batch, we're caught up"). listWithOffset can now return fewer than 100 rows while there is still a backlog, whenever the next events add up to more than 8 MB. So with a backlog of large events, each run reads roughly 8 MB, breaks out of the loop, and waits a full schedule interval instead of using its 10 batches. Audit-log lag then grows while large entities are being changed.

Fix: decide "caught up" from the offset rather than the row count. For example, stop when nothing was processed or when the stored offset has reached changeEventDAO().getLatestOffset(). Or have processBatch report whether its read was cut short by the byte budget.

Stop the loop on an empty read or once the latest offset is reached, not on a short batch
if (processed == 0
    || loadOffsetFromDatabase(collectionDAO).currentOffset()
        >= collectionDAO.changeEventDAO().getLatestOffset()) {
  break;
}
🤖 Prompt for agents
Code Review: Caps change-event reads at 1000 rows and 8 MB of event JSON so large entities can't exhaust the heap during alert and audit-log reads. Changes requested: the new read limits are not recorded in `docs/decisions/`, and `AuditLogConsumer` treats a byte-truncated batch under 100 rows as caught up, so it can stall for a full schedule interval while a backlog of large events remains.

1. ⚠️ Quality: New 1000-row / 8 MB change-event read limits are not recorded
   Files: openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/AccessControlDAOs.java:1278-1292

   This PR adds limits that other code depends on and that were chosen by judgment: `MAX_ROWS_PER_READ = 1000` and `MAX_BYTES_PER_READ = 8 MB`, with a rule that a read always returns at least one event. Every caller of `ChangeEventDAO.listWithOffset` (alerts, `AuditLogConsumer`, `UnprocessedEvents`) now runs under them. No record in `docs/decisions/` covers change-event read limits; the alert records there are about consumer ids and UI widgets. The rule only appears in the PR description ("At most 1000 rows ... At most 8 MB of event JSON, except that it always returns at least one event"), and that description is lost when the PR is squash-merged.
   
   The record should say: "A change-event read (`ChangeEventDAO.listWithOffset`) returns at most 1000 rows and at most 8 MB of stored event JSON, measured as `LENGTH(json)` / `octet_length(json::text)`. It always returns at least the first event. The events it leaves out are the first ones of the next read, so callers must not treat a short read as being caught up."

2. 💡 Bug: AuditLogConsumer reads a byte-truncated batch as "caught up"
   Files: openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/AccessControlDAOs.java:1290-1295

   `AuditLogConsumer.execute` stops its catch-up loop when `processed < BATCH_SIZE` ("If we processed less than a full batch, we're caught up"). `listWithOffset` can now return fewer than 100 rows while there is still a backlog, whenever the next events add up to more than 8 MB. So with a backlog of large events, each run reads roughly 8 MB, breaks out of the loop, and waits a full schedule interval instead of using its 10 batches. Audit-log lag then grows while large entities are being changed.
   
   Fix: decide "caught up" from the offset rather than the row count. For example, stop when nothing was processed or when the stored offset has reached `changeEventDAO().getLatestOffset()`. Or have `processBatch` report whether its read was cut short by the byte budget.

   Fix (Stop the loop on an empty read or once the latest offset is reached, not on a short batch):
   if (processed == 0
       || loadOffsetFromDatabase(collectionDAO).currentOffset()
           >= collectionDAO.changeEventDAO().getLatestOffset()) {
     break;
   }

Verification

Rules No rules evaluated

Functional validation Not enabled

Set up

Auto-approval Not enabled

Set up

For more verification details, comment gitar display:verbose.

Options

Display: compact → Showing compact verification results.

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

Comment on lines +1292 to +1294
List<Long> offsets =
offsetsWithinBudget(listSizesAfter(rows, afterOffset), MAX_BYTES_PER_READ);
return offsets.isEmpty() ? List.of() : listByOffsets(offsets);

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.

P1 Audit catch-up stops early

listWithOffset now returns short pages while more events remain, but AuditLogConsumer.execute still stops whenever processed < BATCH_SIZE. With queued 5 MiB events, it reads one event and waits for the next five-second poll instead of continuing its ten-batch catch-up loop. If such events arrive faster than one per poll, the audit backlog grows.

Update the audit consumer to distinguish a budget-limited page from an exhausted queue, while keeping its batch and error limits.

Comment on lines +30 to +35
EventSubscription alert =
AlertFixtures.tableAlert(
ns,
"read_budget",
null,
List.of(AlertFixtures.external(WEBHOOK, receiver.url("/webhook"))));

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.

P2 Test alert remains enabled

This test creates an enabled alert but never deletes it. TestNamespaceExtension only cleans tracked roots, and this alert is not tracked. Once RecordingReceiver closes, the saved alert and its daily job still point to a stopped server. Repeated runs leave these alerts and jobs on shared test servers.

Delete the alert in a finally block so both passing and failing runs clean up.

@manerow

manerow commented Oct 26, 2026

Copy link
Copy Markdown
Contributor Author

Folded into PR #36279, which now carries all the alerting bounds in one change.

@manerow manerow closed this Oct 26, 2026
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant