jevaro-server 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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ recursive-include tests *.py
@@ -0,0 +1,4 @@
1
+ Jevaro
2
+ Copyright 2026 Columnar Technologies Inc.
3
+
4
+ Licensed under the Apache License, Version 2.0.
@@ -0,0 +1,96 @@
1
+ Metadata-Version: 2.4
2
+ Name: jevaro-server
3
+ Version: 0.1.0
4
+ Summary: A small TypeSafe-to-Arrow streaming proxy
5
+ Author: Columnar Technologies Inc.
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/columnar-tech/jevaro
8
+ Project-URL: Documentation, https://github.com/columnar-tech/jevaro/blob/main/jevaro-server/README.md
9
+ Project-URL: Repository, https://github.com/columnar-tech/jevaro
10
+ Project-URL: Issues, https://github.com/columnar-tech/jevaro/issues
11
+ Requires-Python: >=3.11
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ License-File: NOTICE
15
+ Requires-Dist: fastapi<1,>=0.115
16
+ Requires-Dist: uvicorn<1,>=0.30
17
+ Requires-Dist: typesafe-sdk==0.7.2
18
+ Requires-Dist: pyarrow==25.0.1
19
+ Dynamic: license-file
20
+
21
+ # Jevaro server
22
+
23
+ A Python proxy that evaluates states with TypeSafe and streams the answers
24
+ as Arrow. See the [quickstart](https://github.com/columnar-tech/jevaro/blob/main/docs/quickstart.md)
25
+ for an example using both SDKs.
26
+
27
+ ## Run
28
+
29
+ Requires Python 3.11+.
30
+
31
+ ```sh
32
+ python3 -m venv .venv
33
+ .venv/bin/python -m pip install jevaro-server
34
+ export TYPESAFE_API_KEY="your-api-key"
35
+ .venv/bin/jevaro-server
36
+ ```
37
+
38
+ The default address is `http://127.0.0.1:8000`. Change it with `--host` and
39
+ `--port`. `python -m jevaro_server` runs the same command in an activated
40
+ environment.
41
+
42
+ ## Configuration
43
+
44
+ | Setting | Default | Purpose |
45
+ | --- | --- | --- |
46
+ | `--host` | `127.0.0.1` | Listen address |
47
+ | `--port` | `8000` | Listen port |
48
+ | `TYPESAFE_API_KEY` | Unset | Upstream key when a request has no bearer token |
49
+ | `TYPESAFE_UPSTREAM_URL` | `https://api.typesafe.ai` | Upstream API base URL |
50
+ | `JEVARO_CONCURRENCY` | `8` | Maximum pending calls/results per incoming request; positive integer |
51
+
52
+ An incoming `Authorization: Bearer <key>` overrides the server's key and is
53
+ forwarded to TypeSafe. A request without that header uses the server's key.
54
+ Jevaro has no separate client access control: keep it local, or put
55
+ authentication in front of a shared server.
56
+
57
+ `TYPESAFE_BASE_URL` is an SDK setting for reaching Jevaro. The server uses
58
+ `TYPESAFE_UPSTREAM_URL` to reach TypeSafe.
59
+
60
+ ## Streaming
61
+
62
+ `POST /v1/systemone` accepts `state` or a nonempty `states` array and a map of
63
+ questions. After validating the request, the server sends the schema and an
64
+ empty batch before starting upstream calls. Each later batch contains one
65
+ answer row, in input order.
66
+
67
+ The response uses `application/vnd.apache.arrow.stream` and has no
68
+ `Content-Length`. It sets `X-Accel-Buffering: no`; configure any reverse proxy
69
+ to pass the stream without buffering.
70
+
71
+ See the [HTTP API](https://github.com/columnar-tech/jevaro/blob/main/docs/http-api.md)
72
+ and [Arrow schema](https://github.com/columnar-tech/jevaro/blob/main/docs/arrow-schema.md)
73
+ for the request and result formats.
74
+
75
+ ## Limits
76
+
77
+ The full JSON request is held in memory. Pending calls and completed answers
78
+ waiting for their turn are bounded by `JEVARO_CONCURRENCY`. A slow earlier
79
+ call delays later rows. Closing the stream cancels pending work; calls already
80
+ processed upstream still count as API use.
81
+
82
+ Retries use the official TypeSafe SDK's default policy, including backoff for
83
+ 429 and 529 responses. Concurrency is per incoming request. This version has
84
+ no shared account rate limiter.
85
+
86
+ If an upstream call fails after retries, the HTTP stream aborts. Its status
87
+ is already 200 at that point. Readers must consume the stream successfully
88
+ before treating the result as complete.
89
+
90
+ ## Development
91
+
92
+ See [Contributing](https://github.com/columnar-tech/jevaro/blob/main/CONTRIBUTING.md)
93
+ for setup and tests. The server is independent of the earlier demo scripts.
94
+
95
+ [Apache-2.0](https://github.com/columnar-tech/jevaro/blob/main/LICENSE).
96
+ Copyright 2026 Columnar Technologies Inc.
@@ -0,0 +1,76 @@
1
+ # Jevaro server
2
+
3
+ A Python proxy that evaluates states with TypeSafe and streams the answers
4
+ as Arrow. See the [quickstart](https://github.com/columnar-tech/jevaro/blob/main/docs/quickstart.md)
5
+ for an example using both SDKs.
6
+
7
+ ## Run
8
+
9
+ Requires Python 3.11+.
10
+
11
+ ```sh
12
+ python3 -m venv .venv
13
+ .venv/bin/python -m pip install jevaro-server
14
+ export TYPESAFE_API_KEY="your-api-key"
15
+ .venv/bin/jevaro-server
16
+ ```
17
+
18
+ The default address is `http://127.0.0.1:8000`. Change it with `--host` and
19
+ `--port`. `python -m jevaro_server` runs the same command in an activated
20
+ environment.
21
+
22
+ ## Configuration
23
+
24
+ | Setting | Default | Purpose |
25
+ | --- | --- | --- |
26
+ | `--host` | `127.0.0.1` | Listen address |
27
+ | `--port` | `8000` | Listen port |
28
+ | `TYPESAFE_API_KEY` | Unset | Upstream key when a request has no bearer token |
29
+ | `TYPESAFE_UPSTREAM_URL` | `https://api.typesafe.ai` | Upstream API base URL |
30
+ | `JEVARO_CONCURRENCY` | `8` | Maximum pending calls/results per incoming request; positive integer |
31
+
32
+ An incoming `Authorization: Bearer <key>` overrides the server's key and is
33
+ forwarded to TypeSafe. A request without that header uses the server's key.
34
+ Jevaro has no separate client access control: keep it local, or put
35
+ authentication in front of a shared server.
36
+
37
+ `TYPESAFE_BASE_URL` is an SDK setting for reaching Jevaro. The server uses
38
+ `TYPESAFE_UPSTREAM_URL` to reach TypeSafe.
39
+
40
+ ## Streaming
41
+
42
+ `POST /v1/systemone` accepts `state` or a nonempty `states` array and a map of
43
+ questions. After validating the request, the server sends the schema and an
44
+ empty batch before starting upstream calls. Each later batch contains one
45
+ answer row, in input order.
46
+
47
+ The response uses `application/vnd.apache.arrow.stream` and has no
48
+ `Content-Length`. It sets `X-Accel-Buffering: no`; configure any reverse proxy
49
+ to pass the stream without buffering.
50
+
51
+ See the [HTTP API](https://github.com/columnar-tech/jevaro/blob/main/docs/http-api.md)
52
+ and [Arrow schema](https://github.com/columnar-tech/jevaro/blob/main/docs/arrow-schema.md)
53
+ for the request and result formats.
54
+
55
+ ## Limits
56
+
57
+ The full JSON request is held in memory. Pending calls and completed answers
58
+ waiting for their turn are bounded by `JEVARO_CONCURRENCY`. A slow earlier
59
+ call delays later rows. Closing the stream cancels pending work; calls already
60
+ processed upstream still count as API use.
61
+
62
+ Retries use the official TypeSafe SDK's default policy, including backoff for
63
+ 429 and 529 responses. Concurrency is per incoming request. This version has
64
+ no shared account rate limiter.
65
+
66
+ If an upstream call fails after retries, the HTTP stream aborts. Its status
67
+ is already 200 at that point. Readers must consume the stream successfully
68
+ before treating the result as complete.
69
+
70
+ ## Development
71
+
72
+ See [Contributing](https://github.com/columnar-tech/jevaro/blob/main/CONTRIBUTING.md)
73
+ for setup and tests. The server is independent of the earlier demo scripts.
74
+
75
+ [Apache-2.0](https://github.com/columnar-tech/jevaro/blob/main/LICENSE).
76
+ Copyright 2026 Columnar Technologies Inc.
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0.3"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "jevaro-server"
7
+ version = "0.1.0"
8
+ description = "A small TypeSafe-to-Arrow streaming proxy"
9
+ readme = "README.md"
10
+ authors = [{name = "Columnar Technologies Inc."}]
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE", "NOTICE"]
13
+ requires-python = ">=3.11"
14
+ dependencies = [
15
+ "fastapi>=0.115,<1",
16
+ "uvicorn>=0.30,<1",
17
+ "typesafe-sdk==0.7.2",
18
+ "pyarrow==25.0.1",
19
+ ]
20
+
21
+ [project.urls]
22
+ Homepage = "https://github.com/columnar-tech/jevaro"
23
+ Documentation = "https://github.com/columnar-tech/jevaro/blob/main/jevaro-server/README.md"
24
+ Repository = "https://github.com/columnar-tech/jevaro"
25
+ Issues = "https://github.com/columnar-tech/jevaro/issues"
26
+
27
+ [project.scripts]
28
+ jevaro-server = "jevaro_server.__main__:main"
29
+
30
+ [tool.setuptools.packages.find]
31
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1 @@
1
+ """Jevaro: TypeSafe questions in, ordered Arrow answers out."""
@@ -0,0 +1,15 @@
1
+ import argparse
2
+
3
+ import uvicorn
4
+
5
+
6
+ def main():
7
+ parser = argparse.ArgumentParser(description="Run the Jevaro Arrow proxy")
8
+ parser.add_argument("--host", default="127.0.0.1")
9
+ parser.add_argument("--port", type=int, default=8000)
10
+ args = parser.parse_args()
11
+ uvicorn.run("jevaro_server.app:app", host=args.host, port=args.port)
12
+
13
+
14
+ if __name__ == "__main__":
15
+ main()
@@ -0,0 +1,140 @@
1
+ """POST /v1/systemone: TypeSafe requests with state or a nonempty states array."""
2
+
3
+ import asyncio
4
+ import os
5
+ from collections import deque
6
+ from typing import Annotated
7
+
8
+ import pyarrow as pa
9
+ from fastapi import FastAPI, Header, HTTPException
10
+ from fastapi.responses import StreamingResponse
11
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
12
+ from typesafe_sdk import AsyncTypeSafeClient, Choice, JSONContent, Noul, Score
13
+
14
+ from .arrow import StreamSink, answer_batch, schema_for
15
+
16
+ MEDIA_TYPE = "application/vnd.apache.arrow.stream"
17
+ Question = Annotated[Choice | Score | Noul, Field(discriminator="type")]
18
+
19
+
20
+ class Evaluation(BaseModel):
21
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
22
+
23
+ state: JSONContent | None = None
24
+ states: list[JSONContent] | None = None
25
+ questions: dict[str, Question] = Field(min_length=1)
26
+ model: str = Field(default="jev-latest", min_length=1)
27
+
28
+ @model_validator(mode="after")
29
+ def validate_request(self):
30
+ singular = "state" in self.model_fields_set
31
+ plural = "states" in self.model_fields_set
32
+ if singular == plural:
33
+ raise ValueError("Supply exactly one of state or states")
34
+ if singular and self.state is None:
35
+ raise ValueError("state must be a string, object, or array")
36
+ if plural and not self.states:
37
+ raise ValueError("states must be a nonempty array")
38
+ for question in self.questions.values():
39
+ if isinstance(question, Choice) and not 1 <= len(question.criteria) <= 255:
40
+ raise ValueError("Choice requires 1 to 255 options")
41
+ if isinstance(question, Score) and not 2 <= len(question.criteria) <= 10:
42
+ raise ValueError("Score requires 2 to 10 levels")
43
+ return self
44
+
45
+
46
+ async def ordered_responses(client, states, questions, model, concurrency):
47
+ """A sliding window bounds running calls AND completed results awaiting their turn."""
48
+ remaining = iter(states)
49
+ pending = deque()
50
+
51
+ def submit():
52
+ try:
53
+ state = next(remaining)
54
+ except StopIteration:
55
+ return
56
+ pending.append(asyncio.create_task(
57
+ client.system_one(state=state, questions=questions, model=model)
58
+ ))
59
+
60
+ try:
61
+ for _ in range(min(concurrency, len(states))):
62
+ submit()
63
+ while pending:
64
+ # Keep the task in the deque while awaiting it, so cancellation catches it too.
65
+ response = await pending[0]
66
+ pending.popleft()
67
+ yield response
68
+ submit()
69
+ finally:
70
+ for task in pending:
71
+ task.cancel()
72
+ await asyncio.gather(*pending, return_exceptions=True)
73
+
74
+
75
+ def create_app(*, client_factory=AsyncTypeSafeClient, concurrency=None):
76
+ if concurrency is None:
77
+ concurrency = int(os.environ.get("JEVARO_CONCURRENCY", "8"))
78
+ if isinstance(concurrency, bool) or not isinstance(concurrency, int) or concurrency < 1:
79
+ raise ValueError("JEVARO_CONCURRENCY must be a positive integer")
80
+ app = FastAPI(title="Jevaro", version="0.1.0")
81
+
82
+ @app.post("/v1/systemone", response_class=StreamingResponse)
83
+ async def system_one(
84
+ body: Evaluation, authorization: Annotated[str | None, Header()] = None,
85
+ ):
86
+ if authorization is not None:
87
+ scheme, _, api_key = authorization.partition(" ")
88
+ if scheme.lower() != "bearer" or not api_key.strip():
89
+ raise HTTPException(401, "Expected Authorization: Bearer <TYPESAFE_API_KEY>")
90
+ api_key = api_key.strip()
91
+ else:
92
+ api_key = os.environ.get("TYPESAFE_API_KEY")
93
+ if not api_key:
94
+ raise HTTPException(401, "Set TYPESAFE_API_KEY or send an Authorization bearer token")
95
+
96
+ states = body.states if body.states is not None else [body.state]
97
+ try:
98
+ schema = schema_for(body.questions)
99
+ except (ValueError, TypeError) as error:
100
+ raise HTTPException(422, str(error)) from error
101
+
102
+ async def stream():
103
+ sink = StreamSink()
104
+ writer = pa.ipc.new_stream(sink, schema)
105
+ try:
106
+ # Arrow emits the schema on the first write. Flush a zero-row batch
107
+ # before constructing the upstream client or starting any API calls.
108
+ writer.write_batch(pa.RecordBatch.from_arrays(
109
+ [field.type.array([]) for field in schema], schema=schema,
110
+ ))
111
+ yield sink.drain()
112
+ async with client_factory(
113
+ api_key=api_key,
114
+ base_url=os.environ.get("TYPESAFE_UPSTREAM_URL", "https://api.typesafe.ai"),
115
+ ) as client:
116
+ responses = ordered_responses(
117
+ client, states, body.questions, body.model, concurrency,
118
+ )
119
+ try:
120
+ async for response in responses:
121
+ writer.write_batch(answer_batch(schema, response))
122
+ yield sink.drain()
123
+ finally:
124
+ await responses.aclose()
125
+ writer.close()
126
+ yield sink.drain() # Normal completion alone sends the Arrow EOS marker.
127
+ finally:
128
+ # On failure/disconnect, discard any buffered EOS; the HTTP stream aborts.
129
+ writer.close()
130
+ sink.close()
131
+
132
+ return StreamingResponse(stream(), media_type=MEDIA_TYPE, headers={
133
+ "X-Accel-Buffering": "no",
134
+ "X-Jevaro-Row-Count": str(len(states)),
135
+ })
136
+
137
+ return app
138
+
139
+
140
+ app = create_app()
@@ -0,0 +1,160 @@
1
+ """Compact answer-only Arrow schema. No original prompts or requested model."""
2
+
3
+ import io
4
+ import json
5
+
6
+ import pyarrow as pa
7
+ from typesafe_sdk import Choice, ChoiceAnswer, Noul, NoulAnswer, Score, ScoreAnswer
8
+
9
+
10
+ def required(name, data_type):
11
+ return pa.field(name, data_type, nullable=False)
12
+
13
+
14
+ def probabilities(size):
15
+ return pa.list_(required("item", pa.float64()), size)
16
+
17
+
18
+ class AnswerType(pa.ExtensionType):
19
+ def __init__(self, storage, **metadata):
20
+ self._metadata = json.dumps(
21
+ metadata, ensure_ascii=False,
22
+ separators=(",", ":"), allow_nan=False,
23
+ ).encode()
24
+ super().__init__(storage, f"jevaro.{self.kind}")
25
+
26
+ def __arrow_ext_serialize__(self):
27
+ return self._metadata
28
+
29
+ @classmethod
30
+ def __arrow_ext_deserialize__(cls, storage, serialized):
31
+ metadata = json.loads(serialized)
32
+ result = cls(**metadata)
33
+ if not storage.equals(result.storage_type):
34
+ raise ValueError("Storage does not match Jevaro extension metadata")
35
+ return result
36
+
37
+ def __eq__(self, other):
38
+ if not isinstance(other, AnswerType):
39
+ return NotImplemented
40
+ return (type(self) is type(other) and self.storage_type == other.storage_type
41
+ and self._metadata == other._metadata)
42
+
43
+ def __ne__(self, other):
44
+ equal = self.__eq__(other)
45
+ return NotImplemented if equal is NotImplemented else not equal
46
+
47
+ def __hash__(self):
48
+ return hash((type(self), self.storage_type, self._metadata))
49
+
50
+ def array(self, answers):
51
+ storage = pa.array([self.pack(answer) for answer in answers], self.storage_type)
52
+ return pa.ExtensionArray.from_storage(self, storage)
53
+
54
+
55
+ class ChoiceType(AnswerType):
56
+ kind = "choice"
57
+
58
+ def __init__(self, labels):
59
+ self.labels = tuple(labels)
60
+ if (not 1 <= len(self.labels) <= 255
61
+ or any(not isinstance(label, str) for label in self.labels)
62
+ or len(set(self.labels)) != len(self.labels)):
63
+ raise ValueError("Choice requires 1 to 255 unique string labels")
64
+ super().__init__(pa.struct([
65
+ required("choice", pa.uint8()),
66
+ required("confidence", pa.float64()),
67
+ required("probabilities", probabilities(len(self.labels))),
68
+ ]), labels=self.labels)
69
+
70
+ def pack(self, answer):
71
+ if not isinstance(answer, ChoiceAnswer) or set(answer.probabilities) != set(self.labels):
72
+ raise ValueError("Choice answer does not match the schema")
73
+ return {
74
+ "choice": self.labels.index(answer.choice),
75
+ "confidence": answer.confidence,
76
+ "probabilities": [answer.probabilities[label] for label in self.labels],
77
+ }
78
+
79
+
80
+ class ScoreType(AnswerType):
81
+ kind = "score"
82
+
83
+ def __init__(self, legend):
84
+ if not isinstance(legend, (list, tuple)) or not 2 <= len(legend) <= 10:
85
+ raise ValueError("Score requires 2 to 10 levels")
86
+ super().__init__(pa.struct([
87
+ required("score", pa.float64()),
88
+ required("confidence", pa.float64()),
89
+ required("probabilities", probabilities(len(legend))),
90
+ ]), legend=legend)
91
+
92
+ def pack(self, answer):
93
+ legend = dict(enumerate(json.loads(self._metadata)["legend"]))
94
+ if (not isinstance(answer, ScoreAnswer) or answer.legend != legend
95
+ or set(answer.probabilities) != set(legend)):
96
+ raise ValueError("Score answer does not match the schema")
97
+ return {
98
+ "score": answer.score,
99
+ "confidence": answer.confidence,
100
+ "probabilities": [answer.probabilities[level] for level in legend],
101
+ }
102
+
103
+
104
+ class NoulType(AnswerType):
105
+ kind = "noul"
106
+
107
+ def __init__(self):
108
+ super().__init__(pa.float64())
109
+
110
+ def pack(self, answer):
111
+ if not isinstance(answer, NoulAnswer):
112
+ raise ValueError("Expected a Noul answer")
113
+ return answer.noul
114
+
115
+
116
+ def schema_for(questions):
117
+ def answer_type(question):
118
+ if isinstance(question, Choice):
119
+ return ChoiceType(question.criteria)
120
+ if isinstance(question, Score):
121
+ return ScoreType(question.criteria)
122
+ if isinstance(question, Noul):
123
+ return NoulType()
124
+ raise TypeError("Unsupported question type")
125
+
126
+ return pa.schema([required(name, answer_type(q)) for name, q in questions.items()])
127
+
128
+
129
+ def answer_batch(schema, response):
130
+ if set(response.answers) != set(schema.names):
131
+ raise ValueError("Response answer names do not match the questions")
132
+ return pa.RecordBatch.from_arrays(
133
+ [field.type.array([response.answers[field.name]]) for field in schema], schema=schema,
134
+ )
135
+
136
+
137
+ class StreamSink(io.RawIOBase):
138
+ """Keep only the bytes since the last HTTP chunk, not the whole IPC stream."""
139
+
140
+ def __init__(self):
141
+ super().__init__()
142
+ self._chunks = []
143
+ self._position = 0
144
+
145
+ def writable(self):
146
+ return True
147
+
148
+ def tell(self):
149
+ return self._position
150
+
151
+ def write(self, data):
152
+ data = bytes(data)
153
+ self._chunks.append(data)
154
+ self._position += len(data)
155
+ return len(data)
156
+
157
+ def drain(self):
158
+ data = b"".join(self._chunks)
159
+ self._chunks.clear()
160
+ return data
@@ -0,0 +1,96 @@
1
+ Metadata-Version: 2.4
2
+ Name: jevaro-server
3
+ Version: 0.1.0
4
+ Summary: A small TypeSafe-to-Arrow streaming proxy
5
+ Author: Columnar Technologies Inc.
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/columnar-tech/jevaro
8
+ Project-URL: Documentation, https://github.com/columnar-tech/jevaro/blob/main/jevaro-server/README.md
9
+ Project-URL: Repository, https://github.com/columnar-tech/jevaro
10
+ Project-URL: Issues, https://github.com/columnar-tech/jevaro/issues
11
+ Requires-Python: >=3.11
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ License-File: NOTICE
15
+ Requires-Dist: fastapi<1,>=0.115
16
+ Requires-Dist: uvicorn<1,>=0.30
17
+ Requires-Dist: typesafe-sdk==0.7.2
18
+ Requires-Dist: pyarrow==25.0.1
19
+ Dynamic: license-file
20
+
21
+ # Jevaro server
22
+
23
+ A Python proxy that evaluates states with TypeSafe and streams the answers
24
+ as Arrow. See the [quickstart](https://github.com/columnar-tech/jevaro/blob/main/docs/quickstart.md)
25
+ for an example using both SDKs.
26
+
27
+ ## Run
28
+
29
+ Requires Python 3.11+.
30
+
31
+ ```sh
32
+ python3 -m venv .venv
33
+ .venv/bin/python -m pip install jevaro-server
34
+ export TYPESAFE_API_KEY="your-api-key"
35
+ .venv/bin/jevaro-server
36
+ ```
37
+
38
+ The default address is `http://127.0.0.1:8000`. Change it with `--host` and
39
+ `--port`. `python -m jevaro_server` runs the same command in an activated
40
+ environment.
41
+
42
+ ## Configuration
43
+
44
+ | Setting | Default | Purpose |
45
+ | --- | --- | --- |
46
+ | `--host` | `127.0.0.1` | Listen address |
47
+ | `--port` | `8000` | Listen port |
48
+ | `TYPESAFE_API_KEY` | Unset | Upstream key when a request has no bearer token |
49
+ | `TYPESAFE_UPSTREAM_URL` | `https://api.typesafe.ai` | Upstream API base URL |
50
+ | `JEVARO_CONCURRENCY` | `8` | Maximum pending calls/results per incoming request; positive integer |
51
+
52
+ An incoming `Authorization: Bearer <key>` overrides the server's key and is
53
+ forwarded to TypeSafe. A request without that header uses the server's key.
54
+ Jevaro has no separate client access control: keep it local, or put
55
+ authentication in front of a shared server.
56
+
57
+ `TYPESAFE_BASE_URL` is an SDK setting for reaching Jevaro. The server uses
58
+ `TYPESAFE_UPSTREAM_URL` to reach TypeSafe.
59
+
60
+ ## Streaming
61
+
62
+ `POST /v1/systemone` accepts `state` or a nonempty `states` array and a map of
63
+ questions. After validating the request, the server sends the schema and an
64
+ empty batch before starting upstream calls. Each later batch contains one
65
+ answer row, in input order.
66
+
67
+ The response uses `application/vnd.apache.arrow.stream` and has no
68
+ `Content-Length`. It sets `X-Accel-Buffering: no`; configure any reverse proxy
69
+ to pass the stream without buffering.
70
+
71
+ See the [HTTP API](https://github.com/columnar-tech/jevaro/blob/main/docs/http-api.md)
72
+ and [Arrow schema](https://github.com/columnar-tech/jevaro/blob/main/docs/arrow-schema.md)
73
+ for the request and result formats.
74
+
75
+ ## Limits
76
+
77
+ The full JSON request is held in memory. Pending calls and completed answers
78
+ waiting for their turn are bounded by `JEVARO_CONCURRENCY`. A slow earlier
79
+ call delays later rows. Closing the stream cancels pending work; calls already
80
+ processed upstream still count as API use.
81
+
82
+ Retries use the official TypeSafe SDK's default policy, including backoff for
83
+ 429 and 529 responses. Concurrency is per incoming request. This version has
84
+ no shared account rate limiter.
85
+
86
+ If an upstream call fails after retries, the HTTP stream aborts. Its status
87
+ is already 200 at that point. Readers must consume the stream successfully
88
+ before treating the result as complete.
89
+
90
+ ## Development
91
+
92
+ See [Contributing](https://github.com/columnar-tech/jevaro/blob/main/CONTRIBUTING.md)
93
+ for setup and tests. The server is independent of the earlier demo scripts.
94
+
95
+ [Apache-2.0](https://github.com/columnar-tech/jevaro/blob/main/LICENSE).
96
+ Copyright 2026 Columnar Technologies Inc.
@@ -0,0 +1,18 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ NOTICE
4
+ README.md
5
+ pyproject.toml
6
+ src/jevaro_server/__init__.py
7
+ src/jevaro_server/__main__.py
8
+ src/jevaro_server/app.py
9
+ src/jevaro_server/arrow.py
10
+ src/jevaro_server.egg-info/PKG-INFO
11
+ src/jevaro_server.egg-info/SOURCES.txt
12
+ src/jevaro_server.egg-info/dependency_links.txt
13
+ src/jevaro_server.egg-info/entry_points.txt
14
+ src/jevaro_server.egg-info/requires.txt
15
+ src/jevaro_server.egg-info/top_level.txt
16
+ tests/fake_upstream.py
17
+ tests/live_smoke.py
18
+ tests/test_proxy.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ jevaro-server = jevaro_server.__main__:main
@@ -0,0 +1,4 @@
1
+ fastapi<1,>=0.115
2
+ uvicorn<1,>=0.30
3
+ typesafe-sdk==0.7.2
4
+ pyarrow==25.0.1
@@ -0,0 +1 @@
1
+ jevaro_server
@@ -0,0 +1,91 @@
1
+ """Offline test fixture: real TypeSafe SDK over a mocked upstream transport."""
2
+
3
+ import asyncio
4
+ import json
5
+ import threading
6
+ from collections import Counter
7
+
8
+ import httpx2
9
+ from typesafe_sdk import AsyncTypeSafeClient, RetryPolicy
10
+
11
+ from jevaro_server.app import create_app
12
+
13
+
14
+ class Upstream:
15
+ def __init__(self):
16
+ self.started = []
17
+ self.finished = []
18
+ self.cancelled = []
19
+ self.attempts = Counter()
20
+ self.active = 0
21
+ self.peak = 0
22
+ self.auth_matches = []
23
+ self.gate = threading.Event()
24
+
25
+ def client(self, **kwargs):
26
+ return AsyncTypeSafeClient(
27
+ **kwargs, transport=httpx2.MockTransport(self.handle),
28
+ retry=RetryPolicy(backoff_initial=0.001, backoff_jitter=0),
29
+ )
30
+
31
+ async def handle(self, request):
32
+ payload = json.loads(request.content)
33
+ state = payload["state"]
34
+ config = state if isinstance(state, dict) else {}
35
+ number = config.get("id", 0)
36
+ self.started.append(state)
37
+ self.auth_matches.append(request.headers.get("Authorization") == "Bearer jevaro-test-key")
38
+ self.attempts[number] += 1
39
+ self.active += 1
40
+ self.peak = max(self.peak, self.active)
41
+ try:
42
+ if config.get("gate"):
43
+ while not self.gate.is_set():
44
+ await asyncio.sleep(0.005)
45
+ await asyncio.sleep(config.get("delay", 0))
46
+ statuses = config.get("statuses", [])
47
+ attempt = self.attempts[number] - 1
48
+ if attempt < len(statuses):
49
+ return httpx2.Response(statuses[attempt], json={"error": "test failure"},
50
+ headers={"retry-after-ms": "1"})
51
+ answers = {}
52
+ for name, question in payload["questions"].items():
53
+ kind = question["type"]
54
+ if kind == "noul":
55
+ answers[name] = {"type": kind, "noul": (number % 1000) / 1000}
56
+ elif kind == "choice":
57
+ labels = list(question["criteria"])
58
+ winner = labels[number % len(labels)]
59
+ answers[name] = {
60
+ "type": kind, "choice": winner, "confidence": 0.12345678901234567,
61
+ "probabilities": {label: float(label == winner) for label in labels},
62
+ }
63
+ else:
64
+ levels = question["criteria"]
65
+ answers[name] = {
66
+ "type": kind, "score": 0.9876543210987654,
67
+ "confidence": 0.23456789012345678,
68
+ "legend": dict(enumerate(levels)),
69
+ "probabilities": {str(i): 1 / len(levels) for i in range(len(levels))},
70
+ }
71
+ self.finished.append(number)
72
+ return httpx2.Response(200, json={
73
+ "answers": answers, "model": payload["model"],
74
+ "usage": {"input_tokens": 42, "output_tokens": 4},
75
+ })
76
+ except asyncio.CancelledError:
77
+ self.cancelled.append(number)
78
+ raise
79
+ finally:
80
+ self.active -= 1
81
+
82
+
83
+ upstream = Upstream()
84
+ app = create_app(client_factory=upstream.client, concurrency=3)
85
+
86
+
87
+ @app.get("/__test__/stats")
88
+ def stats():
89
+ return {"started": len(upstream.started), "finished": len(upstream.finished),
90
+ "cancelled": len(upstream.cancelled), "active": upstream.active,
91
+ "auth_matches": all(upstream.auth_matches)}
@@ -0,0 +1,66 @@
1
+ """Optional live check: three states through each SDK (six paid evaluations)."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+ import socket
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ import threading
10
+ import time
11
+
12
+ import pyarrow as pa
13
+ import uvicorn
14
+
15
+ from jevaro_server.app import create_app
16
+
17
+
18
+ def main():
19
+ if not os.environ.get("TYPESAFE_API_KEY"):
20
+ raise SystemExit("Set TYPESAFE_API_KEY before running the live smoke test")
21
+ root = Path(__file__).resolve().parents[2]
22
+ started = time.monotonic()
23
+ with socket.socket() as listener:
24
+ listener.bind(("127.0.0.1", 0))
25
+ base_url = f"http://127.0.0.1:{listener.getsockname()[1]}"
26
+ server = uvicorn.Server(uvicorn.Config(create_app(), log_level="warning", access_log=False))
27
+ thread = threading.Thread(target=server.run, kwargs={"sockets": [listener]}, daemon=True)
28
+ thread.start()
29
+ try:
30
+ deadline = time.monotonic() + 5
31
+ while not server.started:
32
+ if time.monotonic() > deadline:
33
+ raise RuntimeError("Server did not start")
34
+ time.sleep(0.01)
35
+ env = {**os.environ, "TYPESAFE_BASE_URL": base_url}
36
+ with tempfile.TemporaryDirectory(prefix="jevaro-smoke-") as directory:
37
+ output = Path(directory) / "results.arrows"
38
+ python = subprocess.run(
39
+ [sys.executable, str(root / "jevaro-python/example.py"), "--output", str(output)],
40
+ env=env, capture_output=True, text=True, timeout=90, check=True,
41
+ )
42
+ with pa.ipc.open_stream(output) as reader:
43
+ assert reader.read_all().num_rows == 3
44
+ decoded = subprocess.run(
45
+ [sys.executable, str(root / "scripts/read_results.py"), str(output)],
46
+ capture_output=True, text=True, timeout=10, check=True,
47
+ )
48
+ assert len(decoded.stdout.splitlines()) == 3
49
+ assert len(python.stdout.splitlines()) == 3
50
+ print("Python: 3 states streamed, saved as IPC, and decoded from schema metadata")
51
+ javascript = subprocess.run(
52
+ ["node", str(root / "jevaro-javascript/example.mjs")],
53
+ env=env, capture_output=True, text=True, timeout=90, check=True,
54
+ )
55
+ assert len(javascript.stdout.splitlines()) == 3
56
+ print("JavaScript: 3 states streamed and decoded using the schema's labels")
57
+ print(f"Six live evaluations passed in {time.monotonic() - started:.2f}s")
58
+ except subprocess.CalledProcessError as error:
59
+ raise RuntimeError(error.stderr) from error
60
+ finally:
61
+ server.should_exit = True
62
+ thread.join(timeout=10)
63
+
64
+
65
+ if __name__ == "__main__":
66
+ main()
@@ -0,0 +1,228 @@
1
+ import asyncio
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+ import socket
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ import threading
10
+ import time
11
+ import unittest
12
+ from unittest.mock import patch
13
+
14
+ import httpx2
15
+ import pyarrow as pa
16
+ import uvicorn
17
+ from jevaro import AsyncTypeSafeClient, Choice, Noul, Score, TypeSafeClient
18
+ from jevaro_server.app import create_app
19
+ from jevaro_server.arrow import schema_for
20
+
21
+ from fake_upstream import Upstream
22
+
23
+
24
+ QUESTIONS = {
25
+ "department": Choice(instructions="Which department?", criteria={"returns": None, "other": None}),
26
+ "urgency": Score(instructions="Urgency?", criteria=[{"when": "later"}, ["today"]]),
27
+ "refund": Noul(instructions="Refund?"),
28
+ }
29
+ RAW_QUESTIONS = {name: q.model_dump(mode="json") for name, q in QUESTIONS.items()}
30
+
31
+
32
+ class ProxyTests(unittest.TestCase):
33
+ def setUp(self):
34
+ self.upstream = Upstream()
35
+ self.socket = socket.socket()
36
+ self.socket.bind(("127.0.0.1", 0))
37
+ self.base_url = f"http://127.0.0.1:{self.socket.getsockname()[1]}"
38
+ self.server = uvicorn.Server(uvicorn.Config(
39
+ create_app(client_factory=self.upstream.client, concurrency=3),
40
+ log_level="critical", access_log=False,
41
+ ))
42
+ self.thread = threading.Thread(target=self.server.run, kwargs={"sockets": [self.socket]}, daemon=True)
43
+ self.thread.start()
44
+ self.until(lambda: self.server.started)
45
+ self.client = TypeSafeClient(api_key="jevaro-test-key", base_url=self.base_url)
46
+
47
+ def tearDown(self):
48
+ self.upstream.gate.set()
49
+ self.client.close()
50
+ self.server.should_exit = True
51
+ self.thread.join(timeout=5)
52
+ self.socket.close()
53
+ self.assertFalse(self.thread.is_alive(), "HTTP server failed to shut down")
54
+
55
+ def until(self, predicate):
56
+ deadline = time.monotonic() + 3
57
+ while not predicate():
58
+ if time.monotonic() >= deadline:
59
+ self.fail("Timed out waiting for test condition")
60
+ time.sleep(0.005)
61
+
62
+ def test_schema_before_any_answers_and_bounded_cancellation(self):
63
+ reader = self.client.system_one(states=[{"id": i, "gate": True} for i in range(1000)], questions=QUESTIONS)
64
+ self.assertIsInstance(reader, pa.RecordBatchReader)
65
+ self.assertEqual(reader.schema.names, list(QUESTIONS))
66
+ self.assertEqual(next(reader).num_rows, 0)
67
+ self.until(lambda: self.upstream.active == 3)
68
+ self.assertEqual(self.upstream.finished, [])
69
+ self.assertEqual(len(self.upstream.started), 3)
70
+ reader.close()
71
+ self.until(lambda: self.upstream.active == 0)
72
+ self.assertEqual(len(self.upstream.cancelled), 3)
73
+
74
+ def test_order_types_metadata_and_precision(self):
75
+ states = [{"id": i, "delay": 0.08 if i == 0 else 0.001} for i in range(7)]
76
+ with self.client.system_one(states=states, questions=QUESTIONS) as reader:
77
+ table = reader.read_all()
78
+ self.assertEqual(table.num_rows, 7)
79
+ self.assertEqual(table["refund"].to_pylist(), [i / 1000 for i in range(7)])
80
+ self.assertNotEqual(self.upstream.finished, list(range(7)))
81
+ self.assertLessEqual(self.upstream.peak, 3)
82
+ self.assertTrue(all(self.upstream.auth_matches))
83
+ self.assertIsNone(table.schema.metadata)
84
+ expected_metadata = {
85
+ "department": {"labels": ["returns", "other"]},
86
+ "urgency": {"legend": [{"when": "later"}, ["today"]]},
87
+ "refund": {},
88
+ }
89
+ for field in table.schema:
90
+ self.assertFalse(field.nullable)
91
+ metadata = json.loads(field.metadata[b"ARROW:extension:metadata"])
92
+ self.assertEqual(metadata, expected_metadata[field.name])
93
+ for field in schema_for(QUESTIONS):
94
+ extension = field.type
95
+ self.assertEqual(type(extension).__arrow_ext_deserialize__(
96
+ extension.storage_type, extension.__arrow_ext_serialize__(),
97
+ ), extension)
98
+ choice = table.schema.field("department")
99
+ self.assertEqual(choice.type.field("choice").type, pa.uint8())
100
+ self.assertFalse(choice.type.field("probabilities").nullable)
101
+ self.assertFalse(choice.type.field("probabilities").type.value_field.nullable)
102
+ self.assertEqual(choice.type.field("probabilities").type.list_size, 2)
103
+ self.assertEqual(table["department"][0].as_py()["confidence"], 0.12345678901234567)
104
+ self.assertEqual(table["urgency"][0].as_py()["score"], 0.9876543210987654)
105
+ self.assertEqual(json.loads(table.schema.field("urgency").metadata[b"ARROW:extension:metadata"])["legend"],
106
+ [{"when": "later"}, ["today"]])
107
+
108
+ def test_headers_and_single_array_state(self):
109
+ with httpx2.Client() as client:
110
+ with client.stream("POST", f"{self.base_url}/v1/systemone", headers={"Authorization": "Bearer jevaro-test-key"},
111
+ json={"state": ["a", "b"], "questions": RAW_QUESTIONS}) as response:
112
+ self.assertEqual(response.headers["content-type"], "application/vnd.apache.arrow.stream")
113
+ self.assertNotIn("content-length", response.headers)
114
+ self.assertEqual(response.headers["transfer-encoding"], "chunked")
115
+ self.assertEqual(response.headers["x-jevaro-row-count"], "1")
116
+ self.assertEqual(pa.ipc.open_stream(response.read()).read_all().num_rows, 1)
117
+ self.assertEqual(self.upstream.started, [["a", "b"]])
118
+
119
+ def test_validation_before_upstream_and_server_key_fallback(self):
120
+ with httpx2.Client(base_url=self.base_url) as client:
121
+ with patch.dict(os.environ, {"TYPESAFE_API_KEY": "jevaro-test-key"}):
122
+ good = client.post("/v1/systemone", json={"state": "one", "questions": RAW_QUESTIONS})
123
+ self.assertEqual(good.status_code, 200)
124
+ self.assertTrue(all(self.upstream.auth_matches))
125
+ self.upstream.started.clear()
126
+ for body in ({}, {"states": []}, {"states": None}, {"state": None}, {"states": "bad"},
127
+ {"states": [1]}, {"state": "a", "states": ["b"]}, {"state": "a", "extra": True}):
128
+ response = client.post("/v1/systemone", json={"questions": RAW_QUESTIONS, **body})
129
+ self.assertEqual(response.status_code, 422, body)
130
+ with patch.dict(os.environ, {"TYPESAFE_API_KEY": ""}):
131
+ response = client.post("/v1/systemone", json={"state": "a", "questions": RAW_QUESTIONS})
132
+ self.assertEqual(response.status_code, 401)
133
+ self.assertEqual(self.upstream.started, [])
134
+
135
+ def test_question_ids_have_no_reserved_names(self):
136
+ questions = {name: Noul(instructions="Refund?") for name in ("state", "model", "usage")}
137
+ with self.client.system_one(state="one", questions=questions) as reader:
138
+ self.assertEqual(reader.read_all().schema.names, list(questions))
139
+
140
+ def test_429_and_529_retry_in_place(self):
141
+ with self.client.system_one(states=[{"id": 11, "statuses": [429, 529]}, {"id": 12}], questions=QUESTIONS) as reader:
142
+ self.assertEqual(reader.read_all()["refund"].to_pylist(), [0.011, 0.012])
143
+ self.assertEqual(self.upstream.attempts[11], 3)
144
+
145
+ def test_failure_aborts_instead_of_finishing_a_partial_stream(self):
146
+ with self.client.system_one(states=[{"id": 0}, {"id": 1, "statuses": [401]}], questions=QUESTIONS) as reader:
147
+ self.assertEqual(next(reader).num_rows, 0)
148
+ self.assertEqual(next(reader).num_rows, 1)
149
+ with self.assertRaises((httpx2.HTTPError, OSError, pa.ArrowInvalid)):
150
+ next(reader)
151
+ self.assertEqual(self.upstream.attempts[1], 1)
152
+
153
+ def test_async_client(self):
154
+ async def run():
155
+ async with AsyncTypeSafeClient(api_key="jevaro-test-key", base_url=self.base_url) as client:
156
+ async with await client.system_one(states=[{"id": 7}, {"id": 8}], questions=QUESTIONS) as reader:
157
+ self.assertEqual(reader.schema.names, list(QUESTIONS))
158
+ table = await reader.read_all()
159
+ self.assertEqual(table["refund"].to_pylist(), [0.007, 0.008])
160
+ asyncio.run(run())
161
+
162
+ def test_async_cancellation_closes_http_and_upstream_work(self):
163
+ async def run():
164
+ async with AsyncTypeSafeClient(api_key="jevaro-test-key", base_url=self.base_url, timeout=2) as client:
165
+ async with await client.system_one(state={"id": 9, "gate": True}, questions=QUESTIONS) as reader:
166
+ await reader.read_next_batch()
167
+ reading = asyncio.create_task(reader.read_next_batch())
168
+ await asyncio.sleep(0.03)
169
+ started = time.monotonic()
170
+ reading.cancel()
171
+ with self.assertRaises(asyncio.CancelledError):
172
+ await reading
173
+ self.assertLess(time.monotonic() - started, 1.0, "Cancellation waited for the read timeout")
174
+ while self.upstream.active and time.monotonic() - started < 1:
175
+ await asyncio.sleep(0.005)
176
+ self.assertEqual(self.upstream.active, 0, "Upstream work survived cancellation")
177
+ asyncio.run(run())
178
+ self.until(lambda: self.upstream.active == 0)
179
+ self.assertEqual(self.upstream.cancelled, [9])
180
+
181
+ def test_javascript_sdk_over_http(self):
182
+ javascript = Path(__file__).resolve().parents[2] / "jevaro-javascript"
183
+ result = subprocess.run(
184
+ ["node", "--test", "test/integration.test.cjs"], cwd=javascript,
185
+ env={**os.environ, "JEVARO_TEST_URL": self.base_url},
186
+ capture_output=True, text=True, timeout=20,
187
+ )
188
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
189
+ self.until(lambda: self.upstream.active == 0)
190
+ self.assertTrue(all(self.upstream.auth_matches))
191
+
192
+ def test_examples_save_and_decode(self):
193
+ root = Path(__file__).resolve().parents[2]
194
+ env = {**os.environ, "TYPESAFE_BASE_URL": self.base_url,
195
+ "TYPESAFE_API_KEY": "jevaro-test-key"}
196
+ with tempfile.TemporaryDirectory(prefix="jevaro-example-") as directory:
197
+ output = Path(directory) / "results.arrows"
198
+ result = subprocess.run(
199
+ [sys.executable, str(root / "jevaro-python/example.py"), "--output", str(output)],
200
+ env=env, capture_output=True, text=True, timeout=20,
201
+ )
202
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
203
+ self.assertEqual(len(result.stdout.splitlines()), 3)
204
+ with pa.ipc.open_stream(output) as reader:
205
+ self.assertEqual(reader.read_all().num_rows, 3)
206
+ decoded = subprocess.run(
207
+ [sys.executable, str(root / "scripts/read_results.py"), str(output)],
208
+ capture_output=True, text=True, timeout=10,
209
+ )
210
+ self.assertEqual(decoded.returncode, 0, decoded.stderr)
211
+ rows = [json.loads(line) for line in decoded.stdout.splitlines()]
212
+ self.assertEqual(len(rows), 3)
213
+ self.assertEqual(rows[0]["department"]["choice"], "returns")
214
+ self.assertEqual(rows[0]["urgency"]["score"], 0.9876543210987654)
215
+ self.assertEqual(rows[0]["refund"], {"type": "noul", "noul": 0.0})
216
+ result = subprocess.run(
217
+ ["node", str(root / "jevaro-javascript/example.mjs")],
218
+ env=env, capture_output=True, text=True, timeout=20,
219
+ )
220
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
221
+ rows = [json.loads(line) for line in result.stdout.splitlines()]
222
+ self.assertEqual(len(rows), 3)
223
+ self.assertEqual(rows[0]["department"], "returns")
224
+ self.assertTrue(all(self.upstream.auth_matches))
225
+
226
+
227
+ if __name__ == "__main__":
228
+ unittest.main()