Repository navigation
feat(python): test the shared client from several threads #1516
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
yujiyokoo
merged 3 commits into
feat/python-sdk-parity
from
feat/python-sdk-concurrency
Nov 13, 2026
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| """Child process of `test_concurrency_live.py`: the threads make the first | ||
| call of this process together. Prints the counts as JSON.""" | ||
|
|
||
| import json | ||
|
|
||
| from _sync_contract import User, encrypt_from_threads | ||
|
|
||
| from stackencrypt import Cipher, _engine | ||
|
|
||
| assert _engine.client_builds() == 0 | ||
| encrypt_from_threads(Cipher(User), per_thread=1) | ||
| print( | ||
| json.dumps( | ||
| { | ||
| "builds": _engine.client_builds(), | ||
| "keyset_loads": _engine.requests().get("load-keyset", 0), | ||
| } | ||
| ) | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| """Child process of `test_concurrency_live.py`: SIGINT during a long | ||
| `encrypt`. Prints what happened as JSON. | ||
|
|
||
| A reference time is measured first, as the gate test knows its call takes | ||
| one second. It is the fastest of three calls, so a slow one cannot raise | ||
| it. The call starts at 5000 values and doubles until the reference is long | ||
| enough to send a signal into. The signal is sent a quarter of the way into | ||
| one more call. A call cut short would raise at that quarter. A call that | ||
| waits raises after it returns, near the reference time. | ||
| """ | ||
|
|
||
| import json | ||
| import time | ||
|
|
||
| from _sync_contract import User, send_sigint_later, user, wait_for_the_interrupt | ||
|
|
||
| from stackencrypt import Cipher | ||
|
|
||
| LONG_ENOUGH = 0.4 | ||
| MOST_VALUES = 80_000 | ||
|
|
||
|
|
||
| def timed(call): | ||
| started = time.monotonic() | ||
| call() | ||
| return time.monotonic() - started | ||
|
|
||
|
|
||
| cipher = Cipher(User) | ||
| # Load the keyset first, so the timed calls are the values alone. | ||
| cipher.encrypt([user(0)]) | ||
|
|
||
| values = 5000 | ||
| while True: | ||
| models = [user(n) for n in range(values)] | ||
| reference = min(timed(lambda: cipher.encrypt(models)) for _ in range(3)) | ||
| if reference >= LONG_ENOUGH or values >= MOST_VALUES: | ||
| break | ||
| values *= 2 | ||
|
|
||
| interrupts = 0 | ||
| arrived = None | ||
| rows = None | ||
| timer = send_sigint_later(reference / 4) | ||
| started = time.monotonic() | ||
| try: | ||
| rows = cipher.encrypt(models) | ||
| wait_for_the_interrupt() | ||
| except KeyboardInterrupt: | ||
| interrupts += 1 | ||
| arrived = time.monotonic() - started | ||
| timer.join() | ||
|
|
||
| # Python checks for signals many times in the code below. A second | ||
| # interrupt would raise in it, and the process would exit with an error. | ||
| after = cipher.encrypt([user(1)]) | ||
| print( | ||
| json.dumps( | ||
| { | ||
| "values": values, | ||
| "reference": reference, | ||
| "arrived": arrived, | ||
| "interrupts": interrupts, | ||
| "rows": None if rows is None else len(rows), | ||
| "after": len(after), | ||
| } | ||
| ) | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| """The parts of the sync contract tests that more than one file uses: the | ||
| model, the threads, and the interrupt. | ||
|
|
||
| The users are `tests/test_concurrency_live.py`, the deterministic copy in | ||
| `tests_deterministic/test_concurrency.py`, the two child scripts | ||
| `_first_call.py` and `_interrupt.py`, and the gate test | ||
| `test_gate_keyboard_interrupt.py`. Not a test file: pytest collects | ||
| nothing here. | ||
| """ | ||
|
|
||
| import dataclasses | ||
| import os | ||
| import signal | ||
| import threading | ||
| import time | ||
| from typing import Annotated, Dict, List | ||
|
|
||
| import stackencrypt | ||
| from stackencrypt import Cipher, Passthrough, TextEq | ||
|
|
||
| THREADS = 8 | ||
| PER_THREAD = 100 | ||
|
|
||
|
|
||
| @stackencrypt.model("users") | ||
| @dataclasses.dataclass | ||
| class User: | ||
| id: Annotated[int, Passthrough] | ||
| email: Annotated[str, TextEq] | ||
|
|
||
|
|
||
| def user(n: int) -> User: | ||
| return User(id=n, email=f"user{n}@example.com") | ||
|
|
||
|
|
||
| def encrypt_from_threads(cipher: Cipher, per_thread: int) -> List[Dict[str, object]]: | ||
| """Release ``THREADS`` threads at once, each to encrypt ``per_thread`` | ||
| users one call at a time. Returns every row, in user order. Raises if | ||
| any call failed.""" | ||
| sealed: List[List[Dict[str, object]]] = [[] for _ in range(THREADS)] | ||
| failures: List[str] = [] | ||
| start = threading.Barrier(THREADS) | ||
|
yujiyokoo marked this conversation as resolved.
Resolved
|
||
|
|
||
| def encrypt_many(t: int) -> None: | ||
| start.wait() | ||
| try: | ||
| for n in range(per_thread): | ||
| sealed[t].extend(cipher.encrypt([user(t * per_thread + n)])) | ||
| except Exception as error: | ||
| failures.append(repr(error)) | ||
|
|
||
| threads = [threading.Thread(target=encrypt_many, args=(t,)) for t in range(THREADS)] | ||
| for thread in threads: | ||
| thread.start() | ||
| for thread in threads: | ||
| thread.join() | ||
| assert failures == [], failures | ||
| return [row for rows in sealed for row in rows] | ||
|
|
||
|
|
||
| def send_sigint_later(seconds: float) -> threading.Timer: | ||
| """Send SIGINT to this process after ``seconds``.""" | ||
| timer = threading.Timer(seconds, os.kill, (os.getpid(), signal.SIGINT)) | ||
| timer.start() | ||
| return timer | ||
|
|
||
|
|
||
| def wait_for_the_interrupt() -> None: | ||
| """Python raises a pending interrupt at its next check after a call. The | ||
| loop gives it that check, and ends if it never comes.""" | ||
| deadline = time.monotonic() + 5 | ||
| while time.monotonic() < deadline: | ||
| pass | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| """The sync contract from the spec in #1341, held against ZeroKMS: one engine | ||
| client per process, shared by every thread, and a ``KeyboardInterrupt`` | ||
| that waits for the call. | ||
|
|
||
| These tests need the four CipherStash credentials. Without them every test | ||
| here skips. The first-call test and the interrupt test each run a script in | ||
| a new Python process: the client of this one is already built, and the | ||
| interrupt is for the whole process. | ||
| """ | ||
|
|
||
| import json | ||
| import os | ||
| import pathlib | ||
| import subprocess | ||
| import sys | ||
|
|
||
| import pytest | ||
| from _sync_contract import PER_THREAD, THREADS, User, encrypt_from_threads, user | ||
|
|
||
| from stackencrypt import Cipher | ||
|
|
||
| CREDENTIALS = ("CS_CLIENT_ACCESS_KEY", "CS_WORKSPACE_CRN", "CS_CLIENT_ID", "CS_CLIENT_KEY") | ||
|
|
||
| pytestmark = [ | ||
| pytest.mark.live, | ||
| pytest.mark.skipif( | ||
| not all(os.environ.get(name) for name in CREDENTIALS), | ||
| reason="needs CS_CLIENT_ACCESS_KEY, CS_WORKSPACE_CRN, CS_CLIENT_ID and CS_CLIENT_KEY", | ||
| ), | ||
| ] | ||
|
|
||
|
|
||
| def run_child(script): | ||
| """Run ``script``, beside this file, in a new Python process with this | ||
| one's environment. Returns the JSON it printed last.""" | ||
| done = subprocess.run( | ||
| [sys.executable, str(pathlib.Path(__file__).with_name(script))], | ||
| capture_output=True, | ||
| text=True, | ||
| timeout=120, | ||
| ) | ||
| assert done.returncode == 0, done.stderr | ||
| return json.loads(done.stdout.strip().splitlines()[-1]) | ||
|
|
||
|
|
||
| def test_threads_making_their_first_call_at_once_build_one_client(): | ||
| assert run_child("_first_call.py") == {"builds": 1, "keyset_loads": 1} | ||
|
|
||
|
|
||
| def test_threads_encrypt_at_once_and_every_row_opens(): | ||
| cipher = Cipher(User) | ||
|
|
||
| rows = encrypt_from_threads(cipher, PER_THREAD) | ||
|
|
||
| assert cipher.decrypt(rows) == [user(n) for n in range(THREADS * PER_THREAD)] | ||
|
|
||
|
|
||
| @pytest.mark.skipif(sys.platform == "win32", reason="SIGINT is sent with os.kill") | ||
| def test_an_interrupt_during_encrypt_waits_for_it_and_the_cipher_still_works(): | ||
| result = run_child("_interrupt.py") | ||
|
|
||
| # The script grows the call until it takes 0.4 seconds, up to 80,000 | ||
| # values. Below 0.2, there is too little time to send a signal into it. | ||
| assert result["reference"] >= 0.2, result | ||
| assert result["interrupts"] == 1, result | ||
| # A call cut short raises at a quarter of the reference. A call that | ||
| # waits raises after it returns, near the reference time. | ||
| assert result["arrived"] >= result["reference"] / 2, result | ||
| # All the rows, or the interrupt came before the assignment and left | ||
| # nothing: never part of a result. | ||
| assert result["rows"] in (None, result["values"]), result | ||
| assert result["after"] == 1, result |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.