You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by "ryerraguntla (via GitHub)" <gi...@apache.org> on 2026/07/22 01:57:41 UTC

[PR] fix(connectors): harden Elasticsearch sink test readiness [iggy]

ryerraguntla opened a new pull request, #3729:
URL: https://github.com/apache/iggy/pull/3729

   # Pull request draft
   
   For issue: https://github.com/apache/iggy/issues/3728
   
   Create the PR from branch `fix/elasticsearch-sink-test-flakiness`
   against `apache/iggy` `master` (or `main` if that is the default).
   
   Copy **Title** and **Body** below into the PR form.
   Do **not** include `cve-issue-drafts/` in the PR.
   
   ---
   
   ## Title
   
   fix(connectors): harden Elasticsearch sink test readiness
   
   ---
   
   ## Body
   
   ## Summary
   
   - Fixes flaky Elasticsearch sink integration test where `iggy-connectors`
     never becomes healthy because sink `open()` can hang on Elasticsearch HTTP
     with no client timeout, while the connectors HTTP API only binds after
     plugin open.
   - Hardens the Elasticsearch Testcontainers fixture: use `127.0.0.1`, always
     re-check `/_cluster/health` on reuse attach, self-heal a wedged
     `iggy-test-elasticsearch` container only, and sweep stale harness indices
     older than 30 minutes.
   - Improves harness readiness: poll connectors `/health` and fail fast if the
     child process dies during retries; refresh the index before document-count
     polls in the sink fixture.
   
   Closes #3728
   
   ## Test plan
   
   - [ ] `cargo fmt --all`
   - [ ] `cargo sort --no-format --workspace`
   - [ ] `cargo clippy -p iggy_connector_elasticsearch_sink -p integration --all-features --all-targets -- -D warnings`
   - [ ] `cargo test -p integration -- connectors::elasticsearch::elasticsearch_sink::elasticsearch_sink_stores_json_messages`
   - [ ] Confirm `docker rm -f` recovery targets only `iggy-test-elasticsearch`
         (no other Elasticsearch containers)
   - [ ] Optional: leave a reused `iggy-test-elasticsearch` running and re-run
         the sink test to verify reuse + readiness path
   
   ## Notes
   
   - Container force-remove uses the fixed harness name
     `iggy-test-elasticsearch` only.
   - Stale index sweep is best-effort and age-gated so concurrent harness
     tests sharing the reused container are not disrupted.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on PR #3729:
URL: https://github.com/apache/iggy/pull/3729#issuecomment-5172421093

   /ready


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "numinnex (via GitHub)" <gi...@apache.org>.
numinnex commented on code in PR #3729:
URL: https://github.com/apache/iggy/pull/3729#discussion_r3690805996


##########
core/integration/tests/connectors/fixtures/elasticsearch/container.rs:
##########
@@ -137,14 +198,320 @@ impl ElasticsearchContainer {
                 message: "No mapping for Elasticsearch port".to_string(),
             })?;
 
-        let base_url = format!("http://localhost:{mapped_port}");
+        // Prefer IPv4 loopback: Docker publishes 0.0.0.0:HOST→9200. `localhost`
+        // can resolve to ::1 first on macOS and black-hole the elasticsearch-rs
+        // client while the fixture's reqwest client still looks healthy.
+        let base_url = format!("http://127.0.0.1:{mapped_port}");
         info!("Elasticsearch container available at {base_url}");
 
-        Ok(Self {
+        let started = Self {
             container,
             base_url,
+        };
+        // ReuseDirective::Always can attach to a days-old container without
+        // re-running HttpWaitStrategy; verify cluster health on every setup.
+        started.wait_until_ready().await?;
+        started.sweep_stale_indices().await;
+        Ok(started)
+    }
+
+    async fn wait_until_ready(&self) -> Result<(), TestBinaryError> {
+        #[derive(Deserialize)]
+        struct ClusterHealth {
+            timed_out: bool,
+            status: String,
+        }
+
+        // Dedicated probe client: short timeout, no retry middleware. The shared
+        // create_http_client() (30s + 3 retries) turns one black-holed request
+        // into a multi-minute hang that looks like the test is stuck.
+        let client = reqwest::Client::builder()
+            .timeout(std::time::Duration::from_millis(
+                CLUSTER_READY_REQUEST_TIMEOUT_MS,
+            ))
+            .build()
+            .map_err(|error| TestBinaryError::FixtureSetup {
+                fixture_type: "ElasticsearchContainer".to_string(),
+                message: format!("Failed to build readiness HTTP client: {error}"),
+            })?;
+        // wait_for_status=yellow makes ES block until yellow/green or timeout=1s
+        // elapses; without wait_for_*, timeout is ignored and red still returns
+        // 200 with timed_out=false.
+        let health_url = format!(
+            "{}{ELASTICSEARCH_HEALTH_ENDPOINT}?wait_for_status=yellow&timeout=1s",
+            self.base_url
+        );
+        let mut last_error = String::from("no attempts made");
+
+        for attempt in 1..=CLUSTER_READY_ATTEMPTS {
+            match client.get(&health_url).send().await {
+                Ok(response) if response.status().is_success() => {
+                    match response.json::<ClusterHealth>().await {
+                        Ok(health) if !health.timed_out => {
+                            info!(
+                                "Elasticsearch cluster ready at {} (status={})",
+                                self.base_url, health.status
+                            );
+                            return Ok(());
+                        }
+                        Ok(health) => {
+                            last_error = format!(
+                                "cluster health timed out on attempt {attempt}/{CLUSTER_READY_ATTEMPTS} (status={})",
+                                health.status
+                            );
+                        }
+                        Err(error) => {
+                            last_error = format!(
+                                "cluster health body unparsable on attempt {attempt}/{CLUSTER_READY_ATTEMPTS}: {error}"
+                            );
+                        }
+                    }
+                }
+                Ok(response) => {
+                    last_error = format!(
+                        "cluster health status {} on attempt {attempt}/{CLUSTER_READY_ATTEMPTS}",
+                        response.status()
+                    );
+                }
+                Err(error) => {
+                    last_error = format!(
+                        "cluster health request failed on attempt {attempt}/{CLUSTER_READY_ATTEMPTS}: {error}"
+                    );
+                }
+            }
+            tokio::time::sleep(std::time::Duration::from_millis(CLUSTER_READY_INTERVAL_MS)).await;
+        }
+
+        Err(TestBinaryError::FixtureSetup {
+            fixture_type: "ElasticsearchContainer".to_string(),
+            message: format!(
+                "Elasticsearch at {} not ready after {CLUSTER_READY_ATTEMPTS} attempts: {last_error}",
+                self.base_url
+            ),
         })
     }
+
+    /// Delete leftover test indices (empty or partially filled) from previous
+    /// runs so accumulated shards do not degrade the reused container. Only
+    /// indices older than [`STALE_INDEX_MAX_AGE_MS`] are removed, which keeps
+    /// the sweep safe against tests running concurrently in other processes.
+    /// Best-effort: failures are logged, never fail the fixture.
+    async fn sweep_stale_indices(&self) {
+        #[derive(Deserialize)]
+        struct CatIndexEntry {
+            index: String,
+            #[serde(rename = "creation.date")]
+            creation_date: Option<String>,
+        }
+
+        // Short timeout, no retries: sweep is best-effort and must not stall setup.
+        let Ok(client) = reqwest::Client::builder()
+            .timeout(std::time::Duration::from_secs(5))
+            .build()
+        else {
+            warn!("Skipping stale index sweep, failed to build HTTP client");
+            return;
+        };
+        let cat_url = format!(
+            "{}/_cat/indices/{STALE_INDEX_PATTERNS}?format=json&h=index,creation.date",
+            self.base_url
+        );
+
+        let entries = match client.get(&cat_url).send().await {
+            Ok(response) if response.status().is_success() => {
+                match response.json::<Vec<CatIndexEntry>>().await {
+                    Ok(entries) => entries,
+                    Err(error) => {
+                        warn!("Skipping stale index sweep, unparsable _cat response: {error}");
+                        return;
+                    }
+                }
+            }
+            Ok(response) => {
+                warn!(
+                    "Skipping stale index sweep, _cat/indices returned {}",
+                    response.status()
+                );
+                return;
+            }
+            Err(error) => {
+                warn!("Skipping stale index sweep, _cat/indices failed: {error}");
+                return;
+            }
+        };
+
+        let now_ms = std::time::SystemTime::now()
+            .duration_since(std::time::UNIX_EPOCH)
+            .map(|duration| duration.as_millis())
+            .unwrap_or(0);
+
+        let stale: Vec<String> = entries
+            .into_iter()
+            .filter_map(|entry| {
+                let created_ms = entry.creation_date.as_deref()?.parse::<u128>().ok()?;
+                (now_ms.saturating_sub(created_ms) > STALE_INDEX_MAX_AGE_MS).then_some(entry.index)
+            })
+            .collect();
+
+        if stale.is_empty() {
+            return;
+        }
+
+        // Chunked so the URL stays well under limits with many leftovers.
+        for chunk in stale.chunks(20) {
+            let delete_url = format!("{}/{}", self.base_url, chunk.join(","));
+            match client.delete(&delete_url).send().await {
+                Ok(response) if response.status().is_success() => {
+                    info!("Deleted {} stale Elasticsearch test indices", chunk.len());
+                }
+                Ok(response) => {
+                    warn!(
+                        "Failed to delete stale Elasticsearch indices, status {}",
+                        response.status()
+                    );
+                }
+                Err(error) => {
+                    warn!("Failed to delete stale Elasticsearch indices: {error}");
+                }
+            }
+        }
+    }
+}
+
+/// Cross-process advisory lock for inspect+rm recovery of the shared reuse
+/// container. Dropping the file releases the lock (including on process crash).
+///
+/// Assumes every nextest process shares the same `std::env::temp_dir()` (and
+/// thus the same lock file). A per-process `TMPDIR` makes each worker lock its
+/// own path and recovery can race silently.
+struct RecoveryLock {
+    _file: File,
+}
+
+async fn acquire_recovery_lock() -> Result<RecoveryLock, String> {
+    let path = std::env::temp_dir().join(RECOVERY_LOCK_FILE_NAME);
+    let file = OpenOptions::new()
+        .read(true)
+        .write(true)
+        .create(true)
+        .truncate(false)
+        .open(&path)
+        .map_err(|error| format!("open {}: {error}", path.display()))?;
+
+    let deadline = Instant::now() + Duration::from_secs(RECOVERY_LOCK_TIMEOUT_SECS);
+    loop {
+        match file.try_lock() {
+            Ok(()) => return Ok(RecoveryLock { _file: file }),
+            Err(TryLockError::WouldBlock) if Instant::now() < deadline => {
+                tokio::time::sleep(Duration::from_millis(RECOVERY_LOCK_POLL_MS)).await;
+            }
+            Err(TryLockError::WouldBlock) => {
+                return Err(format!(
+                    "timed out after {RECOVERY_LOCK_TIMEOUT_SECS}s waiting for {}",
+                    path.display()
+                ));
+            }
+            Err(TryLockError::Error(error)) => {
+                return Err(format!("lock {}: {error}", path.display()));
+            }
+        }
+    }
+}
+
+/// True only when Docker says the shared container is in a state safe to
+/// force-remove without yanking a healthy instance from a peer process.
+///
+/// Removable: exited/dead/created/paused/restarting, or Docker healthcheck
+/// `unhealthy`. A plain `running` container (even if ES HTTP is flaky) is left
+/// alone: readiness flakes must not `docker rm -f` a shared Always-reuse box.
+async fn container_is_removable_wedged() -> bool {
+    let inspect_format = "{{.State.Status}}|{{if .State.Health}}{{.State.Health.Status}}{{end}}";
+    let Some(stdout) = docker_command_stdout(
+        &[
+            "inspect",
+            "-f",
+            inspect_format,
+            ELASTICSEARCH_CONTAINER_NAME,
+        ],
+        DOCKER_INSPECT_TIMEOUT_SECS,
+    )
+    .await
+    else {
+        return false;
+    };
+
+    let mut parts = stdout.trim().split('|');
+    let status = parts.next().unwrap_or("").trim();
+    let health = parts.next().unwrap_or("").trim();
+
+    matches!(
+        status,
+        "exited" | "dead" | "created" | "paused" | "restarting"
+    ) || health == "unhealthy"

Review Comment:
   This predicate cannot fire for the wedge state the recovery path was written for.
   
   `docker.io/library/elasticsearch:9.3.0` ships no HEALTHCHECK: `docker image inspect docker.io/library/elasticsearch:9.3.0 --format '{{json .Config.Healthcheck}}'` returns `null`, and `GenericImage` does not add one. So `.State.Health` is always nil, the `{{if .State.Health}}` branch in `inspect_format` yields the empty string, and `health == "unhealthy"` is unreachable. The predicate reduces to the status list alone.
   
   That list covers container-level death (an OOM-killed JVM exits, so `exited` catches it), but not the case `wait_until_ready` was added to detect: ES process up, cluster red or HTTP wedged from a corrupted data dir, which is exactly what the doc comment above names as motivation. Docker reports `running`, this returns false, and every Elasticsearch test then fails at fixture setup until someone runs `docker rm -f iggy-test-elasticsearch` by hand. That manual step is what the recovery path was meant to remove.
   
   Two ways out:
   
   1. Treat `running` as removable when readiness already exhausted all `CLUSTER_READY_ATTEMPTS`. Pass that signal in so it stays distinct from a transient start or port flake, and keep the removal under `RecoveryLock`.
   2. If leaving a running container alone is the deliberate call, drop the unreachable `health` leg and put the remediation command in the `warn!` at the caller. It currently says "leaving it in place" with no next step, so whoever hits it has to work out `docker rm -f iggy-test-elasticsearch` themselves.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #3729:
URL: https://github.com/apache/iggy/pull/3729#discussion_r3633252886


##########
core/integration/tests/connectors/fixtures/elasticsearch/container.rs:
##########


Review Comment:
   Let me add the logic to remove when required.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): harden Elasticsearch sink test readiness [iggy]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #3729:
URL: https://github.com/apache/iggy/pull/3729#issuecomment-5040961282

   <!-- iggy-pr-triage-welcome -->
   Thanks for the PR. It is labeled `S-waiting-on-review` and queued for review.
   
   Slash commands (own line, regular comment) move it around the queue:
   
   - `/ready` - back to `S-waiting-on-review` after addressing feedback
   - `/author` - flip to `S-waiting-on-author` while you finish changes
   - `/request-review @user-or-team` - request a reviewer
   
   See [CONTRIBUTING.md](https://github.com/apache/iggy/blob/master/CONTRIBUTING.md#pr-triage-commands) for details.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #3729:
URL: https://github.com/apache/iggy/pull/3729#discussion_r3706588123


##########
core/integration/tests/connectors/fixtures/elasticsearch/sink.rs:
##########


Review Comment:
   Fixed in [58858e8](https://github.com/apache/iggy/pull/3729/commits/58858e820343ac4745449cf291f9354a6269c49b)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio merged PR #3729:
URL: https://github.com/apache/iggy/pull/3729


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on PR #3729:
URL: https://github.com/apache/iggy/pull/3729#issuecomment-5172427006

   /request-review @slbotbm 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on PR #3729:
URL: https://github.com/apache/iggy/pull/3729#issuecomment-5049306332

   /request-review @user-or-team


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "slbotbm (via GitHub)" <gi...@apache.org>.
slbotbm commented on code in PR #3729:
URL: https://github.com/apache/iggy/pull/3729#discussion_r3632922227


##########
core/integration/tests/connectors/fixtures/elasticsearch/container.rs:
##########


Review Comment:
   start() force-removes the shared container after any try_start() error, not only after confirming it is wedged. Transient health, port-inspection, or Docker errors can therefore remove an Elasticsearch container still used by another process. The fixed name limits which container is removed but does not provide ownership or concurrency safety. Could this recovery path verify the container is unhealthy and coordinate removal with a cross-process lock before running docker rm -f?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #3729:
URL: https://github.com/apache/iggy/pull/3729#discussion_r3633446401


##########
core/integration/tests/connectors/fixtures/elasticsearch/container.rs:
##########


Review Comment:
   Fixed



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #3729:
URL: https://github.com/apache/iggy/pull/3729#discussion_r3636828439


##########
core/integration/tests/connectors/fixtures/elasticsearch/container.rs:
##########
@@ -137,14 +195,308 @@ impl ElasticsearchContainer {
                 message: "No mapping for Elasticsearch port".to_string(),
             })?;
 
-        let base_url = format!("http://localhost:{mapped_port}");
+        // Prefer IPv4 loopback: Docker publishes 0.0.0.0:HOST→9200. `localhost`
+        // can resolve to ::1 first on macOS and black-hole the elasticsearch-rs
+        // client while the fixture's reqwest client still looks healthy.
+        let base_url = format!("http://127.0.0.1:{mapped_port}");
         info!("Elasticsearch container available at {base_url}");
 
-        Ok(Self {
+        let started = Self {
             container,
             base_url,
+        };
+        // ReuseDirective::Always can attach to a days-old container without
+        // re-running HttpWaitStrategy; verify cluster health on every setup.
+        started.wait_until_ready().await?;
+        started.sweep_stale_indices().await;
+        Ok(started)
+    }
+
+    async fn wait_until_ready(&self) -> Result<(), TestBinaryError> {
+        // Dedicated probe client: short timeout, no retry middleware. The shared
+        // create_http_client() (30s + 3 retries) turns one black-holed request
+        // into a multi-minute hang that looks like the test is stuck.
+        let client = reqwest::Client::builder()
+            .timeout(std::time::Duration::from_millis(
+                CLUSTER_READY_REQUEST_TIMEOUT_MS,
+            ))
+            .build()
+            .map_err(|error| TestBinaryError::FixtureSetup {
+                fixture_type: "ElasticsearchContainer".to_string(),
+                message: format!("Failed to build readiness HTTP client: {error}"),
+            })?;
+        // timeout=1s keeps ES from holding the request when the cluster is slow.
+        let health_url = format!(
+            "{}{ELASTICSEARCH_HEALTH_ENDPOINT}?timeout=1s",
+            self.base_url
+        );
+        let mut last_error = String::from("no attempts made");
+
+        for attempt in 1..=CLUSTER_READY_ATTEMPTS {
+            match client.get(&health_url).send().await {
+                Ok(response) if response.status().is_success() => {
+                    let body = response.text().await.unwrap_or_default();
+                    if body.contains("\"timed_out\":true") {

Review Comment:
   `?timeout=1s` without a `wait_for_*` param makes `/_cluster/health` return immediately with `timed_out: false`, so this check never fires - and any 200 counts as ready even with cluster status red. `?wait_for_status=yellow&timeout=1s` makes both the timeout param and this check do real work (and then parsing the bool beats string-matching the body).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #3729:
URL: https://github.com/apache/iggy/pull/3729#discussion_r3636828441


##########
core/integration/tests/connectors/fixtures/elasticsearch/container.rs:
##########
@@ -137,14 +195,308 @@ impl ElasticsearchContainer {
                 message: "No mapping for Elasticsearch port".to_string(),
             })?;
 
-        let base_url = format!("http://localhost:{mapped_port}");
+        // Prefer IPv4 loopback: Docker publishes 0.0.0.0:HOST→9200. `localhost`
+        // can resolve to ::1 first on macOS and black-hole the elasticsearch-rs
+        // client while the fixture's reqwest client still looks healthy.
+        let base_url = format!("http://127.0.0.1:{mapped_port}");
         info!("Elasticsearch container available at {base_url}");
 
-        Ok(Self {
+        let started = Self {
             container,
             base_url,
+        };
+        // ReuseDirective::Always can attach to a days-old container without
+        // re-running HttpWaitStrategy; verify cluster health on every setup.
+        started.wait_until_ready().await?;
+        started.sweep_stale_indices().await;
+        Ok(started)
+    }
+
+    async fn wait_until_ready(&self) -> Result<(), TestBinaryError> {
+        // Dedicated probe client: short timeout, no retry middleware. The shared
+        // create_http_client() (30s + 3 retries) turns one black-holed request
+        // into a multi-minute hang that looks like the test is stuck.
+        let client = reqwest::Client::builder()
+            .timeout(std::time::Duration::from_millis(
+                CLUSTER_READY_REQUEST_TIMEOUT_MS,
+            ))
+            .build()
+            .map_err(|error| TestBinaryError::FixtureSetup {
+                fixture_type: "ElasticsearchContainer".to_string(),
+                message: format!("Failed to build readiness HTTP client: {error}"),
+            })?;
+        // timeout=1s keeps ES from holding the request when the cluster is slow.
+        let health_url = format!(
+            "{}{ELASTICSEARCH_HEALTH_ENDPOINT}?timeout=1s",
+            self.base_url
+        );
+        let mut last_error = String::from("no attempts made");
+
+        for attempt in 1..=CLUSTER_READY_ATTEMPTS {
+            match client.get(&health_url).send().await {
+                Ok(response) if response.status().is_success() => {
+                    let body = response.text().await.unwrap_or_default();
+                    if body.contains("\"timed_out\":true") {
+                        last_error = format!(
+                            "cluster health timed out on attempt {attempt}/{CLUSTER_READY_ATTEMPTS}: {body}"
+                        );
+                    } else {
+                        info!("Elasticsearch cluster ready at {}", self.base_url);
+                        return Ok(());
+                    }
+                }
+                Ok(response) => {
+                    last_error = format!(
+                        "cluster health status {} on attempt {attempt}/{CLUSTER_READY_ATTEMPTS}",
+                        response.status()
+                    );
+                }
+                Err(error) => {
+                    last_error = format!(
+                        "cluster health request failed on attempt {attempt}/{CLUSTER_READY_ATTEMPTS}: {error}"
+                    );
+                }
+            }
+            tokio::time::sleep(std::time::Duration::from_millis(CLUSTER_READY_INTERVAL_MS)).await;
+        }
+
+        Err(TestBinaryError::FixtureSetup {
+            fixture_type: "ElasticsearchContainer".to_string(),
+            message: format!(
+                "Elasticsearch at {} not ready after {CLUSTER_READY_ATTEMPTS} attempts: {last_error}",
+                self.base_url
+            ),
         })
     }
+
+    /// Delete leftover test indices (empty or partially filled) from previous
+    /// runs so accumulated shards do not degrade the reused container. Only
+    /// indices older than [`STALE_INDEX_MAX_AGE_MS`] are removed, which keeps
+    /// the sweep safe against tests running concurrently in other processes.
+    /// Best-effort: failures are logged, never fail the fixture.
+    async fn sweep_stale_indices(&self) {
+        #[derive(Deserialize)]
+        struct CatIndexEntry {
+            index: String,
+            #[serde(rename = "creation.date")]
+            creation_date: Option<String>,
+        }
+
+        // Short timeout, no retries: sweep is best-effort and must not stall setup.
+        let Ok(client) = reqwest::Client::builder()
+            .timeout(std::time::Duration::from_secs(5))
+            .build()
+        else {
+            warn!("Skipping stale index sweep, failed to build HTTP client");
+            return;
+        };
+        let cat_url = format!(
+            "{}/_cat/indices/{STALE_INDEX_PATTERNS}?format=json&h=index,creation.date",
+            self.base_url
+        );
+
+        let entries = match client.get(&cat_url).send().await {
+            Ok(response) if response.status().is_success() => {
+                match response.json::<Vec<CatIndexEntry>>().await {
+                    Ok(entries) => entries,
+                    Err(error) => {
+                        warn!("Skipping stale index sweep, unparsable _cat response: {error}");
+                        return;
+                    }
+                }
+            }
+            Ok(response) => {
+                warn!(
+                    "Skipping stale index sweep, _cat/indices returned {}",
+                    response.status()
+                );
+                return;
+            }
+            Err(error) => {
+                warn!("Skipping stale index sweep, _cat/indices failed: {error}");
+                return;
+            }
+        };
+
+        let now_ms = std::time::SystemTime::now()
+            .duration_since(std::time::UNIX_EPOCH)
+            .map(|duration| duration.as_millis())
+            .unwrap_or(0);
+
+        let stale: Vec<String> = entries
+            .into_iter()
+            .filter_map(|entry| {
+                let created_ms = entry.creation_date.as_deref()?.parse::<u128>().ok()?;
+                (now_ms.saturating_sub(created_ms) > STALE_INDEX_MAX_AGE_MS).then_some(entry.index)
+            })
+            .collect();
+
+        if stale.is_empty() {
+            return;
+        }
+
+        // Chunked so the URL stays well under limits with many leftovers.
+        for chunk in stale.chunks(20) {
+            let delete_url = format!("{}/{}", self.base_url, chunk.join(","));
+            match client.delete(&delete_url).send().await {
+                Ok(response) if response.status().is_success() => {
+                    info!("Deleted {} stale Elasticsearch test indices", chunk.len());
+                }
+                Ok(response) => {
+                    warn!(
+                        "Failed to delete stale Elasticsearch indices, status {}",
+                        response.status()
+                    );
+                }
+                Err(error) => {
+                    warn!("Failed to delete stale Elasticsearch indices: {error}");
+                }
+            }
+        }
+    }
+}
+
+/// Cross-process advisory lock for inspect+rm recovery of the shared reuse
+/// container. Dropping the file releases the lock (including on process crash).
+struct RecoveryLock {
+    _file: File,
+}
+
+fn acquire_recovery_lock() -> Result<RecoveryLock, String> {
+    let path = std::env::temp_dir().join(RECOVERY_LOCK_FILE_NAME);

Review Comment:
   cross-process serialization only holds if every nextest process resolves the same `temp_dir()` - with a per-process `TMPDIR` (some sandbox/CI setups) each process locks its own file and recovery races silently. probably fine to accept, but worth a comment stating the assumption.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #3729:
URL: https://github.com/apache/iggy/pull/3729#discussion_r3633446401


##########
core/integration/tests/connectors/fixtures/elasticsearch/container.rs:
##########


Review Comment:
   Fixed in https://github.com/apache/iggy/pull/3729/commits/dd2c04ce743c78260a26d8992a02138c00ff8fc3



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on PR #3729:
URL: https://github.com/apache/iggy/pull/3729#issuecomment-5236791404

   /request-review  @hubcio 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on PR #3729:
URL: https://github.com/apache/iggy/pull/3729#issuecomment-5053116183

   /ready


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on PR #3729:
URL: https://github.com/apache/iggy/pull/3729#issuecomment-5371834532

   /ready


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #3729:
URL: https://github.com/apache/iggy/pull/3729#discussion_r3706589460


##########
core/integration/tests/connectors/fixtures/elasticsearch/container.rs:
##########
@@ -137,14 +198,320 @@ impl ElasticsearchContainer {
                 message: "No mapping for Elasticsearch port".to_string(),
             })?;
 
-        let base_url = format!("http://localhost:{mapped_port}");
+        // Prefer IPv4 loopback: Docker publishes 0.0.0.0:HOST→9200. `localhost`
+        // can resolve to ::1 first on macOS and black-hole the elasticsearch-rs
+        // client while the fixture's reqwest client still looks healthy.
+        let base_url = format!("http://127.0.0.1:{mapped_port}");
         info!("Elasticsearch container available at {base_url}");
 
-        Ok(Self {
+        let started = Self {
             container,
             base_url,
+        };
+        // ReuseDirective::Always can attach to a days-old container without
+        // re-running HttpWaitStrategy; verify cluster health on every setup.
+        started.wait_until_ready().await?;
+        started.sweep_stale_indices().await;
+        Ok(started)
+    }
+
+    async fn wait_until_ready(&self) -> Result<(), TestBinaryError> {
+        #[derive(Deserialize)]
+        struct ClusterHealth {
+            timed_out: bool,
+            status: String,
+        }
+
+        // Dedicated probe client: short timeout, no retry middleware. The shared
+        // create_http_client() (30s + 3 retries) turns one black-holed request
+        // into a multi-minute hang that looks like the test is stuck.
+        let client = reqwest::Client::builder()
+            .timeout(std::time::Duration::from_millis(
+                CLUSTER_READY_REQUEST_TIMEOUT_MS,
+            ))
+            .build()
+            .map_err(|error| TestBinaryError::FixtureSetup {
+                fixture_type: "ElasticsearchContainer".to_string(),
+                message: format!("Failed to build readiness HTTP client: {error}"),
+            })?;
+        // wait_for_status=yellow makes ES block until yellow/green or timeout=1s
+        // elapses; without wait_for_*, timeout is ignored and red still returns
+        // 200 with timed_out=false.
+        let health_url = format!(
+            "{}{ELASTICSEARCH_HEALTH_ENDPOINT}?wait_for_status=yellow&timeout=1s",
+            self.base_url
+        );
+        let mut last_error = String::from("no attempts made");
+
+        for attempt in 1..=CLUSTER_READY_ATTEMPTS {
+            match client.get(&health_url).send().await {
+                Ok(response) if response.status().is_success() => {
+                    match response.json::<ClusterHealth>().await {
+                        Ok(health) if !health.timed_out => {
+                            info!(
+                                "Elasticsearch cluster ready at {} (status={})",
+                                self.base_url, health.status
+                            );
+                            return Ok(());
+                        }
+                        Ok(health) => {
+                            last_error = format!(
+                                "cluster health timed out on attempt {attempt}/{CLUSTER_READY_ATTEMPTS} (status={})",
+                                health.status
+                            );
+                        }
+                        Err(error) => {
+                            last_error = format!(
+                                "cluster health body unparsable on attempt {attempt}/{CLUSTER_READY_ATTEMPTS}: {error}"
+                            );
+                        }
+                    }
+                }
+                Ok(response) => {
+                    last_error = format!(
+                        "cluster health status {} on attempt {attempt}/{CLUSTER_READY_ATTEMPTS}",
+                        response.status()
+                    );
+                }
+                Err(error) => {
+                    last_error = format!(
+                        "cluster health request failed on attempt {attempt}/{CLUSTER_READY_ATTEMPTS}: {error}"
+                    );
+                }
+            }
+            tokio::time::sleep(std::time::Duration::from_millis(CLUSTER_READY_INTERVAL_MS)).await;
+        }
+
+        Err(TestBinaryError::FixtureSetup {
+            fixture_type: "ElasticsearchContainer".to_string(),
+            message: format!(
+                "Elasticsearch at {} not ready after {CLUSTER_READY_ATTEMPTS} attempts: {last_error}",
+                self.base_url
+            ),
         })
     }
+
+    /// Delete leftover test indices (empty or partially filled) from previous
+    /// runs so accumulated shards do not degrade the reused container. Only
+    /// indices older than [`STALE_INDEX_MAX_AGE_MS`] are removed, which keeps
+    /// the sweep safe against tests running concurrently in other processes.
+    /// Best-effort: failures are logged, never fail the fixture.
+    async fn sweep_stale_indices(&self) {
+        #[derive(Deserialize)]
+        struct CatIndexEntry {
+            index: String,
+            #[serde(rename = "creation.date")]
+            creation_date: Option<String>,
+        }
+
+        // Short timeout, no retries: sweep is best-effort and must not stall setup.
+        let Ok(client) = reqwest::Client::builder()
+            .timeout(std::time::Duration::from_secs(5))
+            .build()
+        else {
+            warn!("Skipping stale index sweep, failed to build HTTP client");
+            return;
+        };
+        let cat_url = format!(
+            "{}/_cat/indices/{STALE_INDEX_PATTERNS}?format=json&h=index,creation.date",
+            self.base_url
+        );
+
+        let entries = match client.get(&cat_url).send().await {
+            Ok(response) if response.status().is_success() => {
+                match response.json::<Vec<CatIndexEntry>>().await {
+                    Ok(entries) => entries,
+                    Err(error) => {
+                        warn!("Skipping stale index sweep, unparsable _cat response: {error}");
+                        return;
+                    }
+                }
+            }
+            Ok(response) => {
+                warn!(
+                    "Skipping stale index sweep, _cat/indices returned {}",
+                    response.status()
+                );
+                return;
+            }
+            Err(error) => {
+                warn!("Skipping stale index sweep, _cat/indices failed: {error}");
+                return;
+            }
+        };
+
+        let now_ms = std::time::SystemTime::now()
+            .duration_since(std::time::UNIX_EPOCH)
+            .map(|duration| duration.as_millis())
+            .unwrap_or(0);
+
+        let stale: Vec<String> = entries
+            .into_iter()
+            .filter_map(|entry| {
+                let created_ms = entry.creation_date.as_deref()?.parse::<u128>().ok()?;
+                (now_ms.saturating_sub(created_ms) > STALE_INDEX_MAX_AGE_MS).then_some(entry.index)
+            })
+            .collect();
+
+        if stale.is_empty() {
+            return;
+        }
+
+        // Chunked so the URL stays well under limits with many leftovers.
+        for chunk in stale.chunks(20) {
+            let delete_url = format!("{}/{}", self.base_url, chunk.join(","));
+            match client.delete(&delete_url).send().await {
+                Ok(response) if response.status().is_success() => {
+                    info!("Deleted {} stale Elasticsearch test indices", chunk.len());
+                }
+                Ok(response) => {
+                    warn!(
+                        "Failed to delete stale Elasticsearch indices, status {}",
+                        response.status()
+                    );
+                }
+                Err(error) => {
+                    warn!("Failed to delete stale Elasticsearch indices: {error}");
+                }
+            }
+        }
+    }
+}
+
+/// Cross-process advisory lock for inspect+rm recovery of the shared reuse
+/// container. Dropping the file releases the lock (including on process crash).
+///
+/// Assumes every nextest process shares the same `std::env::temp_dir()` (and
+/// thus the same lock file). A per-process `TMPDIR` makes each worker lock its
+/// own path and recovery can race silently.
+struct RecoveryLock {
+    _file: File,
+}
+
+async fn acquire_recovery_lock() -> Result<RecoveryLock, String> {
+    let path = std::env::temp_dir().join(RECOVERY_LOCK_FILE_NAME);
+    let file = OpenOptions::new()
+        .read(true)
+        .write(true)
+        .create(true)
+        .truncate(false)
+        .open(&path)
+        .map_err(|error| format!("open {}: {error}", path.display()))?;
+
+    let deadline = Instant::now() + Duration::from_secs(RECOVERY_LOCK_TIMEOUT_SECS);
+    loop {
+        match file.try_lock() {
+            Ok(()) => return Ok(RecoveryLock { _file: file }),
+            Err(TryLockError::WouldBlock) if Instant::now() < deadline => {
+                tokio::time::sleep(Duration::from_millis(RECOVERY_LOCK_POLL_MS)).await;
+            }
+            Err(TryLockError::WouldBlock) => {
+                return Err(format!(
+                    "timed out after {RECOVERY_LOCK_TIMEOUT_SECS}s waiting for {}",
+                    path.display()
+                ));
+            }
+            Err(TryLockError::Error(error)) => {
+                return Err(format!("lock {}: {error}", path.display()));
+            }
+        }
+    }
+}
+
+/// True only when Docker says the shared container is in a state safe to
+/// force-remove without yanking a healthy instance from a peer process.
+///
+/// Removable: exited/dead/created/paused/restarting, or Docker healthcheck
+/// `unhealthy`. A plain `running` container (even if ES HTTP is flaky) is left
+/// alone: readiness flakes must not `docker rm -f` a shared Always-reuse box.
+async fn container_is_removable_wedged() -> bool {
+    let inspect_format = "{{.State.Status}}|{{if .State.Health}}{{.State.Health.Status}}{{end}}";
+    let Some(stdout) = docker_command_stdout(
+        &[
+            "inspect",
+            "-f",
+            inspect_format,
+            ELASTICSEARCH_CONTAINER_NAME,
+        ],
+        DOCKER_INSPECT_TIMEOUT_SECS,
+    )
+    .await
+    else {
+        return false;
+    };
+
+    let mut parts = stdout.trim().split('|');
+    let status = parts.next().unwrap_or("").trim();
+    let health = parts.next().unwrap_or("").trim();
+
+    matches!(
+        status,
+        "exited" | "dead" | "created" | "paused" | "restarting"
+    ) || health == "unhealthy"

Review Comment:
   Fixed in [58858e8](https://github.com/apache/iggy/pull/3729/commits/58858e820343ac4745449cf291f9354a6269c49b)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #3729:
URL: https://github.com/apache/iggy/pull/3729#discussion_r3783949387


##########
core/integration/tests/connectors/fixtures/elasticsearch/container.rs:
##########
@@ -37,6 +40,25 @@ const ELASTICSEARCH_HEALTH_ENDPOINT: &str = "/_cluster/health";
 // name. Per-test isolation comes from a unique index per fixture, not a fresh
 // container.
 const ELASTICSEARCH_CONTAINER_NAME: &str = "iggy-test-elasticsearch";
+// Short probe timeouts: create_http_client() uses 30s + retries and must not
+// be used for readiness. One hung attempt there looks like a 60s+ test hang.
+const CLUSTER_READY_ATTEMPTS: usize = 40;

Review Comment:
   this attempt budget is only ~10s while probes fail fast (connection refused during boot), and it's the sole readiness gate when attaching to a container another process just created or restarted - `HttpWaitStrategy` runs only for the creator. a cold boot here took ~12s to go green, so an attaching test ran out of attempts just short of ready. a time deadline (e.g. 60s) fits better than an attempt count: once es answers, each attempt costs up to ~1s server-side, so raising the count alone would stretch the failure path instead.



##########
core/integration/tests/connectors/fixtures/elasticsearch/sink.rs:
##########
@@ -88,6 +106,74 @@ impl ElasticsearchSinkFixture {
     pub async fn refresh_index(&self) -> Result<(), TestBinaryError> {
         ElasticsearchOps::refresh_index(self, &self.index).await
     }
+
+    /// Refresh with a short-timeout client for the document poll loop.
+    async fn refresh_index_probe(&self) -> Result<(), TestBinaryError> {
+        let client = probe_client()?;
+        let url = format!("{}/{}/_refresh", self.container.base_url, self.index);
+        let response =
+            client
+                .post(&url)
+                .send()
+                .await
+                .map_err(|error| TestBinaryError::InvalidState {
+                    message: format!("Failed to refresh index: {error}"),
+                })?;
+        if !response.status().is_success() {
+            let status = response.status();
+            let body = response.text().await.unwrap_or_default();
+            return Err(TestBinaryError::InvalidState {
+                message: format!("Failed to refresh index: status={status}, body={body}"),
+            });
+        }
+        Ok(())
+    }
+
+    /// Count with a short-timeout client for the document poll loop.
+    ///
+    /// `count_documents` (via `ElasticsearchOps`) goes through the shared
+    /// `create_http_client()` - 30s timeout plus 3 retries - so a degraded
+    /// `_count` endpoint could block this poll for minutes even though
+    /// `refresh_index_probe` already uses a short timeout.
+    async fn count_documents_probe(&self) -> Result<usize, TestBinaryError> {
+        let client = probe_client()?;
+        let url = format!("{}/{}/_count", self.container.base_url, self.index);
+        let response =
+            client
+                .get(&url)
+                .send()
+                .await
+                .map_err(|error| TestBinaryError::InvalidState {
+                    message: format!("Failed to count documents: {error}"),
+                })?;
+        if !response.status().is_success() {
+            let status = response.status();
+            let body = response.text().await.unwrap_or_default();
+            return Err(TestBinaryError::InvalidState {
+                message: format!("Failed to count documents: status={status}, body={body}"),
+            });
+        }
+
+        #[derive(serde::Deserialize)]
+        struct CountResponse {
+            count: usize,
+        }
+        let count_response = response.json::<CountResponse>().await.map_err(|error| {
+            TestBinaryError::InvalidState {
+                message: format!("Failed to parse count response: {error}"),
+            }
+        })?;
+        Ok(count_response.count)
+    }
+}
+
+fn probe_client() -> Result<reqwest::Client, TestBinaryError> {

Review Comment:
   this builds a fresh client on every call - twice per poll iteration - and each `Client::build()` re-parses the system ca store via rustls-platform-verifier even for plain http, plus loses keep-alive between probes. build one client before the loop in `wait_for_documents` and pass it to the two probe helpers.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "slbotbm (via GitHub)" <gi...@apache.org>.
slbotbm commented on code in PR #3729:
URL: https://github.com/apache/iggy/pull/3729#discussion_r3699367186


##########
core/integration/tests/connectors/fixtures/elasticsearch/sink.rs:
##########


Review Comment:
   At sink.rs:91, the refresh was moved to a short-timeout client, but `count_documents()` still uses create_http_client() with a 30-second timeout and three retries. The unconditional final count at sink.rs:91 does too. A degraded _count endpoint can therefore keep this failure path blocked for minutes. The short-timeout probe client should cover both refresh and count.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "slbotbm (via GitHub)" <gi...@apache.org>.
slbotbm commented on code in PR #3729:
URL: https://github.com/apache/iggy/pull/3729#discussion_r3839806735


##########
core/integration/src/harness/handle/connectors_runtime.rs:
##########


Review Comment:
   `DEFAULT_HEALTH_CHECK_RETRIES` is 1,000 and the interval is 20 ms. On the black-holed request case these serial 2-second client timeouts make `wait_ready()` take roughly 34 minutes, so the harness can still hang for a long time even after this change. Bound the whole readiness loop with a deadline, or reduce the retry budget to account for the per-request timeout, rather than only bounding each probe.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #3729:
URL: https://github.com/apache/iggy/pull/3729#discussion_r3633252886


##########
core/integration/tests/connectors/fixtures/elasticsearch/container.rs:
##########


Review Comment:
   Let me add remove when required.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #3729:
URL: https://github.com/apache/iggy/pull/3729#discussion_r3636828435


##########
core/integration/src/harness/handle/connectors_runtime.rs:
##########
@@ -243,19 +243,33 @@ impl IggyServerDependent for ConnectorsRuntimeHandle {
     }
 
     async fn wait_ready(&mut self) -> Result<(), TestBinaryError> {
-        let http_address = self.http_url();
+        // Prefer /health over `/` so readiness means the connectors API is up,
+        // not some other listener that happened to bind the reserved port.
+        let health_url = format!("{}/health", self.http_url());
         let client = reqwest::Client::new();

Review Comment:
   `reqwest::Client::new()` has no request timeout, so a black-holed GET (connection accepted, no response) hangs `send()` forever - the loop never gets back to the pid check above and the retry budget never fires. low risk on localhost (dead process means ECONNREFUSED, which fast-fails), but a 1-2s timeout like the fixture probe client makes both guards effective.



##########
core/connectors/sinks/elasticsearch_sink/src/lib.rs:
##########
@@ -83,7 +86,15 @@ impl ElasticsearchSink {
             .map_err(|error| Error::Connection(format!("Invalid Elasticsearch URL: {error}")))?;
 
         let conn_pool = elasticsearch::http::transport::SingleNodeConnectionPool::new(url);
-        let mut transport_builder = TransportBuilder::new(conn_pool);
+        // elasticsearch-rs defaults to no timeout; without this, a hung ES
+        // connection blocks FFI open() and the connectors HTTP health never binds.
+        let timeout_seconds = self
+            .config
+            .timeout_seconds
+            .unwrap_or(DEFAULT_TIMEOUT_SECONDS)
+            .max(1);
+        let mut transport_builder =
+            TransportBuilder::new(conn_pool).timeout(Duration::from_secs(timeout_seconds));

Review Comment:
   this timeout is client-global in elasticsearch-rs, so it bounds bulk requests in `consume()` too, not just `open()`. that changes the failure mode: before, a bulk on degraded ES stalled until it eventually succeeded; now anything over `timeout_seconds` returns `Err`, which the runtime discards (#2927) with the offset already committed at poll (#2928) - the batch is silently dropped. mechanism is pre-existing and tracked there, but this PR is what arms it for slow-ES bulk. worth an upgrade note in the PR description: raise `timeout_seconds` for slow bulk workloads, and note the tradeoff until #2927/#2928 land.
   
   separately, the comment slightly oversells the timeout as the flake fix - with the 30s default the harness readiness budget (~20s) expires first, so what fixes #3728 is the fixture readiness gate; this is the infinite-hang backstop. maybe say that instead.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #3729:
URL: https://github.com/apache/iggy/pull/3729#discussion_r3636828430


##########
core/connectors/sinks/elasticsearch_sink/src/lib.rs:
##########
@@ -83,7 +86,15 @@ impl ElasticsearchSink {
             .map_err(|error| Error::Connection(format!("Invalid Elasticsearch URL: {error}")))?;
 
         let conn_pool = elasticsearch::http::transport::SingleNodeConnectionPool::new(url);
-        let mut transport_builder = TransportBuilder::new(conn_pool);
+        // elasticsearch-rs defaults to no timeout; without this, a hung ES
+        // connection blocks FFI open() and the connectors HTTP health never binds.
+        let timeout_seconds = self
+            .config
+            .timeout_seconds
+            .unwrap_or(DEFAULT_TIMEOUT_SECONDS)
+            .max(1);

Review Comment:
   `.max(1)` silently turns `timeout_seconds: 0` into 1s. defensible - `Duration::ZERO` would instant-fail every request - but undocumented, and clickhouse_sink passes 0 through unclamped, so the two siblings now disagree on the same config field. document the clamp here; clickhouse should probably get the same guard.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): harden Elasticsearch sink test readiness [iggy]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #3729:
URL: https://github.com/apache/iggy/pull/3729#issuecomment-5041022498

   ## [Codecov](https://app.codecov.io/gh/apache/iggy/pull/3729?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :white_check_mark: All modified and coverable lines are covered by tests.
   :white_check_mark: Project coverage is 37.82%. Comparing base ([`a5001d3`](https://app.codecov.io/gh/apache/iggy/commit/a5001d3592889dca2ffc805ea8744d8518cd83bd?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`72fd3b7`](https://app.codecov.io/gh/apache/iggy/commit/72fd3b72a89c3b7c24d31582f51e1be82b2bb4e3?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@              Coverage Diff              @@
   ##             master    #3729       +/-   ##
   =============================================
   - Coverage     74.34%   37.82%   -36.53%     
     Complexity      950      950               
   =============================================
     Files          1303     1301        -2     
     Lines        148712   129057    -19655     
     Branches     124225   104570    -19655     
   =============================================
   - Hits         110562    48811    -61751     
   - Misses        34673    77640    +42967     
   + Partials       3477     2606      -871     
   ```
   
   | [Components](https://app.codecov.io/gh/apache/iggy/pull/3729/components?src=pr&el=components&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [Rust Core](https://app.codecov.io/gh/apache/iggy/pull/3729/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `29.02% <100.00%> (-45.56%)` | :arrow_down: |
   | [Java SDK](https://app.codecov.io/gh/apache/iggy/pull/3729/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `62.64% <ø> (ø)` | |
   | [C# SDK](https://app.codecov.io/gh/apache/iggy/pull/3729/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `72.28% <ø> (ø)` | |
   | [Python SDK](https://app.codecov.io/gh/apache/iggy/pull/3729/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `92.27% <ø> (ø)` | |
   | [PHP SDK](https://app.codecov.io/gh/apache/iggy/pull/3729/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `84.52% <ø> (ø)` | |
   | [Node SDK](https://app.codecov.io/gh/apache/iggy/pull/3729/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `92.70% <ø> (ø)` | |
   | [Go SDK](https://app.codecov.io/gh/apache/iggy/pull/3729/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `43.08% <ø> (ø)` | |
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/iggy/pull/3729?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [...ore/connectors/sinks/elasticsearch\_sink/src/lib.rs](https://app.codecov.io/gh/apache/iggy/pull/3729?src=pr&el=tree&filepath=core%2Fconnectors%2Fsinks%2Felasticsearch_sink%2Fsrc%2Flib.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb25uZWN0b3JzL3NpbmtzL2VsYXN0aWNzZWFyY2hfc2luay9zcmMvbGliLnJz) | `67.60% <100.00%> (+1.42%)` | :arrow_up: |
   
   ... and [515 files with indirect coverage changes](https://app.codecov.io/gh/apache/iggy/pull/3729/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)
   </details>
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "raviyerraguntla (via GitHub)" <gi...@apache.org>.
raviyerraguntla commented on PR #3729:
URL: https://github.com/apache/iggy/pull/3729#issuecomment-5185687149

   /request-review @hubcio @numinnex 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #3729:
URL: https://github.com/apache/iggy/pull/3729#discussion_r3636828449


##########
core/integration/tests/connectors/fixtures/elasticsearch/container.rs:
##########
@@ -137,14 +195,308 @@ impl ElasticsearchContainer {
                 message: "No mapping for Elasticsearch port".to_string(),
             })?;
 
-        let base_url = format!("http://localhost:{mapped_port}");
+        // Prefer IPv4 loopback: Docker publishes 0.0.0.0:HOST→9200. `localhost`
+        // can resolve to ::1 first on macOS and black-hole the elasticsearch-rs
+        // client while the fixture's reqwest client still looks healthy.
+        let base_url = format!("http://127.0.0.1:{mapped_port}");
         info!("Elasticsearch container available at {base_url}");
 
-        Ok(Self {
+        let started = Self {
             container,
             base_url,
+        };
+        // ReuseDirective::Always can attach to a days-old container without
+        // re-running HttpWaitStrategy; verify cluster health on every setup.
+        started.wait_until_ready().await?;
+        started.sweep_stale_indices().await;
+        Ok(started)
+    }
+
+    async fn wait_until_ready(&self) -> Result<(), TestBinaryError> {
+        // Dedicated probe client: short timeout, no retry middleware. The shared
+        // create_http_client() (30s + 3 retries) turns one black-holed request
+        // into a multi-minute hang that looks like the test is stuck.
+        let client = reqwest::Client::builder()
+            .timeout(std::time::Duration::from_millis(
+                CLUSTER_READY_REQUEST_TIMEOUT_MS,
+            ))
+            .build()
+            .map_err(|error| TestBinaryError::FixtureSetup {
+                fixture_type: "ElasticsearchContainer".to_string(),
+                message: format!("Failed to build readiness HTTP client: {error}"),
+            })?;
+        // timeout=1s keeps ES from holding the request when the cluster is slow.
+        let health_url = format!(
+            "{}{ELASTICSEARCH_HEALTH_ENDPOINT}?timeout=1s",
+            self.base_url
+        );
+        let mut last_error = String::from("no attempts made");
+
+        for attempt in 1..=CLUSTER_READY_ATTEMPTS {
+            match client.get(&health_url).send().await {
+                Ok(response) if response.status().is_success() => {
+                    let body = response.text().await.unwrap_or_default();
+                    if body.contains("\"timed_out\":true") {
+                        last_error = format!(
+                            "cluster health timed out on attempt {attempt}/{CLUSTER_READY_ATTEMPTS}: {body}"
+                        );
+                    } else {
+                        info!("Elasticsearch cluster ready at {}", self.base_url);
+                        return Ok(());
+                    }
+                }
+                Ok(response) => {
+                    last_error = format!(
+                        "cluster health status {} on attempt {attempt}/{CLUSTER_READY_ATTEMPTS}",
+                        response.status()
+                    );
+                }
+                Err(error) => {
+                    last_error = format!(
+                        "cluster health request failed on attempt {attempt}/{CLUSTER_READY_ATTEMPTS}: {error}"
+                    );
+                }
+            }
+            tokio::time::sleep(std::time::Duration::from_millis(CLUSTER_READY_INTERVAL_MS)).await;
+        }
+
+        Err(TestBinaryError::FixtureSetup {
+            fixture_type: "ElasticsearchContainer".to_string(),
+            message: format!(
+                "Elasticsearch at {} not ready after {CLUSTER_READY_ATTEMPTS} attempts: {last_error}",
+                self.base_url
+            ),
         })
     }
+
+    /// Delete leftover test indices (empty or partially filled) from previous
+    /// runs so accumulated shards do not degrade the reused container. Only
+    /// indices older than [`STALE_INDEX_MAX_AGE_MS`] are removed, which keeps
+    /// the sweep safe against tests running concurrently in other processes.
+    /// Best-effort: failures are logged, never fail the fixture.
+    async fn sweep_stale_indices(&self) {
+        #[derive(Deserialize)]
+        struct CatIndexEntry {
+            index: String,
+            #[serde(rename = "creation.date")]
+            creation_date: Option<String>,
+        }
+
+        // Short timeout, no retries: sweep is best-effort and must not stall setup.
+        let Ok(client) = reqwest::Client::builder()
+            .timeout(std::time::Duration::from_secs(5))
+            .build()
+        else {
+            warn!("Skipping stale index sweep, failed to build HTTP client");
+            return;
+        };
+        let cat_url = format!(
+            "{}/_cat/indices/{STALE_INDEX_PATTERNS}?format=json&h=index,creation.date",
+            self.base_url
+        );
+
+        let entries = match client.get(&cat_url).send().await {
+            Ok(response) if response.status().is_success() => {
+                match response.json::<Vec<CatIndexEntry>>().await {
+                    Ok(entries) => entries,
+                    Err(error) => {
+                        warn!("Skipping stale index sweep, unparsable _cat response: {error}");
+                        return;
+                    }
+                }
+            }
+            Ok(response) => {
+                warn!(
+                    "Skipping stale index sweep, _cat/indices returned {}",
+                    response.status()
+                );
+                return;
+            }
+            Err(error) => {
+                warn!("Skipping stale index sweep, _cat/indices failed: {error}");
+                return;
+            }
+        };
+
+        let now_ms = std::time::SystemTime::now()
+            .duration_since(std::time::UNIX_EPOCH)
+            .map(|duration| duration.as_millis())
+            .unwrap_or(0);
+
+        let stale: Vec<String> = entries
+            .into_iter()
+            .filter_map(|entry| {
+                let created_ms = entry.creation_date.as_deref()?.parse::<u128>().ok()?;
+                (now_ms.saturating_sub(created_ms) > STALE_INDEX_MAX_AGE_MS).then_some(entry.index)
+            })
+            .collect();
+
+        if stale.is_empty() {
+            return;
+        }
+
+        // Chunked so the URL stays well under limits with many leftovers.
+        for chunk in stale.chunks(20) {
+            let delete_url = format!("{}/{}", self.base_url, chunk.join(","));
+            match client.delete(&delete_url).send().await {
+                Ok(response) if response.status().is_success() => {
+                    info!("Deleted {} stale Elasticsearch test indices", chunk.len());
+                }
+                Ok(response) => {
+                    warn!(
+                        "Failed to delete stale Elasticsearch indices, status {}",
+                        response.status()
+                    );
+                }
+                Err(error) => {
+                    warn!("Failed to delete stale Elasticsearch indices: {error}");
+                }
+            }
+        }
+    }
+}
+
+/// Cross-process advisory lock for inspect+rm recovery of the shared reuse
+/// container. Dropping the file releases the lock (including on process crash).
+struct RecoveryLock {
+    _file: File,
+}
+
+fn acquire_recovery_lock() -> Result<RecoveryLock, String> {
+    let path = std::env::temp_dir().join(RECOVERY_LOCK_FILE_NAME);
+    let file = OpenOptions::new()
+        .read(true)
+        .write(true)
+        .create(true)
+        .truncate(false)
+        .open(&path)
+        .map_err(|error| format!("open {}: {error}", path.display()))?;
+    file.lock()

Review Comment:
   `File::lock()` blocks with no acquire timeout - worst case a peer holds this through its whole recovery (two 120s container starts plus readiness waits), and since the test runtime is current-thread, the block parks the entire runtime for that long. bounded and failure-path-only, so nice-to-have: `try_lock()` with a deadline.



##########
core/integration/tests/connectors/fixtures/elasticsearch/sink.rs:
##########
@@ -61,22 +61,38 @@ impl ElasticsearchSinkFixture {
         &self,
         expected_count: usize,
     ) -> Result<usize, TestBinaryError> {
+        let mut last_error: Option<TestBinaryError> = None;
+
         for _ in 0..POLL_ATTEMPTS {
+            // Refresh so near-real-time search/count sees recently indexed docs.
+            if let Err(error) = self.refresh_index().await {

Review Comment:
   `refresh_index()` goes through `create_http_client()` (30s timeout + 3 retries) inside a 50ms poll loop - on the failure path that is up to 100 refreshes, each with retry backoff. happy path exits in a few iterations so this only inflates time-to-failure; the short-timeout probe-client pattern from container.rs would fit here too.



##########
core/integration/tests/connectors/fixtures/elasticsearch/container.rs:
##########
@@ -137,14 +195,308 @@ impl ElasticsearchContainer {
                 message: "No mapping for Elasticsearch port".to_string(),
             })?;
 
-        let base_url = format!("http://localhost:{mapped_port}");
+        // Prefer IPv4 loopback: Docker publishes 0.0.0.0:HOST→9200. `localhost`
+        // can resolve to ::1 first on macOS and black-hole the elasticsearch-rs
+        // client while the fixture's reqwest client still looks healthy.
+        let base_url = format!("http://127.0.0.1:{mapped_port}");
         info!("Elasticsearch container available at {base_url}");
 
-        Ok(Self {
+        let started = Self {
             container,
             base_url,
+        };
+        // ReuseDirective::Always can attach to a days-old container without
+        // re-running HttpWaitStrategy; verify cluster health on every setup.
+        started.wait_until_ready().await?;
+        started.sweep_stale_indices().await;
+        Ok(started)
+    }
+
+    async fn wait_until_ready(&self) -> Result<(), TestBinaryError> {
+        // Dedicated probe client: short timeout, no retry middleware. The shared
+        // create_http_client() (30s + 3 retries) turns one black-holed request
+        // into a multi-minute hang that looks like the test is stuck.
+        let client = reqwest::Client::builder()
+            .timeout(std::time::Duration::from_millis(
+                CLUSTER_READY_REQUEST_TIMEOUT_MS,
+            ))
+            .build()
+            .map_err(|error| TestBinaryError::FixtureSetup {
+                fixture_type: "ElasticsearchContainer".to_string(),
+                message: format!("Failed to build readiness HTTP client: {error}"),
+            })?;
+        // timeout=1s keeps ES from holding the request when the cluster is slow.
+        let health_url = format!(
+            "{}{ELASTICSEARCH_HEALTH_ENDPOINT}?timeout=1s",
+            self.base_url
+        );
+        let mut last_error = String::from("no attempts made");
+
+        for attempt in 1..=CLUSTER_READY_ATTEMPTS {
+            match client.get(&health_url).send().await {
+                Ok(response) if response.status().is_success() => {
+                    let body = response.text().await.unwrap_or_default();
+                    if body.contains("\"timed_out\":true") {
+                        last_error = format!(
+                            "cluster health timed out on attempt {attempt}/{CLUSTER_READY_ATTEMPTS}: {body}"
+                        );
+                    } else {
+                        info!("Elasticsearch cluster ready at {}", self.base_url);
+                        return Ok(());
+                    }
+                }
+                Ok(response) => {
+                    last_error = format!(
+                        "cluster health status {} on attempt {attempt}/{CLUSTER_READY_ATTEMPTS}",
+                        response.status()
+                    );
+                }
+                Err(error) => {
+                    last_error = format!(
+                        "cluster health request failed on attempt {attempt}/{CLUSTER_READY_ATTEMPTS}: {error}"
+                    );
+                }
+            }
+            tokio::time::sleep(std::time::Duration::from_millis(CLUSTER_READY_INTERVAL_MS)).await;
+        }
+
+        Err(TestBinaryError::FixtureSetup {
+            fixture_type: "ElasticsearchContainer".to_string(),
+            message: format!(
+                "Elasticsearch at {} not ready after {CLUSTER_READY_ATTEMPTS} attempts: {last_error}",
+                self.base_url
+            ),
         })
     }
+
+    /// Delete leftover test indices (empty or partially filled) from previous
+    /// runs so accumulated shards do not degrade the reused container. Only
+    /// indices older than [`STALE_INDEX_MAX_AGE_MS`] are removed, which keeps
+    /// the sweep safe against tests running concurrently in other processes.
+    /// Best-effort: failures are logged, never fail the fixture.
+    async fn sweep_stale_indices(&self) {
+        #[derive(Deserialize)]
+        struct CatIndexEntry {
+            index: String,
+            #[serde(rename = "creation.date")]
+            creation_date: Option<String>,
+        }
+
+        // Short timeout, no retries: sweep is best-effort and must not stall setup.
+        let Ok(client) = reqwest::Client::builder()
+            .timeout(std::time::Duration::from_secs(5))
+            .build()
+        else {
+            warn!("Skipping stale index sweep, failed to build HTTP client");
+            return;
+        };
+        let cat_url = format!(
+            "{}/_cat/indices/{STALE_INDEX_PATTERNS}?format=json&h=index,creation.date",
+            self.base_url
+        );
+
+        let entries = match client.get(&cat_url).send().await {
+            Ok(response) if response.status().is_success() => {
+                match response.json::<Vec<CatIndexEntry>>().await {
+                    Ok(entries) => entries,
+                    Err(error) => {
+                        warn!("Skipping stale index sweep, unparsable _cat response: {error}");
+                        return;
+                    }
+                }
+            }
+            Ok(response) => {
+                warn!(
+                    "Skipping stale index sweep, _cat/indices returned {}",
+                    response.status()
+                );
+                return;
+            }
+            Err(error) => {
+                warn!("Skipping stale index sweep, _cat/indices failed: {error}");
+                return;
+            }
+        };
+
+        let now_ms = std::time::SystemTime::now()
+            .duration_since(std::time::UNIX_EPOCH)
+            .map(|duration| duration.as_millis())
+            .unwrap_or(0);
+
+        let stale: Vec<String> = entries
+            .into_iter()
+            .filter_map(|entry| {
+                let created_ms = entry.creation_date.as_deref()?.parse::<u128>().ok()?;
+                (now_ms.saturating_sub(created_ms) > STALE_INDEX_MAX_AGE_MS).then_some(entry.index)
+            })
+            .collect();
+
+        if stale.is_empty() {
+            return;
+        }
+
+        // Chunked so the URL stays well under limits with many leftovers.
+        for chunk in stale.chunks(20) {
+            let delete_url = format!("{}/{}", self.base_url, chunk.join(","));
+            match client.delete(&delete_url).send().await {
+                Ok(response) if response.status().is_success() => {
+                    info!("Deleted {} stale Elasticsearch test indices", chunk.len());
+                }
+                Ok(response) => {
+                    warn!(
+                        "Failed to delete stale Elasticsearch indices, status {}",
+                        response.status()
+                    );
+                }
+                Err(error) => {
+                    warn!("Failed to delete stale Elasticsearch indices: {error}");
+                }
+            }
+        }
+    }
+}
+
+/// Cross-process advisory lock for inspect+rm recovery of the shared reuse
+/// container. Dropping the file releases the lock (including on process crash).
+struct RecoveryLock {
+    _file: File,
+}
+
+fn acquire_recovery_lock() -> Result<RecoveryLock, String> {
+    let path = std::env::temp_dir().join(RECOVERY_LOCK_FILE_NAME);
+    let file = OpenOptions::new()
+        .read(true)
+        .write(true)
+        .create(true)
+        .truncate(false)
+        .open(&path)
+        .map_err(|error| format!("open {}: {error}", path.display()))?;
+    file.lock()
+        .map_err(|error| format!("lock {}: {error}", path.display()))?;
+    Ok(RecoveryLock { _file: file })
+}
+
+/// True only when Docker says the shared container is in a state safe to
+/// force-remove without yanking a healthy instance from a peer process.
+///
+/// Removable: exited/dead/created/paused/restarting, or Docker healthcheck
+/// `unhealthy`. A plain `running` container (even if ES HTTP is flaky) is left
+/// alone: readiness flakes must not `docker rm -f` a shared Always-reuse box.
+fn container_is_removable_wedged() -> bool {
+    let inspect_format = "{{.State.Status}}|{{if .State.Health}}{{.State.Health.Status}}{{end}}";
+    let Some(stdout) = docker_command_stdout(
+        &[
+            "inspect",
+            "-f",
+            inspect_format,
+            ELASTICSEARCH_CONTAINER_NAME,
+        ],
+        DOCKER_INSPECT_TIMEOUT_SECS,
+    ) else {
+        return false;
+    };
+
+    let mut parts = stdout.trim().split('|');
+    let status = parts.next().unwrap_or("").trim();
+    let health = parts.next().unwrap_or("").trim();
+
+    matches!(
+        status,
+        "exited" | "dead" | "created" | "paused" | "restarting"
+    ) || health == "unhealthy"
+}
+
+fn docker_command_stdout(args: &[&str], timeout_secs: u64) -> Option<String> {

Review Comment:
   `docker_command_stdout` and `force_remove_container` duplicate the spawn / `try_wait` / deadline / kill loop, and both block the async caller (`thread::sleep` on a current-thread runtime). `tokio::process::Command` + `tokio::time::timeout(dur, cmd.output())` + `kill_on_drop(true)` collapses both to a few lines with the same 5s/15s kill semantics - `delta/fixture.rs:254` is the in-repo precedent and tokio `full` is already enabled here. it also removes a latent footgun: stdout is only drained after exit, so docker output over the pipe buffer (~64KB) would deadlock until the timeout kill. fine today with one-line `inspect -f` output, but the helper reads as generic.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on PR #3729:
URL: https://github.com/apache/iggy/pull/3729#issuecomment-5084966929

   /ready
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #3729:
URL: https://github.com/apache/iggy/pull/3729#discussion_r3841205673


##########
core/integration/src/harness/handle/connectors_runtime.rs:
##########


Review Comment:
   fixed



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix(connectors): Harden Elasticsearch sink test readiness [iggy]

Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #3729:
URL: https://github.com/apache/iggy/pull/3729#discussion_r3831725349


##########
core/integration/tests/connectors/fixtures/elasticsearch/container.rs:
##########
@@ -37,6 +40,25 @@ const ELASTICSEARCH_HEALTH_ENDPOINT: &str = "/_cluster/health";
 // name. Per-test isolation comes from a unique index per fixture, not a fresh
 // container.
 const ELASTICSEARCH_CONTAINER_NAME: &str = "iggy-test-elasticsearch";
+// Short probe timeouts: create_http_client() uses 30s + retries and must not
+// be used for readiness. One hung attempt there looks like a 60s+ test hang.
+const CLUSTER_READY_ATTEMPTS: usize = 40;

Review Comment:
   Fixed



##########
core/integration/tests/connectors/fixtures/elasticsearch/sink.rs:
##########
@@ -88,6 +106,74 @@ impl ElasticsearchSinkFixture {
     pub async fn refresh_index(&self) -> Result<(), TestBinaryError> {
         ElasticsearchOps::refresh_index(self, &self.index).await
     }
+
+    /// Refresh with a short-timeout client for the document poll loop.
+    async fn refresh_index_probe(&self) -> Result<(), TestBinaryError> {
+        let client = probe_client()?;
+        let url = format!("{}/{}/_refresh", self.container.base_url, self.index);
+        let response =
+            client
+                .post(&url)
+                .send()
+                .await
+                .map_err(|error| TestBinaryError::InvalidState {
+                    message: format!("Failed to refresh index: {error}"),
+                })?;
+        if !response.status().is_success() {
+            let status = response.status();
+            let body = response.text().await.unwrap_or_default();
+            return Err(TestBinaryError::InvalidState {
+                message: format!("Failed to refresh index: status={status}, body={body}"),
+            });
+        }
+        Ok(())
+    }
+
+    /// Count with a short-timeout client for the document poll loop.
+    ///
+    /// `count_documents` (via `ElasticsearchOps`) goes through the shared
+    /// `create_http_client()` - 30s timeout plus 3 retries - so a degraded
+    /// `_count` endpoint could block this poll for minutes even though
+    /// `refresh_index_probe` already uses a short timeout.
+    async fn count_documents_probe(&self) -> Result<usize, TestBinaryError> {
+        let client = probe_client()?;
+        let url = format!("{}/{}/_count", self.container.base_url, self.index);
+        let response =
+            client
+                .get(&url)
+                .send()
+                .await
+                .map_err(|error| TestBinaryError::InvalidState {
+                    message: format!("Failed to count documents: {error}"),
+                })?;
+        if !response.status().is_success() {
+            let status = response.status();
+            let body = response.text().await.unwrap_or_default();
+            return Err(TestBinaryError::InvalidState {
+                message: format!("Failed to count documents: status={status}, body={body}"),
+            });
+        }
+
+        #[derive(serde::Deserialize)]
+        struct CountResponse {
+            count: usize,
+        }
+        let count_response = response.json::<CountResponse>().await.map_err(|error| {
+            TestBinaryError::InvalidState {
+                message: format!("Failed to parse count response: {error}"),
+            }
+        })?;
+        Ok(count_response.count)
+    }
+}
+
+fn probe_client() -> Result<reqwest::Client, TestBinaryError> {

Review Comment:
   fixed



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org