async-sonic 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ root = true
2
+
3
+ [*]
4
+ charset = utf-8
5
+ end_of_line = lf
6
+ insert_final_newline = true
7
+ trim_trailing_whitespace = true
8
+ indent_style = space
9
+ indent_size = 4
10
+
11
+ [*.{yml,yaml,toml,cfg}]
12
+ indent_size = 2
13
+
14
+ [*.md]
15
+ trim_trailing_whitespace = false
@@ -0,0 +1,42 @@
1
+ name: Bug report
2
+ description: Something does not work as documented
3
+ labels: [bug]
4
+ body:
5
+ - type: textarea
6
+ id: what
7
+ attributes:
8
+ label: What happened?
9
+ description: What you did, what you expected and what you got instead.
10
+ validations:
11
+ required: true
12
+ - type: textarea
13
+ id: repro
14
+ attributes:
15
+ label: Minimal reproduction
16
+ description: A short script we can run against a Sonic server.
17
+ render: python
18
+ validations:
19
+ required: true
20
+ - type: textarea
21
+ id: traceback
22
+ attributes:
23
+ label: Traceback or output
24
+ render: text
25
+ - type: input
26
+ id: sonic
27
+ attributes:
28
+ label: Sonic server version
29
+ placeholder: v1.9.1
30
+ validations:
31
+ required: true
32
+ - type: input
33
+ id: python
34
+ attributes:
35
+ label: Python version and OS
36
+ placeholder: "3.14.0, macOS 15"
37
+ validations:
38
+ required: true
39
+ - type: input
40
+ id: version
41
+ attributes:
42
+ label: async-sonic version or commit
@@ -0,0 +1,5 @@
1
+ blank_issues_enabled: false
2
+ contact_links:
3
+ - name: Security vulnerability
4
+ url: https://github.com/cr0hn/async-sonic/security/advisories/new
5
+ about: Please report vulnerabilities privately, not as a public issue.
@@ -0,0 +1,28 @@
1
+ name: Feature request
2
+ description: Suggest an improvement
3
+ labels: [enhancement]
4
+ body:
5
+ - type: textarea
6
+ id: problem
7
+ attributes:
8
+ label: What problem would this solve?
9
+ validations:
10
+ required: true
11
+ - type: textarea
12
+ id: proposal
13
+ attributes:
14
+ label: Proposed solution
15
+ description: Include the API you would like to call, if it applies.
16
+ validations:
17
+ required: true
18
+ - type: textarea
19
+ id: alternatives
20
+ attributes:
21
+ label: Alternatives considered
22
+ - type: checkboxes
23
+ id: scope
24
+ attributes:
25
+ label: Scope
26
+ options:
27
+ - label: It does not require runtime dependencies
28
+ required: true
@@ -0,0 +1,11 @@
1
+ ## What and why
2
+
3
+ <!-- What does this change, and why? Link the issue if there is one. -->
4
+
5
+ ## Checklist
6
+
7
+ - [ ] Unit test added or updated (`tests/test_unit.py`)
8
+ - [ ] Integration test added or updated, if it affects real-server behaviour (`tests/test_integration.py`)
9
+ - [ ] `uv run ruff check .`, `uv run ruff format --check .`, `uv run pyright` and `uv run pytest` pass (0 skipped)
10
+ - [ ] `README.md` and `llms.txt` updated if the public API changed
11
+ - [ ] No new runtime dependencies
@@ -0,0 +1,10 @@
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: github-actions
4
+ directory: /
5
+ schedule:
6
+ interval: weekly
7
+ - package-ecosystem: uv
8
+ directory: /
9
+ schedule:
10
+ interval: weekly
@@ -0,0 +1,31 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ test:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - uses: astral-sh/setup-uv@v6
17
+ with:
18
+ python-version: "3.14"
19
+ - run: uv sync --locked
20
+ - run: uv run ruff check .
21
+ - run: uv run ruff format --check .
22
+ - run: uv run pyright
23
+ - name: Pre-pull the Sonic image
24
+ run: docker pull valeriansaliou/sonic:v1.9.1
25
+ - name: Tests (unit + integration against a real Sonic; nothing may be skipped)
26
+ run: |
27
+ uv run pytest -ra | tee pytest.log
28
+ if grep -Eq '[0-9]+ skipped' pytest.log; then
29
+ echo "::error::Tests were skipped; CI requires every test to run"
30
+ exit 1
31
+ fi
@@ -0,0 +1,50 @@
1
+ name: Publish
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+ workflow_dispatch:
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ build:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - uses: astral-sh/setup-uv@v6
17
+ with:
18
+ python-version: "3.14"
19
+ - run: uv sync --locked
20
+ - run: uv run ruff check .
21
+ - run: uv run ruff format --check .
22
+ - run: uv run pyright
23
+ - name: Pre-pull the Sonic image
24
+ run: docker pull valeriansaliou/sonic:v1.9.1
25
+ - name: Tests (nothing may be skipped)
26
+ run: |
27
+ uv run pytest -ra | tee pytest.log
28
+ if grep -Eq '[0-9]+ skipped' pytest.log; then
29
+ echo "Tests were skipped; refusing to publish."
30
+ exit 1
31
+ fi
32
+ - run: uv build
33
+ - run: uvx twine check dist/*
34
+ - uses: actions/upload-artifact@v4
35
+ with:
36
+ name: dist
37
+ path: dist/
38
+
39
+ publish:
40
+ needs: build
41
+ runs-on: ubuntu-latest
42
+ environment: pypi
43
+ permissions:
44
+ id-token: write # Trusted Publishing (OIDC); no API token stored in secrets
45
+ steps:
46
+ - uses: actions/download-artifact@v4
47
+ with:
48
+ name: dist
49
+ path: dist/
50
+ - uses: pypa/gh-action-pypi-publish@v1.12.4
@@ -0,0 +1,5 @@
1
+ .venv/
2
+ __pycache__/
3
+ .pytest_cache/
4
+ .ruff_cache/
5
+ dist/
@@ -0,0 +1,85 @@
1
+
2
+ # Contributor Covenant Code of Conduct
3
+
4
+ ## Our Pledge
5
+
6
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
7
+
8
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
9
+
10
+ ## Our Standards
11
+
12
+ Examples of behavior that contributes to a positive environment for our community include:
13
+
14
+ * Demonstrating empathy and kindness toward other people
15
+ * Being respectful of differing opinions, viewpoints, and experiences
16
+ * Giving and gracefully accepting constructive feedback
17
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
18
+ * Focusing on what is best not just for us as individuals, but for the overall community
19
+
20
+ Examples of unacceptable behavior include:
21
+
22
+ * The use of sexualized language or imagery, and sexual attention or advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email address, without their explicit permission
26
+ * Other conduct which could reasonably be considered inappropriate in a professional setting
27
+
28
+ ## Enforcement Responsibilities
29
+
30
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
31
+
32
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
33
+
34
+ ## Scope
35
+
36
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
37
+
38
+ ## Enforcement
39
+
40
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at cr0hn@cr0hn.com. All complaints will be reviewed and investigated promptly and fairly.
41
+
42
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
43
+
44
+ ## Enforcement Guidelines
45
+
46
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
47
+
48
+ ### 1. Correction
49
+
50
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
51
+
52
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
53
+
54
+ ### 2. Warning
55
+
56
+ **Community Impact**: A violation through a single incident or series of actions.
57
+
58
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
59
+
60
+ ### 3. Temporary Ban
61
+
62
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
63
+
64
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
65
+
66
+ ### 4. Permanent Ban
67
+
68
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
69
+
70
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
71
+
72
+ ## Attribution
73
+
74
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
75
+
76
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
77
+
78
+ For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].
79
+
80
+ [homepage]: https://www.contributor-covenant.org
81
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
82
+ [Mozilla CoC]: https://github.com/mozilla/diversity
83
+ [FAQ]: https://www.contributor-covenant.org/faq
84
+ [translations]: https://www.contributor-covenant.org/translations
85
+
@@ -0,0 +1,62 @@
1
+ # Contributing to async-sonic
2
+
3
+ Thanks for your interest. Bug reports, fixes and improvements are welcome.
4
+
5
+ ## Ground rules
6
+
7
+ - **Zero runtime dependencies.** The client is the Sonic protocol on top of `asyncio`; keep it that way.
8
+ - **Keep it small.** The library is a single module on purpose. Prefer the simplest change that works.
9
+ - **Tests at both levels.** Every change comes with a unit test (fake server, `tests/test_unit.py`) and,
10
+ when it touches behaviour visible to a real server, an integration test (`tests/test_integration.py`).
11
+ - **English** for code, comments, docs, error messages and commit messages.
12
+ - Protocol questions are settled by Sonic's [`PROTOCOL.md`](https://github.com/valeriansaliou/sonic/blob/master/PROTOCOL.md)
13
+ and by what a real server does; when they disagree, document the deviation in the README.
14
+
15
+ ## Setup
16
+
17
+ Python 3.14+ and [uv](https://docs.astral.sh/uv/). Integration tests also need Docker.
18
+
19
+ ```bash
20
+ git clone https://github.com/cr0hn/async-sonic
21
+ cd async-sonic
22
+ uv sync
23
+ ```
24
+
25
+ ## Before opening a pull request
26
+
27
+ ```bash
28
+ uv run ruff check .
29
+ uv run ruff format --check .
30
+ uv run pyright
31
+ uv run pytest
32
+ ```
33
+
34
+ CI runs the same commands against a real Sonic in Docker and **fails if any test is skipped**, so
35
+ run the whole suite with Docker available and check that the `skipped` count is 0.
36
+
37
+ If you change the public API, update `README.md` and `llms.txt` in the same pull request.
38
+
39
+ ## Commits
40
+
41
+ Use [Conventional Commits](https://www.conventionalcommits.org/) (`feat:`, `fix:`, `docs:`, `test:`,
42
+ `chore:`...). There is no `CHANGELOG.md`: the git history is the changelog.
43
+
44
+ ## Releasing (maintainers)
45
+
46
+ Publishing uses PyPI Trusted Publishing (OIDC); there are no tokens in the repository secrets.
47
+ One-time setup: on PyPI, add a trusted publisher for this repository, workflow `publish.yml`,
48
+ environment `pypi`.
49
+
50
+ 1. Bump `version` in `pyproject.toml` and merge it to `main` with CI green.
51
+ 2. Tag it: `git tag vX.Y.Z && git push origin vX.Y.Z`.
52
+ 3. Publish a GitHub Release for that tag. The `Publish` workflow re-runs ruff, pyright and the full
53
+ test suite against a real Sonic, builds, runs `twine check` and uploads to PyPI.
54
+
55
+ The workflow can also be started manually (`workflow_dispatch`) from the Actions tab.
56
+
57
+ ## Reporting bugs and security issues
58
+
59
+ Use the issue templates. For vulnerabilities, follow [SECURITY.md](SECURITY.md) instead of opening a
60
+ public issue.
61
+
62
+ By contributing you agree that your contributions are licensed under the [MIT License](LICENSE).
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Daniel Alfocea
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,269 @@
1
+ Metadata-Version: 2.5
2
+ Name: async-sonic
3
+ Version: 0.1.0
4
+ Summary: A zero-dependency, fully typed asyncio client for the Sonic search index, with connection pooling and pipelining.
5
+ Project-URL: Homepage, https://github.com/cr0hn/async-sonic
6
+ Project-URL: Repository, https://github.com/cr0hn/async-sonic
7
+ Project-URL: Issues, https://github.com/cr0hn/async-sonic/issues
8
+ Author-email: Daniel Alfocea <cr0hn@cr0hn.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: async,asyncio,client,connection-pool,pipelining,search,sonic,sonic-search,typed
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Framework :: AsyncIO
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Topic :: Database :: Front-Ends
19
+ Classifier: Topic :: Internet
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.14
22
+ Description-Content-Type: text/markdown
23
+
24
+ # async-sonic
25
+
26
+ A zero-dependency, fully typed asyncio client for the [Sonic](https://github.com/valeriansaliou/sonic) search index, with connection pooling and pipelining.
27
+
28
+ [![CI](https://github.com/cr0hn/async-sonic/actions/workflows/ci.yml/badge.svg)](https://github.com/cr0hn/async-sonic/actions/workflows/ci.yml)
29
+ ![Python 3.14+](https://img.shields.io/badge/python-3.14%2B-blue)
30
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE)
31
+
32
+ LLM-friendly reference: [`llms.txt`](llms.txt).
33
+
34
+ ## Table of contents
35
+
36
+ - [Why async-sonic](#why-async-sonic)
37
+ - [Installation](#installation)
38
+ - [Quickstart](#quickstart)
39
+ - [API reference](#api-reference)
40
+ - [Concurrency and performance](#concurrency-and-performance)
41
+ - [Error handling](#error-handling)
42
+ - [Escaping and limits](#escaping-and-limits)
43
+ - [Compatibility and limitations](#compatibility-and-limitations)
44
+ - [Development](#development)
45
+ - [Contributing](#contributing)
46
+ - [License](#license)
47
+
48
+ ## Why async-sonic
49
+
50
+ Sonic is a fast, lightweight search index that speaks a plain-text protocol
51
+ ([`PROTOCOL.md`](https://github.com/valeriansaliou/sonic/blob/master/PROTOCOL.md)).
52
+ The asyncio client that existed on PyPI (`asonic`, last released in 2020) does not work, and
53
+ the other clients are synchronous. `async-sonic` implements the protocol from its specification
54
+ on top of `asyncio.open_connection` and nothing else.
55
+
56
+ - **One class**: `Sonic(host, port, password)` used as `async with`, with flat, obviously named
57
+ methods (`push`, `query`, `suggest`, ...). Channels, handshake and pool are hidden.
58
+ - **Fast**: a lazy per-channel connection pool plus pipelining (one background reader per
59
+ connection). See [the numbers](#concurrency-and-performance).
60
+ - **Zero runtime dependencies**, Python 3.14+, strict typing, `py.typed`.
61
+ - **Honest errors**: no hidden retries; every exception message says what happened and what to do.
62
+ - **LLM-friendly**: short docstrings with a one-line example on every public method, plus
63
+ [`llms.txt`](llms.txt).
64
+
65
+ ## Installation
66
+
67
+ ```bash
68
+ uv add async-sonic # or: pip install async-sonic
69
+ ```
70
+
71
+ The package is not on PyPI yet; until then install from Git:
72
+
73
+ ```bash
74
+ uv add git+https://github.com/cr0hn/async-sonic
75
+ # or: pip install git+https://github.com/cr0hn/async-sonic
76
+ ```
77
+
78
+ ## Quickstart
79
+
80
+ <!-- quickstart -->
81
+ ```python
82
+ import asyncio
83
+ from async_sonic import Sonic
84
+
85
+
86
+ async def main() -> None:
87
+ async with Sonic("localhost", 1491, "SecretPassword") as sonic:
88
+ await sonic.push("videos", "catalog", "video:1", "cats and dogs are funny", lang="eng")
89
+ await sonic.push("videos", "catalog", "video:2", "stray dogs", lang="eng")
90
+ print(await sonic.query("videos", "catalog", "cats", lang="eng"))
91
+ await sonic.trigger(
92
+ "consolidate"
93
+ ) # SUGGEST reads a graph that is only updated on consolidate
94
+ print(await sonic.suggest("videos", "catalog", "fun"))
95
+ await sonic.flush_collection("videos")
96
+
97
+
98
+ asyncio.run(main())
99
+ ```
100
+ Output:
101
+ ```text
102
+ ['video:1']
103
+ ['funny']
104
+ ```
105
+ <!-- /quickstart -->
106
+
107
+ This block is executed as a test against a real Sonic
108
+ (`tests/test_integration.py::test_readme_quickstart_runs`), so it cannot drift from the code.
109
+ To try it, start Sonic (see [Development](#development)) and use its host, port and password.
110
+
111
+ ## API reference
112
+
113
+ `Sonic` opens nothing on construction or on `async with` entry: connections are opened lazily on
114
+ the first command, one pool per channel.
115
+
116
+ ```python
117
+ Sonic(host="localhost", port=1491, password="", *,
118
+ pool_size=4, max_in_flight=None, timeout=10.0, connect_timeout=5.0)
119
+ ```
120
+
121
+ | Method | Sonic command | Channel | Returns |
122
+ |---|---|---|---|
123
+ | `query(collection, bucket, terms, *, limit, offset, lang)` | `QUERY` | search | `list[str]` object ids, best first |
124
+ | `suggest(collection, bucket, word, *, limit)` | `SUGGEST` | search | `list[str]` words |
125
+ | `list_words(collection, bucket, *, limit, offset)` | `LIST` | search | `list[str]` words |
126
+ | `push(collection, bucket, object, text, *, lang)` | `PUSH` | ingest | `None` |
127
+ | `pop(collection, bucket, object, text)` | `POP` | ingest | `int` |
128
+ | `count(collection, bucket=None, object=None)` | `COUNT` | ingest | `int` |
129
+ | `flush_collection(collection)` | `FLUSHC` | ingest | `int` |
130
+ | `flush_bucket(collection, bucket)` | `FLUSHB` | ingest | `int` |
131
+ | `flush_object(collection, bucket, object)` | `FLUSHO` | ingest | `int` |
132
+ | `trigger(action=None, data=None)` | `TRIGGER` | control | `str` |
133
+ | `info()` | `INFO` | control | `dict[str, int]` |
134
+ | `ping()` | `PING` | control | `None` |
135
+ | `help(manual=None)` | `HELP` | control | `str` |
136
+
137
+ `close()` (or leaving the `async with`) sends `QUIT` on every connection. `quote(text)` is public.
138
+
139
+ `lang` is an ISO 639-3 code (`"eng"`, `"spa"`) or `"none"`. If omitted, Sonic guesses the
140
+ language of the text, and may guess differently at index and query time: pass it on both sides.
141
+
142
+ Deliberate differences from the protocol:
143
+
144
+ - `list_words`: Sonic's `LIST` enumerates **words** of the index, not objects.
145
+ - `count` uses `COUNT` rather than `COUNTC/COUNTB/COUNTO` (see [Compatibility](#compatibility-and-limitations)).
146
+
147
+ ## Concurrency and performance
148
+
149
+ A Sonic channel is a TCP connection in one mode (search, ingest or control).
150
+
151
+ - **Pool**: up to `pool_size` connections per channel, opened when needed (an idle connection is
152
+ reused before a new one is opened). A command goes to the least loaded connection.
153
+ - **Pipelining**: each connection writes commands without waiting for replies, and a background
154
+ reader task hands the replies to futures. `PROTOCOL.md` allows this: immediate replies (`OK`,
155
+ `RESULT`, `PONG`, `PENDING <id>`, `ERR`) arrive **in order** (a FIFO of futures), while the
156
+ `EVENT` lines of `QUERY`/`SUGGEST`/`LIST` may arrive **out of order** and are matched by the
157
+ id of their `PENDING`. `max_in_flight` caps simultaneous commands per connection
158
+ (`None` = unlimited, `1` = no pipelining).
159
+ - **No retries, no magic reconnection.** If a connection drops, its in-flight commands fail with
160
+ `SonicConnectionError`; the *next* command opens a fresh connection. What to retry, and when,
161
+ is your decision (a `PUSH` is idempotent if you `flush_object` first; a `POP` is not).
162
+ - **Per-command timeout** (`timeout`) raises `SonicTimeout`, but the connection stays usable: the
163
+ late reply is discarded when it arrives and nothing gets out of sync.
164
+
165
+ ### Measured numbers
166
+
167
+ `benchmarks/bench.py`: 2000 operations per row, Sonic v1.9.1 in Docker Desktop (4 CPUs) on an
168
+ Apple M2 Max, over localhost. **It is a single run and numbers vary from run to run**: trust the
169
+ orders of magnitude, not the decimals.
170
+
171
+ | Scenario | QUERY ops/s | PUSH ops/s |
172
+ |---|---:|---:|
173
+ | 1 connection, sequential | 2205 | 3061 |
174
+ | pool of 8, concurrent, no pipelining | 10549 | 7559 |
175
+ | 1 connection, pipelining | 13464 | 12795 |
176
+ | pool of 8 + pipelining | 14843 | 11104 |
177
+
178
+ Pipelining is the big lever: 4x to 6x over sequential. On top of it the pool did not help in
179
+ this run (an earlier run showed +40% for queries and nothing for writes), so with pipelining one
180
+ connection is often enough; the pool mostly matters when `max_in_flight` is capped. Over a real
181
+ network with latency the gap to the sequential case is larger, because a round trip is paid once
182
+ per burst instead of once per command; that was not measured.
183
+
184
+ ## Error handling
185
+
186
+ Every exception inherits from `SonicError`; messages say what happened and what to do.
187
+
188
+ | Exception | When |
189
+ |---|---|
190
+ | `SonicConnectionError` | could not connect, or the connection dropped, was closed or received `ENDED` |
191
+ | `SonicTimeout` (subclass of the previous one) | `connect_timeout` or `timeout` expired |
192
+ | `SonicServerError` | Sonic answered `ERR ...` (`.code`, `.line`); also a wrong password (`authentication_failed`) |
193
+ | `SonicProtocolError` | Sonic said something outside `PROTOCOL.md`; the connection is closed |
194
+ | `ValueError` (builtin) | invalid argument, or a command that does not fit in the buffer; nothing is sent |
195
+
196
+ ```python
197
+ from async_sonic import Sonic, SonicServerError, SonicTimeout
198
+
199
+ async with Sonic(password="SecretPassword") as sonic:
200
+ try:
201
+ await sonic.query("videos", "catalog", "cats", limit=0)
202
+ except SonicServerError as exc:
203
+ print(exc.code) # policy_reject
204
+ except SonicTimeout:
205
+ ... # Sonic did not answer in time; the connection is still usable
206
+ ```
207
+
208
+ ## Escaping and limits
209
+
210
+ `quote(text)` wraps text in quotes: `"` becomes `\"`, `\` becomes `\\` (so a trailing backslash
211
+ cannot swallow the closing quote) and newlines (`\n`, `\r`) become a space, because a raw newline
212
+ would cut the command in two; Sonic tokenizes on whitespace, so no word is lost. Unicode goes
213
+ through as UTF-8. `collection`, `bucket`, `object`, `action`... cannot be empty or contain
214
+ whitespace, quotes or control characters (`ValueError`).
215
+
216
+ **Buffer.** `STARTED ... buffer(N)` (20000 by default) is the limit of a whole command line,
217
+ newline included. `PROTOCOL.md` asks clients to split: `push` does it for you, emitting several
218
+ `PUSH` commands for the same object, always cutting **between words**. `query`, `suggest` and
219
+ `pop` are not split (splitting would change their meaning) and raise `ValueError`, as does a
220
+ single word longer than the buffer.
221
+
222
+ ## Compatibility and limitations
223
+
224
+ - **Verified**: Sonic **v1.9.1** (official image `valeriansaliou/sonic:v1.9.1`) on Docker
225
+ Desktop, macOS arm64, Python 3.14. Every command in the table above; text with quotes,
226
+ backslashes, newlines, accents, CJK and emoji; a 48 KB text (split by the buffer); real `ERR`
227
+ replies; a wrong password; and 200 concurrent queries over the pool with pipelining.
228
+ - **Deviations from `PROTOCOL.md` found on v1.9.1**:
229
+ - `COUNTC`, `COUNTB` and `COUNTO` answer `ERR unknown_command`; `COUNT` is used instead, and
230
+ `count(collection, bucket)` returns the number of **distinct words**, not of objects
231
+ (measured: 2 objects, 4 words, `count` returned 4).
232
+ - `SUGGEST` and `LIST` only see new words after `trigger("consolidate")`.
233
+ - A wrong password is answered with `ENDED authentication_failed` (surfaced as `SonicServerError`).
234
+ - Replies end in `\r\n`.
235
+ - **Not verified**: other Sonic versions (the `COUNTC/B/O` commands may exist in later ones);
236
+ `TRIGGER backup` and `restore` (they are sent, never tested against real data); Linux and
237
+ Windows (CI covers Linux); sustained load or a server with many clients; network latency.
238
+ - No TLS: Sonic Channel is plain TCP. Do not expose it to an untrusted network.
239
+ - Searching without accents (`cancion` for `canción`) depends on the server configuration
240
+ (`diacritic_folding_enabled`), not on this client; the test `sonic.cfg` does not enable it.
241
+
242
+ ## Development
243
+
244
+ ```bash
245
+ uv sync
246
+ uv run ruff check . && uv run ruff format --check .
247
+ uv run pyright
248
+ uv run pytest # everything
249
+ uv run pytest tests/test_unit.py # unit tests only, no docker needed
250
+ uv run python benchmarks/bench.py # benchmark against a real Sonic
251
+ ```
252
+
253
+ - `tests/test_unit.py` runs against a fake asyncio server (`tests/fake_sonic.py`) that speaks the
254
+ real protocol: handshake, out-of-order `PENDING`/`EVENT`, `ERR`, abrupt close, `ENDED`, slow
255
+ replies (timeouts and late replies), buffer splitting, pool and pipelining with latency.
256
+ - `tests/test_integration.py` runs against a **real Sonic**. If `docker` is available, the
257
+ fixture starts `valeriansaliou/sonic:v1.9.1` with `tests/sonic.cfg` (password `SecretPassword`)
258
+ on a free port. **Without docker these tests are skipped with an explicit reason**
259
+ (`SKIPPED: docker is not available...`): always check the `skipped` count, because a green run
260
+ with every integration test skipped does not prove the real wiring. CI fails if any test is skipped.
261
+
262
+ ## Contributing
263
+
264
+ Issues and pull requests are welcome; see [CONTRIBUTING.md](CONTRIBUTING.md). Please follow the
265
+ [Code of Conduct](CODE_OF_CONDUCT.md). Security reports: [SECURITY.md](SECURITY.md).
266
+
267
+ ## License
268
+
269
+ [MIT](LICENSE) (c) 2026 Daniel Alfocea.