Skip to content

feat(python): add AsyncKoshaClient with cancellation and lifecycle management - #611

Merged
decover-admin merged 2 commits into
decover-tech:mainfrom
khoap1220-hue:feat/async-python-client-595
Nov 29, 2026
Merged

decover-admin merged 2 commits into
decover-tech:mainfrom
khoap1220-hue:feat/async-python-client-595

Conversation

@khoap1220-hue

@khoap1220-hue khoap1220-hue commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

What and why

In clients/python/kosha_client/async_transport.py, clients/python/kosha_client/async_client.py, clients/python/kosha_client/native.py, and clients/python/kosha_client/transport.py, this PR adds an asynchronous Python client (AsyncKoshaClient), immutable namespace handles (AsyncNamespace and matching synchronous Namespace on KoshaClient), nonblocking asyncio HTTP/1.1 transport (AsyncTransport), async pagination (AsyncSearchIterator), and async bulk indexing (async_bulk_index).

Addresses #595 (dependencies #591, #592, and #594 are still open, so this preserves the existing KoshaClient OpenSearch compatibility surface and zero-dependency pyproject.toml packaging while aligning the native /v1 client/namespace API with clients/typescript and clients/go).

Summary of changes

  • clients/python/kosha_client/transport.py: Factored resolve_connection_config, build_request_url, build_request_headers, decode_response_or_error, and _BaseTransport (_backoff_ms, _should_retry_transport_error, _next_retry_delay_ms) so Transport and AsyncTransport share one serialization, error-mapping, idempotency, and clients/conformance/RETRY.md retry implementation.
  • clients/python/kosha_client/async_transport.py: Added pure-stdlib asyncio HTTP/1.1 AsyncTransport and client-scoped _AsyncPool supporting keep-alive connection reuse, stale-connection read resend, Content-Length / Transfer-Encoding: chunked / 204 framing, TLS, HTTP proxy forwarding, async with / idempotent aclose() cleanup, and immediate socket abort on asyncio.CancelledError without retrying.
  • clients/python/kosha_client/native.py: Added immutable sync Namespace, cancellation-safe AsyncSearchIterator (async_search_all, supporting aclose() and async with), and async_bulk_index (accepting Iterable and AsyncIterable, enforcing count/UTF-8 byte caps and last-occurrence-wins ordering, and cancelling all in-flight batch tasks on CancelledError).
  • clients/python/kosha_client/async_client.py & clients/python/kosha_client/client.py: Added AsyncKoshaClient / AsyncNamespace and matching native sync methods (namespace, create_namespace, list_namespaces, delete_namespace, request, __enter__/__exit__) on KoshaClient; exported new public symbols in clients/python/kosha_client/__init__.py.
  • clients/python/examples/async_agent_retrieval.py & clients/python/README.md: Added bounded-concurrency (asyncio.Semaphore) parallel agent retrieval example (retrieve_parallel) and documented AsyncKoshaClient lifecycle and cancellation behavior.
  • clients/python/tests/test_async_client.py & clients/python/tests/test_dsl_registry.py: Added 33 deterministic pytest tests (running via asyncio.run with no extra test-runner dependency) and registered the new native KoshaClient methods in NOT_APIS.

Mapping to #595 Done-When criteria

  • Delayed HTTP calls do not block an independent event-loop task: AsyncTransport over asyncio.open_connection verified by test_delayed_http_does_not_block_independent_event_loop_task and test_concurrent_requests_run_in_parallel_not_serially.
  • Cancelling a request or iterator prevents later retries/dispatch and releases request resources: Verified across in-flight requests, retry backoff sleeps, search_all pagination, bulk_index, and ping (test_cancel_in_flight_request_aborts_socket_and_prevents_retries, test_cancel_during_retry_backoff_prevents_later_attempts, test_cancel_during_search_all_stops_paging_and_releases_resources, test_search_all_aclose_and_context_manager_prevent_later_fetches, test_cancel_during_bulk_index_aborts_inflight_batches_and_stops_dispatch, test_ping_propagates_cancellation_and_returns_false_on_error).
  • Closing the client releases connections; async context-manager behavior is documented: Verified by test_keepalive_reuses_connection_and_aclose_releases_all_connections, test_async_context_manager_closes_on_normal_exit_and_exception, test_closed_client_rejects_requests_and_reentry, test_aclose_during_retry_backoff_prevents_further_attempts, and documented in clients/python/README.md.
  • Shared error/retry/serialization fixtures pass for synchronous and asynchronous variants: Verified by 11 side-by-side sync/async parity tests covering Retry-After, quota 429, bare 503, max_retry_after_ms, body vs header delay precedence, total_budget_ms, 502 / details.outcome == "unknown" idempotency, timeouts, refused connections, non-JSON error fallbacks, and byte-identical UTF-8 JSON replay.
  • The same native documents and query options work with both variants: Verified by test_sync_and_async_namespace_crud_and_native_document_parity, test_namespace_handles_are_immutable_and_isolated, test_sync_and_async_search_all_parity_and_validation, and test_sync_and_async_bulk_index_parity_and_async_iterable.
  • The example demonstrates parallel retrieval with an explicit concurrency bound: clients/python/examples/async_agent_retrieval.py (retrieve_parallel) verified by test_bounded_concurrency_agent_retrieval_example_enforces_bound and test_bounded_concurrency_example_cancels_sibling_tasks_on_cancel.

How it was tested

python -m pytest clients/python/tests/test_async_client.py -q
33 passed

python -m pytest clients/python/tests/test_dsl_registry.py -q
30 passed

python -m pytest scripts/tests/ -q
99 passed, 1 skipped

ruff check --target-version py310 clients/python/kosha_client/async_transport.py clients/python/kosha_client/async_client.py clients/python/kosha_client/__init__.py clients/python/examples/async_agent_retrieval.py clients/python/tests/test_async_client.py
All checks passed!

python clients/conformance/check_coverage.py
conformance coverage: 12 operations covered, 20 excluded

Full clients/python/tests/ suite ran on Python 3.12 with all new tests and existing non-symlink tests passing (on unprivileged Windows, pre-existing test_ingest.py::test_iter_files_skips_symlinks_out_of_the_folder requires SeCreateSymbolicLinkPrivilege and test_keepalive.py's 0.0s timer checks depend on time.monotonic() tick resolution).

Compatibility

Does this change any of the following?

  • The on-disk segment format (files under a segment, footer, posting/vector/filter layout)
  • The manifest, WAL, or Postgres schema
  • The /v1 wire contract (proto/kosha/v1/kosha.proto, request/response JSON)
  • None of the above

Checklist

  • cargo fmt --all -- --check (no Rust files changed)
  • cargo clippy --all-targets --all-features -- -D warnings (no Rust files changed)
  • cargo test --all-features (no Rust files changed)
  • make client-python-test (clients/python/tests/ + scripts/tests/)
  • docker build -t kosha:ci . (no Docker/build files changed)
  • New KOSHA_* variables have a row in docs/configuration.md (no new env vars added)
  • README / docs updated for user-visible changes

NativeNamespace._call and AsyncNamespace._call join the action onto
ns_path(ns, action) = /v1/namespaces/{ns}/{action}, so _call("POST",
"search", ...) is not a legacy unversioned route, same as client.py's
_request.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---kosha-bench---
microbenchmark: segment_memory (cargo bench -p kosha-query --bench segment_memory)
corpus: 8 segments × 4000 docs (32000 total), vocab ~20000
runner: Darwin 25.5.0 arm64 | rustc 1.97.1 (8bab26f4f 2026-07-14) | 2026-11-29T04:52:41Z

latency (v2 = current lazy format, median of inner samples):
  cold broad ("the")                 5.3 ms
  warm broad ("the")                 0.37 ms
  warm 2-term AND                    0.41 ms
  warm phrase                        0.39 ms
  warm wildcard w1*                  126.18 ms
---end kosha-bench---
@decover-admin
decover-admin merged commit b979142 into decover-tech:main Nov 29, 2026
23 checks passed
khoap1220-hue added a commit to khoap1220-hue/khoap1220-hue.github.io that referenced this pull request Nov 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants