Skip to content

Make search embeddings, reindex auto-tune, and audit export resilient on any pod size - #29833

Merged
mohityadav766 merged 23 commits into
mainfrom
fix/embedding-provider-circuit-breaker
Jul 15, 2026
Merged

mohityadav766 merged 23 commits into
mainfrom
fix/embedding-provider-circuit-breaker

Conversation

@mohityadav766

@mohityadav766 mohityadav766 commented Jul 8, 2026 •

Copy link
Copy Markdown
Member

Three search/export-side reliability fixes that all surfaced as collate server OOMKills / restarts — under an unreachable embedding provider, a memory-constrained pod, and concurrent audit-log exports.

1. Embedding provider circuit breaker

When an embedding provider is persistently unavailable — e.g. AWS Bedrock AccessDeniedException when the deployment's role has no Bedrock permission, throttling, or an outage — the vector pipeline called the provider for every entity lifecycle event with no back-off (observed ~12 failures/sec, each a full stack trace, continuously), burning threads/CPU and flooding logs.

  • Provider-agnostic circuit breaker in EmbeddingClient: after 5 consecutive failures (or immediately on a permanent auth/config failure) the circuit opens and embed() fast-fails with EmbeddingUnavailableException without a provider call — one WARN + a search.embedding.circuit_opened metric instead of per-entity stack traces. Half-opens after a cooldown (60s transient / 300s permanent) and closes on recovery.
  • BedrockEmbeddingClient classifies 401/403/404 as permanent and drops its per-call error stack traces to debug.
  • OpenSearchVectorService skips embedding work entirely while the circuit is open, so entities are still indexed without vectors and enrichment resumes automatically.

2. Container-aware reindex auto-tune memory bound

SearchClusterMetrics auto-tune sized reindex memory against the JVM heap (Runtime.getRuntime().maxMemory() = -Xmx) and capped concurrency and payload size independently, but never bounded their product. Bulk-request payloads are held largely in off-heap direct buffers, so concurrentRequests × maxPayloadSize (up to ~cores×10 × ~90 MB ≈ 3.6 GB) could exceed the container cgroup limit while the heap looked fine → OOMKilled (137). Auto-tune never read the pod's own memory ceiling, so it did not "just work" on memory-constrained pods.

  • Cap concurrent bulk requests so concurrentRequests × maxPayloadSize fits half the off-heap headroom (containerLimit − maxHeap), reading the container limit from com.sun.management.OperatingSystemMXBean.getTotalMemorySize() (container-aware with UseContainerSupport). Applied to both the metrics-based and conservative-default paths.
  • Added an off-heap in-flight bulk-memory estimate to the recommendation log (it previously logged only queue heap, blind to its biggest consumer).

3. Audit-log export streaming + spool download

Concurrent audit-log exports (GET /v1/audit/logs/export) were the actual driver of the nightly restarts. The handler loaded up to 100,000 AuditLogEntry records into a List, serialized the whole thing to one JSON String, and sent it inline over the csvExportChannel WebSocket — on the shared async executor. Under parallel exports (e.g. 4 Playwright shards) these multi-hundred-MB payloads piled up as G1 humongous byte[]: first exhausting the heap (Java OOM + dump), and — once concurrency alone was bounded — the off-heap netty send buffer (OOMKilled 137). Reproduced locally end-to-end: ~45 concurrent exports produced a 3.8 GB heap dump whose byte[] are exactly the csvExportChannel audit payloads. This path was never covered by the entity/search CSV-export spool fix.

  • AuditLogRepository.streamExportAsJson writes each 1000-row batch straight to a CsvExportSpool file (one batch in heap at a time), never materializing the full list or string.
  • The COMPLETED WebSocket event now carries only a download reference (data: null) instead of the inline payload; a new GET /v1/audit/logs/export/{jobId}/result streams the spooled file via StreamingOutput.
  • A dedicated 2-thread AUDIT_EXPORT_EXECUTOR also caps how many exports run at once (DB load / spool writers), mirroring the entity/search CSV export's already-bounded worker pool.

Frontend follow-up (separate UI PR): useCSVExportWebSocket should download the audit export from the result endpoint on the COMPLETED event, the same way the entity/search CSV export already does.

Tests

  • EmbeddingClientTest: circuit opens after N failures / opens immediately on a permanent failure / recovers when the provider returns.
  • SearchClusterMetricsTest: boundConcurrentRequestsToMemory shrinks concurrency to the off-heap budget, leaves it untouched when memory is ample, and degrades to serial when there's no headroom.
  • Audit export: verified by the concurrent-export reproduction — the 150-concurrent hammer that previously OOM'd (3.8 GB heap dump, then OOMKilled) now leaves the server running (peak G1 humongous 322, GC'd to ~3) and the 180 MB result downloads correctly.

Verifying in AUT

Both surfaced in the AUT nightly (Bedrock unauthorized). With the circuit breaker deployed, the BedrockEmbeddingClient log flood dropped from thousands/5min to ~0 and search.embedding.circuit_opened engaged; the auto-tune bound addresses the reindex-time off-heap OOM on memory-constrained pods; and the audit-export streaming fix targets the confirmed root cause of the nightly restarts — the captured heap dump's byte[] are csvExportChannel audit payloads.

🤖 Generated with Claude Code


Summary by Gitar

  • Embedding circuit breaker:
    • Added EmbeddingClient circuit breaker to handle transient/permanent provider failures.
    • Implemented isAvailable() check in OpenSearchVectorService and VectorDocBuilder to skip embedding work during outages.
    • Added EmbeddingUnavailableException for fast-failure and ensured BedrockEmbeddingClient identifies non-retryable status codes.
  • Bulk reindexing safety:
    • Added boundConcurrentRequestsToMemory and boundQueueSizeToHeap to SearchClusterMetrics to prevent OOMs by sizing buffers against container limits and JVM heap.
  • Audit log reliability:
    • Replaced in-memory List<AuditLogEntry> exports with streamExportAsJson using CsvExportSpool to prevent heap exhaustion.
    • Added MAX_CONCURRENT_AUDIT_EXPORTS = 2 and a dedicated AUDIT_EXPORT_EXECUTOR to bound resource contention.
    • Added downloadAuditExportResult endpoint to retrieve spooled files via StreamingOutput after receiving completion notifications.

This will update automatically on new commits.

Greptile Summary

This PR makes search embeddings, reindex sizing, and audit export more resilient. The main changes are:

  • Added an embedding provider circuit breaker and outage-aware vector indexing paths.
  • Bounded reindex bulk concurrency and queue size using container and heap memory estimates.
  • Streamed audit-log exports to spool files with a result download endpoint.
  • Added tests for embedding circuit behavior, reindex memory bounds, and vector outage handling.

Confidence Score: 4/5

This is close, but the search outage path should be fixed before merging.

  • The indexing and chunk-update paths now avoid destructive chunk replacement during embedding outages.
  • The half-open circuit path now limits recovery probing.
  • Semantic search can still fail the request when query embedding fast-fails through the new circuit path.

openmetadata-service/src/main/java/org/openmetadata/service/search/vector/client/EmbeddingClient.java and the semantic search caller in OpenSearchVectorService

Important Files Changed

Filename Overview
openmetadata-service/src/main/java/org/openmetadata/service/search/vector/client/EmbeddingClient.java Adds circuit-breaker state handling for embedding calls, but query embeddings can now fast-fail a search request during an outage.
openmetadata-service/src/main/java/org/openmetadata/service/search/vector/OpenSearchVectorService.java Skips unavailable embedding work for indexing paths and catches chunk-build outages, while the search path still needs outage handling.
openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorDocBuilder.java Uses an explicit unavailable exception instead of returning an empty chunk list during provider outages.
openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSink.java Avoids generating new embeddings during reindex when the provider circuit is unavailable.
openmetadata-service/src/main/java/org/openmetadata/service/search/SearchClusterMetrics.java Adds memory-aware bounds for reindex concurrency and queue sizing.
openmetadata-service/src/main/java/org/openmetadata/service/audit/AuditLogRepository.java Streams audit export JSON directly to an output stream.
openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java Runs audit exports on a bounded executor and exposes a spooled result download endpoint.

Comments Outside Diff (2)

  1. openmetadata-service/src/main/java/org/openmetadata/service/search/vector/client/EmbeddingClient.java, line 86-88 (link)

    P1 embedQuery bypasses the circuit breaker

    embedQuery calls embedWithLimit(() -> doEmbedQuery(text)) directly, skipping guardCircuit(). The circuit can be open while embedQuery still issues provider calls — every semantic search query routed through OpenSearchVectorService.search() (which calls embeddingClient.embedQuery(query)) will keep hitting a failed provider and propagate as an uncaught RuntimeException, rather than receiving the fast-fail EmbeddingUnavailableException the entity-write path now correctly gets. embedQuery needs to call guardCircuit() and route through recordSuccess/recordFailure the same way the new embed method does.

  2. openmetadata-service/src/main/java/org/openmetadata/service/search/vector/client/EmbeddingClient.java, line 78 (link)

    P1 Search fast-fails

    embedQuery() now goes through the circuit breaker, but the semantic search caller does not handle the new fast-fail exception. When the provider circuit is open, OpenSearchVectorService.search() calls embeddingClient.embedQuery(query) before its OpenSearch error handling and can let EmbeddingUnavailableException escape as a server error. Search should degrade cleanly while embeddings are unavailable instead of failing the request.

Reviews (21): Last reviewed commit: "Merge branch 'main' into fix/embedding-p..." | Re-trigger Greptile

Context used (3)

  • Context used - CLAUDE.md (source)
  • Context used - openmetadata-ui-core-components/CLAUDE.md (source)
  • Context used - AGENTS.md (source)

When an embedding provider is persistently unavailable (e.g. Bedrock
AccessDenied when the deployment lacks Bedrock permission, throttling, or an
outage), the vector pipeline previously called the provider for every entity
lifecycle event with no back-off, flooding logs with per-entity stack traces
and burning threads/CPU.

Add a provider-agnostic circuit breaker in EmbeddingClient: after five
consecutive failures (or immediately on a permanent auth/config failure) the
circuit opens and embed() fast-fails with EmbeddingUnavailableException without
a provider call; it half-opens after a cooldown and closes on recovery.
BedrockEmbeddingClient classifies 401/403/404 as permanent and drops its
per-call error stack traces to debug. OpenSearchVectorService skips embedding
work entirely while the circuit is open, so entities are still indexed without
vectors during an outage and enrichment resumes automatically on recovery.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings July 8, 2026 09:38
@github-actions

github-actions Bot commented Jul 8, 2026

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.

@github-actions github-actions Bot added backend safe to test Add this label to run secure Github workflows on PRs labels Jul 8, 2026

Copilot AI left a comment

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.

Pull request overview

This PR introduces a provider-agnostic circuit breaker in the shared EmbeddingClient to prevent repeated embedding-provider calls (and stack-trace log flooding) during persistent outages/misconfiguration, while allowing automatic recovery once the provider becomes healthy again.

Changes:

  • Add a circuit breaker to EmbeddingClient (failure threshold, open/half-open/closed state, cooldowns) with a new EmbeddingUnavailableException for fast-fail while open.
  • Update OpenSearchVectorService to skip embedding work when the provider is unavailable and to treat the new exception as a soft/skip condition.
  • Update BedrockEmbeddingClient to classify certain HTTP statuses as permanent failures and reduce per-call error logging; add unit tests validating circuit behavior.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
openmetadata-service/src/main/java/org/openmetadata/service/search/vector/client/EmbeddingClient.java Adds circuit-breaker state machine, cooldowns, and isAvailable() gating.
openmetadata-service/src/main/java/org/openmetadata/service/search/vector/client/EmbeddingUnavailableException.java New exception type for fast-fail when the circuit is open.
openmetadata-service/src/main/java/org/openmetadata/service/search/vector/OpenSearchVectorService.java Skips embedding work when unavailable; catches EmbeddingUnavailableException as a soft skip.
openmetadata-service/src/main/java/org/openmetadata/service/search/vector/client/BedrockEmbeddingClient.java Classifies permanent Bedrock failures (401/403/404) and reduces duplicate stack-trace logging.
openmetadata-service/src/test/java/org/openmetadata/service/search/vector/EmbeddingClientTest.java Adds tests for open-after-N, immediate-open-on-permanent, and recovery behavior.

@github-actions

github-actions Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

🔴 Playwright Results — 1 failure(s), 23 flaky

✅ 4530 passed · ❌ 1 failed · 🟡 23 flaky · ⏭️ 96 skipped

Shard Passed Failed Flaky Skipped
🟡 Shard 1 424 0 3 16
✅ Shard 2 11 0 0 0
🔴 Shard 3 824 1 6 9
🟡 Shard 4 820 0 2 18
🟡 Shard 5 837 0 2 5
🟡 Shard 6 787 0 1 46
🟡 Shard 7 827 0 9 2

Genuine Failures (failed on all attempts)

❌ Features/ContextCenterArticles.spec.ts › Article list cards, recently viewed widget, and pagination work (shard 3)
�[31mTest timeout of 60000ms exceeded.�[39m
🟡 23 flaky test(s) (passed on retry)
  • Features/EntityRenameConsolidation.spec.ts › Classification - rename then update description should preserve tags (shard 1, 1 retry)
  • Pages/Lineage/LineageRightPanel.spec.ts › Verify custom properties tab IS visible for supported type: metric (shard 1, 1 retry)
  • Flow/SearchRBAC.spec.ts › a dashboard-scoped user sees dashboards but never tables (shard 1, 1 retry)
  • Features/BulkImportWithDotInName.spec.ts › Bulk edit existing entity with dot in service name (shard 3, 1 retry)
  • Features/ContextCenterArchivePage.spec.ts › archive page lazy-loads more rows on scroll within its own scroll container (shard 3, 1 retry)
  • Features/ContextCenterArticles.spec.ts › Article listing search filters, clears, and shows empty state (shard 3, 1 retry)
  • Features/ContextCenterArticles.spec.ts › Article edit persistence and unsaved title behavior are correct (shard 3, 2 retries)
  • Features/ContextCenterMemories.spec.ts › adding a linked asset in edit mode shows entity badge on the row (shard 3, 1 retry)
  • Features/ContextCenterPermission.spec.ts › created-by-me filter on the archive page shows only the current user's archived documents (shard 3, 1 retry)
  • Features/Glossary/LargeGlossaryPerformance.spec.ts › should handle drag and drop for term reordering (shard 4, 1 retry)
  • Features/SearchExport.spec.ts › Export queues a background job and downloads from the jobs tray (shard 4, 1 retry)
  • Flow/ServiceCreationPermissions.spec.ts › Owner can delete their own service (shard 5, 1 retry)
  • Pages/CustomProperties.spec.ts › Integer (shard 5, 1 retry)
  • Pages/ExploreBrowse.spec.ts › service type drill-down disables unrelated roots and query-panel Clear resets it (shard 6, 1 retry)
  • Pages/ExplorePageRightPanel.spec.ts › Should verify deleted user not visible in owner selection for table (shard 7, 1 retry)
  • Pages/Glossary.spec.ts › Approve and reject glossary term from Glossary Listing (shard 7, 1 retry)
  • Pages/Glossary.spec.ts › Column dropdown drag-and-drop functionality for Glossary Terms table (shard 7, 1 retry)
  • Pages/Lineage/LineageFilters.spec.ts › Verify Impact Analysis service filter selection (shard 7, 1 retry)
  • Pages/Lineage/LineageRightPanel.spec.ts › Verify custom properties tab is NOT visible for pipelineService in platform lineage (shard 7, 1 retry)
  • Pages/Lineage/LineageRightPanel.spec.ts › Verify custom properties tab is NOT visible for apiService in platform lineage (shard 7, 1 retry)
  • Pages/ServiceListing.spec.ts › should render the service listing page (shard 7, 1 retry)
  • Pages/TestSuite.spec.ts › Logical TestSuite (shard 7, 1 retry)
  • Pages/UserDetails.spec.ts › Admin user can get all the roles hierarchy and edit roles (shard 7, 1 retry)

📦 Download artifacts

How to debug locally
# Download playwright-test-results-<shard> artifact and unzip
npx playwright show-trace path/to/trace.zip    # view trace

Auto-tune sized reindex memory against the JVM heap (Runtime.maxMemory() = -Xmx)
and capped concurrency and payload size independently, but never bounded their
product. Bulk-request payloads are held largely in off-heap direct buffers, so
concurrentRequests x maxPayloadSize could exceed the container cgroup limit while
the heap looked fine, and the pod was OOMKilled (137) -- so auto-tune did not
"just work" on memory-constrained pods.

Cap concurrent bulk requests so concurrentRequests x maxPayloadSize fits half the
pod's off-heap headroom (container limit - max heap), reading the container limit
from com.sun.management.OperatingSystemMXBean.getTotalMemorySize() (container-aware
with UseContainerSupport). Applied to both the metrics-based and conservative-default
paths, plus an off-heap bulk-memory estimate in the recommendation log.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings July 9, 2026 10:02
@mohityadav766 mohityadav766 changed the title Add a circuit breaker to the embedding provider client Make search embeddings + reindex auto-tune resilient on any pod size Jul 9, 2026

Copilot AI left a comment

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.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 3 comments.

Copilot AI review requested due to automatic review settings July 9, 2026 10:14

Copilot AI left a comment

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.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

AuditLogResource.exportAuditLogs materialized up to 100K audit entries as one JSON string and sent it inline over the csvExportChannel websocket, on the shared AsyncService executor. Parallel exports (e.g. Playwright shards) piled multi-hundred-MB byte[] onto the heap and OOM'd the server — locally reproduced (heap dump byte[] = the audit export payloads), matching the AUT nightly restarts.

Route audit exports through a dedicated 2-thread executor so at most 2 serialize a payload at once (mirrors the entity/search CSV export path, which already runs on the bounded GenericBackgroundWorker pool). Separate from the #29342 CSV-export spool fix, which never covered the audit export.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

Copilot AI left a comment

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

…he websocket

The audit export built the full List<AuditLogEntry> + one JSON String in memory and sent it inline over the csvExportChannel websocket. Concurrent exports OOM'd the server — first on-heap (Java OOM + dump), then off-heap (OOMKilled 137, netty send buffer) once concurrency was merely bounded. Reproduced locally end-to-end.

streamExportAsJson now writes each 1000-row batch straight to a CsvExportSpool file (one batch in heap at a time), and the COMPLETED event carries only a download reference (null data). New GET /v1/audit/logs/export/{jobId}/result streams the spooled result. Verified: the 150-concurrent hammer that previously OOM'd leaves the server running (peak humongous 322, GC'd to ~3) and the 180 MB result downloads correctly.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

Copilot AI left a comment

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Copilot AI left a comment

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

harshach
harshach previously approved these changes Jul 14, 2026
@harshach

Copy link
Copy Markdown
Collaborator

@mohityadav766 lets address bot reviews

…l, audit export hardening

- EmbeddingClient: make HALF_OPEN a deterministic single-probe state (reject
  concurrent callers by state, not a time deadline), keep isAvailable() false
  while a probe is in flight, and record permit-acquisition failures so a
  promoted probe always resolves. Adds a latch-based single-probe test.
- VectorDocBuilder.fromEntity: throw EmbeddingUnavailableException on outage
  instead of returning an empty list callers cannot distinguish from
  "no chunks" (which would delete existing vectors).
- OpenSearchVectorService: drop the racy chunksEmptyFromOutage guard; catch the
  outage exception so replaceChunks never deletes chunks during a provider outage.
- OpenSearchBulkSink: skip the embedding call during an outage so a transient
  provider outage indexes without embeddings (self-heals next reindex) instead
  of failing every entity in the reindex.
- SearchClusterMetrics.boundConcurrentRequestsToMemory: compute the memory cap
  in long and cast after Math.min so a tiny payload can't overflow to negative
  concurrency. Adds a regression test.
- AuditLogResource: validate the export jobId is a server-generated UUID before
  touching the spool path (path-traversal guard) and delete a partial spool on
  export failure.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

Copilot AI left a comment

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@mohityadav766

Copy link
Copy Markdown
Member Author

Addressed the open review threads in 51ca7466.

Fixed

  • Half-open probe fan-out (EmbeddingClient L145/L147, isAvailable L113, permit-race L84): HALF_OPEN is now a deterministic single-probe state — concurrent callers are rejected by state rather than a time deadline, so a probe that outlives the cooldown can't leak extra probes. isAvailable() returns false while a probe is in flight, and a permit-acquisition failure is now recorded so a promoted probe always resolves (closed/reopened) and never wedges the circuit half-open. New latch-based testHalfOpenAllowsOnlyOneConcurrentProbe.
  • Empty-list deletes existing vectors (VectorDocBuilder L156; OpenSearchVectorService L225/L752): fromEntity now throws EmbeddingUnavailableException on outage instead of returning List.of(), which callers couldn't distinguish from "no chunks". The racy chunksEmptyFromOutage re-check is removed and both write paths catch the exception, so replaceChunks never runs during an outage.
  • Reindex sink (OpenSearchBulkSink): the embedding call is skipped when the circuit is open, so a transient outage indexes entities without embeddings (self-heals on the next reindex) rather than marking every entity failed.
  • Int overflow (SearchClusterMetrics L445): the memory cap is computed in long and cast after Math.min, so a tiny payload can't overflow to negative concurrency. Regression test added.
  • Audit export (AuditLogResource L262/L323): jobId is validated as a server-generated UUID before touching the spool path (path-traversal guard), and a partial spool is deleted on export failure.

Already resolved / stale (from earlier commits): openCause null-guard (L182-183), the "syntactically broken"/"breaker bypassed" comments, the ponytail: marker, and the conservative-queue ordering (queue is sized from the bounded concurrency).

Deliberately not changed

  • Permit-race fail-fast (L67): inherent to any breaker with in-flight requests — bounded by the concurrency limiter and self-correcting via recordFailure. A naive re-guard after the permit would reject the legitimate probe.
  • Off-heap throttle to ~1 on high-Xmx (L454) and queue floor of 1000 (L472): intended safety tradeoffs (both already LOG.info-warned). Throttling to fit off-heap headroom is exactly the OOMKill-137 fix this PR is about; loosening it reintroduces the bug.

@mohityadav766

Copy link
Copy Markdown
Member Author

@mohityadav766 lets address bot reviews

done @harshach

The sink now skips embedding generation when the provider circuit is open, so
the recompute-path happy tests must stub a healthy provider — bare
mock(EmbeddingClient) reports isAvailable()=false by default, which correctly
short-circuits the new guard. Add an availableClient() helper (hoisted to a
local to avoid nested-when UnfinishedStubbing) and a
enrichWithEmbeddingSkipsGenerationWhenProviderUnavailable test asserting an
outage indexes the entity without embeddings and counts it a success rather
than calling the provider or failing the reindex.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

Copilot AI left a comment

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@@ -952,12 +950,13 @@ private String enrichWithEmbedding(
// chunk docs reflect committed entity state, so writing them mid-reindex is safe even if

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 Stale chunks persist

When this branch runs with no reusable cached embedding and an open circuit, the reindex writes the entity document without vectors and skips chunk maintenance entirely. Existing chunk documents for the same entity stay in the chunk index, so semantic or RAG queries can still return text from the previous entity version until a later successful reindex. This path needs a separate cleanup or stale-state marker so unavailable embeddings do not leave old chunks searchable as current data.

Copilot AI left a comment

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Comment on lines 950 to +953
// chunk docs reflect committed entity state, so writing them mid-reindex is safe even if
// the staged index is never promoted.
vectorService.updateEntityEmbeddingChunks(entity);
} else {
} else if (embeddingClient != null && embeddingClient.isAvailable()) {

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 Stale chunks persist

When reindexing an entity whose content changed while the embedding circuit is open, this branch skips both fresh chunk generation and writeEntityChunks(...). The staged entity document is still indexed without new vectors, but any existing chunk docs for the same entity remain in the live chunk index with the old text and vectors. Semantic or RAG queries can then return stale entity content until a later successful reindex rewrites those chunks.

Copilot AI left a comment

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Copilot AI left a comment

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@sonarqubecloud

Copy link
Copy Markdown

@gitar-bot

gitar-bot Bot commented Jul 15, 2026

Copy link
Copy Markdown
Code Review ✅ Approved 8 resolved / 8 findings

Increases system resilience against pod OOMs and service outages by adding an embedding-provider circuit breaker, memory-aware reindex bounds, and a streaming spooler for audit exports. All findings from the review process have been addressed.

✅ 8 resolved
✅ Edge Case: Off-heap cap can throttle reindex concurrency to ~1 on high-Xmx pods

📄 openmetadata-service/src/main/java/org/openmetadata/service/search/SearchClusterMetrics.java:433-447
availableOffHeapBudgetBytes() computes containerMemoryLimitBytes() - Runtime.getRuntime().maxMemory(). In container deployments that set -Xmx to a large fraction of the cgroup limit (a common pattern, e.g. 75–80%), the resulting headroom is small; after the 0.5 safety factor safeBytes may be only a few payload sizes (or zero, when Xmx >= container limit), so boundConcurrentRequestsToMemory caps recommendedConcurrentRequests down to 1–2. This can drastically slow reindexing in otherwise healthy clusters. The behavior is intentional (the test asserts 0 budget -> 1 'rather than OOMKilling') and is logged, but the aggressiveness in high-Xmx containers is easy to overlook.

Additionally, the budget only subtracts max heap and ignores other committed native memory (metaspace, thread stacks, code cache, GC structures), so on the other side it can slightly over-estimate available off-heap. The 0.5 factor mostly covers this.

Suggested: consider a small floor on concurrency (e.g. Math.max(<minConcurrent>, maxByMemory)) or emit the cap at WARN when it collapses to 1–2 so operators can spot unexpectedly serialized reindexes, and document the interaction with -Xmx sizing.

✅ Quality: Half-open state lets a burst of probes hit provider, not one

📄 openmetadata-service/src/main/java/org/openmetadata/service/search/vector/client/EmbeddingClient.java:111-125
When the cooldown elapses, the first thread in guardCircuit() transitions the state from OPEN to HALF_OPEN via rejectOrProbe(). Because guardCircuit() only rejects/probes when circuitState == OPEN, every subsequent concurrent (and following) thread now sees HALF_OPEN and passes through freely, calling the provider. So instead of a single recovery probe, up to maxConcurrentRequests calls are dispatched to the provider on each half-open window. The first failure among them will reopen the circuit (shouldOpen returns true for HALF_OPEN), but the intended "probe with one request" behavior described in the PR is not enforced.

Impact is bounded by the concurrency limiter, so it is not severe, but under a persistent outage the provider still receives a periodic burst rather than a single probe. Consider gating the probe with a dedicated flag/permit so exactly one request runs while HALF_OPEN and others continue to fast-fail with EmbeddingUnavailableException until the probe resolves.

✅ Edge Case: openCause may be null, producing 'null' in log/exception text

📄 openmetadata-service/src/main/java/org/openmetadata/service/search/vector/client/EmbeddingClient.java:162 📄 openmetadata-service/src/main/java/org/openmetadata/service/search/vector/client/EmbeddingClient.java:119-123 📄 openmetadata-service/src/main/java/org/openmetadata/service/search/vector/client/EmbeddingClient.java:165-170
openCause = failure.getMessage() can be null (many RuntimeExceptions carry no message). It is later interpolated into the WARN log and into the EmbeddingUnavailableException message, yielding text like "...circuit open: null". Since the whole point is to surface a single clear summary line during an outage, a null cause hurts diagnosability. Fall back to the exception class name (or String.valueOf) when the message is null.

✅ Edge Case: boundQueueSizeToHeap floor of 1000 can exceed heap budget

📄 openmetadata-service/src/main/java/org/openmetadata/service/search/SearchClusterMetrics.java:462-466
boundQueueSizeToHeap applies Math.max(1000, heapBudget / ESTIMATED_ENTITY_BYTES), so the 1000-entity floor is taken before clamping to the actual heap budget. On the memory-constrained pods this PR targets, this partly defeats the stated intent. Example (also asserted by the new test at SearchClusterMetricsTest.java:68-71): a 128 MB heap gives heapBudget = 32 MB, 32MB/100KB ≈ 335, but the method still returns 1000. At 100 KB/entity that is ~100 MB of buffered entities against a 128 MB heap — roughly 78% of heap and ~3× the intended 25% (QUEUE_HEAP_FRACTION) budget. The floor is reasonable for keeping the queue functional, but on the smallest pods it re-introduces exactly the heap pressure the bound is meant to prevent. Consider computing the raw budgeted value first and only flooring when heap is genuinely tiny, or documenting that the 1000 floor may exceed QUEUE_HEAP_FRACTION on sub-~400 MB heaps.

✅ Quality: Conservative queue sized from pre-bound concurrency

📄 openmetadata-service/src/main/java/org/openmetadata/service/search/SearchClusterMetrics.java:505-507 📄 openmetadata-service/src/main/java/org/openmetadata/service/search/SearchClusterMetrics.java:549-551
In getConservativeDefaults, conservativeQueueSize = conservativeBatchSize * conservativeConcurrentRequests * 2 (line 505) is computed from the un-bounded concurrency figure, and boundQueueSizeToHeap is applied at line 506-507. Only afterward (line 549-551) is conservativeConcurrentRequests reduced by boundConcurrentRequestsToMemory. So on a memory-constrained pod where concurrency is cut to 1, the queue is still sized as if concurrency were 25–50. The new boundQueueSizeToHeap heap cap keeps this from OOMing, so the impact is limited to a larger-than-necessary buffered working set rather than a crash. Consider computing conservativeQueueSize after the concurrency bound so the queue tracks the actual concurrency used.

...and 3 more resolved from earlier reviews

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 👍 / 👎 | Gitar

This branch was previously deployed

1 inactive deployment
test — c1203c88 Deployed Jul 14, 2026 by mohityadav766 via playwright-ci-postgresql (4, 7) #56512
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.

4 participants