From 61e39c2e392c2d54016ccd0564ef913c799cb4f7 Mon Sep 17 00:00:00 2001 From: Mauro Sanz Date: Tue, 27 Oct 2026 23:06:14 +0000 Subject: [PATCH 01/16] chore: remove SonarQube steps from CI pipeline (#2) * 8fd954 chore: retrigger CI after fixing pilot trigger branch * 29eed7 Merge branch ci/pythonclient-hc of l7B_kbSEQD2wjrM7PShm5w/PROD/Harness_Split/python-client (#3) * 6eb55d chore: retrigger CI for Harness Code pilot * 684564 ci: add Harness Code copy of pythonclient pipeline for trigger pilot * 7f657a chore: use Harness Code repo for codebase clone * b3f82f chore: retrigger CI via Harness Code PR trigger * b984fc chore: remove SonarQube scan steps from CI pipeline * dbc8f1 chore(ci): remove Post Quality Gate step from Harness pipeline * 5cfab9 fix: [BT-22244]: Enable code coverage (#1) * 2d8412 Merge pull request #658 from splitio/development --- .../Harness_Split/pipelines/pythonclient.yaml | 93 +++----------- .../pythonclient/input_sets/pythonclient.yaml | 1 - .../pipelines/pythonclient_hc.yaml | 118 ++++++++++++++++++ .../input_sets/pythonclient_hc.yaml | 15 +++ 4 files changed, 150 insertions(+), 77 deletions(-) create mode 100644 .harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc.yaml create mode 100644 .harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc.yaml diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient.yaml index c4773569..d9015243 100644 --- a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient.yaml +++ b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient.yaml @@ -7,8 +7,7 @@ pipeline: properties: ci: codebase: - connectorRef: <+input> - repoName: <+input> + repoName: python-client build: <+input> stages: - stage: @@ -18,6 +17,8 @@ pipeline: type: CI spec: cloneCodebase: true + envVariables: + CI_ENABLE_HCLI_FOR_TESTS: "true" caching: enabled: true override: true @@ -94,83 +95,23 @@ pipeline: eval "$(mise activate bash)" python setup.py test - step: - type: Run - name: SonarQube Scan - identifier: SonarQube_Scan - when: - stageStatus: Success - condition: <+matrix.pythonVersion> == "3.7.16" - spec: - shell: Sh - command: |- - if [ "<+codebase.prNumber>" != "" ]; then - docker run --rm \ - -e SONAR_HOST_URL="https://sonar.harness.io" \ - -e SONAR_TOKEN="<+secrets.getValue("sonarqube-token")>" \ - -v "$(pwd):/usr/src" \ - sonarsource/sonar-scanner-cli \ - -Dsonar.projectKey=python-client \ - -Dsonar.sources=splitio \ - -Dsonar.tests=tests \ - -Dsonar.python.coverage.reportPaths=coverage.xml \ - -Dsonar.pullrequest.key=<+codebase.prNumber> \ - -Dsonar.pullrequest.branch=<+codebase.sourceBranch> \ - -Dsonar.pullrequest.base=<+codebase.targetBranch> - else - docker run --rm \ - -e SONAR_HOST_URL="https://sonar.harness.io" \ - -e SONAR_TOKEN="<+secrets.getValue("sonarqube-token")>" \ - -v "$(pwd):/usr/src" \ - sonarsource/sonar-scanner-cli \ - -Dsonar.projectKey=python-client \ - -Dsonar.sources=splitio \ - -Dsonar.tests=tests \ - -Dsonar.python.coverage.reportPaths=coverage.xml \ - -Dsonar.branch.name=<+codebase.branch> - fi - - step: - type: Run - name: Post Quality Gate - identifier: Post_Quality_Gate + name: harnessCoverage + identifier: harnessCoverage when: stageStatus: Success condition: <+matrix.pythonVersion> == "3.7.16" - spec: - shell: Bash - command: |- - #!/bin/bash - set -e - - SONAR_TOKEN="<+secrets.getValue("sonarqube-token")>" - SONAR_URL="https://sonar.harness.io" - SONAR_PROJECT_KEY="python-client" - GITHUB_TOKEN="<+secrets.getValue("github-devops-token")>" - GITHUB_REPO="python-client" - COMMIT_SHA="<+codebase.commitSha>" - - STATUS_JSON=$(curl -sf \ - -H "Authorization: Bearer ${SONAR_TOKEN}" \ - "${SONAR_URL}/api/qualitygates/project_status?projectKey=${SONAR_PROJECT_KEY}") - - QG_STATUS=$(echo "$STATUS_JSON" | python3 -c "import sys,json; print(json.load(sys.stdin)['projectStatus']['status'])") - - case "$QG_STATUS" in - OK) GH_STATE="success"; DESCRIPTION="Quality gate passed" ;; - ERROR) GH_STATE="failure"; DESCRIPTION="Quality gate failed" ;; - WARN) GH_STATE="success"; DESCRIPTION="Quality gate passed with warnings" ;; - *) GH_STATE="pending"; DESCRIPTION="Quality gate status unknown" ;; - esac - - TARGET_URL="${SONAR_URL}/dashboard?id=${SONAR_PROJECT_KEY}" - - curl -sf -X POST \ - -H "Authorization: token ${GITHUB_TOKEN}" \ - -H "Accept: application/vnd.github.v3+json" \ - -H "Content-Type: application/json" \ - -d "{\"state\":\"${GH_STATE}\",\"description\":\"${DESCRIPTION}\",\"context\":\"sonarqube/quality-gate\",\"target_url\":\"${TARGET_URL}\"}" \ - "https://api.github.com/repos/splitio/${GITHUB_REPO}/statuses/${COMMIT_SHA}" - - echo "Posted SonarQube quality gate status: ${GH_STATE}" + template: + templateRef: account.codeCoverage + versionLabel: v1 + templateInputs: + type: Run + spec: + envVariables: + patch_coverage_percent: "80" + file_path: "coverage.xml" + overall_coverage_percent: "" + ignore_failure: "true" + exclude: "**/venv/**,**/__pycache__/**,**/test_*.py,**/*_test.py,**/tests/**" strategy: matrix: pythonVersion: diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient/input_sets/pythonclient.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient/input_sets/pythonclient.yaml index 31ad6fff..02d1bcfb 100644 --- a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient/input_sets/pythonclient.yaml +++ b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient/input_sets/pythonclient.yaml @@ -8,7 +8,6 @@ inputSet: properties: ci: codebase: - connectorRef: fmegithubharnessgitops repoName: python-client build: type: PR diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc.yaml new file mode 100644 index 00000000..ebffdf2a --- /dev/null +++ b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc.yaml @@ -0,0 +1,118 @@ +pipeline: + name: python-client hc + identifier: pythonclient_hc + projectIdentifier: Harness_Split + orgIdentifier: PROD + tags: {} + properties: + ci: + codebase: + repoName: python-client + build: <+input> + stages: + - stage: + name: Build and Test + identifier: Build_and_Test + description: "" + type: CI + spec: + cloneCodebase: true + envVariables: + CI_ENABLE_HCLI_FOR_TESTS: "true" + caching: + enabled: true + override: true + platform: + os: Linux + arch: Amd64 + runtime: + type: Cloud + spec: + size: flex + execution: + steps: + - step: + type: Run + name: Install Python + identifier: Install_Python + spec: + shell: Bash + command: |- + curl https://mise.run | sh + export PATH="$HOME/.local/bin:$PATH" + mise use --global python@<+matrix.pythonVersion> + eval "$(mise activate bash)" + python --version + pip --version + - step: + type: Run + name: Start Redis + identifier: Start_Redis + spec: + shell: Sh + command: |- + apt-get update -qq + apt-get install -y redis-server -qq + redis-server --daemonize yes --port 6379 + redis-cli ping + - step: + type: Run + name: Wait for Redis + identifier: Wait_for_Redis + spec: + shell: Sh + command: |- + for i in $(seq 1 15); do + redis-cli ping && break + echo "Waiting for Redis... attempt $i" + sleep 1 + done + - step: + type: Run + name: Install Dependencies + identifier: Install_Dependencies + spec: + shell: Bash + command: |- + export PATH="$HOME/.local/bin:$PATH" + eval "$(mise activate bash)" + apt-get install -y libkrb5-dev musl-dev libffi-dev build-essential -qq + pip install --upgrade pip setuptools wheel + pip install Cython + pip install aiohttp + pip install cryptography + pip install pycparser + pip install redis + pip install -e . + - step: + type: Run + name: Run Tests + identifier: Run_Tests + spec: + shell: Bash + command: |- + export PATH="$HOME/.local/bin:$PATH" + eval "$(mise activate bash)" + python setup.py test + - step: + name: harnessCoverage + identifier: harnessCoverage + when: + stageStatus: Success + condition: <+matrix.pythonVersion> == "3.7.16" + template: + templateRef: account.codeCoverage + versionLabel: v1 + templateInputs: + type: Run + spec: + envVariables: + patch_coverage_percent: "80" + file_path: "coverage.xml" + overall_coverage_percent: "" + ignore_failure: "true" + exclude: "**/venv/**,**/__pycache__/**,**/test_*.py,**/*_test.py,**/tests/**" + strategy: + matrix: + pythonVersion: + - "3.7.16" diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc.yaml new file mode 100644 index 00000000..c3045725 --- /dev/null +++ b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc.yaml @@ -0,0 +1,15 @@ +inputSet: + name: python-client hc + identifier: pythonclient_hc + orgIdentifier: PROD + projectIdentifier: Harness_Split + pipeline: + identifier: pythonclient_hc + properties: + ci: + codebase: + repoName: python-client + build: + type: PR + spec: + number: <+trigger.prNumber> From 791d9d5ac28abae06d848499d8307edbcc646838 Mon Sep 17 00:00:00 2001 From: Emiliano Sanchez Date: Mon, 2 Nov 2026 15:54:13 -0300 Subject: [PATCH 02/16] updated AGENTS.md, renamed master references to main and replaced README badge with PyPI version --- AGENTS.md | 115 ++++++++++++++++++++++++++++++++++++++++++ CLAUDE.md | 1 + CONTRIBUTORS-GUIDE.md | 2 +- README.md | 2 +- 4 files changed, 118 insertions(+), 2 deletions(-) create mode 100644 AGENTS.md create mode 120000 CLAUDE.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..9216b1c0 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,115 @@ +# AGENTS.md + +## Project Overview + +Split.io Python SDK — a feature flag evaluation client for the [Split platform](https://www.split.io/). Serves feature flag treatments to users and supports multiple runtime modes: standard (synchronous), asyncio (async), Redis-backed, uWSGI, and Kerberos-authenticated deployments. + +- GitHub: https://github.com/splitio/python-client +- Compatible with Python 3.7+ +- Published to PyPI as `splitio_client` + +## Build System + +- **Build tool**: setuptools / pip +- **Install (dev + test deps)**: `pip install -e ".[test]"` +- **Install with extras**: `pip install -e ".[redis,asyncio,kerberos]"` + +## Testing + +- **Run all tests**: `pytest` +- **Coverage**: enabled by default — `setup.cfg` addopts add `--verbose --cov=splitio --cov-report xml` (writes `coverage.xml`) +- **Run a specific test file**: `pytest tests/client/test_client.py` +- **Run a specific test case**: `pytest tests/client/test_client.py::ClientTests::test_get_treatment` +- **Run async tests**: `pytest tests/ -k "async"` +- **Test file pattern**: `tests//test_.py`, classes named `*Tests` +- **Redis tests**: `tests/integration/test_redis_integration.py` and other Redis-backed tests need a local `redis-server` on `localhost:6379` +- **CI**: Harness pipeline (`.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient.yaml`) installs with `pip install -e .`, starts `redis-server`, runs `python setup.py test` on Python 3.7.16, then runs SonarQube using `coverage.xml` + +## Linting & Formatting + +- **Lint check**: `flake8 splitio/` +- **Max line length**: 100 characters +- **Linting excludes**: `tests/` +- Run flake8 before committing to catch style issues early. + +## Git Workflow + +- **Default branch**: `main` +- **Development branch**: `development` (integration branch; target of all PRs) +- **Branch naming**: `short-description` or `ticket-short-description` +- **Commit format**: Free-form, descriptive (e.g., `"fixed typo for segment event type"`, `"added support for rule-based segments"`) +- **PR title format (required)**: PR title must follow the expected format: `: [PROJECT-123]: ` + - Example: `feat: [BT-100]: Add new dashboard endpoint` + - Valid types: `feat`, `fix`, `techdebt`, `hotfixpreqa`, `chore` +- **PR target branch**: Always open PRs against `development`, never `main`. `main` is the default + branch and holds released code; it is only updated by merging `development` during a release. + The PR creation UI preselects `main`, so set the target branch explicitly. +- **PR description**: No PR template in the repo — describe what you accomplished, how to test it, and any extra notes. + +## DOs + +- Always update `CHANGES.txt` when adding new features or fixing bugs. Follow the existing format: `version (date)\n- Description`. +- Run `flake8 splitio/` before committing to check for style violations. +- Run `pytest` before committing to verify tests pass. +- Match existing code style — synchronous and async variants of classes live side by side in the same module, async ones suffixed `Async` (e.g., `Client` / `ClientAsync` in `splitio/client/client.py`, `InMemorySplitStorage` / `InMemorySplitStorageAsync` in `splitio/storage/inmemmory.py`), often sharing a `*Base` class. +- When adding a new capability, check if both the sync and the `*Async` variant need updating, along with their tests. +- Import optional dependencies (`aiohttp`, `aiofiles`, etc.) through `splitio/optional/loaders.py` rather than directly, so the SDK still works without the `asyncio` extra. +- Follow the existing package structure: logic in `splitio/`, tests mirroring in `tests/`. + +## DON'Ts + +- Never force push to `main` or `development`. +- Never commit secrets, `.env` files, or API keys. +- Never skip flake8 or pytest when implementing changes. +- Never modify `.harness/` CI pipeline files unless specifically asked to update the pipeline. + +## Commands to Never Run + +- `git push --force origin main` +- `git push --force origin development` +- `rm -rf /` or any destructive recursive delete outside the repo +- `DROP DATABASE` / `DROP TABLE` (not applicable here but listed for completeness) + +## Project Structure + +``` +python-client/ +├── splitio/ # Main SDK package +│ ├── api/ # HTTP API clients (feature flags, segments, auth, telemetry) +│ ├── client/ # Public SDK client & factory (get_factory, Client, SplitFactory) +│ ├── engine/ # Feature flag evaluation engine (matchers, splitter, rules) +│ ├── events/ # Event tracking and delivery +│ ├── models/ # Data models (splits, segments, impressions, events) +│ ├── optional/ # Optional-dependency loaders (asyncio/aiohttp/aiofiles) +│ ├── push/ # Streaming / push notification support (SSE) +│ ├── recorder/ # Impression and event recorders +│ ├── storage/ # Storage backends (in-memory, Redis, pluggable); adapters/ holds Redis/cache adapters +│ ├── sync/ # Synchronization managers (polling, streaming) +│ ├── tasks/ # Background tasks (periodic sync, impression flush) +│ ├── util/ # Utilities (logging, decorators, etc.) +│ ├── factories.py # Backwards-compat shim re-exporting get_factory from client/factory.py +│ ├── impressions.py # Backwards-compat shim re-exporting ImpressionListener +│ ├── exceptions.py # Re-exports public exceptions (TimeoutException, SentinelConfigurationException) +│ ├── spec.py # SDK spec version (SPEC_VERSION) +│ └── version.py # Package version (__version__), read by setup.py +├── tests/ # Test suite mirroring splitio/ structure +│ ├── integration/ # Integration tests +│ └── helpers/ # Test helpers and fixtures +├── setup.py # Package metadata and dependencies +├── setup.cfg # pytest, flake8, and wheel config +├── CHANGES.txt # Changelog — update for every release +└── .harness/ # Harness CI pipeline + input sets (don't edit unless asked) +``` + +## Important Packages + +- `splitio/client/` — Public API surface (`Client`/`ClientAsync`, `SplitFactory`/`SplitFactoryAsync`, `get_factory`, config, input validation). Entry point for most feature work. +- `splitio/engine/` — Core evaluation logic. Changes here affect all treatment results. +- `splitio/storage/` — Storage abstraction layer. Supports in-memory, Redis, and pluggable backends. +- `splitio/sync/` — Manages synchronization of feature flags and segments from the Split backend. +- `splitio/push/` — SSE-based streaming update support. +- `splitio/api/` — HTTP communication with Split backend services (including proxy support). + +## Language-Specific Guidelines + +This is a Python project. Use the `make-agent-friendly:python-conventions` skill for Python-specific patterns, testing conventions, and tooling guidance. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 120000 index 00000000..47dc3e3d --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/CONTRIBUTORS-GUIDE.md b/CONTRIBUTORS-GUIDE.md index befff911..38739f3b 100644 --- a/CONTRIBUTORS-GUIDE.md +++ b/CONTRIBUTORS-GUIDE.md @@ -14,7 +14,7 @@ Split SDK is an open source project and we welcome feedback and contribution. Th 6. Run all tests and make sure there are no failures. 7. `git push` your changes to GitHub within your topic branch. 8. Open a Pull Request(PR) from your forked repo and into the `development` branch of the original repository. -9. When creating your PR, please fill out all the fields of the PR template, as applicable, for the project. +9. When creating your PR, please describe what you accomplished, how to test your changes, and any extra notes reviewers should know about. 10. Check for conflicts once the pull request is created to make sure your PR can be merged cleanly into `development`. 11. Keep an eye out for any feedback or comments from Split's SDK team. diff --git a/README.md b/README.md index 5dae06bf..9d32e4c9 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # Split Python SDK -![Build Status](https://github.com/splitio/python-client/actions/workflows/ci.yml/badge.svg?branch=master) +[![PyPI version](https://badge.fury.io/py/splitio_client.svg)](https://badge.fury.io/py/splitio_client) ## Overview This SDK is designed to work with Split, the platform for controlled rollouts, which serves features to your users via a Split feature flag to manage your complete customer experience. From a195f4028f1a7ca7ddc8e18116f2c4ae07aa52bc Mon Sep 17 00:00:00 2001 From: Emiliano Sanchez Date: Mon, 2 Nov 2026 16:56:55 -0300 Subject: [PATCH 03/16] re-trigger ci From 758edd6194e27bec336e6abd47007b1d3ea53957 Mon Sep 17 00:00:00 2001 From: Rithish Reddy Sama Date: Thu, 5 Nov 2026 12:44:25 +0000 Subject: [PATCH 04/16] feat: [BT-24148]: add Baseline coverage input set (#6) * 0ffd48 add Baseline coverage input set --- .../pythonclient_hc/input_sets/Baseline.yaml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/Baseline.yaml diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/Baseline.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/Baseline.yaml new file mode 100644 index 00000000..5c5c8f0a --- /dev/null +++ b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/Baseline.yaml @@ -0,0 +1,14 @@ +inputSet: + name: Baseline + identifier: Baseline + orgIdentifier: PROD + projectIdentifier: Harness_Split + pipeline: + identifier: pythonclient_hc + properties: + ci: + codebase: + build: + type: branch + spec: + branch: <+trigger.branch> From b08772c9de3f15c08176c19b92094da1e002cf7a Mon Sep 17 00:00:00 2001 From: Emiliano Sanchez Date: Thu, 5 Nov 2026 19:04:34 -0300 Subject: [PATCH 05/16] update CI pipeline, tests, complementary and configuration files --- .gitignore | 4 +- .../Harness_Split/pipelines/pythonclient.yaml | 7 +- .../pipelines/pythonclient_hc.yaml | 7 +- .python-version | 1 + AGENTS.md | 32 ++++++-- CHANGES.txt | 5 ++ CONTRIBUTORS-GUIDE.md | 21 ++++-- setup.cfg | 4 +- setup.py | 28 +++++-- sonar-project.properties | 10 --- splitio/client/factory.py | 15 ++-- splitio/version.py | 2 +- tests/api/test_auth.py | 10 +-- tests/api/test_events.py | 10 +-- tests/api/test_impressions_api.py | 20 ++--- tests/api/test_segments_api.py | 10 +-- tests/api/test_splits_api.py | 32 ++++---- tests/api/test_telemetry_api.py | 20 ++--- tests/client/test_client.py | 10 +++ tests/client/test_factory.py | 36 +++++++++ tests/client/test_input_validator.py | 39 +++++----- tests/conftest.py | 25 +++++++ tests/integration/test_client_e2e.py | 4 + tests/integration/test_streaming_e2e.py | 75 +++++++++++++------ tests/models/test_telemetry_model.py | 37 ++++----- tests/push/test_manager.py | 1 - tests/recorder/test_recorder.py | 2 - 27 files changed, 299 insertions(+), 168 deletions(-) create mode 100644 .python-version delete mode 100644 sonar-project.properties create mode 100644 tests/conftest.py diff --git a/.gitignore b/.gitignore index d2f290a3..6a3126a7 100644 --- a/.gitignore +++ b/.gitignore @@ -24,6 +24,7 @@ var/ .installed.cfg *.egg venv/ +.venv/ .vscode # PyInstaller @@ -73,6 +74,3 @@ target/ *.swp .DS_Store - -# Sonarqube -.scannerwork diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient.yaml index d9015243..9c81479e 100644 --- a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient.yaml +++ b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient.yaml @@ -79,11 +79,9 @@ pipeline: apt-get install -y libkrb5-dev musl-dev libffi-dev build-essential -qq pip install --upgrade pip setuptools wheel pip install Cython - pip install aiohttp pip install cryptography pip install pycparser - pip install redis - pip install -e . + pip install -e ".[test,redis,asyncio,kerberos]" - step: type: Run name: Run Tests @@ -93,7 +91,7 @@ pipeline: command: |- export PATH="$HOME/.local/bin:$PATH" eval "$(mise activate bash)" - python setup.py test + python -m pytest - step: name: harnessCoverage identifier: harnessCoverage @@ -116,3 +114,4 @@ pipeline: matrix: pythonVersion: - "3.7.16" + - "latest" diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc.yaml index ebffdf2a..9459ca8d 100644 --- a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc.yaml +++ b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc.yaml @@ -79,11 +79,9 @@ pipeline: apt-get install -y libkrb5-dev musl-dev libffi-dev build-essential -qq pip install --upgrade pip setuptools wheel pip install Cython - pip install aiohttp pip install cryptography pip install pycparser - pip install redis - pip install -e . + pip install -e ".[test,redis,asyncio,kerberos]" - step: type: Run name: Run Tests @@ -93,7 +91,7 @@ pipeline: command: |- export PATH="$HOME/.local/bin:$PATH" eval "$(mise activate bash)" - python setup.py test + python -m pytest - step: name: harnessCoverage identifier: harnessCoverage @@ -116,3 +114,4 @@ pipeline: matrix: pythonVersion: - "3.7.16" + - "latest" diff --git a/.python-version b/.python-version new file mode 100644 index 00000000..e4fba218 --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.12 diff --git a/AGENTS.md b/AGENTS.md index 9216b1c0..88d58a16 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,12 +8,30 @@ Split.io Python SDK — a feature flag evaluation client for the [Split platform - Compatible with Python 3.7+ - Published to PyPI as `splitio_client` +## Prerequisites + +- **Python**: 3.7+ is supported (3.7 to latest stable). Develop on 3.12 (see `.python-version`); CI runs 3.7.16 and latest stable. +- **Redis**: local `redis-server` on `localhost:6379` for the Redis-backed tests. +- **Kerberos extra**: only needed for Kerberos proxy auth, but installed by the test extras. Builds `gssapi` from source: on Debian/Ubuntu install `libkrb5-dev` + `build-essential` first; macOS needs nothing extra (`brew install krb5` only if the build fails). +- **Optional**: a virtual environment (`python -m venv .venv` or uv) and pyenv/uv to switch Python versions. + ## Build System - **Build tool**: setuptools / pip - **Install (dev + test deps)**: `pip install -e ".[test]"` - **Install with extras**: `pip install -e ".[redis,asyncio,kerberos]"` +### Optional: uv + +[uv](https://docs.astral.sh/uv/) is optional; plain `pip`/`pytest` keep working. The repo has no `pyproject.toml` +or `uv.lock`, so don't add them (that would make uv mandatory). + +- **Setup uv (one time)**: `brew install uv`, then in the repo root: + `uv venv --seed --python 3.12` (`--seed` adds `pip` to `.venv`) and + `uv pip install -e ".[test,redis,asyncio,kerberos]"` +- **Using uv**: prefix commands with `uv run` to use `.venv` without activating it: + `uv run pytest`, `uv run flake8 splitio/`. Re-run the `uv pip install` command when `setup.py` dependencies change. + ## Testing - **Run all tests**: `pytest` @@ -23,7 +41,7 @@ Split.io Python SDK — a feature flag evaluation client for the [Split platform - **Run async tests**: `pytest tests/ -k "async"` - **Test file pattern**: `tests//test_.py`, classes named `*Tests` - **Redis tests**: `tests/integration/test_redis_integration.py` and other Redis-backed tests need a local `redis-server` on `localhost:6379` -- **CI**: Harness pipeline (`.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient.yaml`) installs with `pip install -e .`, starts `redis-server`, runs `python setup.py test` on Python 3.7.16, then runs SonarQube using `coverage.xml` +- **CI**: Harness pipeline (`.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient.yaml`) installs with `pip install -e ".[test,redis,asyncio,kerberos]"`, starts `redis-server`, runs `python -m pytest` on Python 3.7.16 and latest stable, and reports coverage (`coverage.xml`) ## Linting & Formatting @@ -35,15 +53,19 @@ Split.io Python SDK — a feature flag evaluation client for the [Split platform ## Git Workflow - **Default branch**: `main` -- **Development branch**: `development` (integration branch; target of all PRs) +- **Development branch**: `development` (integration branch; target of feature and refactor PRs) - **Branch naming**: `short-description` or `ticket-short-description` - **Commit format**: Free-form, descriptive (e.g., `"fixed typo for segment event type"`, `"added support for rule-based segments"`) - **PR title format (required)**: PR title must follow the expected format: `: [PROJECT-123]: ` - Example: `feat: [BT-100]: Add new dashboard endpoint` - Valid types: `feat`, `fix`, `techdebt`, `hotfixpreqa`, `chore` -- **PR target branch**: Always open PRs against `development`, never `main`. `main` is the default - branch and holds released code; it is only updated by merging `development` during a release. - The PR creation UI preselects `main`, so set the target branch explicitly. +- **Branching model (GitFlow)**: + - `main`: stable release history. Every stable release is tagged with its version, but not every commit on `main` necessarily maps to a release (e.g. chores on metadata or CI files have no tag). + - `development`: integration branch for new features and ongoing development. + - Other branches: features, refactors, hotfixes, and optional `release-x.x.x` (to prepare stable releases). + - RC releases can be done from any branch and don't require a tag. +- **PR target branch**: Open PRs against `development`, including `release-x.x.x` branches; `development` is then merged into `main` for stable releases. Hotfixes may target `main` directly, bypassing `development`. + The PR creation UI preselects `main`, so always set the target branch explicitly. - **PR description**: No PR template in the repo — describe what you accomplished, how to test it, and any extra notes. ## DOs diff --git a/CHANGES.txt b/CHANGES.txt index 61253c32..2bc8774b 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,3 +1,8 @@ +10.7.1 (Nov 6, 2026) +- Fixed async factory readiness being delayed by the telemetry config post: SplitFactoryAsync now becomes ready before posting telemetry, as the sync factory does. +- Updated package metadata: declared python_requires>=3.7, updated the trove classifiers (3.7 to latest stable, Python 2 removed) and removed the universal wheel setting (wheels are now tagged py3). +- Updated CI, tests and test dependencies to improve reliability and to validate the SDK on Python 3.7 and latest stable. + 10.7.0 (Oct 5, 2026) - Added ability to use proxy url for all http connections. diff --git a/CONTRIBUTORS-GUIDE.md b/CONTRIBUTORS-GUIDE.md index 38739f3b..9ffeae68 100644 --- a/CONTRIBUTORS-GUIDE.md +++ b/CONTRIBUTORS-GUIDE.md @@ -4,9 +4,16 @@ Split SDK is an open source project and we welcome feedback and contribution. Th ## Development +### Prerequisites + +- **Python**: 3.7 or newer. Python 3.12 is recommended for day-to-day development; the repo's `.python-version` points to it for pyenv/uv users. +- **Redis**: a local `redis-server` listening on `localhost:6379`, required by the Redis tests. +- **Kerberos extra** (`pip install -e ".[kerberos]"`): only needed for Kerberos proxy authentication, and installed by the test extras since the tests cover it. It builds `gssapi` from source, so on Debian/Ubuntu install `libkrb5-dev` and `build-essential` first. macOS ships Kerberos, so nothing extra is usually needed (`brew install krb5` only if the build fails). +- **Optional**: a virtual environment (`python -m venv .venv`, or [uv](https://docs.astral.sh/uv/)) to keep dependencies isolated, and pyenv or uv to install other Python versions. + ### Development process -1. Fork the repository and create a topic branch from `development` branch. Please use a descriptive name for your branch. +1. Fork the repository and create a topic branch from `development` branch (we follow GitFlow: `main` holds the stable release history and `development` is the integration branch). Please use a descriptive name for your branch. 2. While developing, use descriptive messages in your commits. Avoid short or meaningless sentences like "fix bug". 3. Make sure to add tests for both positive and negative cases. 4. Run the linter script of the project and fix any issues you find. @@ -20,11 +27,15 @@ Split SDK is an open source project and we welcome feedback and contribution. Th ### Running tests -To run test you need to execute the following commands: +To run the tests, from the repository root: 1. `pip install -U pip setuptools` -2. `python setup.py install` -3. `pip install redis pytest pytest-cov pytest-mock` -4. `python setup.py test` +2. `pip install -e ".[test,redis,asyncio,kerberos]"` +3. Start Redis if it isn't running: `redis-server --daemonize yes` +4. `python -m pytest` + +### Linting and other useful checks + +To lint, run `flake8 splitio/`. # Contact diff --git a/setup.cfg b/setup.cfg index 1fa09f42..c4e3f0d1 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,6 +1,3 @@ -[wheel] -universal = 1 - [metadata] name = splitio_client description = This SDK is designed to work with Split, the platform for controlled rollouts, which serves features to your users via a Split feature flag to manage your complete customer experience. @@ -17,6 +14,7 @@ test=pytest [tool:pytest] addopts = --verbose --cov=splitio --cov-report xml python_classes=*Tests +pythonpath = . [build_sphinx] source-dir = doc/source diff --git a/setup.py b/setup.py index e2b4c74a..771be171 100644 --- a/setup.py +++ b/setup.py @@ -6,15 +6,21 @@ TESTS_REQUIRES = [ 'flake8', - 'pytest==7.0.1', - 'pytest-mock==3.11.1', - 'coverage==7.0.0', - 'pytest-cov==4.1.0', + # Python 3.7/3.8 keep the original pins; newer Pythons need newer test tools (pytest 7 fails on 3.14+) + 'pytest==7.0.1;python_version<"3.9"', + 'pytest>=8.4,<9;python_version>="3.9"', + 'pytest-mock==3.11.1;python_version<"3.9"', + 'pytest-mock>=3.14;python_version>="3.9"', + 'coverage==7.0.0;python_version<"3.9"', + 'coverage>=7.6;python_version>="3.9"', + 'pytest-cov==4.1.0;python_version<"3.9"', + 'pytest-cov>=6;python_version>="3.9"', 'importlib-metadata==6.7', 'tomli==1.2.3', 'iniconfig==1.1.1', 'attrs==22.1.0', - 'pytest-asyncio==0.21.0', + 'pytest-asyncio==0.21.0;python_version<"3.9"', + 'pytest-asyncio==0.21.2;python_version>="3.9"', 'aiohttp>=3.8.4', 'aiofiles>=23.1.0', 'requests-kerberos>=0.15.0', @@ -41,6 +47,7 @@ url='https://github.com/splitio/python-client', download_url=('https://github.com/splitio/python-client/tarball/' + __version__), # pylint: disable=undefined-variable license='Apache License 2.0', + python_requires='>=3.7', install_requires=INSTALL_REQUIRES, tests_require=TESTS_REQUIRES, extras_require={ @@ -56,8 +63,17 @@ 'Environment :: Console', 'Intended Audience :: Developers', 'Programming Language :: Python', - 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3 :: Only', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3.10', + 'Programming Language :: Python :: 3.11', + 'Programming Language :: Python :: 3.12', + 'Programming Language :: Python :: 3.13', + 'Programming Language :: Python :: 3.14', + 'Programming Language :: Python :: 3.15', 'Topic :: Software Development :: Libraries' ], packages=find_packages(exclude=('tests', 'tests.*')) diff --git a/sonar-project.properties b/sonar-project.properties deleted file mode 100644 index 009f4fd7..00000000 --- a/sonar-project.properties +++ /dev/null @@ -1,10 +0,0 @@ -sonar.projectName=python-client -sonar.projectKey=python-client -sonar.python.version=3.6 -sonar.sources=splitio -sonar.tests=tests -sonar.text.excluded.file.suffixes=.csv -sonar.python.coverage.reportPaths=coverage.xml -sonar.coverage.exclusions=**/__init__.py -sonar.links.ci=https://github.com/splitio/python-client -sonar.links.scm=https://github.com/splitio/python-client/actions diff --git a/splitio/client/factory.py b/splitio/client/factory.py index 6ec97604..8557f7f4 100644 --- a/splitio/client/factory.py +++ b/splitio/client/factory.py @@ -403,17 +403,22 @@ async def _update_status_when_ready_async(self): if self._manager_start_task is not None: await self._manager_start_task self._manager_start_task = None - await self._telemetry_init_producer.record_ready_time(get_current_epoch_time_ms() - self._ready_time) + ready_time = get_current_epoch_time_ms() - self._ready_time + self._status = Status.READY + self._sdk_ready_flag.set() + await self._internal_events_queue.put( + SdkInternalEventNotification(SdkInternalEvent.SDK_READY, None)) + + # Telemetry is posted after the SDK is ready, so its latency doesn't delay readiness. + await self._telemetry_init_producer.record_ready_time(ready_time) redundant_factory_count, active_factory_count = _get_active_and_redundant_count() - await self._telemetry_init_producer.record_active_and_redundant_factories(active_factory_count, redundant_factory_count) + await self._telemetry_init_producer.record_active_and_redundant_factories( + active_factory_count, redundant_factory_count) try: await self._telemetry_submitter.synchronize_config() except Exception as e: _LOGGER.error("Failed to post Telemetry config") _LOGGER.debug(str(e)) - self._status = Status.READY - self._sdk_ready_flag.set() - await self._internal_events_queue.put(SdkInternalEventNotification(SdkInternalEvent.SDK_READY, None)) def manager(self): """ diff --git a/splitio/version.py b/splitio/version.py index 07b6b73d..6d6c1900 100644 --- a/splitio/version.py +++ b/splitio/version.py @@ -1 +1 @@ -__version__ = '10.7.0' \ No newline at end of file +__version__ = '10.7.1rc1' \ No newline at end of file diff --git a/tests/api/test_auth.py b/tests/api/test_auth.py index 175977a2..0944731f 100644 --- a/tests/api/test_auth.py +++ b/tests/api/test_auth.py @@ -48,9 +48,8 @@ def raise_exception(*args, **kwargs): raise client.HttpClientException('some_message') httpclient.get.side_effect = raise_exception with pytest.raises(APIException) as exc_info: - response = auth_api.authenticate() - assert exc_info.type == APIException - assert exc_info.value.message == 'some_message' + auth_api.authenticate() + assert str(exc_info.value.__cause__) == 'some_message' # original HTTP error is chained class AuthAPIAsyncTests(object): @@ -103,6 +102,5 @@ def raise_exception(*args, **kwargs): httpclient.get = raise_exception with pytest.raises(APIException) as exc_info: - response = await auth_api.authenticate() - assert exc_info.type == APIException - assert exc_info.value.message == 'some_message' + await auth_api.authenticate() + assert str(exc_info.value.__cause__) == 'some_message' # original HTTP error is chained diff --git a/tests/api/test_events.py b/tests/api/test_events.py index 07fe9473..130e0fc8 100644 --- a/tests/api/test_events.py +++ b/tests/api/test_events.py @@ -60,9 +60,8 @@ def raise_exception(*args, **kwargs): raise client.HttpClientException('some_message') httpclient.post.side_effect = raise_exception with pytest.raises(APIException) as exc_info: - response = events_api.flush_events(self.events) - assert exc_info.type == APIException - assert exc_info.value.message == 'some_message' + events_api.flush_events(self.events) + assert str(exc_info.value.__cause__) == 'some_message' # original HTTP error is chained def test_post_events_ip_address_disabled(self, mocker): """Test impressions posting API call.""" @@ -150,9 +149,8 @@ def raise_exception(*args, **kwargs): raise client.HttpClientException('some_message') httpclient.post = raise_exception with pytest.raises(APIException) as exc_info: - response = await events_api.flush_events(self.events) - assert exc_info.type == APIException - assert exc_info.value.message == 'some_message' + await events_api.flush_events(self.events) + assert str(exc_info.value.__cause__) == 'some_message' # original HTTP error is chained @pytest.mark.asyncio async def test_post_events_ip_address_disabled(self, mocker): diff --git a/tests/api/test_impressions_api.py b/tests/api/test_impressions_api.py index b022a464..dfc7c343 100644 --- a/tests/api/test_impressions_api.py +++ b/tests/api/test_impressions_api.py @@ -84,9 +84,8 @@ def raise_exception(*args, **kwargs): raise client.HttpClientException('some_message') httpclient.post.side_effect = raise_exception with pytest.raises(APIException) as exc_info: - response = impressions_api.flush_impressions(impressions_mock) - assert exc_info.type == APIException - assert exc_info.value.message == 'some_message' + impressions_api.flush_impressions(impressions_mock) + assert str(exc_info.value.__cause__) == 'some_message' # original HTTP error is chained def test_post_impressions_ip_address_disabled(self, mocker): """Test impressions posting API call.""" @@ -143,9 +142,8 @@ def raise_exception(*args, **kwargs): raise client.HttpClientException('some_message') httpclient.post.side_effect = raise_exception with pytest.raises(APIException) as exc_info: - response = impressions_api.flush_counters(counters) - assert exc_info.type == APIException - assert exc_info.value.message == 'some_message' + impressions_api.flush_counters(counters) + assert str(exc_info.value.__cause__) == 'some_message' # original HTTP error is chained class ImpressionsAPIAsyncTests(object): @@ -200,9 +198,8 @@ def raise_exception(*args, **kwargs): raise client.HttpClientException('some_message') httpclient.post = raise_exception with pytest.raises(APIException) as exc_info: - response = await impressions_api.flush_impressions(impressions_mock) - assert exc_info.type == APIException - assert exc_info.value.message == 'some_message' + await impressions_api.flush_impressions(impressions_mock) + assert str(exc_info.value.__cause__) == 'some_message' # original HTTP error is chained @pytest.mark.asyncio async def test_post_impressions_ip_address_disabled(self, mocker): @@ -289,6 +286,5 @@ def raise_exception(*args, **kwargs): raise client.HttpClientException('some_message') httpclient.post = raise_exception with pytest.raises(APIException) as exc_info: - response = await impressions_api.flush_counters(counters) - assert exc_info.type == APIException - assert exc_info.value.message == 'some_message' + await impressions_api.flush_counters(counters) + assert str(exc_info.value.__cause__) == 'some_message' # original HTTP error is chained diff --git a/tests/api/test_segments_api.py b/tests/api/test_segments_api.py index 8681be59..ff304886 100644 --- a/tests/api/test_segments_api.py +++ b/tests/api/test_segments_api.py @@ -55,9 +55,8 @@ def raise_exception(*args, **kwargs): raise client.HttpClientException('some_message') httpclient.get.side_effect = raise_exception with pytest.raises(APIException) as exc_info: - response = segment_api.fetch_segment('some_segment', 123, FetchOptions()) - assert exc_info.type == APIException - assert exc_info.value.message == 'some_message' + segment_api.fetch_segment('some_segment', 123, FetchOptions()) + assert str(exc_info.value.__cause__) == 'some_message' # original HTTP error is chained class SegmentAPIAsyncTests(object): @@ -128,6 +127,5 @@ def raise_exception(*args, **kwargs): raise client.HttpClientException('some_message') httpclient.get = raise_exception with pytest.raises(APIException) as exc_info: - response = await segment_api.fetch_segment('some_segment', 123, FetchOptions(None, None, None, None, None)) - assert exc_info.type == APIException - assert exc_info.value.message == 'some_message' + await segment_api.fetch_segment('some_segment', 123, FetchOptions(None, None, None, None, None)) + assert str(exc_info.value.__cause__) == 'some_message' # original HTTP error is chained diff --git a/tests/api/test_splits_api.py b/tests/api/test_splits_api.py index c9aeee8b..b25457a6 100644 --- a/tests/api/test_splits_api.py +++ b/tests/api/test_splits_api.py @@ -56,9 +56,9 @@ def raise_exception(*args, **kwargs): raise client.HttpClientException('some_message') httpclient.get.side_effect = raise_exception with pytest.raises(APIException) as exc_info: - response = split_api.fetch_splits(123, 12, FetchOptions()) - assert exc_info.type == APIException - assert exc_info.value.message == 'some_message' + split_api.fetch_splits(123, 12, FetchOptions()) + assert str(exc_info.value) == 'Feature flags not fetched correctly.' + assert str(exc_info.value.__cause__) == 'some_message' # original HTTP error is chained def test_old_spec(self, mocker): """Test old split changes fetching API call.""" @@ -77,11 +77,11 @@ def get(sdk, splitChanges, sdk_key, extra_headers, query): split_api = splits.SplitsAPI(httpclient, 'some_api_key', SdkMetadata('1.0', 'some', '1.2.3.4'), mocker.Mock()) httpclient.is_sdk_endpoint_overridden.return_value = False - try: - response = split_api.fetch_splits(123, -1, FetchOptions(False, None, None, None)) - except Exception as e: - print(e) - + # new spec fails with 400 and the endpoint isn't overridden: raise, don't retry with the old spec + with pytest.raises(APIException) as exc_info: + split_api.fetch_splits(123, -1, FetchOptions(False, None, None, None)) + assert exc_info.value.status_code == 400 + # no attempt to fetch old spec assert self.query == [{'s': '1.3', 'since': 123, 'rbSince': -1}] @@ -225,9 +225,9 @@ def raise_exception(*args, **kwargs): raise client.HttpClientException('some_message') httpclient.get = raise_exception with pytest.raises(APIException) as exc_info: - response = await split_api.fetch_splits(123, 12, FetchOptions()) - assert exc_info.type == APIException - assert exc_info.value.message == 'some_message' + await split_api.fetch_splits(123, 12, FetchOptions()) + assert str(exc_info.value) == 'Feature flags not fetched correctly.' + assert str(exc_info.value.__cause__) == 'some_message' # original HTTP error is chained @pytest.mark.asyncio async def test_old_spec(self, mocker): @@ -248,11 +248,11 @@ async def get(sdk, splitChanges, sdk_key, extra_headers, query): split_api = splits.SplitsAPIAsync(httpclient, 'some_api_key', SdkMetadata('1.0', 'some', '1.2.3.4'), mocker.Mock()) httpclient.is_sdk_endpoint_overridden.return_value = False - try: - response = await split_api.fetch_splits(123, -1, FetchOptions(False, None, None, None)) - except Exception as e: - print(e) - + # new spec fails with 400 and the endpoint isn't overridden: raise, don't retry with the old spec + with pytest.raises(APIException) as exc_info: + await split_api.fetch_splits(123, -1, FetchOptions(False, None, None, None)) + assert exc_info.value.status_code == 400 + # no attempt to fetch old spec assert self.query == [{'s': '1.3', 'since': 123, 'rbSince': -1}] diff --git a/tests/api/test_telemetry_api.py b/tests/api/test_telemetry_api.py index 5a857789..4077ff9d 100644 --- a/tests/api/test_telemetry_api.py +++ b/tests/api/test_telemetry_api.py @@ -49,9 +49,8 @@ def raise_exception(*args, **kwargs): raise client.HttpClientException('some_message') httpclient.post.side_effect = raise_exception with pytest.raises(APIException) as exc_info: - response = telemetry_api.record_unique_keys(uniques) - assert exc_info.type == APIException - assert exc_info.value.message == 'some_message' + telemetry_api.record_unique_keys(uniques) + assert str(exc_info.value.__cause__) == 'some_message' # original HTTP error is chained def test_record_init(self, mocker): """Test telemetry posting init configs.""" @@ -116,9 +115,8 @@ def raise_exception(*args, **kwargs): raise client.HttpClientException('some_message') httpclient.post.side_effect = raise_exception with pytest.raises(APIException) as exc_info: - response = telemetry_api.record_stats(uniques) - assert exc_info.type == APIException - assert exc_info.value.message == 'some_message' + telemetry_api.record_stats(uniques) + assert str(exc_info.value.__cause__) == 'some_message' # original HTTP error is chained class TelemetryAPIAsyncTests(object): @@ -170,9 +168,8 @@ def raise_exception(*args, **kwargs): raise client.HttpClientException('some_message') httpclient.post = raise_exception with pytest.raises(APIException) as exc_info: - response = await telemetry_api.record_unique_keys(uniques) - assert exc_info.type == APIException - assert exc_info.value.message == 'some_message' + await telemetry_api.record_unique_keys(uniques) + assert str(exc_info.value.__cause__) == 'some_message' # original HTTP error is chained @pytest.mark.asyncio async def test_record_init(self, mocker): @@ -261,6 +258,5 @@ def raise_exception(*args, **kwargs): raise client.HttpClientException('some_message') httpclient.post = raise_exception with pytest.raises(APIException) as exc_info: - response = await telemetry_api.record_stats(uniques) - assert exc_info.type == APIException - assert exc_info.value.message == 'some_message' + await telemetry_api.record_stats(uniques) + assert str(exc_info.value.__cause__) == 'some_message' # original HTTP error is chained diff --git a/tests/client/test_client.py b/tests/client/test_client.py index 1efd4143..10835ca3 100644 --- a/tests/client/test_client.py +++ b/tests/client/test_client.py @@ -145,6 +145,7 @@ def test_get_treatment_with_config(self, mocker): telemetry_producer.get_telemetry_init_producer(), mocker.Mock() ) + factory.block_until_ready(1) # ready flag is a Mock, so the status thread sets READY at once class TelemetrySubmitterMock(): def synchronize_config(*_): pass @@ -226,6 +227,7 @@ def test_get_treatments(self, mocker): telemetry_producer.get_telemetry_init_producer(), mocker.Mock() ) + factory.block_until_ready(1) # ready flag is a Mock, so the status thread sets READY at once class TelemetrySubmitterMock(): def synchronize_config(*_): pass @@ -309,6 +311,7 @@ def test_get_treatments_by_flag_set(self, mocker): telemetry_producer.get_telemetry_init_producer(), mocker.Mock() ) + factory.block_until_ready(1) # ready flag is a Mock, so the status thread sets READY at once class TelemetrySubmitterMock(): def synchronize_config(*_): pass @@ -391,6 +394,7 @@ def test_get_treatments_by_flag_sets(self, mocker): telemetry_producer.get_telemetry_init_producer(), mocker.Mock() ) + factory.block_until_ready(1) # ready flag is a Mock, so the status thread sets READY at once class TelemetrySubmitterMock(): def synchronize_config(*_): pass @@ -472,6 +476,7 @@ def test_get_treatments_with_config(self, mocker): telemetry_producer.get_telemetry_init_producer(), mocker.Mock() ) + factory.block_until_ready(1) # ready flag is a Mock, so the status thread sets READY at once class TelemetrySubmitterMock(): def synchronize_config(*_): pass @@ -559,6 +564,7 @@ def test_get_treatments_with_config_by_flag_set(self, mocker): telemetry_producer.get_telemetry_init_producer(), mocker.Mock() ) + factory.block_until_ready(1) # ready flag is a Mock, so the status thread sets READY at once class TelemetrySubmitterMock(): def synchronize_config(*_): pass @@ -642,6 +648,7 @@ def test_get_treatments_with_config_by_flag_sets(self, mocker): telemetry_producer.get_telemetry_init_producer(), mocker.Mock() ) + factory.block_until_ready(1) # ready flag is a Mock, so the status thread sets READY at once class TelemetrySubmitterMock(): def synchronize_config(*_): pass @@ -1236,6 +1243,7 @@ def test_telemetry_method_latency(self, mocker): telemetry_producer.get_telemetry_init_producer(), mocker.Mock() ) + factory.block_until_ready(1) # ready flag is a Mock, so the status thread sets READY at once class TelemetrySubmitterMock(): def synchronize_config(*_): pass @@ -1471,6 +1479,7 @@ def test_fallback_treatment_eval_exception(self, mocker): telemetry_producer.get_telemetry_init_producer(), mocker.Mock() ) + factory.block_until_ready(1) # ready flag is a Mock, so the status thread sets READY at once self.imps = None def put(impressions): @@ -1612,6 +1621,7 @@ def test_fallback_treatment_exception(self, mocker): telemetry_producer.get_telemetry_init_producer(), mocker.Mock() ) + factory.block_until_ready(1) # ready flag is a Mock, so the status thread sets READY at once self.imps = None def put(impressions): diff --git a/tests/client/test_factory.py b/tests/client/test_factory.py index fb72a951..a2c800a4 100644 --- a/tests/client/test_factory.py +++ b/tests/client/test_factory.py @@ -1111,4 +1111,40 @@ async def record_active_and_redundant_factories(*_): event = await factory._internal_events_queue.get() assert event.internal_event == SdkInternalEvent.SDK_READY assert event.metadata == None + await factory.destroy() + + @pytest.mark.asyncio + async def test_ready_not_blocked_by_telemetry_config_async(self, mocker): + """Test that a slow telemetry config post does not delay SDK readiness.""" + def _split_synchronizer(self, ready_flag, some, auth_api, streaming_enabled, sdk_matadata, telemetry_runtime_producer, sse_url=None, client_key=None, proxy_host=None, proxy_port=None, proxy=None): + synchronizer = mocker.Mock(spec=SynchronizerAsync) + async def sync_all(*_): + return None + synchronizer.sync_all = sync_all + + def start_periodic_fetching(): + pass + synchronizer.start_periodic_fetching = start_periodic_fetching + + def start_periodic_data_recording(): + pass + synchronizer.start_periodic_data_recording = start_periodic_data_recording + + self._ready_flag = ready_flag + self._synchronizer = synchronizer + self._streaming_enabled = False + self._telemetry_runtime_producer = telemetry_runtime_producer + + mocker.patch('splitio.sync.manager.ManagerAsync.__init__', new=_split_synchronizer) + + config_posted = asyncio.Event() + async def synchronize_config(*_): + await asyncio.sleep(5) + config_posted.set() + mocker.patch('splitio.sync.telemetry.InMemoryTelemetrySubmitterAsync.synchronize_config', new=synchronize_config) + + factory = await get_factory_async('some_api_key', config={'streamingEnabled': False}) + await factory.block_until_ready(1) # would raise TimeoutException if ready waited for telemetry + assert factory.ready + assert not config_posted.is_set() await factory.destroy() \ No newline at end of file diff --git a/tests/client/test_input_validator.py b/tests/client/test_input_validator.py index e1634f54..7f8d33f5 100644 --- a/tests/client/test_input_validator.py +++ b/tests/client/test_input_validator.py @@ -60,6 +60,7 @@ def test_get_treatment(self, mocker): telemetry_producer.get_telemetry_init_producer(), mocker.Mock() ) + factory.block_until_ready(1) # ready flag is a Mock, so the status thread sets READY at once client = Client(factory, mocker.Mock(), mocker.Mock(), mocker.Mock(), FallbackTreatmentCalculator(None)) _logger = mocker.Mock() @@ -303,6 +304,7 @@ def _configs(treatment): telemetry_producer.get_telemetry_init_producer(), mocker.Mock() ) + factory.block_until_ready(1) # ready flag is a Mock, so the status thread sets READY at once client = Client(factory, mocker.Mock(), mocker.Mock(), mocker.Mock(), FallbackTreatmentCalculator(None)) _logger = mocker.Mock() @@ -1012,6 +1014,7 @@ def test_get_treatments_with_config(self, mocker): telemetry_producer.get_telemetry_init_producer(), mocker.Mock() ) + factory.block_until_ready(1) # ready flag is a Mock, so the status thread sets READY at once split_mock.name = 'some_feature' def _configs(treatment): @@ -2732,6 +2735,7 @@ async def fetch_many_rbs(*_): mocker.Mock(), None ) + mocker.patch.object(SplitFactoryAsync, 'ready', new_callable=mocker.PropertyMock, return_value=True) split_mock.name = 'some_feature' def _configs(treatment): @@ -3631,6 +3635,7 @@ async def get(*_): mocker.Mock() ) + mocker.patch.object(SplitFactoryAsync, 'ready', new_callable=mocker.PropertyMock, return_value=True) manager = SplitManagerAsync(factory) _logger = mocker.Mock() mocker.patch('splitio.client.input_validator._LOGGER', new=_logger) @@ -3750,59 +3755,59 @@ class PluggableInputValidationTests(object): #pylint: disable=too-few-public-me class mock_adapter0(): def set(self, key, value): - print(key) + pass class mock_adapter1(object): def set(self, key, value): - print(key) + pass class mock_adapter2(mock_adapter1): def get(self, key): - print(key) + pass def get_items(self, key): - print(key) + pass def get_many(self, keys): - print(keys) + pass def push_items(self, key, *value): - print(key) + pass def delete(self, key): - print(key) + pass def increment(self, key, value): - print(key) + pass def decrement(self, key, value): - print(key) + pass def get_keys_by_prefix(self, prefix): - print(prefix) + pass def get_many(self, keys): - print(keys) + pass def add_items(self, key, added_items): - print(key) + pass def remove_items(self, key, removed_items): - print(key) + pass def item_contains(self, key, item): - print(key) + pass def get_items_count(self, key): - print(key) + pass class mock_adapter3(mock_adapter2): def expire(self, key): - print(key) + pass class mock_adapter4(mock_adapter2): def expire(self, key, value, till): - print(key) + pass def test_validate_pluggable_adapter(self): # missing storageWrapper config parameter diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 00000000..e59da461 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,25 @@ +"""Shared pytest fixtures.""" +import pytest + +from splitio.client.factory import SplitFactoryBase, SplitFactory, SplitFactoryAsync + +_FACTORY_CLASSES = (SplitFactoryBase, SplitFactory, SplitFactoryAsync) +_MISSING = object() + + +@pytest.fixture(autouse=True) +def _restore_factory_ready_property(): + """ + Undo class-level overrides of `ready` made by tests. + + Many tests do `type(factory).ready = PropertyMock(...)`, which replaces the property on the + factory class itself and leaks into every later test in the session. + """ + saved = {cls: vars(cls).get('ready', _MISSING) for cls in _FACTORY_CLASSES} + yield + for cls, original in saved.items(): + if original is _MISSING: + if 'ready' in vars(cls): + delattr(cls, 'ready') + else: + setattr(cls, 'ready', original) diff --git a/tests/integration/test_client_e2e.py b/tests/integration/test_client_e2e.py index 2cce4249..b64cdba7 100644 --- a/tests/integration/test_client_e2e.py +++ b/tests/integration/test_client_e2e.py @@ -860,6 +860,7 @@ def setup_method(self): kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % self.split_backend.port(), + 'telemetry_api_base_url': 'http://localhost:1/api', # unused port: never hit the real endpoint 'events_api_base_url': 'http://localhost:%d/api' % self.split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % self.split_backend.port(), 'config': {'connectTimeout': 10000, @@ -1021,6 +1022,7 @@ def setup_method(self): kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % self.split_backend.port(), + 'telemetry_api_base_url': 'http://localhost:1/api', # unused port: never hit the real endpoint 'events_api_base_url': 'http://localhost:%d/api' % self.split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % self.split_backend.port(), 'config': {'connectTimeout': 10000, @@ -3266,6 +3268,7 @@ async def _setup_method(self): kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % self.split_backend.port(), + 'telemetry_api_base_url': 'http://localhost:1/api', # unused port: never hit the real endpoint 'events_api_base_url': 'http://localhost:%d/api' % self.split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % self.split_backend.port(), 'config': {'connectTimeout': 10000, @@ -3462,6 +3465,7 @@ async def _setup_method(self): kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % self.split_backend.port(), + 'telemetry_api_base_url': 'http://localhost:1/api', # unused port: never hit the real endpoint 'events_api_base_url': 'http://localhost:%d/api' % self.split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % self.split_backend.port(), 'config': {'connectTimeout': 10000, diff --git a/tests/integration/test_streaming_e2e.py b/tests/integration/test_streaming_e2e.py index d7b3103a..8405f2bb 100644 --- a/tests/integration/test_streaming_e2e.py +++ b/tests/integration/test_streaming_e2e.py @@ -17,6 +17,39 @@ from splitio.models.telemetry import StreamingEventTypes, SSESyncMode +def _wait_until(predicate, timeout=10, interval=0.1): + """Poll predicate until it's truthy or timeout (seconds) expires. Returns its last result.""" + deadline = time.time() + timeout + while True: + result = predicate() + if result or time.time() >= deadline: + return result + time.sleep(interval) + + +async def _wait_until_async(predicate, timeout=10, interval=0.1): + """Async version of _wait_until: yields to the event loop between polls.""" + deadline = time.time() + timeout + while True: + result = predicate() + if result or time.time() >= deadline: + return result + await asyncio.sleep(interval) + + +def _switched_to_streaming(factory): + """ + Whether the SDK recorded a SYNC_MODE_UPDATE=STREAMING telemetry event. + + Checks any position, not the last one: the push status handler records SYNC_MODE_UPDATE + while the SSE connection records OCCUPANCY_PRI/SEC concurrently, so their order varies. + Re-reads the list each call because telemetry replaces it when popping events. + """ + events = factory._telemetry_evaluation_producer._telemetry_storage._streaming_events._streaming_events + return any(e._type == StreamingEventTypes.SYNC_MODE_UPDATE.value and e._data == SSESyncMode.STREAMING.value + for e in events) + + class StreamingIntegrationTests(object): """Test streaming operation and failover.""" @@ -68,6 +101,7 @@ def test_happiness(self): kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), + 'telemetry_api_base_url': 'http://localhost:1/api', # unused port: never hit the real endpoint 'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), @@ -80,9 +114,7 @@ def test_happiness(self): assert factory.ready assert factory.client().get_treatment('maldo', 'split1') == 'on' - time.sleep(1) - assert(factory._telemetry_evaluation_producer._telemetry_storage._streaming_events._streaming_events[len(factory._telemetry_evaluation_producer._telemetry_storage._streaming_events._streaming_events)-1]._type == StreamingEventTypes.SYNC_MODE_UPDATE.value) - assert(factory._telemetry_evaluation_producer._telemetry_storage._streaming_events._streaming_events[len(factory._telemetry_evaluation_producer._telemetry_storage._streaming_events._streaming_events)-1]._data == SSESyncMode.STREAMING.value) + assert _wait_until(lambda: _switched_to_streaming(factory)) split_changes[1] = { 'ff': { 's': 1, @@ -287,6 +319,7 @@ def test_occupancy_flicker(self): kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), + 'telemetry_api_base_url': 'http://localhost:1/api', # unused port: never hit the real endpoint 'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), @@ -506,6 +539,7 @@ def test_start_without_occupancy(self): kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), + 'telemetry_api_base_url': 'http://localhost:1/api', # unused port: never hit the real endpoint 'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), @@ -654,6 +688,7 @@ def test_streaming_status_changes(self): kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), + 'telemetry_api_base_url': 'http://localhost:1/api', # unused port: never hit the real endpoint 'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), @@ -729,7 +764,8 @@ def test_streaming_status_changes(self): time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert task.running() - assert 'PushStatusHandler' not in [t.name for t in threading.enumerate()] + # Check this factory's handler thread exits (not by name: other tests may leave theirs alive) + assert _wait_until(lambda: not factory._sync_manager._push_status_handler.is_alive()) # Validate the SSE request sse_request = sse_requests.get() @@ -880,6 +916,7 @@ def test_server_closes_connection(self): kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), + 'telemetry_api_base_url': 'http://localhost:1/api', # unused port: never hit the real endpoint 'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), @@ -1058,13 +1095,6 @@ def test_server_closes_connection(self): def test_ably_errors_handling(self): """Test incoming ably errors and validate its handling.""" - import logging - logger = logging.getLogger('splitio') - handler = logging.StreamHandler() - formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s') - handler.setFormatter(formatter) - logger.addHandler(handler) - logger.setLevel(logging.DEBUG) auth_server_response = { 'pushEnabled': True, 'token': ('eyJhbGciOiJIUzI1NiIsImtpZCI6IjVZOU05US45QnJtR0EiLCJ0eXAiOiJKV1QifQ.' @@ -1104,6 +1134,7 @@ def test_ably_errors_handling(self): kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), + 'telemetry_api_base_url': 'http://localhost:1/api', # unused port: never hit the real endpoint 'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), @@ -1171,7 +1202,8 @@ def test_ably_errors_handling(self): # Assert sync-task is running and the streaming status handler thread is over assert task.running() - assert 'PushStatusHandler' not in [t.name for t in threading.enumerate()] + # Check this factory's handler thread exits (not by name: other tests may leave theirs alive) + assert _wait_until(lambda: not factory._sync_manager._push_status_handler.is_alive()) # Validate the SSE requests sse_request = sse_requests.get() @@ -1334,6 +1366,7 @@ def test_change_number(mocker): kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), + 'telemetry_api_base_url': 'http://localhost:1/api', # unused port: never hit the real endpoint 'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), @@ -1416,6 +1449,7 @@ async def test_happiness(self): kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), + 'telemetry_api_base_url': 'http://localhost:1/api', # unused port: never hit the real endpoint 'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), @@ -1428,9 +1462,7 @@ async def test_happiness(self): assert factory.ready assert await factory.client().get_treatment('maldo', 'split1') == 'on' - await asyncio.sleep(1) - assert(factory._telemetry_evaluation_producer._telemetry_storage._streaming_events._streaming_events[len(factory._telemetry_evaluation_producer._telemetry_storage._streaming_events._streaming_events)-1]._type == StreamingEventTypes.SYNC_MODE_UPDATE.value) - assert(factory._telemetry_evaluation_producer._telemetry_storage._streaming_events._streaming_events[len(factory._telemetry_evaluation_producer._telemetry_storage._streaming_events._streaming_events)-1]._data == SSESyncMode.STREAMING.value) + assert await _wait_until_async(lambda: _switched_to_streaming(factory)) split_changes[1] = {'ff': { 's': 1, 't': 2, @@ -1613,6 +1645,7 @@ async def test_occupancy_flicker(self): kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), + 'telemetry_api_base_url': 'http://localhost:1/api', # unused port: never hit the real endpoint 'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), @@ -1828,6 +1861,7 @@ async def test_start_without_occupancy(self): kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), + 'telemetry_api_base_url': 'http://localhost:1/api', # unused port: never hit the real endpoint 'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), @@ -1976,6 +2010,7 @@ async def test_streaming_status_changes(self): kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), + 'telemetry_api_base_url': 'http://localhost:1/api', # unused port: never hit the real endpoint 'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), @@ -2200,6 +2235,7 @@ async def test_server_closes_connection(self): kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), + 'telemetry_api_base_url': 'http://localhost:1/api', # unused port: never hit the real endpoint 'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), @@ -2376,13 +2412,6 @@ async def test_server_closes_connection(self): @pytest.mark.asyncio async def test_ably_errors_handling(self): """Test incoming ably errors and validate its handling.""" - import logging - logger = logging.getLogger('splitio') - handler = logging.StreamHandler() - formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s') - handler.setFormatter(formatter) - logger.addHandler(handler) - logger.setLevel(logging.DEBUG) auth_server_response = { 'pushEnabled': True, 'token': ('eyJhbGciOiJIUzI1NiIsImtpZCI6IjVZOU05US45QnJtR0EiLCJ0eXAiOiJKV1QifQ.' @@ -2421,6 +2450,7 @@ async def test_ably_errors_handling(self): kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), + 'telemetry_api_base_url': 'http://localhost:1/api', # unused port: never hit the real endpoint 'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), @@ -2650,6 +2680,7 @@ async def test_change_number(mocker): kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), + 'telemetry_api_base_url': 'http://localhost:1/api', # unused port: never hit the real endpoint 'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), diff --git a/tests/models/test_telemetry_model.py b/tests/models/test_telemetry_model.py index 7032c359..deb1c5dc 100644 --- a/tests/models/test_telemetry_model.py +++ b/tests/models/test_telemetry_model.py @@ -14,28 +14,21 @@ class TelemetryModelTests(object): """Telemetry model test cases.""" def test_latency_bucket_index(self): - for i in range(50000): - latency = random.randint(10, 9987885) - old_bucket = 0 - result_bucket = 0 - counter = -1 - for j in ModelTelemetry.BUCKETS: - counter += 1 - if old_bucket == 0: - if latency < j: - old_bucket = 0 - break - old_bucket = j - continue - if counter == ModelTelemetry.MAX_LATENCY_BUCKET_COUNT - 1: - result_bucket = 22 - break - if latency > old_bucket and latency <= j: - result_bucket = counter - break - old_bucket = j - print(latency, old_bucket, j) - assert(result_bucket == ModelTelemetry.get_latency_bucket_index(latency)) + """Bucket i holds latencies in (BUCKETS[i-1], BUCKETS[i]]; bucket 0 starts at 0; above MAX_LATENCY is the last bucket.""" + get_index = ModelTelemetry.get_latency_bucket_index + buckets = ModelTelemetry.BUCKETS + last = ModelTelemetry.MAX_LATENCY_BUCKET_COUNT - 1 + + assert get_index(0) == 0 + assert get_index(1) == 0 + for i, upper in enumerate(buckets): + lower = buckets[i - 1] if i > 0 else 0 + assert get_index(lower + 1) == i # first value of the bucket + assert get_index((lower + upper) // 2) == i + assert get_index(upper) == i # upper bound is inclusive + assert get_index(upper + 1) == min(i + 1, last) + assert get_index(ModelTelemetry.MAX_LATENCY) == last + assert get_index(ModelTelemetry.MAX_LATENCY * 10) == last def test_storage_type_and_operation_mode(self, mocker): assert(StorageType.MEMORY.value == 'memory') diff --git a/tests/push/test_manager.py b/tests/push/test_manager.py index 3525baf3..92b8e2d8 100644 --- a/tests/push/test_manager.py +++ b/tests/push/test_manager.py @@ -265,7 +265,6 @@ async def authenticate(): self.token = None def timer_mock(token): - print("timer_mock") self.token = token return (token.exp - token.iat) - _TOKEN_REFRESH_GRACE_PERIOD diff --git a/tests/recorder/test_recorder.py b/tests/recorder/test_recorder.py index cf226613..99164c3e 100644 --- a/tests/recorder/test_recorder.py +++ b/tests/recorder/test_recorder.py @@ -113,7 +113,6 @@ def put(x): for _ in range(100): recorder.record_treatment_stats(impressions, 1, 'some', 'get_treatment') - print(recorder._impression_storage.put.call_count) assert recorder._impression_storage.put.call_count < 80 assert recorder._imp_counter.track.mock_calls == [] assert recorder._unique_keys_tracker.track.mock_calls == [] @@ -269,7 +268,6 @@ async def put(x): for _ in range(100): await recorder.record_treatment_stats(impressions, 1, 'some', 'get_treatment') - print(recorder._impression_storage.put.call_count) assert recorder._impression_storage.put.call_count < 80 assert self.count == [] assert self.unique_keys == [] From 346490c56c2a2c48c36bbbc41273916374b6ecdc Mon Sep 17 00:00:00 2001 From: Luis Sanchez Date: Fri, 6 Nov 2026 03:53:59 +0000 Subject: [PATCH 06/16] Create inputset python-client hc pr --- .../input_sets/pythonclient_hc_pr.yaml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_pr.yaml diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_pr.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_pr.yaml new file mode 100644 index 00000000..f51599c0 --- /dev/null +++ b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_pr.yaml @@ -0,0 +1,14 @@ +inputSet: + name: "python-client hc pr " + identifier: pythonclient_hc_pr + orgIdentifier: PROD + projectIdentifier: Harness_Split + pipeline: + identifier: pythonclient_hc + properties: + ci: + codebase: + build: + type: PR + spec: + number: <+trigger.prNumber> From 1fddf93577ff85a8ab247e7bbfd8f2d4d2542a46 Mon Sep 17 00:00:00 2001 From: Luis Sanchez Date: Fri, 6 Nov 2026 03:54:55 +0000 Subject: [PATCH 07/16] Create inputset python-client hc push --- .../input_sets/pythonclient_hc_push.yaml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_push.yaml diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_push.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_push.yaml new file mode 100644 index 00000000..77e0901c --- /dev/null +++ b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_push.yaml @@ -0,0 +1,14 @@ +inputSet: + name: python-client hc push + identifier: pythonclient_hc_push + orgIdentifier: PROD + projectIdentifier: Harness_Split + pipeline: + identifier: pythonclient_hc + properties: + ci: + codebase: + build: + type: branch + spec: + branch: <+trigger.branch> From baf227527cf7b91034a9227d461f1ecde15e4164 Mon Sep 17 00:00:00 2001 From: Emiliano Sanchez Date: Fri, 6 Nov 2026 01:29:25 -0300 Subject: [PATCH 08/16] Polish tests and CI --- .../Harness_Split/pipelines/pythonclient.yaml | 117 ------------------ .../pythonclient/input_sets/pythonclient.yaml | 15 --- .../pipelines/pythonclient_hc.yaml | 4 +- .../pythonclient_hc/input_sets/Baseline.yaml | 1 + .../input_sets/pythonclient_hc_pr.yaml | 14 --- .../input_sets/pythonclient_hc_push.yaml | 14 --- tests/client/test_factory.py | 24 +++- tests/conftest.py | 57 +++++++++ tests/integration/test_client_e2e.py | 8 ++ tests/storage/adapters/test_cache_trait.py | 4 +- tests/storage/test_redis.py | 14 +-- tests/sync/test_manager.py | 6 + tests/sync/test_synchronizer.py | 6 + 13 files changed, 111 insertions(+), 173 deletions(-) delete mode 100644 .harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient.yaml delete mode 100644 .harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient/input_sets/pythonclient.yaml delete mode 100644 .harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_pr.yaml delete mode 100644 .harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_push.yaml diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient.yaml deleted file mode 100644 index 9c81479e..00000000 --- a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient.yaml +++ /dev/null @@ -1,117 +0,0 @@ -pipeline: - name: python-client - identifier: pythonclient - projectIdentifier: Harness_Split - orgIdentifier: PROD - tags: {} - properties: - ci: - codebase: - repoName: python-client - build: <+input> - stages: - - stage: - name: Build and Test - identifier: Build_and_Test - description: "" - type: CI - spec: - cloneCodebase: true - envVariables: - CI_ENABLE_HCLI_FOR_TESTS: "true" - caching: - enabled: true - override: true - platform: - os: Linux - arch: Amd64 - runtime: - type: Cloud - spec: - size: flex - execution: - steps: - - step: - type: Run - name: Install Python - identifier: Install_Python - spec: - shell: Bash - command: |- - curl https://mise.run | sh - export PATH="$HOME/.local/bin:$PATH" - mise use --global python@<+matrix.pythonVersion> - eval "$(mise activate bash)" - python --version - pip --version - - step: - type: Run - name: Start Redis - identifier: Start_Redis - spec: - shell: Sh - command: |- - apt-get update -qq - apt-get install -y redis-server -qq - redis-server --daemonize yes --port 6379 - redis-cli ping - - step: - type: Run - name: Wait for Redis - identifier: Wait_for_Redis - spec: - shell: Sh - command: |- - for i in $(seq 1 15); do - redis-cli ping && break - echo "Waiting for Redis... attempt $i" - sleep 1 - done - - step: - type: Run - name: Install Dependencies - identifier: Install_Dependencies - spec: - shell: Bash - command: |- - export PATH="$HOME/.local/bin:$PATH" - eval "$(mise activate bash)" - apt-get install -y libkrb5-dev musl-dev libffi-dev build-essential -qq - pip install --upgrade pip setuptools wheel - pip install Cython - pip install cryptography - pip install pycparser - pip install -e ".[test,redis,asyncio,kerberos]" - - step: - type: Run - name: Run Tests - identifier: Run_Tests - spec: - shell: Bash - command: |- - export PATH="$HOME/.local/bin:$PATH" - eval "$(mise activate bash)" - python -m pytest - - step: - name: harnessCoverage - identifier: harnessCoverage - when: - stageStatus: Success - condition: <+matrix.pythonVersion> == "3.7.16" - template: - templateRef: account.codeCoverage - versionLabel: v1 - templateInputs: - type: Run - spec: - envVariables: - patch_coverage_percent: "80" - file_path: "coverage.xml" - overall_coverage_percent: "" - ignore_failure: "true" - exclude: "**/venv/**,**/__pycache__/**,**/test_*.py,**/*_test.py,**/tests/**" - strategy: - matrix: - pythonVersion: - - "3.7.16" - - "latest" diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient/input_sets/pythonclient.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient/input_sets/pythonclient.yaml deleted file mode 100644 index 02d1bcfb..00000000 --- a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient/input_sets/pythonclient.yaml +++ /dev/null @@ -1,15 +0,0 @@ -inputSet: - name: python-client - identifier: pythonclient - orgIdentifier: PROD - projectIdentifier: Harness_Split - pipeline: - identifier: pythonclient - properties: - ci: - codebase: - repoName: python-client - build: - type: PR - spec: - number: <+trigger.prNumber> diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc.yaml index 9459ca8d..4eba66f8 100644 --- a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc.yaml +++ b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc.yaml @@ -54,7 +54,6 @@ pipeline: apt-get update -qq apt-get install -y redis-server -qq redis-server --daemonize yes --port 6379 - redis-cli ping - step: type: Run name: Wait for Redis @@ -63,10 +62,11 @@ pipeline: shell: Sh command: |- for i in $(seq 1 15); do - redis-cli ping && break + redis-cli ping && exit 0 echo "Waiting for Redis... attempt $i" sleep 1 done + echo "Redis did not start"; exit 1 - step: type: Run name: Install Dependencies diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/Baseline.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/Baseline.yaml index 5c5c8f0a..9a5da3b5 100644 --- a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/Baseline.yaml +++ b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/Baseline.yaml @@ -8,6 +8,7 @@ inputSet: properties: ci: codebase: + repoName: python-client build: type: branch spec: diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_pr.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_pr.yaml deleted file mode 100644 index f51599c0..00000000 --- a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_pr.yaml +++ /dev/null @@ -1,14 +0,0 @@ -inputSet: - name: "python-client hc pr " - identifier: pythonclient_hc_pr - orgIdentifier: PROD - projectIdentifier: Harness_Split - pipeline: - identifier: pythonclient_hc - properties: - ci: - codebase: - build: - type: PR - spec: - number: <+trigger.prNumber> diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_push.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_push.yaml deleted file mode 100644 index 77e0901c..00000000 --- a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_push.yaml +++ /dev/null @@ -1,14 +0,0 @@ -inputSet: - name: python-client hc push - identifier: pythonclient_hc_push - orgIdentifier: PROD - projectIdentifier: Harness_Split - pipeline: - identifier: pythonclient_hc - properties: - ci: - codebase: - build: - type: branch - spec: - branch: <+trigger.branch> diff --git a/tests/client/test_factory.py b/tests/client/test_factory.py index a2c800a4..122b0365 100644 --- a/tests/client/test_factory.py +++ b/tests/client/test_factory.py @@ -9,6 +9,7 @@ import queue from splitio.optional.loaders import asyncio +from splitio.api.client import HttpResponse from splitio.client.factory import get_factory, get_factory_async, SplitFactory, _INSTANTIATED_FACTORIES, Status,\ _LOGGER as _logger, SplitFactoryAsync from splitio.client.config import DEFAULT_CONFIG @@ -44,6 +45,23 @@ class SplitFactoryTests(object): """Split factory test cases.""" + @pytest.fixture(autouse=True) + def _offline(self, mocker): + """Factories built here start real sync threads: answer their HTTP calls locally, never reach split.io.""" + def get(server, path, sdk_key, query=None, extra_headers=None): + if server == 'auth': + return HttpResponse(200, '{"pushEnabled": false}', {}) + return HttpResponse(200, '{"ff": {"d": [], "s": -1, "t": -1}, "rbs": {"d": [], "s": -1, "t": -1}}', {}) + + mocker.patch('splitio.api.client.HttpClient.get', side_effect=get) + mocker.patch('splitio.api.client.HttpClient.post', return_value=HttpResponse(200, '', {})) + before = set(threading.enumerate()) + yield + # let the factory's status threads finish while the patches are still active + for thread in set(threading.enumerate()) - before: + if thread.name in ('SDKInitializer', 'SDKReadyFlagUpdater'): + thread.join(2) + def test_flag_sets_counts(self): factory = get_factory("none", config={ 'flagSetsFilter': ['set1', 'set2', 'set3'] @@ -772,10 +790,12 @@ def synchronize_config(*_): assert event.metadata == None factory.destroy() - def test_uwsgi_forked_client_creation(self): + def test_uwsgi_forked_client_creation(self, mocker): """Test client with preforked initialization.""" - # Invalid API Key with preforked should exit after 3 attempts. + # No real network: the initial sync is stubbed (it would retry against sdk.split.io with backoff). + sync_all = mocker.patch('splitio.sync.synchronizer.Synchronizer.sync_all') factory = get_factory('some_api_key', config={'preforkedInitialization': True}) + sync_all.assert_called_once() class TelemetrySubmitterMock(): def synchronize_config(*_): pass diff --git a/tests/conftest.py b/tests/conftest.py index e59da461..77376aa1 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,4 +1,8 @@ """Shared pytest fixtures.""" +import faulthandler +import socket +import threading + import pytest from splitio.client.factory import SplitFactoryBase, SplitFactory, SplitFactoryAsync @@ -23,3 +27,56 @@ def _restore_factory_ready_property(): delattr(cls, 'ready') else: setattr(cls, 'ready', original) + + +def pytest_sessionfinish(session, exitstatus): + """ + Fail fast if the process doesn't exit after the tests end. + + A leaked non-daemon thread would keep the interpreter alive forever (and the CI step until its + timeout). If still alive after 120s, dump every thread's stack to stderr and exit with code 1. + The timer is cancelled when the interpreter exits normally. + """ + faulthandler.dump_traceback_later(120, exit=True) + + +_BLOCKED_SUFFIX = '.split.io' +_net_violations = [] +_current_test = {'id': None} +_real_getaddrinfo = socket.getaddrinfo +_real_thread_init = threading.Thread.__init__ + + +def _tracking_thread_init(self, *args, **kwargs): + # remember which test created the thread, to name the real culprit of a leaked background client + parent = threading.current_thread() + self._created_by_test = getattr(parent, '_created_by_test', None) or _current_test['id'] + _real_thread_init(self, *args, **kwargs) + + +threading.Thread.__init__ = _tracking_thread_init + + +def _guarded_getaddrinfo(host, *args, **kwargs): + name = host.decode() if isinstance(host, bytes) else host + if isinstance(name, str) and name.endswith(_BLOCKED_SUFFIX): + _net_violations.append((getattr(threading.current_thread(), '_created_by_test', None) or _current_test['id'], + name, threading.current_thread().name)) + raise socket.gaierror(socket.EAI_NONAME, 'network access to %s blocked by tests/conftest.py' % name) + return _real_getaddrinfo(host, *args, **kwargs) + + +socket.getaddrinfo = _guarded_getaddrinfo + + +@pytest.fixture(autouse=True) +def _no_split_network(request): + """Tests must not contact the Split backend (sdk/events/telemetry/auth *.split.io).""" + _current_test['id'] = request.node.nodeid + start = len(_net_violations) + yield + _current_test['id'] = None + found = _net_violations[start:] + if found: + pytest.fail('test contacted the Split backend (mock the HTTP layer): %s' % sorted( + {'%s from thread %s created in %s' % (host, thr, origin) for origin, host, thr in found}), pytrace=False) diff --git a/tests/integration/test_client_e2e.py b/tests/integration/test_client_e2e.py index b64cdba7..bea314b4 100644 --- a/tests/integration/test_client_e2e.py +++ b/tests/integration/test_client_e2e.py @@ -2655,6 +2655,10 @@ def test_sdk_ready(self): client = factory.client() client.on(SdkEvent.SDK_READY, self._ready_callback) factory.block_until_ready(5) + for _ in range(50): # the callback is delivered by the events task, not by block_until_ready + if self.ready_flag: + break + time.sleep(0.1) assert self.ready_flag """Shut down the factory.""" @@ -2812,6 +2816,10 @@ async def test_sdk_ready(self): client = factory.client() await client.on(SdkEvent.SDK_READY, self._ready_callback) await factory.block_until_ready(5) + for _ in range(50): # the callback is delivered by the events task, not by block_until_ready + if self.ready_flag: + break + await asyncio.sleep(0.1) assert self.ready_flag """Shut down the factory.""" diff --git a/tests/storage/adapters/test_cache_trait.py b/tests/storage/adapters/test_cache_trait.py index 5643cb32..749bfb16 100644 --- a/tests/storage/adapters/test_cache_trait.py +++ b/tests/storage/adapters/test_cache_trait.py @@ -101,7 +101,7 @@ def test_expiration_behaviour(self, mocker): assert cache.get('other') == 5 # cached key retains value until it's expired assert cache.get('kkk') == 4 # non-cached key calls function anyway and gets new result. - time.sleep(1) + time.sleep(1.2) assert cache.get('key') == 4 assert cache.get('other') == 6 @@ -137,5 +137,5 @@ async def test_async_add_and_get_key(self, mocker): cache = cache_trait.LocalMemoryCacheAsync(None, None, 1, 1) await cache.add_key('split', {'split_name': 'split'}) assert await cache.get_key('split') == {'split_name': 'split'} - await asyncio.sleep(1) + await asyncio.sleep(1.2) assert await cache.get_key('split') == None diff --git a/tests/storage/test_redis.py b/tests/storage/test_redis.py index a45c4ad2..ac4996e7 100644 --- a/tests/storage/test_redis.py +++ b/tests/storage/test_redis.py @@ -74,7 +74,7 @@ def test_get_split_with_cache(self, mocker): # Still cached result = storage.get('some_split') assert result is not None - time.sleep(1) # wait for expiration + time.sleep(1.2) # wait for expiration result = storage.get('some_split') assert result is None assert adapter.get.mock_calls == [mocker.call('SPLITIO.split.some_split')] @@ -171,11 +171,11 @@ def test_is_valid_traffic_type_with_cache(self, mocker): adapter.get.return_value = '0' assert storage.is_valid_traffic_type('any') is True - time.sleep(1) + time.sleep(1.2) assert storage.is_valid_traffic_type('any') is False adapter.get.return_value = None - time.sleep(1) + time.sleep(1.2) assert storage.is_valid_traffic_type('any') is False @mock.patch('splitio.storage.adapters.redis.RedisPipelineAdapter.execute', return_value = [{'split1', 'split2'}]) @@ -275,7 +275,7 @@ async def get2(sel, name): result = await storage.get('some_split') assert result is not None assert self.name == None - await asyncio.sleep(1) # wait for expiration + await asyncio.sleep(1.2) # wait for expiration result = await storage.get('some_split') assert self.name == 'SPLITIO.split.some_split' assert result is None @@ -317,7 +317,7 @@ async def mget(sel, name): assert self.name == None # wait for expire - await asyncio.sleep(1) + await asyncio.sleep(1.2) self.name = None result = await storage.fetch_many(['split1', 'split2', 'split3']) assert self.name == ['SPLITIO.split.split1', 'SPLITIO.split.split2', 'SPLITIO.split.split3'] @@ -438,13 +438,13 @@ async def get2(sel, name): return '0' mocker.patch('splitio.storage.adapters.redis.RedisAdapterAsync.get', new=get2) assert await storage.is_valid_traffic_type('any') is True - await asyncio.sleep(1) + await asyncio.sleep(1.2) assert await storage.is_valid_traffic_type('any') is False async def get3(sel, name): return None mocker.patch('splitio.storage.adapters.redis.RedisAdapterAsync.get', new=get3) - await asyncio.sleep(1) + await asyncio.sleep(1.2) assert await storage.is_valid_traffic_type('any') is False diff --git a/tests/sync/test_manager.py b/tests/sync/test_manager.py index 47ac3f01..efc52f1e 100644 --- a/tests/sync/test_manager.py +++ b/tests/sync/test_manager.py @@ -29,6 +29,12 @@ from splitio.client.util import SdkMetadata +@pytest.fixture(autouse=True) +def _no_backoff_wait(mocker): + """Retry loops back off 1, 2, 4... seconds; don't actually wait in tests.""" + mocker.patch('splitio.util.backoff.Backoff.get', return_value=0) + + class SyncManagerTests(object): """Synchronizer Manager tests.""" diff --git a/tests/sync/test_synchronizer.py b/tests/sync/test_synchronizer.py index 1244429b..41035d30 100644 --- a/tests/sync/test_synchronizer.py +++ b/tests/sync/test_synchronizer.py @@ -51,6 +51,12 @@ }] }] +@pytest.fixture(autouse=True) +def _no_backoff_wait(mocker): + """Retry loops back off 1, 2, 4... seconds; don't actually wait in tests.""" + mocker.patch('splitio.util.backoff.Backoff.get', return_value=0) + + class SynchronizerTests(object): def test_sync_all_failed_splits(self, mocker): api = mocker.Mock() From d57de77c2279c189089d99af6c1bd51933085f75 Mon Sep 17 00:00:00 2001 From: Emiliano Sanchez Date: Fri, 6 Nov 2026 11:18:36 -0300 Subject: [PATCH 09/16] Align input sets with python-commons and python-configs-client repos --- .../Harness_Split/pipelines/pythonclient.yaml | 118 ------------------ .../pythonclient/input_sets/pythonclient.yaml | 15 --- .../pipelines/pythonclient_hc.yaml | 11 +- ...client_hc.yaml => pythonclient_hc_pr.yaml} | 4 +- ...aseline.yaml => pythonclient_hc_push.yaml} | 5 +- 5 files changed, 10 insertions(+), 143 deletions(-) delete mode 100644 .harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient.yaml delete mode 100644 .harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient/input_sets/pythonclient.yaml rename .harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/{pythonclient_hc.yaml => pythonclient_hc_pr.yaml} (82%) rename .harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/{Baseline.yaml => pythonclient_hc_push.yaml} (72%) diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient.yaml deleted file mode 100644 index d9015243..00000000 --- a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient.yaml +++ /dev/null @@ -1,118 +0,0 @@ -pipeline: - name: python-client - identifier: pythonclient - projectIdentifier: Harness_Split - orgIdentifier: PROD - tags: {} - properties: - ci: - codebase: - repoName: python-client - build: <+input> - stages: - - stage: - name: Build and Test - identifier: Build_and_Test - description: "" - type: CI - spec: - cloneCodebase: true - envVariables: - CI_ENABLE_HCLI_FOR_TESTS: "true" - caching: - enabled: true - override: true - platform: - os: Linux - arch: Amd64 - runtime: - type: Cloud - spec: - size: flex - execution: - steps: - - step: - type: Run - name: Install Python - identifier: Install_Python - spec: - shell: Bash - command: |- - curl https://mise.run | sh - export PATH="$HOME/.local/bin:$PATH" - mise use --global python@<+matrix.pythonVersion> - eval "$(mise activate bash)" - python --version - pip --version - - step: - type: Run - name: Start Redis - identifier: Start_Redis - spec: - shell: Sh - command: |- - apt-get update -qq - apt-get install -y redis-server -qq - redis-server --daemonize yes --port 6379 - redis-cli ping - - step: - type: Run - name: Wait for Redis - identifier: Wait_for_Redis - spec: - shell: Sh - command: |- - for i in $(seq 1 15); do - redis-cli ping && break - echo "Waiting for Redis... attempt $i" - sleep 1 - done - - step: - type: Run - name: Install Dependencies - identifier: Install_Dependencies - spec: - shell: Bash - command: |- - export PATH="$HOME/.local/bin:$PATH" - eval "$(mise activate bash)" - apt-get install -y libkrb5-dev musl-dev libffi-dev build-essential -qq - pip install --upgrade pip setuptools wheel - pip install Cython - pip install aiohttp - pip install cryptography - pip install pycparser - pip install redis - pip install -e . - - step: - type: Run - name: Run Tests - identifier: Run_Tests - spec: - shell: Bash - command: |- - export PATH="$HOME/.local/bin:$PATH" - eval "$(mise activate bash)" - python setup.py test - - step: - name: harnessCoverage - identifier: harnessCoverage - when: - stageStatus: Success - condition: <+matrix.pythonVersion> == "3.7.16" - template: - templateRef: account.codeCoverage - versionLabel: v1 - templateInputs: - type: Run - spec: - envVariables: - patch_coverage_percent: "80" - file_path: "coverage.xml" - overall_coverage_percent: "" - ignore_failure: "true" - exclude: "**/venv/**,**/__pycache__/**,**/test_*.py,**/*_test.py,**/tests/**" - strategy: - matrix: - pythonVersion: - - "3.7.16" diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient/input_sets/pythonclient.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient/input_sets/pythonclient.yaml deleted file mode 100644 index 02d1bcfb..00000000 --- a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient/input_sets/pythonclient.yaml +++ /dev/null @@ -1,15 +0,0 @@ -inputSet: - name: python-client - identifier: pythonclient - orgIdentifier: PROD - projectIdentifier: Harness_Split - pipeline: - identifier: pythonclient - properties: - ci: - codebase: - repoName: python-client - build: - type: PR - spec: - number: <+trigger.prNumber> diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc.yaml index ebffdf2a..4eba66f8 100644 --- a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc.yaml +++ b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc.yaml @@ -54,7 +54,6 @@ pipeline: apt-get update -qq apt-get install -y redis-server -qq redis-server --daemonize yes --port 6379 - redis-cli ping - step: type: Run name: Wait for Redis @@ -63,10 +62,11 @@ pipeline: shell: Sh command: |- for i in $(seq 1 15); do - redis-cli ping && break + redis-cli ping && exit 0 echo "Waiting for Redis... attempt $i" sleep 1 done + echo "Redis did not start"; exit 1 - step: type: Run name: Install Dependencies @@ -79,11 +79,9 @@ pipeline: apt-get install -y libkrb5-dev musl-dev libffi-dev build-essential -qq pip install --upgrade pip setuptools wheel pip install Cython - pip install aiohttp pip install cryptography pip install pycparser - pip install redis - pip install -e . + pip install -e ".[test,redis,asyncio,kerberos]" - step: type: Run name: Run Tests @@ -93,7 +91,7 @@ pipeline: command: |- export PATH="$HOME/.local/bin:$PATH" eval "$(mise activate bash)" - python setup.py test + python -m pytest - step: name: harnessCoverage identifier: harnessCoverage @@ -116,3 +114,4 @@ pipeline: matrix: pythonVersion: - "3.7.16" + - "latest" diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_pr.yaml similarity index 82% rename from .harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc.yaml rename to .harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_pr.yaml index c3045725..68940c42 100644 --- a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc.yaml +++ b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_pr.yaml @@ -1,6 +1,6 @@ inputSet: - name: python-client hc - identifier: pythonclient_hc + name: python-client hc pr + identifier: pythonclient_hc_pr orgIdentifier: PROD projectIdentifier: Harness_Split pipeline: diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/Baseline.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_push.yaml similarity index 72% rename from .harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/Baseline.yaml rename to .harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_push.yaml index 5c5c8f0a..54658cf7 100644 --- a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/Baseline.yaml +++ b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc/input_sets/pythonclient_hc_push.yaml @@ -1,6 +1,6 @@ inputSet: - name: Baseline - identifier: Baseline + name: python-client hc push + identifier: pythonclient_hc_push orgIdentifier: PROD projectIdentifier: Harness_Split pipeline: @@ -8,6 +8,7 @@ inputSet: properties: ci: codebase: + repoName: python-client build: type: branch spec: From 0987ceb017890df72da93cbf8d40111301effdfc Mon Sep 17 00:00:00 2001 From: Emiliano Sanchez Date: Fri, 6 Nov 2026 13:36:12 -0300 Subject: [PATCH 10/16] Fix streaming recovery issues that could leave the SDK serving stale flags (FME-21783) - Handle unexpected streaming auth/connection errors (non-JSON auth response, malformed token, SSE client errors) as retryable, falling back to polling. - Keep the streaming status handler alive on unexpected errors (sync and async). - Fix the async token refresh being cancelled by the cleanup of the connection it closes. - Consider streaming connected once the SSE connection opens, not on the first event. - Keep the SSE socket so non-chunked connections can be shut down. - Retry auth responses with a malformed token instead of disabling streaming. - Don't open SSE or retry auth when the SDK is destroyed while authenticating or waiting for the retry backoff. - Disable aiohttp's silent re-send of requests on dropped connections, which bypassed the streaming retry backoff. --- AGENTS.md | 1 + CHANGES.txt | 12 +- splitio/api/client.py | 4 + splitio/models/token.py | 16 +- splitio/push/manager.py | 65 +++++++- splitio/push/splitsse.py | 3 - splitio/push/sse.py | 31 +++- splitio/sync/manager.py | 179 +++++++++++++------- splitio/version.py | 2 +- tests/api/test_httpclient.py | 8 + tests/helpers/mockserver.py | 23 ++- tests/integration/test_streaming_e2e.py | 17 +- tests/models/test_token.py | 9 + tests/push/test_manager.py | 212 ++++++++++++++++++++++++ tests/push/test_splitsse.py | 17 +- tests/push/test_sse.py | 24 ++- tests/sync/test_manager.py | 165 ++++++++++++++++++ 17 files changed, 692 insertions(+), 96 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 88d58a16..2750cdb0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,6 +7,7 @@ Split.io Python SDK — a feature flag evaluation client for the [Split platform - GitHub: https://github.com/splitio/python-client - Compatible with Python 3.7+ - Published to PyPI as `splitio_client` +- **Release candidate versions**: `X.Y.ZrcN` (for example `10.7.0rc1`). This is the PEP 440 form this package publishes. `X.Y.Z-rcN` and `X.Y.Z.rcN` normalize to the same version, but write the version without a separator. ## Prerequisites diff --git a/CHANGES.txt b/CHANGES.txt index 2bc8774b..be70d303 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,7 +1,17 @@ 10.7.1 (Nov 6, 2026) -- Fixed async factory readiness being delayed by the telemetry config post: SplitFactoryAsync now becomes ready before posting telemetry, as the sync factory does. - Updated package metadata: declared python_requires>=3.7, updated the trove classifiers (3.7 to latest stable, Python 2 removed) and removed the universal wheel setting (wheels are now tagged py3). - Updated CI, tests and test dependencies to improve reliability and to validate the SDK on Python 3.7 and latest stable. +- Fixed async factory readiness being delayed by the telemetry config post: SplitFactoryAsync now becomes ready before posting telemetry, as the sync factory does. +- Fixed an issue where the SDK could stop applying feature flag updates when streaming is enabled, serving stale definitions until restart: + - Unexpected errors during the streaming authentication or connection (e.g. a non-JSON response or a malformed token) are now handled as retryable errors: the SDK switches to polling and retries streaming with backoff. + - Unexpected errors in the streaming status handler no longer stop it; the SDK switches to polling and retries streaming with backoff. + - Fixed the asyncio token refresh being cancelled by the cleanup of the connection it closes, which could leave the SDK without streaming and without polling. +- Fixed several streaming (SSE) connection issues: + - The streaming connection is now considered established once the SSE connection opens, instead of waiting for the first event. Previously, the token refresh and the reconnection after a retryable error waited for an incoming event to resume streaming. + - Fixed the SSE connection not being closed on token refresh or SDK destroy when the server response is not chunked, which could block the token refresh. + - An auth response with a malformed token is now handled as a retryable error instead of disabling streaming. + - Destroying the SDK while authenticating or waiting to retry streaming no longer opens a new SSE connection or retries the authentication. + - Fixed asyncio HTTP and SSE requests being silently re-sent when the server closes the connection, bypassing the streaming retry backoff. 10.7.0 (Oct 5, 2026) - Added ability to use proxy url for all http connections. diff --git a/splitio/api/client.py b/splitio/api/client.py index 5673ed96..143041d2 100644 --- a/splitio/api/client.py +++ b/splitio/api/client.py @@ -272,6 +272,10 @@ def __init__(self, timeout=None, sdk_url=None, events_url=None, auth_url=None, t """ HttpClientBase.__init__(self, timeout, sdk_url, events_url, auth_url, telemetry_url, proxies) self._session = aiohttp.ClientSession() + # aiohttp silently re-sends an idempotent request once if the server drops a persistent + # connection: disable it so that failures are retried with the SDK backoff + if hasattr(self._session, '_retry_connection'): + self._session._retry_connection = False # pylint: disable=protected-access self._proxy = None if len(self._proxies) > 0: http_key = next(iter(self._proxies)) diff --git a/splitio/models/token.py b/splitio/models/token.py index f2b0cf9c..baa8ecb6 100644 --- a/splitio/models/token.py +++ b/splitio/models/token.py @@ -73,11 +73,17 @@ def from_raw(raw_token): token = raw_token['token'] push_enabled = raw_token['pushEnabled'] - token_parts = token.strip().split('.') - if not push_enabled or len(token_parts) < 2: + if not push_enabled or not token: # empty token when streaming is disabled return Token(False, None, None, None, None) - to_decode = token_parts[1] - decoded_token = json.loads(base64.b64decode(to_decode + '='*(-len(to_decode) % 4))) - return Token(push_enabled, token, json.loads(decoded_token['x-ably-capability']), decoded_token['exp'], decoded_token['iat']) \ No newline at end of file + # A token that cannot be decoded is an error (retried by the caller), not streaming disabled + try: + to_decode = token.strip().split('.')[1] + decoded_token = json.loads(base64.b64decode(to_decode + '='*(-len(to_decode) % 4))) + channels = json.loads(decoded_token['x-ably-capability']) + exp, iat = decoded_token['exp'], decoded_token['iat'] + except Exception as exc: # pylint:disable=broad-except + raise ValueError('Invalid auth token') from exc + + return Token(push_enabled, token, channels, exp, iat) \ No newline at end of file diff --git a/splitio/push/manager.py b/splitio/push/manager.py index e4e6a096..e5f8b3d4 100644 --- a/splitio/push/manager.py +++ b/splitio/push/manager.py @@ -1,6 +1,6 @@ """Push subsystem manager class and helpers.""" import logging -from threading import Timer +from threading import Timer, Event import abc import sys @@ -92,6 +92,7 @@ def __init__(self, auth_api, synchronizer, feedback_loop, sdk_metadata, telemetr self._sse_client = SplitSSEClient(self._event_handler, sdk_metadata, self._handle_connection_ready, self._handle_connection_end, client_key, **kwargs, proxy_url=proxy_url) self._running = False + self._stop_requested = Event() # set by stop() to abort an ongoing connection flow self._next_refresh = Timer(0, lambda: 0) self._telemetry_runtime_producer = telemetry_runtime_producer @@ -111,12 +112,26 @@ def start(self): _LOGGER.warning('Push manager already has a connection running. Ignoring') return + self._stop_requested.clear() self._trigger_connection_flow() def stop(self, blocking=False): """ Stop the current ongoing connection. + If called while connecting (e.g. waiting for the auth response), the connection flow is + aborted and no streaming connection is opened. + + :param blocking: whether to wait for the connection to be successfully closed or not + :type blocking: bool + """ + self._stop_requested.set() + self._stop_connection(blocking) + + def _stop_connection(self, blocking): + """ + Close the current connection, if any. + :param blocking: whether to wait for the connection to be successfully closed or not :type blocking: bool """ @@ -161,8 +176,15 @@ def _event_handler(self, event): def _token_refresh(self): """Refresh auth token.""" _LOGGER.info("retriggering authentication flow.") - self.stop(True) - self._trigger_connection_flow() + try: + self._stop_connection(True) + self._trigger_connection_flow() + except Exception: # pylint:disable=broad-except + # This runs in the TokenRefresh timer thread. If it dies here, streaming stays + # stopped and polling is never started, so the SDK would stop receiving updates. + _LOGGER.error('unexpected error refreshing streaming token.') + _LOGGER.debug('stack trace: ', exc_info=True) + self._feedback_loop.put(Status.PUSH_RETRYABLE_ERROR) def _trigger_connection_flow(self): """Authenticate and start a connection.""" @@ -173,6 +195,16 @@ def _trigger_connection_flow(self): _LOGGER.debug('stack trace: ', exc_info=True) self._feedback_loop.put(Status.PUSH_RETRYABLE_ERROR) return + except Exception: # pylint:disable=broad-except + # e.g. a non-JSON 200 response or a malformed token. + _LOGGER.error('unexpected error performing sse auth request.') + _LOGGER.debug('stack trace: ', exc_info=True) + self._feedback_loop.put(Status.PUSH_RETRYABLE_ERROR) + return + + if self._stop_requested.is_set(): + _LOGGER.debug('push manager stopped while authenticating. not connecting to streaming.') + return if token is None or not token.push_enabled: self._feedback_loop.put(Status.PUSH_NONRETRYABLE_ERROR) @@ -180,7 +212,20 @@ def _trigger_connection_flow(self): self._telemetry_runtime_producer.record_token_refreshes() _LOGGER.debug("auth token fetched. connecting to streaming.") self._status_tracker.reset() - if self._sse_client.start(token): + try: + connected = self._sse_client.start(token) + except Exception: # pylint:disable=broad-except + _LOGGER.error('unexpected error connecting to streaming.') + _LOGGER.debug('stack trace: ', exc_info=True) + self._feedback_loop.put(Status.PUSH_RETRYABLE_ERROR) + return + + if connected and self._stop_requested.is_set(): + _LOGGER.debug('push manager stopped while connecting. closing streaming connection.') + self._sse_client.stop() + return + + if connected: _LOGGER.debug("connected to streaming, scheduling next refresh") self._setup_next_token_refresh(token) self._running = True @@ -398,6 +443,10 @@ async def _token_refresh(self, current_token): """ _LOGGER.debug("Next token refresh in " + str(self._get_time_period(current_token)) + " seconds") await asyncio.sleep(self._get_time_period(current_token)) + # This task is self._token_task. Detach it before closing the current connection, + # otherwise the connection task's cleanup cancels it and the new connection is never + # started, leaving the SDK without streaming and without polling. + self._token_task = None await self._stop_current_conn() self._running_task = asyncio.get_running_loop().create_task(self._trigger_connection_flow()) @@ -446,6 +495,14 @@ async def _trigger_connection_flow(self): _LOGGER.debug("trace: ", exc_info=True) except StopAsyncIteration: # will enter here if there was an error await self._feedback_loop.put(Status.PUSH_RETRYABLE_ERROR) + except asyncio.CancelledError: # subclass of Exception in python 3.7 + raise + except Exception: # pylint:disable=broad-except + # e.g. a non-JSON 200 auth response, a malformed token or an sse client error. + # Without this the task ends silently and polling is never started. + _LOGGER.error('unexpected error in streaming connection flow.') + _LOGGER.debug('stack trace: ', exc_info=True) + await self._feedback_loop.put(Status.PUSH_RETRYABLE_ERROR) finally: if self._token_task is not None: self._token_task.cancel() diff --git a/splitio/push/splitsse.py b/splitio/push/splitsse.py index 10773b2b..d56db9ee 100644 --- a/splitio/push/splitsse.py +++ b/splitio/push/splitsse.py @@ -223,9 +223,6 @@ async def start(self, token): self._event_source_ended.clear() self._event_source = self._client.start(url, extra_headers=self._metadata, proxy_url=self._proxy) first_event = await anext(self._event_source) - if first_event.event == SSE_EVENT_ERROR: - return - yield first_event self.status = SplitSSEClient._Status.CONNECTED _LOGGER.debug("Split SSE client started") diff --git a/splitio/push/sse.py b/splitio/push/sse.py index cd4dd162..0c693109 100644 --- a/splitio/push/sse.py +++ b/splitio/push/sse.py @@ -59,6 +59,7 @@ def __init__(self, callback): :type callback: callable """ self._conn = None + self._sock = None self._event_callback = callback self._shutdown_requested = False @@ -71,6 +72,12 @@ def _read_events(self): """ try: response = self._conn.getresponse() + if response.status != 200: + _LOGGER.error('sse request status code: %d', response.status) + return self._shutdown_requested + + # Signal the connection is open before reading events (like EventSource `open`) + self._event_callback(SSEEvent(None, None, None, None)) event_builder = EventBuilder() while True: line = response.readline() @@ -91,7 +98,10 @@ def _read_events(self): if not self._shutdown_requested: _LOGGER.debug('stack trace: ', exc_info=True) finally: + sock, self._sock = self._sock, None self._conn.close() + if sock is not None: + sock.close() self._conn = None # clear so it can be started again return self._shutdown_requested @@ -132,6 +142,9 @@ def start(self, url, extra_headers=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, else HTTPConnection(url.hostname, port=url.port, timeout=timeout)) self._conn.request('GET', '%s?%s' % (url.path, url.query), headers=headers) + # Keep the socket: for responses delimited by connection close (no chunked encoding nor + # content-length), getresponse() clears self._conn.sock while the response keeps reading. + self._sock = self._conn.sock return self._read_events() def _get_proxy_info(self, proxy_url): @@ -156,7 +169,8 @@ def _get_proxy_info(self, proxy_url): def shutdown(self): """Shutdown the current connection.""" - if self._conn is None or self._conn.sock is None: + sock = self._sock + if self._conn is None or sock is None: _LOGGER.warning("no sse connection has been started on this SSEClient instance. Ignoring") return @@ -165,7 +179,10 @@ def shutdown(self): return self._shutdown_requested = True - self._conn.sock.shutdown(socket.SHUT_RDWR) + try: + sock.shutdown(socket.SHUT_RDWR) + except OSError: # connection ended (and socket closed) concurrently + _LOGGER.debug('sse connection already ended.') class SSEClientAsync(object): @@ -189,6 +206,10 @@ def __init__(self, socket_read_timeout=_DEFAULT_SOCKET_READ_TIMEOUT): self._done = asyncio.Event() self._client_timeout = aiohttp.ClientTimeout(total=60*60, sock_read=self._socket_read_timeout) self._sess = aiohttp.ClientSession(timeout=self._client_timeout) + # aiohttp silently re-sends an idempotent request once if the server drops the connection, + # which would hide a failed attempt from the push manager's retry/backoff logic. + if hasattr(self._sess, '_retry_connection'): + self._sess._retry_connection = False # pylint: disable=protected-access async def start(self, url, extra_headers=None, proxy_url=None): # pylint:disable=protected-access """ @@ -210,7 +231,13 @@ async def start(self, url, extra_headers=None, proxy_url=None): # pylint:disabl timeout=self._client_timeout, proxy=proxy_url, ) as response: + if response.status != 200: + _LOGGER.error('sse request status code: %d', response.status) + return + self._response = response + # Signal the connection is open before reading events (like EventSource `open`) + yield SSEEvent(None, None, None, None) event_builder = EventBuilder() async for line in response.content: if line.startswith(b':'): diff --git a/splitio/sync/manager.py b/splitio/sync/manager.py index 34346d34..a7146049 100644 --- a/splitio/sync/manager.py +++ b/splitio/sync/manager.py @@ -1,7 +1,6 @@ """Synchronization manager module.""" import logging -import time -from threading import Thread +from threading import Thread, Event from queue import Queue from splitio.optional.loaders import asyncio @@ -54,6 +53,7 @@ def __init__(self, ready_flag, synchronizer, auth_api, streaming_enabled, sdk_me self._telemetry_runtime_producer = telemetry_runtime_producer if self._streaming_enabled: self._push_status_handler_active = True + self._stop_event = Event() # interrupts the backoff between streaming retries self._backoff = Backoff() self._queue = Queue() self._push = PushManager(auth_api, synchronizer, self._queue, sdk_metadata, telemetry_runtime_producer, sse_url, client_key, proxy_url) @@ -91,6 +91,7 @@ def stop(self, blocking): _LOGGER.info('Stopping manager tasks') if self._streaming_enabled: self._push_status_handler_active = False + self._stop_event.set() self._queue.put(self._CENTINEL_EVENT) self._push.stop() self._synchronizer.shutdown(blocking) @@ -107,36 +108,64 @@ def _streaming_feedback_handler(self): if status == self._CENTINEL_EVENT: continue - if status == Status.PUSH_SUBSYSTEM_UP: - self._synchronizer.stop_periodic_fetching() - self._synchronizer.sync_all() - self._push.update_workers_status(True) - self._backoff.reset() - _LOGGER.info('streaming up and running. disabling periodic fetching.') - self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.SYNC_MODE_UPDATE, SSESyncMode.STREAMING.value, get_current_epoch_time_ms())) - elif status == Status.PUSH_SUBSYSTEM_DOWN: - self._push.update_workers_status(False) - self._synchronizer.sync_all() - self._synchronizer.start_periodic_fetching() - _LOGGER.info('streaming temporarily down. starting periodic fetching') - self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.SYNC_MODE_UPDATE, SSESyncMode.POLLING.value, get_current_epoch_time_ms())) - elif status == Status.PUSH_RETRYABLE_ERROR: - self._push.update_workers_status(False) - self._push.stop(True) - self._synchronizer.sync_all() - self._synchronizer.start_periodic_fetching() + try: + if status == Status.PUSH_SUBSYSTEM_UP: + self._synchronizer.stop_periodic_fetching() + self._synchronizer.sync_all() + self._push.update_workers_status(True) + self._backoff.reset() + _LOGGER.info('streaming up and running. disabling periodic fetching.') + self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.SYNC_MODE_UPDATE, SSESyncMode.STREAMING.value, get_current_epoch_time_ms())) + elif status == Status.PUSH_SUBSYSTEM_DOWN: + self._push.update_workers_status(False) + self._synchronizer.sync_all() + self._synchronizer.start_periodic_fetching() + _LOGGER.info('streaming temporarily down. starting periodic fetching') + self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.SYNC_MODE_UPDATE, SSESyncMode.POLLING.value, get_current_epoch_time_ms())) + elif status == Status.PUSH_RETRYABLE_ERROR: + self._push.update_workers_status(False) + self._push.stop(True) + self._synchronizer.sync_all() + self._synchronizer.start_periodic_fetching() + how_long = self._backoff.get() + _LOGGER.info('error in streaming. restarting flow in %d seconds', how_long) + if self._stop_event.wait(how_long): + return # manager stopped while waiting: don't restart streaming + self._push.start() + elif status == Status.PUSH_NONRETRYABLE_ERROR: + self._push.update_workers_status(False) + self._push.stop(False) + self._synchronizer.sync_all() + self._synchronizer.start_periodic_fetching() + _LOGGER.info('non-recoverable error in streaming. switching to polling.') + self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.SYNC_MODE_UPDATE, SSESyncMode.POLLING.value, get_current_epoch_time_ms())) + return + except Exception: # pylint:disable=broad-except + # Keep this thread alive: if it dies, no further streaming status change is + # handled and the SDK can be left without streaming and without polling. + _LOGGER.error('unexpected error handling streaming status %s. ' + 'falling back to periodic fetching.', status) + _LOGGER.debug('Exception information: ', exc_info=True) + self._fall_back_to_polling() + if status == Status.PUSH_NONRETRYABLE_ERROR: + # streaming was being disabled for good: stay in polling mode. + return + + # A local error has no streaming error code, so it is handled as retryable: + # restart the streaming flow with backoff. how_long = self._backoff.get() - _LOGGER.info('error in streaming. restarting flow in %d seconds', how_long) - time.sleep(how_long) - self._push.start() - elif status == Status.PUSH_NONRETRYABLE_ERROR: - self._push.update_workers_status(False) - self._push.stop(False) - self._synchronizer.sync_all() - self._synchronizer.start_periodic_fetching() - _LOGGER.info('non-recoverable error in streaming. switching to polling.') - self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.SYNC_MODE_UPDATE, SSESyncMode.POLLING.value, get_current_epoch_time_ms())) - return + _LOGGER.info('retrying streaming in %d seconds', how_long) + if self._stop_event.wait(how_long): + return # manager stopped while waiting: don't restart streaming + self._queue.put(Status.PUSH_RETRYABLE_ERROR) + + def _fall_back_to_polling(self): + """Start periodic fetching after an unexpected error in the streaming status handler.""" + try: + self._synchronizer.start_periodic_fetching() + except Exception: # pylint:disable=broad-except + _LOGGER.error('could not start periodic fetching.') + _LOGGER.debug('Exception information: ', exc_info=True) class ManagerAsync(object): # pylint:disable=too-many-instance-attributes @@ -220,36 +249,68 @@ async def _streaming_feedback_handler(self): status = await self._queue.get() if status == self._CENTINEL_EVENT: continue - if status == Status.PUSH_SUBSYSTEM_UP: - await self._synchronizer.stop_periodic_fetching() - await self._synchronizer.sync_all() - await self._push.update_workers_status(True) - self._backoff.reset() - _LOGGER.info('streaming up and running. disabling periodic fetching.') - await self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.SYNC_MODE_UPDATE, SSESyncMode.STREAMING.value, get_current_epoch_time_ms())) - elif status == Status.PUSH_SUBSYSTEM_DOWN: - await self._push.update_workers_status(False) - await self._synchronizer.sync_all() - self._synchronizer.start_periodic_fetching() - _LOGGER.info('streaming temporarily down. starting periodic fetching') - await self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.SYNC_MODE_UPDATE, SSESyncMode.POLLING.value, get_current_epoch_time_ms())) - elif status == Status.PUSH_RETRYABLE_ERROR: - await self._push.update_workers_status(False) - await self._push.stop(True) - await self._synchronizer.sync_all() - self._synchronizer.start_periodic_fetching() + try: + if status == Status.PUSH_SUBSYSTEM_UP: + await self._synchronizer.stop_periodic_fetching() + await self._synchronizer.sync_all() + await self._push.update_workers_status(True) + self._backoff.reset() + _LOGGER.info('streaming up and running. disabling periodic fetching.') + await self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.SYNC_MODE_UPDATE, SSESyncMode.STREAMING.value, get_current_epoch_time_ms())) + elif status == Status.PUSH_SUBSYSTEM_DOWN: + await self._push.update_workers_status(False) + await self._synchronizer.sync_all() + self._synchronizer.start_periodic_fetching() + _LOGGER.info('streaming temporarily down. starting periodic fetching') + await self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.SYNC_MODE_UPDATE, SSESyncMode.POLLING.value, get_current_epoch_time_ms())) + elif status == Status.PUSH_RETRYABLE_ERROR: + await self._push.update_workers_status(False) + await self._push.stop(True) + await self._synchronizer.sync_all() + self._synchronizer.start_periodic_fetching() + how_long = self._backoff.get() + _LOGGER.info('error in streaming. restarting flow in %d seconds', how_long) + await asyncio.sleep(how_long) + if not self._push_status_handler_active: + return # manager stopped while waiting: don't restart streaming + self._push.start() + elif status == Status.PUSH_NONRETRYABLE_ERROR: + await self._push.update_workers_status(False) + await self._push.stop(False) + await self._synchronizer.sync_all() + self._synchronizer.start_periodic_fetching() + _LOGGER.info('non-recoverable error in streaming. switching to polling.') + await self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.SYNC_MODE_UPDATE, SSESyncMode.POLLING.value, get_current_epoch_time_ms())) + return + except asyncio.CancelledError: # subclass of Exception in python 3.7 + raise + except Exception: # pylint:disable=broad-except + # Keep this task alive: if it ends, no further streaming status change is + # handled and the SDK can be left without streaming and without polling. + _LOGGER.error('unexpected error handling streaming status %s. ' + 'falling back to periodic fetching.', status) + _LOGGER.debug('Exception information: ', exc_info=True) + self._fall_back_to_polling() + if status == Status.PUSH_NONRETRYABLE_ERROR: + # streaming was being disabled for good: stay in polling mode. + return + + # A local error has no streaming error code, so it is handled as retryable: + # restart the streaming flow with backoff. how_long = self._backoff.get() - _LOGGER.info('error in streaming. restarting flow in %d seconds', how_long) + _LOGGER.info('retrying streaming in %d seconds', how_long) await asyncio.sleep(how_long) - self._push.start() - elif status == Status.PUSH_NONRETRYABLE_ERROR: - await self._push.update_workers_status(False) - await self._push.stop(False) - await self._synchronizer.sync_all() - self._synchronizer.start_periodic_fetching() - _LOGGER.info('non-recoverable error in streaming. switching to polling.') - await self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.SYNC_MODE_UPDATE, SSESyncMode.POLLING.value, get_current_epoch_time_ms())) - return + if not self._push_status_handler_active: + return # manager stopped while waiting: don't restart streaming + await self._queue.put(Status.PUSH_RETRYABLE_ERROR) + + def _fall_back_to_polling(self): + """Start periodic fetching after an unexpected error in the streaming status handler.""" + try: + self._synchronizer.start_periodic_fetching() + except Exception: # pylint:disable=broad-except + _LOGGER.error('could not start periodic fetching.') + _LOGGER.debug('Exception information: ', exc_info=True) class RedisManagerBase(object): # pylint:disable=too-many-instance-attributes diff --git a/splitio/version.py b/splitio/version.py index 6d6c1900..26dfc4df 100644 --- a/splitio/version.py +++ b/splitio/version.py @@ -1 +1 @@ -__version__ = '10.7.1rc1' \ No newline at end of file +__version__ = '10.7.1rc1' diff --git a/tests/api/test_httpclient.py b/tests/api/test_httpclient.py index a9713649..5d971ae7 100644 --- a/tests/api/test_httpclient.py +++ b/tests/api/test_httpclient.py @@ -580,6 +580,14 @@ async def __aenter__(self): class HttpClientAsyncTests(object): """Http Client test cases.""" + @pytest.mark.asyncio + async def test_no_hidden_retry(self): + """Test aiohttp doesn't re-send a request on a dropped connection: SDK backoff retries it.""" + httpclient = client.HttpClientAsync() + if hasattr(httpclient._session, '_retry_connection'): + assert httpclient._session._retry_connection is False + await httpclient.close_session() + @pytest.mark.asyncio async def test_get(self, mocker): """Test HTTP GET verb requests.""" diff --git a/tests/helpers/mockserver.py b/tests/helpers/mockserver.py index 8d41cfd2..f243e687 100644 --- a/tests/helpers/mockserver.py +++ b/tests/helpers/mockserver.py @@ -19,11 +19,17 @@ class SSEMockServer(object): GRACEFUL_REQUEST_END = 'REQ-END' VIOLENT_REQUEST_END = 'REQ-KILL' - def __init__(self, req_queue=None): - """Consruct a mock server.""" + def __init__(self, req_queue=None, chunked=True): + """ + Consruct a mock server. + + :param chunked: if False, the response body is delimited by the connection close + (no Transfer-Encoding nor Content-Length headers), instead of chunked. + """ self._queue = queue.Queue() self._server = HTTPServer(('localhost', 0), - lambda *xs: SSEHandler(self._queue, *xs, req_queue=req_queue)) + lambda *xs: SSEHandler(self._queue, *xs, req_queue=req_queue, + chunked=chunked)) self._server_thread = threading.Thread(target=self._blocking_run, daemon=True) self._done_event = threading.Event() @@ -60,14 +66,16 @@ def __init__(self, event_queue, *args, **kwargs): """Construct a handler.""" self._queue = event_queue self._req_queue = kwargs.get('req_queue') + self._chunked = kwargs.get('chunked', True) BaseHTTPRequestHandler.__init__(self, *args) def do_GET(self): #pylint:disable=invalid-name """Respond to a GET request.""" self.send_response(200) self.send_header("Content-type", "text/event-stream") - self.send_header("Transfer-Encoding", "chunked") - self.send_header("Connection", "keep-alive") + if self._chunked: + self.send_header("Transfer-Encoding", "chunked") + self.send_header("Connection", "keep-alive") self.end_headers() if self._req_queue is not None: @@ -76,7 +84,7 @@ def do_GET(self): #pylint:disable=invalid-name def write_chunk(chunk): """Write an event/chunk.""" - tosend = '%X\r\n%s\r\n'%(len(chunk), chunk) + tosend = '%X\r\n%s\r\n'%(len(chunk), chunk) if self._chunked else chunk self.wfile.write(tosend.encode('utf-8')) while True: @@ -94,7 +102,8 @@ def write_chunk(chunk): if chunk != '': write_chunk(chunk + '\r\n') - self.wfile.write('0\r\n\r\n'.encode('utf-8')) + if self._chunked: + self.wfile.write('0\r\n\r\n'.encode('utf-8')) class SplitMockServer(object): diff --git a/tests/integration/test_streaming_e2e.py b/tests/integration/test_streaming_e2e.py index 8405f2bb..30d14373 100644 --- a/tests/integration/test_streaming_e2e.py +++ b/tests/integration/test_streaming_e2e.py @@ -1170,16 +1170,18 @@ def test_ably_errors_handling(self): sse_server.publish(make_ably_error_event(40145, 401)) sse_server.publish(sse_server.GRACEFUL_REQUEST_END) - time.sleep(3) + # Falls back to polling while waiting for the retry (1st backoff: 1 second) + time.sleep(0.5) assert task.running() - assert factory.client().get_treatment('maldo', 'split1') == 'off' - # Re-publish initial events so that the retry succeeds + # The retry reconnects: streaming is up once the SSE connection opens, before any event sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2)) time.sleep(3) assert not task.running() + # The change was fetched when falling back to polling or when streaming reconnected + assert factory.client().get_treatment('maldo', 'split1') == 'off' # Assert streaming is working properly split_changes[2] = {'ff': { @@ -2488,17 +2490,18 @@ async def test_ably_errors_handling(self): sse_server.publish(make_ably_error_event(40145, 401)) sse_server.publish(sse_server.GRACEFUL_REQUEST_END) - await asyncio.sleep(3) - + # Falls back to polling while waiting for the retry (1st backoff: 1 second) + await asyncio.sleep(0.5) assert task.running() - assert await factory.client().get_treatment('maldo', 'split1') == 'off' - # Re-publish initial events so that the retry succeeds + # The retry reconnects: streaming is up once the SSE connection opens, before any event sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2)) await asyncio.sleep(3) assert not task.running() + # The change was fetched when falling back to polling or when streaming reconnected + assert await factory.client().get_treatment('maldo', 'split1') == 'off' # Assert streaming is working properly split_changes[2] = {'ff': { diff --git a/tests/models/test_token.py b/tests/models/test_token.py index 35444f97..8e89d618 100644 --- a/tests/models/test_token.py +++ b/tests/models/test_token.py @@ -47,3 +47,12 @@ def test_from_raw(self): assert parsed.channels['NzM2MDI5Mzc0_MTgyNTg1MTgwNg==_splits'] == ['subscribe'] assert parsed.channels['control_pri'] == ['subscribe', 'channel-metadata:publishers'] assert parsed.channels['control_sec'] == ['subscribe', 'channel-metadata:publishers'] + + def test_from_raw_invalid_token(self): + """Test a token that cannot be decoded raises, so that the caller retries.""" + for raw_token in ['not-a-valid-jwt', 'not.a-jwt', 'a.%s.c' % 'eyJleHAiOjF9']: # last: missing claims + try: + token.from_raw({'pushEnabled': True, 'token': raw_token}) + assert False, 'ValueError expected for %s' % raw_token + except ValueError: + pass diff --git a/tests/push/test_manager.py b/tests/push/test_manager.py index 92b8e2d8..8571d919 100644 --- a/tests/push/test_manager.py +++ b/tests/push/test_manager.py @@ -157,6 +157,125 @@ def test_auth_apiexception(self, mocker): assert timer_mock.mock_calls == [mocker.call(0, Any())] assert sse_mock.mock_calls == [] + def _build_manager(self, mocker, api_mock, sse_mock, timer_mock, feedback_loop): + sse_constructor_mock = mocker.Mock() + sse_constructor_mock.return_value = sse_mock + mocker.patch('splitio.push.manager.Timer', new=timer_mock) + mocker.patch('splitio.push.manager.SplitSSEClient', new=sse_constructor_mock) + telemetry_storage = InMemoryTelemetryStorage() + telemetry_producer = TelemetryStorageProducer(telemetry_storage) + telemetry_runtime_producer = telemetry_producer.get_telemetry_runtime_producer() + return PushManager(api_mock, mocker.Mock(), feedback_loop, mocker.Mock(), telemetry_runtime_producer) + + def test_auth_unexpected_exception(self, mocker): + """Test a non-API error during auth (e.g. non-JSON 200 response) is reported as retryable.""" + api_mock = mocker.Mock() + api_mock.authenticate.side_effect = ValueError('Expecting value: line 1 column 1 (char 0)') + sse_mock = mocker.Mock(spec=SplitSSEClient) + timer_mock = mocker.Mock() + feedback_loop = Queue() + manager = self._build_manager(mocker, api_mock, sse_mock, timer_mock, feedback_loop) + + manager.start() + assert feedback_loop.get(timeout=1) == Status.PUSH_RETRYABLE_ERROR + assert sse_mock.mock_calls == [] + assert not manager._running + + def test_stop_while_authenticating(self, mocker): + """Test the SSE connection is not opened if the manager is stopped during auth.""" + feedback_loop = Queue() + sse_mock = mocker.Mock(spec=SplitSSEClient) + api_mock = mocker.Mock() + manager = self._build_manager(mocker, api_mock, sse_mock, mocker.Mock(), feedback_loop) + def authenticate(): + manager.stop() # destroyed while waiting for the auth response + return Token(True, 'abc', {}, 2000000, 1000000) + api_mock.authenticate.side_effect = authenticate + + manager.start() + assert sse_mock.start.mock_calls == [] + assert feedback_loop.empty() + assert not manager._running + + def test_stop_while_connecting(self, mocker): + """Test the SSE connection is closed if the manager is stopped while connecting.""" + feedback_loop = Queue() + sse_mock = mocker.Mock(spec=SplitSSEClient) + api_mock = mocker.Mock() + api_mock.authenticate.return_value = Token(True, 'abc', {}, 2000000, 1000000) + timer_mock = mocker.Mock() + manager = self._build_manager(mocker, api_mock, sse_mock, timer_mock, feedback_loop) + def start(token): + manager.stop() # destroyed while opening the SSE connection + return True + sse_mock.start.side_effect = start + + manager.start() + assert sse_mock.stop.mock_calls == [mocker.call()] + assert timer_mock.mock_calls == [mocker.call(0, Any())] # no token refresh scheduled + assert feedback_loop.empty() + assert not manager._running + + # It can be started again + sse_mock.start.side_effect = None + sse_mock.start.return_value = True + manager.start() + assert manager._running + + def test_sse_start_unexpected_exception(self, mocker): + """Test an error raised by the sse client when connecting is reported as retryable.""" + api_mock = mocker.Mock() + api_mock.authenticate.return_value = Token(True, 'abc', {}, 2000000, 1000000) + sse_mock = mocker.Mock(spec=SplitSSEClient) + sse_mock.start.side_effect = Exception('SseClient already started.') + timer_mock = mocker.Mock() + feedback_loop = Queue() + manager = self._build_manager(mocker, api_mock, sse_mock, timer_mock, feedback_loop) + + manager.start() + assert feedback_loop.get(timeout=1) == Status.PUSH_RETRYABLE_ERROR + assert timer_mock.mock_calls == [mocker.call(0, Any())] # no token refresh scheduled + assert not manager._running + + def test_token_refresh_unexpected_exception(self, mocker): + """Test a failed token refresh reports a retryable error instead of killing the thread.""" + api_mock = mocker.Mock() + api_mock.authenticate.side_effect = [ + Token(True, 'abc', {}, 2000000, 1000000), + KeyError('x-ably-capability'), + ] + sse_mock = mocker.Mock(spec=SplitSSEClient) + sse_mock.start.return_value = True + timer_mock = mocker.Mock() + feedback_loop = Queue() + manager = self._build_manager(mocker, api_mock, sse_mock, timer_mock, feedback_loop) + + manager.start() + assert manager._running + + # Run the refresh in its own thread, as Timer would. + refresh = Thread(target=manager._token_refresh) + refresh.start() + refresh.join(1) + assert not refresh.is_alive() + assert feedback_loop.get(timeout=1) == Status.PUSH_RETRYABLE_ERROR + assert not manager._running + + def test_token_refresh_stop_exception(self, mocker): + """Test an error while closing the connection during a token refresh is reported.""" + api_mock = mocker.Mock() + api_mock.authenticate.return_value = Token(True, 'abc', {}, 2000000, 1000000) + sse_mock = mocker.Mock(spec=SplitSSEClient) + sse_mock.start.return_value = True + sse_mock.stop.side_effect = OSError('Transport endpoint is not connected') + timer_mock = mocker.Mock() + feedback_loop = Queue() + manager = self._build_manager(mocker, api_mock, sse_mock, timer_mock, feedback_loop) + + manager.start() + manager._token_refresh() + assert feedback_loop.get(timeout=1) == Status.PUSH_RETRYABLE_ERROR + def test_split_change(self, mocker): """Test update-type messages are properly forwarded to the processor.""" sse_event = SSEEvent('1', EventType.MESSAGE, '', '{}') @@ -388,6 +507,99 @@ async def test_auth_apiexception(self, mocker): await manager.stop(True) assert not manager._running + @pytest.mark.asyncio + async def test_auth_unexpected_exception(self, mocker): + """Test a non-API error during auth (e.g. non-JSON 200 response) is reported as retryable.""" + api_mock = mocker.Mock() + async def authenticate(): + raise ValueError('Expecting value: line 1 column 1 (char 0)') + api_mock.authenticate.side_effect = authenticate + + sse_mock = mocker.Mock(spec=SplitSSEClientAsync) + feedback_loop = asyncio.Queue() + telemetry_storage = await InMemoryTelemetryStorageAsync.create() + telemetry_producer = TelemetryStorageProducerAsync(telemetry_storage) + telemetry_runtime_producer = telemetry_producer.get_telemetry_runtime_producer() + manager = PushManagerAsync(api_mock, mocker.Mock(), feedback_loop, mocker.Mock(), telemetry_runtime_producer) + manager._sse_client = sse_mock + + manager.start() + assert await asyncio.wait_for(feedback_loop.get(), 1) == Status.PUSH_RETRYABLE_ERROR + assert sse_mock.mock_calls == [] + assert not manager._running + + @pytest.mark.asyncio + async def test_sse_start_unexpected_exception(self, mocker): + """Test an error raised by the sse client is reported as retryable.""" + api_mock = mocker.Mock() + async def authenticate(): + return Token(True, 'abc', {}, 2000000, 1000000) + api_mock.authenticate.side_effect = authenticate + + sse_mock = mocker.Mock(spec=SplitSSEClientAsync) + sse_mock.start.side_effect = Exception('sse client error') + feedback_loop = asyncio.Queue() + telemetry_storage = await InMemoryTelemetryStorageAsync.create() + telemetry_producer = TelemetryStorageProducerAsync(telemetry_storage) + telemetry_runtime_producer = telemetry_producer.get_telemetry_runtime_producer() + manager = PushManagerAsync(api_mock, mocker.Mock(), feedback_loop, mocker.Mock(), telemetry_runtime_producer) + manager._sse_client = sse_mock + + manager.start() + assert await asyncio.wait_for(feedback_loop.get(), 1) == Status.PUSH_RETRYABLE_ERROR + assert not manager._running + + @pytest.mark.asyncio + async def test_token_refresh_reconnects(self, mocker): + """Test a token refresh is not cancelled by the cleanup of the connection it closes.""" + api_mock = mocker.Mock() + auth_calls = [] + async def authenticate(): + auth_calls.append(1) + return Token(True, 'abc', {}, 2000000, 1000000) + api_mock.authenticate.side_effect = authenticate + + class FakeSSEClient(object): + """Ends the event stream on stop() and waits for it, without masking cancellation.""" + def __init__(self): + self.starts = 0 + def start(self, token): + self.starts += 1 + self._shutdown = asyncio.Event() + self._ended = asyncio.Event() + async def events(): + try: + yield SSEEvent('1', EventType.MESSAGE, None, None) + await self._shutdown.wait() + finally: + self._ended.set() + return events() + async def stop(self): + self._shutdown.set() + await self._ended.wait() + + feedback_loop = asyncio.Queue() + telemetry_storage = await InMemoryTelemetryStorageAsync.create() + telemetry_producer = TelemetryStorageProducerAsync(telemetry_storage) + telemetry_runtime_producer = telemetry_producer.get_telemetry_runtime_producer() + manager = PushManagerAsync(api_mock, mocker.Mock(), feedback_loop, mocker.Mock(), telemetry_runtime_producer) + processor = mocker.Mock() + async def update_workers_status(enabled): + pass + processor.update_workers_status = update_workers_status + manager._processor = processor + manager._get_time_period = lambda token: 0.1 + manager._sse_client = FakeSSEClient() + + manager.start() + await asyncio.sleep(0.5) + assert len(auth_calls) >= 3 # initial connection + refreshes + assert manager._sse_client.starts == len(auth_calls) + assert manager._running + + await manager.stop(True) + assert not manager._running + @pytest.mark.asyncio async def test_split_change(self, mocker): """Test update-type messages are properly forwarded to the processor.""" diff --git a/tests/push/test_splitsse.py b/tests/push/test_splitsse.py index c461f9fe..5940d66b 100644 --- a/tests/push/test_splitsse.py +++ b/tests/push/test_splitsse.py @@ -104,8 +104,12 @@ def on_disconnect(): token = Token(True, 'some', {'chan1': ['subscribe'], 'chan2': ['subscribe', 'channel-metadata:publishers']}, 1, 2) - server.publish({'event': 'error'}) # send an error event early to unblock start - assert not client.start(token) + # Connection is open before any event is read; the error event is then passed to the handler + assert client.start(token) + server.publish({'event': 'error', 'data': 'a'}) + time.sleep(1) + assert events == [SSEEvent(None, 'error', None, 'a')] + client.stop(True) request = request_queue.get(1) assert request.path == '/event-stream?v=1.1&accessToken=some&channels=chan1,[?occupancy=metrics.publishers]chan2' @@ -191,9 +195,15 @@ async def test_split_sse_error(self): 1, 2) events_source = client.start(token) - server.publish({'event': 'error'}) # send an error event early to unblock start + server.publish({'event': 'error', 'data': 'a'}) + # Connection is open before any event is read; the error event is then yielded to be handled + first_event = await events_source.__anext__() + assert first_event == SSEEvent(None, None, None, None) + error_event = await events_source.__anext__() + assert error_event.event == SSE_EVENT_ERROR + server.publish(SSEMockServer.VIOLENT_REQUEST_END) with pytest.raises(StopAsyncIteration): await events_source.__anext__() assert client.status == SplitSSEClient._Status.IDLE @@ -206,5 +216,4 @@ async def test_split_sse_error(self): assert request.headers['SplitSDKMachineName'] == 'some' assert request.headers['SplitSDKClientKey'] == 'abcd' - server.publish(SSEMockServer.VIOLENT_REQUEST_END) server.stop() diff --git a/tests/push/test_sse.py b/tests/push/test_sse.py index 5aa26bb3..332c9487 100644 --- a/tests/push/test_sse.py +++ b/tests/push/test_sse.py @@ -12,9 +12,10 @@ class SSEClientTests(object): """SSEClient test cases.""" - def test_sse_client_disconnects(self): - """Test correct initialization. Client ends the connection.""" - server = SSEMockServer() + @pytest.mark.parametrize('chunked', [True, False]) + def test_sse_client_disconnects(self, chunked): + """Test correct initialization. Client ends the connection, chunked or close-delimited.""" + server = SSEMockServer(chunked=chunked) server.start() events = [] @@ -42,6 +43,7 @@ def runner(): time.sleep(1) assert events == [ + SSEEvent(None, None, None, None), # connection open SSEEvent('1', None, None, None), SSEEvent('2', 'message', None, 'abc'), SSEEvent('3', 'message', None, 'def'), @@ -81,6 +83,7 @@ def runner(): time.sleep(1) assert events == [ + SSEEvent(None, None, None, None), # connection open SSEEvent('1', None, None, None), SSEEvent('2', 'message', None, 'abc'), SSEEvent('3', 'message', None, 'def'), @@ -118,6 +121,7 @@ def runner(): time.sleep(1) assert events == [ + SSEEvent(None, None, None, None), # connection open SSEEvent('1', None, None, None), SSEEvent('2', 'message', None, 'abc'), SSEEvent('3', 'message', None, 'def'), @@ -407,6 +411,14 @@ def close(self): class SSEClientAsyncTests(object): """SSEClient test cases.""" + @pytest.mark.asyncio + async def test_no_hidden_retry(self): + """Test aiohttp doesn't re-send the request on a dropped connection: SDK backoff retries it.""" + client = SSEClientAsync() + if hasattr(client._sess, '_retry_connection'): + assert client._sess._retry_connection is False + await client.close_session() + @pytest.mark.asyncio async def test_sse_client_disconnects(self): """Test correct initialization. Client ends the connection.""" @@ -420,6 +432,8 @@ async def test_sse_client_disconnects(self): server.publish({'id': '3', 'event': 'message', 'data': 'def'}) server.publish({'id': '4', 'event': 'message', 'data': 'ghi'}) + open_event = await sse_events_loop.__anext__() + assert open_event == SSEEvent(None, None, None, None) event1 = await sse_events_loop.__anext__() event2 = await sse_events_loop.__anext__() event3 = await sse_events_loop.__anext__() @@ -453,6 +467,8 @@ async def test_sse_server_disconnects(self): server.publish({'id': '3', 'event': 'message', 'data': 'def'}) server.publish({'id': '4', 'event': 'message', 'data': 'ghi'}) + open_event = await sse_events_loop.__anext__() + assert open_event == SSEEvent(None, None, None, None) event1 = await sse_events_loop.__anext__() event2 = await sse_events_loop.__anext__() event3 = await sse_events_loop.__anext__() @@ -488,6 +504,8 @@ async def test_sse_server_disconnects_abruptly(self): server.publish({'id': '3', 'event': 'message', 'data': 'def'}) server.publish({'id': '4', 'event': 'message', 'data': 'ghi'}) + open_event = await sse_events_loop.__anext__() + assert open_event == SSEEvent(None, None, None, None) event1 = await sse_events_loop.__anext__() event2 = await sse_events_loop.__anext__() event3 = await sse_events_loop.__anext__() diff --git a/tests/sync/test_manager.py b/tests/sync/test_manager.py index efc52f1e..18932324 100644 --- a/tests/sync/test_manager.py +++ b/tests/sync/test_manager.py @@ -84,6 +84,7 @@ def test_telemetry(self, mocker): telemetry_producer = TelemetryStorageProducer(telemetry_storage) telemetry_runtime_producer = telemetry_producer.get_telemetry_runtime_producer() manager = Manager(splits_ready_event, synchronizer, mocker.Mock(), True, SdkMetadata('1.0', 'some', '1.2.3.4'), telemetry_runtime_producer) + manager._push = mocker.Mock() # don't open a real streaming connection try: manager.start() except: @@ -98,6 +99,94 @@ def test_telemetry(self, mocker): assert(telemetry_storage._streaming_events._streaming_events[len(telemetry_storage._streaming_events._streaming_events)-1]._type == StreamingEventTypes.SYNC_MODE_UPDATE.value) assert(telemetry_storage._streaming_events._streaming_events[len(telemetry_storage._streaming_events._streaming_events)-1]._data == SSESyncMode.POLLING.value) + def _wait_for(self, condition, timeout=2): + deadline = time.time() + timeout + while not condition() and time.time() < deadline: + time.sleep(0.01) + return condition() + + def _build_streaming_manager(self, mocker): + synchronizer = mocker.Mock(spec=Synchronizer) + manager = Manager(threading.Event(), synchronizer, mocker.Mock(), True, + SdkMetadata('1.0', 'some', '1.2.3.4'), mocker.Mock()) + manager._backoff = mocker.Mock() + manager._backoff.get.return_value = 0 + manager._push = mocker.Mock() + return manager, synchronizer, manager._push + + def _stop_handler(self, manager): + manager._push_status_handler_active = False + manager._queue.put(manager._CENTINEL_EVENT) + manager._push_status_handler.join(1) + assert not manager._push_status_handler.is_alive() + + def test_streaming_handler_survives_unexpected_exception(self, mocker): + """Test the status handler falls back to polling, retries streaming and keeps running.""" + manager, synchronizer, push_mock = self._build_streaming_manager(mocker) + worker_calls = [] + def update_workers_status(enabled): + worker_calls.append(enabled) + if len(worker_calls) == 1: + raise RuntimeError("can't start new thread") + push_mock.update_workers_status.side_effect = update_workers_status + manager._push_status_handler.start() + + # PUSH_SUBSYSTEM_UP stops polling and then fails enabling workers: polling must restart + # and the streaming flow must be retried (as a retryable error). + manager._queue.put(Status.PUSH_SUBSYSTEM_UP) + assert self._wait_for(lambda: len(push_mock.start.mock_calls) == 1) + assert len(synchronizer.stop_periodic_fetching.mock_calls) == 1 + assert len(synchronizer.start_periodic_fetching.mock_calls) == 2 # fallback + retry flow + assert push_mock.stop.mock_calls == [mocker.call(True)] + assert manager._push_status_handler.is_alive() + + # The handler still processes later status changes. + manager._queue.put(Status.PUSH_SUBSYSTEM_DOWN) + assert self._wait_for(lambda: len(synchronizer.start_periodic_fetching.mock_calls) == 3) + assert manager._push_status_handler.is_alive() + self._stop_handler(manager) + + def test_streaming_handler_retryable_error_restart_fails(self, mocker): + """Test streaming is retried when restarting it raises after a retryable error.""" + manager, synchronizer, push_mock = self._build_streaming_manager(mocker) + push_mock.start.side_effect = [Exception('SseClient already started.'), None] + manager._push_status_handler.start() + + manager._queue.put(Status.PUSH_RETRYABLE_ERROR) + assert self._wait_for(lambda: len(push_mock.start.mock_calls) == 2) + assert len(synchronizer.start_periodic_fetching.mock_calls) == 3 # flow, fallback, flow + assert manager._push_status_handler.is_alive() + time.sleep(0.1) + assert len(push_mock.start.mock_calls) == 2 # no more retries once it succeeds + self._stop_handler(manager) + + def test_streaming_handler_nonretryable_error_fails(self, mocker): + """Test an error while disabling streaming leaves polling on and streaming off.""" + manager, synchronizer, push_mock = self._build_streaming_manager(mocker) + push_mock.stop.side_effect = OSError('Transport endpoint is not connected') + manager._push_status_handler.start() + + manager._queue.put(Status.PUSH_NONRETRYABLE_ERROR) + manager._push_status_handler.join(1) + assert not manager._push_status_handler.is_alive() + assert len(synchronizer.start_periodic_fetching.mock_calls) == 1 + assert push_mock.start.mock_calls == [] + + def test_stop_while_backing_off(self, mocker): + """Test streaming is not restarted when the manager is stopped during the retry backoff.""" + manager, synchronizer, push_mock = self._build_streaming_manager(mocker) + manager._backoff.get.return_value = 30 + manager._push_status_handler.start() + + manager._queue.put(Status.PUSH_RETRYABLE_ERROR) + assert self._wait_for(lambda: len(synchronizer.start_periodic_fetching.mock_calls) == 1) + start = time.time() + manager.stop(True) + manager._push_status_handler.join(1) + assert not manager._push_status_handler.is_alive() + assert time.time() - start < 1 # the backoff wait was interrupted + assert push_mock.start.mock_calls == [] + class SyncManagerAsyncTests(object): """Synchronizer Manager tests.""" @@ -185,6 +274,82 @@ async def stop_periodic_fetching(): assert(telemetry_storage._streaming_events._streaming_events[len(telemetry_storage._streaming_events._streaming_events)-1]._type == StreamingEventTypes.SYNC_MODE_UPDATE.value) assert(telemetry_storage._streaming_events._streaming_events[len(telemetry_storage._streaming_events._streaming_events)-1]._data == SSESyncMode.POLLING.value) + @pytest.mark.asyncio + async def test_streaming_handler_survives_unexpected_exception(self, mocker): + """Test the status handler falls back to polling, retries streaming and keeps running.""" + synchronizer = mocker.Mock(spec=SynchronizerAsync) + calls = {'sync_all': 0, 'stop_periodic_fetching': 0} + async def sync_all(retry=1): + calls['sync_all'] += 1 + synchronizer.sync_all = sync_all + async def stop_periodic_fetching(): + calls['stop_periodic_fetching'] += 1 + synchronizer.stop_periodic_fetching = stop_periodic_fetching + + telemetry_storage = await InMemoryTelemetryStorageAsync.create() + telemetry_producer = TelemetryStorageProducerAsync(telemetry_storage) + manager = ManagerAsync(synchronizer, mocker.Mock(), True, + SdkMetadata('1.0', 'some', '1.2.3.4'), + telemetry_producer.get_telemetry_runtime_producer()) + manager._backoff = mocker.Mock() + manager._backoff.get.return_value = 0 + push_mock = mocker.Mock() + worker_calls = [] + async def update_workers_status(enabled): + worker_calls.append(enabled) + if len(worker_calls) == 1: + raise RuntimeError('worker failure') + push_mock.update_workers_status = update_workers_status + stop_calls = [] + async def stop(blocking=False): + stop_calls.append(blocking) + push_mock.stop = stop + manager._push = push_mock + handler = asyncio.get_running_loop().create_task(manager._streaming_feedback_handler()) + + # PUSH_SUBSYSTEM_UP stops polling and then fails enabling workers: polling must restart + # and the streaming flow must be retried (as a retryable error). + await manager._queue.put(Status.PUSH_SUBSYSTEM_UP) + await asyncio.sleep(0.1) + assert calls['stop_periodic_fetching'] == 1 + assert len(synchronizer.start_periodic_fetching.mock_calls) == 2 # fallback + retry flow + assert stop_calls == [True] + assert len(push_mock.start.mock_calls) == 1 + assert not handler.done() + + # The handler still processes later status changes. + await manager._queue.put(Status.PUSH_SUBSYSTEM_DOWN) + await asyncio.sleep(0.1) + assert len(synchronizer.start_periodic_fetching.mock_calls) == 3 + assert not handler.done() + + manager._push_status_handler_active = False + await manager._queue.put(manager._CENTINEL_EVENT) + await asyncio.wait_for(handler, 1) + + @pytest.mark.asyncio + async def test_stop_while_backing_off(self, mocker): + """Test streaming is not restarted when the manager is stopped during the retry backoff.""" + synchronizer = mocker.Mock(spec=SynchronizerAsync) + async def noop(*_args, **_kwargs): + pass + synchronizer.sync_all = noop + manager = ManagerAsync(synchronizer, mocker.Mock(), True, + SdkMetadata('1.0', 'some', '1.2.3.4'), mocker.Mock()) + manager._backoff = mocker.Mock() + manager._backoff.get.return_value = 0.2 + push_mock = mocker.Mock() + push_mock.update_workers_status = noop + push_mock.stop = noop + manager._push = push_mock + handler = asyncio.get_running_loop().create_task(manager._streaming_feedback_handler()) + + await manager._queue.put(Status.PUSH_RETRYABLE_ERROR) + await asyncio.sleep(0.05) + manager._push_status_handler_active = False # as done by stop() + await asyncio.wait_for(handler, 1) + assert push_mock.start.mock_calls == [] + class RedisSyncManagerTests(object): """Synchronizer Redis Manager tests.""" From 2338e314b4547322f1cd83b0ab185fee12e05a45 Mon Sep 17 00:00:00 2001 From: Emiliano Sanchez Date: Fri, 6 Nov 2026 13:59:35 -0300 Subject: [PATCH 11/16] Fix error handling during token refresh --- CHANGES.txt | 2 +- splitio/push/manager.py | 22 +++++++++++++---- tests/push/test_manager.py | 48 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 6 deletions(-) diff --git a/CHANGES.txt b/CHANGES.txt index be70d303..b37bc4a4 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -5,7 +5,7 @@ - Fixed an issue where the SDK could stop applying feature flag updates when streaming is enabled, serving stale definitions until restart: - Unexpected errors during the streaming authentication or connection (e.g. a non-JSON response or a malformed token) are now handled as retryable errors: the SDK switches to polling and retries streaming with backoff. - Unexpected errors in the streaming status handler no longer stop it; the SDK switches to polling and retries streaming with backoff. - - Fixed the asyncio token refresh being cancelled by the cleanup of the connection it closes, which could leave the SDK without streaming and without polling. + - Fixed the asyncio token refresh being cancelled by the cleanup of the connection it closes, which could leave the SDK without streaming and without polling. Errors during the asyncio token refresh are now handled as retryable errors, as in the sync mode. - Fixed several streaming (SSE) connection issues: - The streaming connection is now considered established once the SSE connection opens, instead of waiting for the first event. Previously, the token refresh and the reconnection after a retryable error waited for an incoming event to resume streaming. - Fixed the SSE connection not being closed on token refresh or SDK destroy when the server response is not chunked, which could block the token refresh. diff --git a/splitio/push/manager.py b/splitio/push/manager.py index e5f8b3d4..840b5867 100644 --- a/splitio/push/manager.py +++ b/splitio/push/manager.py @@ -447,8 +447,17 @@ async def _token_refresh(self, current_token): # otherwise the connection task's cleanup cancels it and the new connection is never # started, leaving the SDK without streaming and without polling. self._token_task = None - await self._stop_current_conn() - self._running_task = asyncio.get_running_loop().create_task(self._trigger_connection_flow()) + try: + await self._stop_current_conn() + self._running_task = asyncio.get_running_loop().create_task( + self._trigger_connection_flow()) + except asyncio.CancelledError: # subclass of Exception in python 3.7 + raise + except Exception: # pylint:disable=broad-except + # If this task ends here, streaming stays stopped and polling is never started. + _LOGGER.error('unexpected error refreshing streaming token.') + _LOGGER.debug('stack trace: ', exc_info=True) + await self._feedback_loop.put(Status.PUSH_RETRYABLE_ERROR) async def _get_auth_token(self): """Get new auth token""" @@ -593,7 +602,10 @@ async def _stop_current_conn(self): await self._processor.update_workers_status(False) self._status_tracker.notify_sse_shutdown_expected() await self._sse_client.stop() - self._running_task.cancel() - await self._running_task - self._running_task = None + task, self._running_task = self._running_task, None + if task is not None: + task.cancel() + # Wait for the connection task to end. gather() keeps its cancellation from being + # raised here (only a cancellation of this coroutine is) + await asyncio.gather(task, return_exceptions=True) _LOGGER.debug("SplitSSE tasks are stopped") diff --git a/tests/push/test_manager.py b/tests/push/test_manager.py index 8571d919..f2cd0988 100644 --- a/tests/push/test_manager.py +++ b/tests/push/test_manager.py @@ -600,6 +600,54 @@ async def update_workers_status(enabled): await manager.stop(True) assert not manager._running + async def _build_refresh_manager(self, mocker, feedback_loop): + async def noop(*_args, **_kwargs): + pass + telemetry_storage = await InMemoryTelemetryStorageAsync.create() + telemetry_producer = TelemetryStorageProducerAsync(telemetry_storage) + manager = PushManagerAsync(mocker.Mock(), mocker.Mock(), feedback_loop, mocker.Mock(), + telemetry_producer.get_telemetry_runtime_producer()) + manager._processor = mocker.Mock() + manager._processor.update_workers_status = noop + manager._sse_client = mocker.Mock() + manager._sse_client.stop = noop + manager._get_time_period = lambda token: 0 + return manager + + @pytest.mark.asyncio + async def test_token_refresh_connection_task_pending(self, mocker): + """Test the refresh reconnects when the connection task is still ending when cancelled.""" + feedback_loop = asyncio.Queue() + manager = await self._build_refresh_manager(mocker, feedback_loop) + async def ending_connection(): # e.g. still running its cleanup + await asyncio.sleep(1) + manager._running_task = asyncio.get_running_loop().create_task(ending_connection()) + await asyncio.sleep(0) + flows = [] + async def connection_flow(): + flows.append(1) + manager._trigger_connection_flow = connection_flow + + refresh = asyncio.get_running_loop().create_task( + manager._token_refresh(Token(True, 'abc', {}, 2000000, 1000000))) + await asyncio.wait_for(refresh, 1) + assert not refresh.cancelled() + await asyncio.sleep(0) + assert flows == [1] # new connection flow started + assert feedback_loop.empty() + + @pytest.mark.asyncio + async def test_token_refresh_stop_exception(self, mocker): + """Test an error while closing the connection during a token refresh is reported.""" + feedback_loop = asyncio.Queue() + manager = await self._build_refresh_manager(mocker, feedback_loop) + async def stop(): + raise OSError('Transport endpoint is not connected') + manager._sse_client.stop = stop + + await manager._token_refresh(Token(True, 'abc', {}, 2000000, 1000000)) + assert await asyncio.wait_for(feedback_loop.get(), 1) == Status.PUSH_RETRYABLE_ERROR + @pytest.mark.asyncio async def test_split_change(self, mocker): """Test update-type messages are properly forwarded to the processor.""" From 05715f7fe8531d45f4acee4a5a23583c280464d3 Mon Sep 17 00:00:00 2001 From: Emiliano Sanchez Date: Fri, 6 Nov 2026 14:42:09 -0300 Subject: [PATCH 12/16] Change to debug why Run Tests step is hanging in latest python --- .../pipelines/pythonclient_hc.yaml | 1 + tests/conftest.py | 148 +++++++++++++----- tests/helpers/proxyserver.py | 40 +++-- 3 files changed, 136 insertions(+), 53 deletions(-) diff --git a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc.yaml b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc.yaml index 4eba66f8..1f86c541 100644 --- a/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc.yaml +++ b/.harness/orgs/PROD/projects/Harness_Split/pipelines/pythonclient_hc.yaml @@ -86,6 +86,7 @@ pipeline: type: Run name: Run Tests identifier: Run_Tests + timeout: 15m spec: shell: Bash command: |- diff --git a/tests/conftest.py b/tests/conftest.py index 77376aa1..63aaf8c4 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,7 +1,11 @@ """Shared pytest fixtures.""" import faulthandler import socket +import sys import threading +import time +import traceback +import weakref import pytest @@ -10,6 +14,55 @@ _FACTORY_CLASSES = (SplitFactoryBase, SplitFactory, SplitFactoryAsync) _MISSING = object() +_BLOCKED_SUFFIX = '.split.io' +_net_violations = [] +_current_test = {'id': None} +_live_factories = weakref.WeakSet() +_real_getaddrinfo = socket.getaddrinfo +_real_thread_init = threading.Thread.__init__ +_real_factory_init = SplitFactory.__init__ + + +def _guarded_getaddrinfo(host, *args, **kwargs): + """Refuse to resolve the Split backend hosts, and remember who tried.""" + name = host.decode() if isinstance(host, bytes) else host + if isinstance(name, str) and name.endswith(_BLOCKED_SUFFIX): + thread = threading.current_thread() + _net_violations.append((getattr(thread, '_created_by_test', None) or _current_test['id'], name, thread.name)) + raise socket.gaierror(socket.EAI_NONAME, 'network access to %s blocked by tests/conftest.py' % name) + return _real_getaddrinfo(host, *args, **kwargs) + + +def _tracking_thread_init(self, *args, **kwargs): + """Remember which test created each thread, to name the culprit of a leaked background client.""" + parent = threading.current_thread() + self._created_by_test = getattr(parent, '_created_by_test', None) or _current_test['id'] + _real_thread_init(self, *args, **kwargs) + + +def _tracking_factory_init(self, *args, **kwargs): + _real_factory_init(self, *args, **kwargs) + _live_factories.add(self) + + +socket.getaddrinfo = _guarded_getaddrinfo +threading.Thread.__init__ = _tracking_thread_init +SplitFactory.__init__ = _tracking_factory_init + + +@pytest.fixture(autouse=True) +def _no_split_network(request): + """Tests must not contact the Split backend (sdk/events/telemetry/auth *.split.io).""" + _current_test['id'] = request.node.nodeid + start = len(_net_violations) + yield + _destroy_leaked_factories() + _current_test['id'] = None + found = _net_violations[start:] + if found: + pytest.fail('test contacted the Split backend (mock the HTTP layer): %s' % sorted( + {'%s from thread %s created in %s' % (host, thr, origin) for origin, host, thr in found}), pytrace=False) + @pytest.fixture(autouse=True) def _restore_factory_ready_property(): @@ -37,46 +90,63 @@ def pytest_sessionfinish(session, exitstatus): timeout). If still alive after 120s, dump every thread's stack to stderr and exit with code 1. The timer is cancelled when the interpreter exits normally. """ + _report_leaked_threads() + # Timers (e.g. the push manager's TokenRefresh) are non-daemon: a leaked one blocks exit until it fires. + for thread in threading.enumerate(): + if isinstance(thread, threading.Timer): + thread.cancel() + threading.Thread(target=_report_blocking_threads, args=(60,), daemon=True, name='exit-watchdog').start() faulthandler.dump_traceback_later(120, exit=True) -_BLOCKED_SUFFIX = '.split.io' -_net_violations = [] -_current_test = {'id': None} -_real_getaddrinfo = socket.getaddrinfo -_real_thread_init = threading.Thread.__init__ - - -def _tracking_thread_init(self, *args, **kwargs): - # remember which test created the thread, to name the real culprit of a leaked background client - parent = threading.current_thread() - self._created_by_test = getattr(parent, '_created_by_test', None) or _current_test['id'] - _real_thread_init(self, *args, **kwargs) - - -threading.Thread.__init__ = _tracking_thread_init - - -def _guarded_getaddrinfo(host, *args, **kwargs): - name = host.decode() if isinstance(host, bytes) else host - if isinstance(name, str) and name.endswith(_BLOCKED_SUFFIX): - _net_violations.append((getattr(threading.current_thread(), '_created_by_test', None) or _current_test['id'], - name, threading.current_thread().name)) - raise socket.gaierror(socket.EAI_NONAME, 'network access to %s blocked by tests/conftest.py' % name) - return _real_getaddrinfo(host, *args, **kwargs) - - -socket.getaddrinfo = _guarded_getaddrinfo - +def _report_blocking_threads(delay): + """ + If the interpreter is still alive `delay` seconds after the session, say what blocks it. -@pytest.fixture(autouse=True) -def _no_split_network(request): - """Tests must not contact the Split backend (sdk/events/telemetry/auth *.split.io).""" - _current_test['id'] = request.node.nodeid - start = len(_net_violations) - yield - _current_test['id'] = None - found = _net_violations[start:] - if found: - pytest.fail('test contacted the Split backend (mock the HTTP layer): %s' % sorted( - {'%s from thread %s created in %s' % (host, thr, origin) for origin, host, thr in found}), pytrace=False) + faulthandler only prints the first 100 threads (all idle daemon workers here), so print the + main thread and every non-worker thread explicitly, with their stacks. + """ + time.sleep(delay) + frames = sys._current_frames() + me = threading.current_thread() + main = threading.main_thread() + others = [t for t in threading.enumerate() + if t is not me and t is not main and not t.name.startswith('pool_worker_')] + lines = ['\nPROCESS DID NOT EXIT %ds after the session.' % delay] + lines.append('main thread alive: %s' % main.is_alive()) + for thread in [main] + others[:40]: + lines.append(' %s (%s, daemon=%s)' % (thread.name, type(thread).__name__, thread.daemon)) + if thread.ident in frames: + lines.extend(' ' + l for l in ''.join(traceback.format_stack(frames[thread.ident])).splitlines()) + lines.append('non-daemon threads: %s' % [t.name for t in threading.enumerate() if not t.daemon]) + sys.stderr.write('\n'.join(lines) + '\n') + sys.stderr.flush() + + +def _report_leaked_threads(): + """Print the SDK threads still running after the last test, grouped by the test that started them.""" + leaked = {} + for thread in threading.enumerate(): + if thread is threading.main_thread() or thread.name.startswith('pool_worker_'): + continue + if thread.name == 'exit-watchdog': + continue + leaked.setdefault(getattr(thread, '_created_by_test', None), []).append(thread.name) + if leaked: + sys.stderr.write('\nTHREADS STILL ALIVE AFTER THE SESSION (factory/client not destroyed?):\n') + for test, names in sorted(leaked.items(), key=lambda kv: str(kv[0])): + sys.stderr.write(' %s\n %s\n' % (test, ', '.join(sorted(set(names))))) + sys.stderr.flush() + + +def _destroy_leaked_factories(): + """Stop the sync/polling threads of factories a test created but didn't destroy.""" + for factory in list(_live_factories): + _live_factories.discard(factory) + try: + if not factory.destroyed: + done = threading.Event() + factory.destroy(done) + done.wait(5) + except Exception: # pylint: disable=broad-except + pass # factories built from mocks may not be destroyable; threads are daemons anyway diff --git a/tests/helpers/proxyserver.py b/tests/helpers/proxyserver.py index 2f196528..7111e3cd 100644 --- a/tests/helpers/proxyserver.py +++ b/tests/helpers/proxyserver.py @@ -7,23 +7,25 @@ # Define the port the proxy server will listen on PORT = 8808 +# Upstream requests must never block forever: a stuck handler thread would hang the server close. +REQUEST_TIMEOUT = 10 + class ProxyServer(object): def start_proxy(self): self.server_address = ('', PORT) - print(f"[*] Starting proxy server on port {PORT}...") - start_thread = threading.Thread(target=self._run) + # Daemon: a proxy a test forgot (or failed) to stop must not keep the interpreter alive at exit. + start_thread = threading.Thread(target=self._run, daemon=True) start_thread.start() def _run(self): with ThreadingHTTPServer(self.server_address, ProxyHTTPRequestHandler) as self.httpd: - try: - self.httpd.serve_forever() - except KeyboardInterrupt: - print("\n[-] Shutting down proxy server.") - + self.httpd.serve_forever() + + def stop(self): - print("\n[-] Shutting down proxy server.") - self.httpd.shutdown() + httpd = getattr(self, 'httpd', None) + if httpd is not None: + httpd.shutdown() class ProxyHTTPRequestHandler(http.server.SimpleHTTPRequestHandler): def do_GET(self): @@ -31,12 +33,10 @@ def do_GET(self): # If accessing via browser proxy settings, self.path will be the full URL target_url = self.path - print(f"[+] Proxying request for: {target_url}") - try: # Re-transmit the request to the destination server req = urllib.request.Request(target_url, headers=self.headers) - with urllib.request.urlopen(req) as response: + with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as response: # Send the HTTP status code back to the client self.send_response(response.status) @@ -55,10 +55,22 @@ def do_GET(self): except Exception as e: self.send_error(500, f"Internal Server Error: {str(e)}") + def log_message(self, format, *args): + pass # keep the test output quiet + def do_POST(self): - self.wfile.write("ok") + length = int(self.headers.get('Content-Length') or 0) + if length: + self.rfile.read(length) + self.send_response(200) + self.send_header('Content-Length', '2') + self.end_headers() + self.wfile.write(b"ok") # ThreadingTCPServer allows handling multiple client connections simultaneously class ThreadingHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer): - pass + # Handler threads are daemons and are not joined on close: a handler stuck on an upstream + # request that never finishes would otherwise block both server_close() and interpreter exit. + daemon_threads = True + block_on_close = False From 83f115a6572794f3479c74dd32d545c91d51e3a6 Mon Sep 17 00:00:00 2001 From: Emiliano Sanchez Date: Fri, 6 Nov 2026 16:19:41 -0300 Subject: [PATCH 13/16] rc --- splitio/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/splitio/version.py b/splitio/version.py index 26dfc4df..fa490597 100644 --- a/splitio/version.py +++ b/splitio/version.py @@ -1 +1 @@ -__version__ = '10.7.1rc1' +__version__ = '10.7.1rc2' From 057b42891fcfa5d4af54c8edda2fcddbf59a2d52 Mon Sep 17 00:00:00 2001 From: Emiliano Sanchez Date: Fri, 6 Nov 2026 16:41:54 -0300 Subject: [PATCH 14/16] Prepare release 10.7.1 --- splitio/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/splitio/version.py b/splitio/version.py index fa490597..f130e55d 100644 --- a/splitio/version.py +++ b/splitio/version.py @@ -1 +1 @@ -__version__ = '10.7.1rc2' +__version__ = '10.7.1' From 4365b2ca3148a77c222b9330229784ae1a985934 Mon Sep 17 00:00:00 2001 From: Emiliano Sanchez Date: Fri, 6 Nov 2026 17:05:53 -0300 Subject: [PATCH 15/16] Prevent the asyncio token refresh from reconnecting after stop AI-Session-Id: 593b31d2-e45f-49ac-84dd-f184c9ed3c63 AI-Tool: claude-code AI-Model: unknown --- CHANGES.txt | 2 +- splitio/push/manager.py | 11 +++++++++ tests/push/test_manager.py | 46 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 1 deletion(-) diff --git a/CHANGES.txt b/CHANGES.txt index b37bc4a4..19b564d7 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -10,7 +10,7 @@ - The streaming connection is now considered established once the SSE connection opens, instead of waiting for the first event. Previously, the token refresh and the reconnection after a retryable error waited for an incoming event to resume streaming. - Fixed the SSE connection not being closed on token refresh or SDK destroy when the server response is not chunked, which could block the token refresh. - An auth response with a malformed token is now handled as a retryable error instead of disabling streaming. - - Destroying the SDK while authenticating or waiting to retry streaming no longer opens a new SSE connection or retries the authentication. + - Destroying the SDK while authenticating, refreshing the streaming token or waiting to retry streaming no longer opens a new SSE connection or retries the authentication. - Fixed asyncio HTTP and SSE requests being silently re-sent when the server closes the connection, bypassing the streaming retry backoff. 10.7.0 (Oct 5, 2026) diff --git a/splitio/push/manager.py b/splitio/push/manager.py index 840b5867..325db850 100644 --- a/splitio/push/manager.py +++ b/splitio/push/manager.py @@ -369,8 +369,10 @@ def __init__(self, auth_api, synchronizer, feedback_loop, sdk_metadata, telemetr kwargs = {} if sse_url is None else {'base_url': sse_url} self._sse_client = SplitSSEClientAsync(sdk_metadata, client_key, **kwargs, proxy=proxy) self._running = False + self._stop_requested = False # set by stop() to abort an ongoing connection flow self._telemetry_runtime_producer = telemetry_runtime_producer self._token_task = None + self._running_task = None async def update_workers_status(self, enabled): """ @@ -387,6 +389,7 @@ def start(self): _LOGGER.warning('Push manager already has a connection running. Ignoring') return + self._stop_requested = False self._running_task = asyncio.get_running_loop().create_task(self._trigger_connection_flow()) async def stop(self, blocking=False): @@ -396,6 +399,7 @@ async def stop(self, blocking=False): :param blocking: whether to wait for the connection to be successfully closed or not :type blocking: bool """ + self._stop_requested = True if not self._running: _LOGGER.warning('Push manager does not have an open SSE connection. Ignoring') return @@ -449,6 +453,10 @@ async def _token_refresh(self, current_token): self._token_task = None try: await self._stop_current_conn() + if self._stop_requested: + # stop() can't cancel this task once detached: don't reconnect after it. + _LOGGER.debug('push manager stopped while refreshing token. not reconnecting.') + return self._running_task = asyncio.get_running_loop().create_task( self._trigger_connection_flow()) except asyncio.CancelledError: # subclass of Exception in python 3.7 @@ -484,6 +492,9 @@ async def _trigger_connection_flow(self): try: token = await self._get_auth_token() + if self._stop_requested: + _LOGGER.debug('push manager stopped while authenticating. not connecting.') + return events_source = self._sse_client.start(token) self._running = True diff --git a/tests/push/test_manager.py b/tests/push/test_manager.py index f2cd0988..14ab8eff 100644 --- a/tests/push/test_manager.py +++ b/tests/push/test_manager.py @@ -648,6 +648,52 @@ async def stop(): await manager._token_refresh(Token(True, 'abc', {}, 2000000, 1000000)) assert await asyncio.wait_for(feedback_loop.get(), 1) == Status.PUSH_RETRYABLE_ERROR + @pytest.mark.asyncio + async def test_stop_during_token_refresh(self, mocker): + """Test a stop while the refresh closes the connection doesn't reconnect.""" + feedback_loop = asyncio.Queue() + manager = await self._build_refresh_manager(mocker, feedback_loop) + manager._running = True + stop_tasks = [] + async def sse_stop(): # stop() arrives while the refresh is closing the connection + if not stop_tasks: + stop_tasks.append(asyncio.get_running_loop().create_task(manager.stop(True))) + await asyncio.sleep(0) + manager._sse_client.stop = sse_stop + flows = [] + async def connection_flow(): + flows.append(1) + manager._trigger_connection_flow = connection_flow + + await asyncio.wait_for(manager._token_refresh(Token(True, 'abc', {}, 2000000, 1000000)), 1) + await asyncio.gather(*stop_tasks) + await asyncio.sleep(0) + assert flows == [] # no new connection flow after stop + assert manager._running_task is None + assert feedback_loop.empty() + + @pytest.mark.asyncio + async def test_stop_while_authenticating(self, mocker): + """Test a stop during the auth request doesn't open the SSE connection.""" + feedback_loop = asyncio.Queue() + manager = await self._build_refresh_manager(mocker, feedback_loop) + auth_started = asyncio.Event() + release_auth = asyncio.Event() + async def get_token(): + auth_started.set() + await release_auth.wait() + return Token(True, 'abc', {}, 2000000, 1000000) + manager._get_auth_token = get_token + + manager.start() + await asyncio.wait_for(auth_started.wait(), 1) + await manager.stop(True) # not running yet: only flags the stop + release_auth.set() + await asyncio.sleep(0.1) + assert manager._sse_client.start.mock_calls == [] + assert not manager._running + assert feedback_loop.empty() + @pytest.mark.asyncio async def test_split_change(self, mocker): """Test update-type messages are properly forwarded to the processor.""" From 81bd974168c78e6caa3dd884fb6e13411696f582 Mon Sep 17 00:00:00 2001 From: Emiliano Sanchez Date: Fri, 6 Nov 2026 17:16:00 -0300 Subject: [PATCH 16/16] Simplify CHANGES entry --- CHANGES.txt | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/CHANGES.txt b/CHANGES.txt index 19b564d7..b4768a3c 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -2,16 +2,13 @@ - Updated package metadata: declared python_requires>=3.7, updated the trove classifiers (3.7 to latest stable, Python 2 removed) and removed the universal wheel setting (wheels are now tagged py3). - Updated CI, tests and test dependencies to improve reliability and to validate the SDK on Python 3.7 and latest stable. - Fixed async factory readiness being delayed by the telemetry config post: SplitFactoryAsync now becomes ready before posting telemetry, as the sync factory does. -- Fixed an issue where the SDK could stop applying feature flag updates when streaming is enabled, serving stale definitions until restart: - - Unexpected errors during the streaming authentication or connection (e.g. a non-JSON response or a malformed token) are now handled as retryable errors: the SDK switches to polling and retries streaming with backoff. - - Unexpected errors in the streaming status handler no longer stop it; the SDK switches to polling and retries streaming with backoff. - - Fixed the asyncio token refresh being cancelled by the cleanup of the connection it closes, which could leave the SDK without streaming and without polling. Errors during the asyncio token refresh are now handled as retryable errors, as in the sync mode. -- Fixed several streaming (SSE) connection issues: - - The streaming connection is now considered established once the SSE connection opens, instead of waiting for the first event. Previously, the token refresh and the reconnection after a retryable error waited for an incoming event to resume streaming. - - Fixed the SSE connection not being closed on token refresh or SDK destroy when the server response is not chunked, which could block the token refresh. - - An auth response with a malformed token is now handled as a retryable error instead of disabling streaming. - - Destroying the SDK while authenticating, refreshing the streaming token or waiting to retry streaming no longer opens a new SSE connection or retries the authentication. - - Fixed asyncio HTTP and SSE requests being silently re-sent when the server closes the connection, bypassing the streaming retry backoff. +- Fixed an issue where the SDK could stop applying feature flag updates when streaming is enabled, serving stale definitions until restart. Unexpected streaming errors are now handled as retryable: the SDK switches to polling and retries streaming with backoff. +- Fixed several streaming issues: + - Streaming is now considered connected once the SSE connection opens, instead of waiting for the first event. + - Fixed the streaming token refresh being blocked or cancelled, which could leave the SDK without streaming. + - Fixed an auth response with a malformed token disabling streaming instead of being retried. + - Fixed the SDK connecting to streaming after being destroyed. + - Fixed asyncio HTTP requests being silently re-sent when the server closes the connection, bypassing the retry backoff. 10.7.0 (Oct 5, 2026) - Added ability to use proxy url for all http connections.