Repository navigation
Make search embeddings, reindex auto-tune, and audit export resilient on any pod size - #29833
Conversation
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]>
❌ 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 |
There was a problem hiding this comment.
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 newEmbeddingUnavailableExceptionfor fast-fail while open. - Update
OpenSearchVectorServiceto skip embedding work when the provider is unavailable and to treat the new exception as a soft/skip condition. - Update
BedrockEmbeddingClientto 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. |
🔴 Playwright Results — 1 failure(s), 23 flaky✅ 4530 passed · ❌ 1 failed · 🟡 23 flaky · ⏭️ 96 skipped
Genuine Failures (failed on all attempts)❌
|
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]>
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]>
…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]>
|
@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]>
|
Addressed the open review threads in Fixed
Already resolved / stale (from earlier commits): Deliberately not changed
|
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]>
| @@ -952,12 +950,13 @@ private String enrichWithEmbedding( | |||
| // chunk docs reflect committed entity state, so writing them mid-reindex is safe even if | |||
There was a problem hiding this comment.
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.
| // 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()) { |
There was a problem hiding this comment.
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.
|
Code Review ✅ Approved 8 resolved / 8 findingsIncreases 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
✅ Quality: Half-open state lets a burst of probes hit provider, not one
✅ Edge Case: openCause may be null, producing 'null' in log/exception text
✅ Edge Case: boundQueueSizeToHeap floor of 1000 can exceed heap budget
✅ Quality: Conservative queue sized from pre-bound concurrency
...and 3 more resolved from earlier reviews OptionsDisplay: compact → Showing less information. Comment with these commands to change the behavior for this request:
Was this helpful? React with 👍 / 👎 | Gitar |



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
AccessDeniedExceptionwhen 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.EmbeddingClient: after 5 consecutive failures (or immediately on a permanent auth/config failure) the circuit opens andembed()fast-fails withEmbeddingUnavailableExceptionwithout a provider call — one WARN + asearch.embedding.circuit_openedmetric instead of per-entity stack traces. Half-opens after a cooldown (60s transient / 300s permanent) and closes on recovery.BedrockEmbeddingClientclassifies 401/403/404 as permanent and drops its per-call error stack traces to debug.OpenSearchVectorServiceskips 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
SearchClusterMetricsauto-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, soconcurrentRequests × 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.concurrentRequests × maxPayloadSizefits half the off-heap headroom (containerLimit − maxHeap), reading the container limit fromcom.sun.management.OperatingSystemMXBean.getTotalMemorySize()(container-aware withUseContainerSupport). Applied to both the metrics-based and conservative-default paths.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,000AuditLogEntryrecords into aList, serialized the whole thing to one JSONString, and sent it inline over thecsvExportChannelWebSocket — on the shared async executor. Under parallel exports (e.g. 4 Playwright shards) these multi-hundred-MB payloads piled up as G1 humongousbyte[]: 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 whosebyte[]are exactly thecsvExportChannelaudit payloads. This path was never covered by the entity/search CSV-export spool fix.AuditLogRepository.streamExportAsJsonwrites each 1000-row batch straight to aCsvExportSpoolfile (one batch in heap at a time), never materializing the full list or string.COMPLETEDWebSocket event now carries only a download reference (data: null) instead of the inline payload; a newGET /v1/audit/logs/export/{jobId}/resultstreams the spooled file viaStreamingOutput.AUDIT_EXPORT_EXECUTORalso caps how many exports run at once (DB load / spool writers), mirroring the entity/search CSV export's already-bounded worker pool.Tests
EmbeddingClientTest: circuit opens after N failures / opens immediately on a permanent failure / recovers when the provider returns.SearchClusterMetricsTest:boundConcurrentRequestsToMemoryshrinks concurrency to the off-heap budget, leaves it untouched when memory is ample, and degrades to serial when there's no headroom.Verifying in AUT
Both surfaced in the AUT nightly (Bedrock unauthorized). With the circuit breaker deployed, the
BedrockEmbeddingClientlog flood dropped from thousands/5min to ~0 andsearch.embedding.circuit_openedengaged; 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'sbyte[]arecsvExportChannelaudit payloads.🤖 Generated with Claude Code
Summary by Gitar
EmbeddingClientcircuit breaker to handle transient/permanent provider failures.isAvailable()check inOpenSearchVectorServiceandVectorDocBuilderto skip embedding work during outages.EmbeddingUnavailableExceptionfor fast-failure and ensuredBedrockEmbeddingClientidentifies non-retryable status codes.boundConcurrentRequestsToMemoryandboundQueueSizeToHeaptoSearchClusterMetricsto prevent OOMs by sizing buffers against container limits and JVM heap.List<AuditLogEntry>exports withstreamExportAsJsonusingCsvExportSpoolto prevent heap exhaustion.MAX_CONCURRENT_AUDIT_EXPORTS = 2and a dedicatedAUDIT_EXPORT_EXECUTORto bound resource contention.downloadAuditExportResultendpoint to retrieve spooled files viaStreamingOutputafter 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:
Confidence Score: 4/5
This is close, but the search outage path should be fixed before merging.
openmetadata-service/src/main/java/org/openmetadata/service/search/vector/client/EmbeddingClient.java and the semantic search caller in OpenSearchVectorService
Important Files Changed
Comments Outside Diff (2)
openmetadata-service/src/main/java/org/openmetadata/service/search/vector/client/EmbeddingClient.java, line 86-88 (link)embedQuerybypasses the circuit breakerembedQuerycallsembedWithLimit(() -> doEmbedQuery(text))directly, skippingguardCircuit(). The circuit can be open whileembedQuerystill issues provider calls — every semantic search query routed throughOpenSearchVectorService.search()(which callsembeddingClient.embedQuery(query)) will keep hitting a failed provider and propagate as an uncaughtRuntimeException, rather than receiving the fast-failEmbeddingUnavailableExceptionthe entity-write path now correctly gets.embedQueryneeds to callguardCircuit()and route throughrecordSuccess/recordFailurethe same way the newembedmethod does.openmetadata-service/src/main/java/org/openmetadata/service/search/vector/client/EmbeddingClient.java, line 78 (link)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()callsembeddingClient.embedQuery(query)before its OpenSearch error handling and can letEmbeddingUnavailableExceptionescape 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)