reef-client 0.2.0__tar.gz → 0.3.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.
Files changed (23) hide show
  1. {reef_client-0.2.0/reef_client.egg-info → reef_client-0.3.0}/PKG-INFO +48 -1
  2. reef_client-0.3.0/README.md +93 -0
  3. {reef_client-0.2.0 → reef_client-0.3.0}/pyproject.toml +4 -1
  4. {reef_client-0.2.0 → reef_client-0.3.0}/reef_client/__init__.py +2 -1
  5. reef_client-0.3.0/reef_client/__main__.py +27 -0
  6. reef_client-0.3.0/reef_client/record_import.py +284 -0
  7. {reef_client-0.2.0 → reef_client-0.3.0}/reef_client/serve.py +10 -1
  8. {reef_client-0.2.0 → reef_client-0.3.0/reef_client.egg-info}/PKG-INFO +48 -1
  9. {reef_client-0.2.0 → reef_client-0.3.0}/reef_client.egg-info/SOURCES.txt +5 -0
  10. reef_client-0.3.0/reef_client.egg-info/entry_points.txt +2 -0
  11. reef_client-0.3.0/tests/test_https_upstream.py +91 -0
  12. reef_client-0.3.0/tests/test_record_import.py +175 -0
  13. reef_client-0.2.0/README.md +0 -46
  14. {reef_client-0.2.0 → reef_client-0.3.0}/LICENSE +0 -0
  15. {reef_client-0.2.0 → reef_client-0.3.0}/reef_client/client.py +0 -0
  16. {reef_client-0.2.0 → reef_client-0.3.0}/reef_client/skill.py +0 -0
  17. {reef_client-0.2.0 → reef_client-0.3.0}/reef_client/sse.py +0 -0
  18. {reef_client-0.2.0 → reef_client-0.3.0}/reef_client.egg-info/dependency_links.txt +0 -0
  19. {reef_client-0.2.0 → reef_client-0.3.0}/reef_client.egg-info/top_level.txt +0 -0
  20. {reef_client-0.2.0 → reef_client-0.3.0}/setup.cfg +0 -0
  21. {reef_client-0.2.0 → reef_client-0.3.0}/tests/test_client_disconnects.py +0 -0
  22. {reef_client-0.2.0 → reef_client-0.3.0}/tests/test_sse_receipt.py +0 -0
  23. {reef_client-0.2.0 → reef_client-0.3.0}/tests/test_streaming_head.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: reef-client
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Stdlib-only client SDK for the Reef protocol
5
5
  Author: Human-Agent-Society
6
6
  License-Expression: Apache-2.0
@@ -61,3 +61,50 @@ pip install -e .
61
61
 
62
62
  The package is standard library only — copying the inner `reef_client/`
63
63
  directory into your harness works too.
64
+
65
+ ## Import existing records
66
+
67
+ Run the importer on the machine holding your data, pointing it at a running
68
+ Reef service that supports `POST /reef/records/batch`:
69
+
70
+ ```bash
71
+ reef-client import records.jsonl --url https://reef.example.com --scenario my-agent
72
+ # Also works without a console-script installation:
73
+ python -m reef_client import records.jsonl --url https://reef.example.com --scenario my-agent
74
+ ```
75
+
76
+ No `reef-infra`, training libraries, or third-party HTTP client is required.
77
+ Authentication is read from `REEF_TOKEN` when set.
78
+
79
+ Each UTF-8 JSONL line is an existing record envelope. IDs must stay stable and
80
+ reports must follow their referenced inferences:
81
+
82
+ ```jsonl
83
+ {"agent_record_id":"sample-1","request_type":"inference","payload":{"messages":[{"role":"user","content":"2+2?"}],"response":{"choices":[{"message":{"role":"assistant","content":"4"}}]}}}
84
+ {"agent_record_id":"score-1","request_type":"report","payload":{"references":["sample-1"],"score":1}}
85
+ ```
86
+
87
+ The selected server recipe determines which inference payload and feedback fields
88
+ it needs. The importer preserves IDs and payloads; it does not run inference or
89
+ convert arbitrary dataset schemas.
90
+
91
+ - Reads incrementally, limiting each request by `--batch-size` (default 128)
92
+ and `--max-batch-bytes` (default 524288). Requests must stay below 1 MiB and
93
+ contain at most 1000 records. Each source line must fit the byte limit.
94
+ - Reuses the HTTP connection and retries transient failures with backoff
95
+ (`--retries`, default 3). It sends unchanged record IDs on retry.
96
+ - Saves acknowledged byte offsets to `FILE.reef-import.json`, or `--progress PATH`.
97
+ Re-run the same command after interruption. A full bounded-memory checksum pass
98
+ verifies the source on each invocation before seeking to saved progress.
99
+ - Binds the checkpoint to the file checksum, service URL and scenario, and locks
100
+ it against concurrent importers. Keep the source immutable. Checkpoints contain
101
+ no token or record payloads. POSIX file locking requires Linux/macOS.
102
+ - Stops on permanent failures without advancing the failed batch's checkpoint.
103
+ Previously acknowledged batches remain stored. Lost responses can be retried
104
+ safely because the server deduplicates stable record IDs.
105
+
106
+ Python callers can use `reef_client.record_import.import_records_file(Path(...),
107
+ url=..., scenario=...)`. It returns the cumulative number of acknowledged source
108
+ rows, including existing records; it does not count completed training samples.
109
+ After import, continue sending chat/report traffic to the same scenario.
110
+ Import completion means records were acknowledged, not that training has finished.
@@ -0,0 +1,93 @@
1
+ # reef_client
2
+
3
+ Stdlib-only client SDK for the [Reef](https://github.com/Human-Agent-Society/reef) protocol. `reef_client` is a client of
4
+ Reef's HTTP wire protocol, not of the `reef` package: it never imports `reef`
5
+ and has no dependencies, so external harnesses can install it or copy it into
6
+ environments that cannot take the `reef` wheel's dependencies.
7
+
8
+ The distribution is `reef-client` ([`pyproject.toml`](pyproject.toml)); the
9
+ import package is the inner [`reef_client/`](reef_client) directory:
10
+
11
+ - [`client.py`](reef_client/client.py) is `ReefClient`, the
12
+ ask/observe/report loop every example shares (see the
13
+ [Reef docs](https://github.com/Human-Agent-Society/reef/blob/main/docs/reference/reef-client.md)),
14
+ plus the harness update channel reads: `harness_versions` (the version
15
+ catalog with gate metrics) and `harness_pull` (write one served tree, head
16
+ or version-addressed, into a directory).
17
+ - [`skill.py`](reef_client/skill.py) fetches and syncs the scenario's served
18
+ skill file (`fetch_skill`/`sync_skill`);
19
+ - [`sse.py`](reef_client/sse.py) converts between buffered chat completions
20
+ and OpenAI-style SSE chunk streams in both directions
21
+ (`synthesize_sse_events` / `SSEAccumulator`).
22
+ - [`serve.py`](reef_client/serve.py) is serve mode: a local sidecar that
23
+ agents treat as their model endpoint (`python -m reef_client.serve`),
24
+ owning session stamping, trajectory capture, receipt collection, and SSE
25
+ passthrough/synthesis so reef-oblivious agents need no SDK. See the
26
+ [reference](https://github.com/Human-Agent-Society/reef/blob/main/docs/reference/reef-client.md#serve-mode-a-local-proxy-for-reef-oblivious-agents).
27
+
28
+ The client and skill helpers are re-exported at the package root:
29
+ `from reef_client import ReefClient, fetch_skill, sync_skill`. Import the
30
+ `sse`/`serve` submodules directly.
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ pip install reef-client
36
+ ```
37
+
38
+ For development:
39
+
40
+ ```bash
41
+ git clone https://github.com/Human-Agent-Society/reef-client && cd reef-client
42
+ pip install -e .
43
+ ```
44
+
45
+ The package is standard library only — copying the inner `reef_client/`
46
+ directory into your harness works too.
47
+
48
+ ## Import existing records
49
+
50
+ Run the importer on the machine holding your data, pointing it at a running
51
+ Reef service that supports `POST /reef/records/batch`:
52
+
53
+ ```bash
54
+ reef-client import records.jsonl --url https://reef.example.com --scenario my-agent
55
+ # Also works without a console-script installation:
56
+ python -m reef_client import records.jsonl --url https://reef.example.com --scenario my-agent
57
+ ```
58
+
59
+ No `reef-infra`, training libraries, or third-party HTTP client is required.
60
+ Authentication is read from `REEF_TOKEN` when set.
61
+
62
+ Each UTF-8 JSONL line is an existing record envelope. IDs must stay stable and
63
+ reports must follow their referenced inferences:
64
+
65
+ ```jsonl
66
+ {"agent_record_id":"sample-1","request_type":"inference","payload":{"messages":[{"role":"user","content":"2+2?"}],"response":{"choices":[{"message":{"role":"assistant","content":"4"}}]}}}
67
+ {"agent_record_id":"score-1","request_type":"report","payload":{"references":["sample-1"],"score":1}}
68
+ ```
69
+
70
+ The selected server recipe determines which inference payload and feedback fields
71
+ it needs. The importer preserves IDs and payloads; it does not run inference or
72
+ convert arbitrary dataset schemas.
73
+
74
+ - Reads incrementally, limiting each request by `--batch-size` (default 128)
75
+ and `--max-batch-bytes` (default 524288). Requests must stay below 1 MiB and
76
+ contain at most 1000 records. Each source line must fit the byte limit.
77
+ - Reuses the HTTP connection and retries transient failures with backoff
78
+ (`--retries`, default 3). It sends unchanged record IDs on retry.
79
+ - Saves acknowledged byte offsets to `FILE.reef-import.json`, or `--progress PATH`.
80
+ Re-run the same command after interruption. A full bounded-memory checksum pass
81
+ verifies the source on each invocation before seeking to saved progress.
82
+ - Binds the checkpoint to the file checksum, service URL and scenario, and locks
83
+ it against concurrent importers. Keep the source immutable. Checkpoints contain
84
+ no token or record payloads. POSIX file locking requires Linux/macOS.
85
+ - Stops on permanent failures without advancing the failed batch's checkpoint.
86
+ Previously acknowledged batches remain stored. Lost responses can be retried
87
+ safely because the server deduplicates stable record IDs.
88
+
89
+ Python callers can use `reef_client.record_import.import_records_file(Path(...),
90
+ url=..., scenario=...)`. It returns the cumulative number of acknowledged source
91
+ rows, including existing records; it does not count completed training samples.
92
+ After import, continue sending chat/report traffic to the same scenario.
93
+ Import completion means records were acknowledged, not that training has finished.
@@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta"
6
6
 
7
7
  [project]
8
8
  name = "reef-client"
9
- version = "0.2.0"
9
+ version = "0.3.0"
10
10
  description = "Stdlib-only client SDK for the Reef protocol"
11
11
  readme = "README.md"
12
12
  license = "Apache-2.0"
@@ -23,6 +23,9 @@ classifiers = [
23
23
  # dependencies. Keep this list empty.
24
24
  dependencies = []
25
25
 
26
+ [project.scripts]
27
+ reef-client = "reef_client.__main__:main"
28
+
26
29
  [project.urls]
27
30
  Homepage = "https://github.com/Human-Agent-Society/reef-client"
28
31
  Repository = "https://github.com/Human-Agent-Society/reef-client"
@@ -2,7 +2,8 @@
2
2
 
3
3
  Components: ``client`` (the ask/observe/report loop), ``skill`` (fetch and
4
4
  sync the served skill file), ``sse`` (stream synthesis/accumulation), and
5
- ``serve`` (a local sidecar agents treat as their model endpoint).
5
+ ``serve`` (a local sidecar agents treat as their model endpoint), and
6
+ ``record_import`` (resumable uploads of existing records).
6
7
  Everything is standard library only, so external harnesses can copy or
7
8
  import the package with no dependency on the ``reef`` package.
8
9
 
@@ -0,0 +1,27 @@
1
+ """Commands run on the user machine against a remote Reef service."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from collections.abc import Sequence
8
+
9
+
10
+ def main(argv: Sequence[str] | None = None) -> None:
11
+ arguments = list(sys.argv[1:] if argv is None else argv)
12
+ if arguments and arguments[0] == "import":
13
+ from reef_client.record_import import main as import_main
14
+
15
+ import_main(arguments[1:])
16
+ return
17
+ parser = argparse.ArgumentParser(prog="reef-client", description=__doc__)
18
+ parser.add_argument(
19
+ "command",
20
+ choices=("import",),
21
+ help="import a records JSONL file with resumable batch uploads",
22
+ )
23
+ parser.parse_args(arguments)
24
+
25
+
26
+ if __name__ == "__main__":
27
+ main()
@@ -0,0 +1,284 @@
1
+ """Stream a records JSONL file into Reef with bounded batches and resume state."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import fcntl
7
+ import hashlib
8
+ import http.client
9
+ import json
10
+ import os
11
+ import sys
12
+ import time
13
+ from collections.abc import Iterator, Mapping, Sequence
14
+ from contextlib import closing
15
+ from pathlib import Path
16
+ from typing import BinaryIO
17
+ from urllib.parse import urlsplit
18
+
19
+
20
+ def record_batches(
21
+ source: BinaryIO, *, batch_size: int, max_bytes: int
22
+ ) -> Iterator[tuple[bytes, int, int]]:
23
+ """Yield encoded requests, end byte offsets and record counts, with at most one record of look-ahead."""
24
+ prefix, suffix = b'{"records":[', b"]}"
25
+ records: list[bytes] = []
26
+ body_bytes = len(prefix) + len(suffix)
27
+ end_offset = source.tell()
28
+ while line := source.readline(max_bytes + 1):
29
+ if len(line) > max_bytes:
30
+ raise ValueError(
31
+ f"JSONL record at byte {end_offset} exceeds the batch byte limit"
32
+ )
33
+ if not line.strip():
34
+ end_offset = source.tell()
35
+ continue
36
+ try:
37
+ record = json.loads(line)
38
+ except (ValueError, UnicodeDecodeError) as exc:
39
+ raise ValueError(f"invalid JSONL record at byte {end_offset}") from exc
40
+ if not isinstance(record, dict):
41
+ raise ValueError(f"JSONL record at byte {end_offset} must be an object")
42
+ encoded = json.dumps(
43
+ record, ensure_ascii=False, separators=(",", ":"), allow_nan=False
44
+ ).encode("utf-8")
45
+ if len(prefix) + len(encoded) + len(suffix) > max_bytes:
46
+ raise ValueError(
47
+ f"JSONL record at byte {end_offset} exceeds the batch byte limit"
48
+ )
49
+ extra_bytes = len(encoded) + bool(records)
50
+ if records and (
51
+ len(records) == batch_size or body_bytes + extra_bytes > max_bytes
52
+ ):
53
+ yield prefix + b",".join(records) + suffix, end_offset, len(records)
54
+ records = []
55
+ body_bytes = len(prefix) + len(suffix)
56
+ records.append(encoded)
57
+ body_bytes += len(encoded) + (len(records) > 1)
58
+ end_offset = source.tell()
59
+ if records:
60
+ yield prefix + b",".join(records) + suffix, end_offset, len(records)
61
+
62
+
63
+ def upload_batch(
64
+ connection: http.client.HTTPConnection,
65
+ path: str,
66
+ headers: Mapping[str, str],
67
+ body: bytes,
68
+ *,
69
+ scenario: str,
70
+ max_retries: int,
71
+ ) -> None:
72
+ """Retry transient failures with unchanged IDs; require every record receipt."""
73
+ expected = [
74
+ {
75
+ "agent_record_id": record["agent_record_id"],
76
+ "request_type": record["request_type"],
77
+ "scenario": scenario,
78
+ }
79
+ for record in json.loads(body)["records"]
80
+ ]
81
+ for attempt in range(max_retries + 1):
82
+ delay_seconds = min(2**attempt, 30)
83
+ try:
84
+ connection.request("POST", path, body=body, headers=dict(headers))
85
+ response = connection.getresponse()
86
+ response_body = response.read()
87
+ if response.status == 200:
88
+ result = json.loads(response_body)
89
+ if not isinstance(result, dict) or result.get("records") != expected:
90
+ raise ValueError(
91
+ "batch response did not acknowledge the submitted records"
92
+ )
93
+ return
94
+ if (
95
+ response.status not in (408, 429, 500, 502, 503, 504)
96
+ or attempt == max_retries
97
+ ):
98
+ raise ValueError(
99
+ f"batch rejected with HTTP {response.status}; import progress was not advanced"
100
+ )
101
+ retry_after = response.getheader("Retry-After", "")
102
+ if retry_after.isdecimal():
103
+ delay_seconds = min(int(retry_after), 60)
104
+ except (OSError, http.client.HTTPException):
105
+ connection.close()
106
+ if attempt == max_retries:
107
+ raise
108
+ time.sleep(delay_seconds)
109
+
110
+
111
+ def save_progress(path: Path, state: dict[str, object]) -> None:
112
+ temporary = path.with_name(path.name + ".tmp")
113
+ with temporary.open("w") as target:
114
+ json.dump(state, target)
115
+ target.flush()
116
+ os.fsync(target.fileno())
117
+ temporary.replace(path)
118
+
119
+
120
+ def import_records_file(
121
+ source_path: Path,
122
+ *,
123
+ url: str,
124
+ scenario: str,
125
+ progress_path: Path | None = None,
126
+ token: str | None = None,
127
+ batch_size: int = 128,
128
+ max_batch_bytes: int = 512 * 1024,
129
+ max_retries: int = 3,
130
+ ) -> int:
131
+ """Import immutable JSONL records; return the cumulative acknowledged count.
132
+
133
+ A local checkpoint is bound to the file checksum, destination and scenario.
134
+ It advances only after a whole batch is acknowledged. An interrupted batch
135
+ is resent with the source IDs, so server-side deduplication handles a lost
136
+ response. Concurrent use of the same checkpoint is rejected.
137
+ """
138
+ url = url.rstrip("/")
139
+ destination = urlsplit(url)
140
+ if destination.scheme not in ("http", "https") or not destination.hostname:
141
+ raise ValueError("url must be an HTTP(S) Reef base URL")
142
+ if (
143
+ destination.username
144
+ or destination.password
145
+ or destination.query
146
+ or destination.fragment
147
+ ):
148
+ raise ValueError(
149
+ "url must not contain credentials, a query or a fragment; use REEF_TOKEN"
150
+ )
151
+ scenario = scenario.strip()
152
+ if not scenario:
153
+ raise ValueError("scenario must not be empty")
154
+ if (
155
+ not 1 <= batch_size <= 1000
156
+ or not 128 <= max_batch_bytes < 1024 * 1024
157
+ or max_retries < 0
158
+ ):
159
+ raise ValueError(
160
+ "require batch-size 1..1000, max-batch-bytes 128..1048575 and nonnegative retries"
161
+ )
162
+ source_path = source_path.resolve()
163
+ progress_path = (
164
+ progress_path or source_path.with_name(source_path.name + ".reef-import.json")
165
+ ).resolve()
166
+ lock_path = progress_path.with_name(progress_path.name + ".lock")
167
+ if source_path in (
168
+ progress_path,
169
+ lock_path,
170
+ progress_path.with_name(progress_path.name + ".tmp"),
171
+ ):
172
+ raise ValueError("progress files must not overwrite the source")
173
+ with lock_path.open("a") as lock, source_path.open("rb") as source:
174
+ try:
175
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
176
+ except BlockingIOError as exc:
177
+ raise ValueError("another importer is using this progress file") from exc
178
+ initial_stat = os.fstat(source.fileno())
179
+ digest = hashlib.sha256()
180
+ while chunk := source.read(1024 * 1024):
181
+ digest.update(chunk)
182
+ checksum = digest.hexdigest()
183
+ identity = {
184
+ "version": 1,
185
+ "sha256": checksum,
186
+ "url": url,
187
+ "scenario": scenario,
188
+ "size": initial_stat.st_size,
189
+ }
190
+ offset = count = 0
191
+ if progress_path.exists():
192
+ state = json.loads(progress_path.read_text())
193
+ if not isinstance(state, dict) or any(
194
+ state.get(key) != value for key, value in identity.items()
195
+ ):
196
+ raise ValueError(
197
+ "progress belongs to a different file, destination or scenario"
198
+ )
199
+ saved_offset, saved_count = state.get("offset"), state.get("count")
200
+ if (
201
+ type(saved_offset) is not int
202
+ or type(saved_count) is not int
203
+ or not 0 <= saved_offset <= initial_stat.st_size
204
+ or saved_count < 0
205
+ ):
206
+ raise ValueError("invalid import progress")
207
+ offset, count = saved_offset, saved_count
208
+ source.seek(offset)
209
+ save_progress(progress_path, {**identity, "offset": offset, "count": count})
210
+ headers = {"x-reef-scenario": scenario, "Content-Type": "application/json"}
211
+ if token:
212
+ headers["Authorization"] = f"Bearer {token}"
213
+ connection_type = (
214
+ http.client.HTTPSConnection
215
+ if destination.scheme == "https"
216
+ else http.client.HTTPConnection
217
+ )
218
+ with closing(
219
+ connection_type(destination.hostname, destination.port, timeout=60)
220
+ ) as connection:
221
+ for body, end_offset, batch_count in record_batches(
222
+ source, batch_size=batch_size, max_bytes=max_batch_bytes
223
+ ):
224
+ current_stat = os.fstat(source.fileno())
225
+ if (current_stat.st_size, current_stat.st_mtime_ns) != (
226
+ initial_stat.st_size,
227
+ initial_stat.st_mtime_ns,
228
+ ):
229
+ raise ValueError("source file changed during import")
230
+ try:
231
+ upload_batch(
232
+ connection,
233
+ destination.path + "/reef/records/batch",
234
+ headers,
235
+ body,
236
+ scenario=scenario,
237
+ max_retries=max_retries,
238
+ )
239
+ except (ValueError, KeyError) as exc:
240
+ raise ValueError(f"import stopped at byte {offset}: {exc}") from exc
241
+ offset = end_offset
242
+ count += batch_count
243
+ save_progress(
244
+ progress_path, {**identity, "offset": offset, "count": count}
245
+ )
246
+ print(
247
+ f"Acknowledged {count} records ({offset}/{initial_stat.st_size} bytes)",
248
+ file=sys.stderr,
249
+ )
250
+ return count
251
+
252
+
253
+ def main(argv: Sequence[str] | None = None) -> None:
254
+ parser = argparse.ArgumentParser(prog="reef-client import", description=__doc__)
255
+ parser.add_argument(
256
+ "file", type=Path, help="JSONL file containing one record envelope per line"
257
+ )
258
+ parser.add_argument("--url", required=True, help="Reef service base URL")
259
+ parser.add_argument("--scenario", required=True)
260
+ parser.add_argument(
261
+ "--progress",
262
+ type=Path,
263
+ help="checkpoint path; defaults to FILE.reef-import.json",
264
+ )
265
+ parser.add_argument("--batch-size", type=int, default=128)
266
+ parser.add_argument("--max-batch-bytes", type=int, default=512 * 1024)
267
+ parser.add_argument("--retries", type=int, default=3)
268
+ args = parser.parse_args(argv)
269
+ try:
270
+ count = import_records_file(
271
+ args.file,
272
+ url=args.url,
273
+ scenario=args.scenario,
274
+ progress_path=args.progress,
275
+ token=os.environ.get("REEF_TOKEN"),
276
+ batch_size=args.batch_size,
277
+ max_batch_bytes=args.max_batch_bytes,
278
+ max_retries=args.retries,
279
+ )
280
+ except (OSError, ValueError, http.client.HTTPException) as exc:
281
+ parser.exit(1, f"reef-client import: {exc}\n")
282
+ print(
283
+ f"Import complete: {count} records acknowledged. Training may still be running."
284
+ )
@@ -172,6 +172,8 @@ class ServeConfig:
172
172
  def __post_init__(self) -> None:
173
173
  if not self.upstream:
174
174
  raise ValueError("upstream must be non-empty")
175
+ if urlsplit(self.upstream).scheme not in ("http", "https"):
176
+ raise ValueError(f"upstream must be an http or https URL, got {self.upstream!r}")
175
177
 
176
178
 
177
179
  def build_handler(config: ServeConfig, store: CaptureStore) -> type[BaseHTTPRequestHandler]:
@@ -368,7 +370,14 @@ def build_handler(config: ServeConfig, store: CaptureStore) -> type[BaseHTTPRequ
368
370
  if client_stream:
369
371
  self._begin_sse()
370
372
 
371
- conn = http.client.HTTPConnection(parsed.hostname, parsed.port, timeout=config.timeout_s)
373
+ # The upstream's own scheme: an https upstream (the API platform) over a plain connection is
374
+ # answered with a redirect and an empty body, which the agent sees as an empty completion.
375
+ if parsed.scheme == "https":
376
+ conn: http.client.HTTPConnection = http.client.HTTPSConnection(
377
+ parsed.hostname, parsed.port, timeout=config.timeout_s
378
+ )
379
+ else:
380
+ conn = http.client.HTTPConnection(parsed.hostname, parsed.port, timeout=config.timeout_s)
372
381
  started = time.monotonic()
373
382
  try:
374
383
  conn.request(self.command, forward_path, body=forward_body, headers=headers)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: reef-client
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Stdlib-only client SDK for the Reef protocol
5
5
  Author: Human-Agent-Society
6
6
  License-Expression: Apache-2.0
@@ -61,3 +61,50 @@ pip install -e .
61
61
 
62
62
  The package is standard library only — copying the inner `reef_client/`
63
63
  directory into your harness works too.
64
+
65
+ ## Import existing records
66
+
67
+ Run the importer on the machine holding your data, pointing it at a running
68
+ Reef service that supports `POST /reef/records/batch`:
69
+
70
+ ```bash
71
+ reef-client import records.jsonl --url https://reef.example.com --scenario my-agent
72
+ # Also works without a console-script installation:
73
+ python -m reef_client import records.jsonl --url https://reef.example.com --scenario my-agent
74
+ ```
75
+
76
+ No `reef-infra`, training libraries, or third-party HTTP client is required.
77
+ Authentication is read from `REEF_TOKEN` when set.
78
+
79
+ Each UTF-8 JSONL line is an existing record envelope. IDs must stay stable and
80
+ reports must follow their referenced inferences:
81
+
82
+ ```jsonl
83
+ {"agent_record_id":"sample-1","request_type":"inference","payload":{"messages":[{"role":"user","content":"2+2?"}],"response":{"choices":[{"message":{"role":"assistant","content":"4"}}]}}}
84
+ {"agent_record_id":"score-1","request_type":"report","payload":{"references":["sample-1"],"score":1}}
85
+ ```
86
+
87
+ The selected server recipe determines which inference payload and feedback fields
88
+ it needs. The importer preserves IDs and payloads; it does not run inference or
89
+ convert arbitrary dataset schemas.
90
+
91
+ - Reads incrementally, limiting each request by `--batch-size` (default 128)
92
+ and `--max-batch-bytes` (default 524288). Requests must stay below 1 MiB and
93
+ contain at most 1000 records. Each source line must fit the byte limit.
94
+ - Reuses the HTTP connection and retries transient failures with backoff
95
+ (`--retries`, default 3). It sends unchanged record IDs on retry.
96
+ - Saves acknowledged byte offsets to `FILE.reef-import.json`, or `--progress PATH`.
97
+ Re-run the same command after interruption. A full bounded-memory checksum pass
98
+ verifies the source on each invocation before seeking to saved progress.
99
+ - Binds the checkpoint to the file checksum, service URL and scenario, and locks
100
+ it against concurrent importers. Keep the source immutable. Checkpoints contain
101
+ no token or record payloads. POSIX file locking requires Linux/macOS.
102
+ - Stops on permanent failures without advancing the failed batch's checkpoint.
103
+ Previously acknowledged batches remain stored. Lost responses can be retried
104
+ safely because the server deduplicates stable record IDs.
105
+
106
+ Python callers can use `reef_client.record_import.import_records_file(Path(...),
107
+ url=..., scenario=...)`. It returns the cumulative number of acknowledged source
108
+ rows, including existing records; it does not count completed training samples.
109
+ After import, continue sending chat/report traffic to the same scenario.
110
+ Import completion means records were acknowledged, not that training has finished.
@@ -2,14 +2,19 @@ LICENSE
2
2
  README.md
3
3
  pyproject.toml
4
4
  reef_client/__init__.py
5
+ reef_client/__main__.py
5
6
  reef_client/client.py
7
+ reef_client/record_import.py
6
8
  reef_client/serve.py
7
9
  reef_client/skill.py
8
10
  reef_client/sse.py
9
11
  reef_client.egg-info/PKG-INFO
10
12
  reef_client.egg-info/SOURCES.txt
11
13
  reef_client.egg-info/dependency_links.txt
14
+ reef_client.egg-info/entry_points.txt
12
15
  reef_client.egg-info/top_level.txt
13
16
  tests/test_client_disconnects.py
17
+ tests/test_https_upstream.py
18
+ tests/test_record_import.py
14
19
  tests/test_sse_receipt.py
15
20
  tests/test_streaming_head.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ reef-client = reef_client.__main__:main
@@ -0,0 +1,91 @@
1
+ """An https upstream is reached over TLS, not over a plain connection to its host.
2
+
3
+ The API platform serves reef behind https. A plain connection to that host is
4
+ answered with a redirect to https and no body, which serve relayed as an empty
5
+ completion; the agent then reported an empty upstream response for every call.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import http.client
11
+ import json
12
+ import socket
13
+ import threading
14
+ from http.server import ThreadingHTTPServer
15
+
16
+ import pytest
17
+
18
+ from reef_client.serve import CaptureStore, ServeConfig, build_handler
19
+
20
+
21
+ def _serve(upstream_url: str) -> ThreadingHTTPServer:
22
+ proxy = ThreadingHTTPServer(("127.0.0.1", 0), build_handler(ServeConfig(upstream=upstream_url, listen_port=0), CaptureStore()))
23
+ threading.Thread(target=proxy.serve_forever, daemon=True).start()
24
+ return proxy
25
+
26
+
27
+ def _post(port: int) -> bytes:
28
+ body = json.dumps({"model": "m", "messages": [{"role": "user", "content": "hi"}]})
29
+ raw = socket.create_connection(("127.0.0.1", port))
30
+ raw.sendall(
31
+ f"POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\n"
32
+ f"Content-Length: {len(body)}\r\nConnection: close\r\n\r\n".encode()
33
+ + body.encode()
34
+ )
35
+ raw.settimeout(10)
36
+ chunks = []
37
+ while True:
38
+ try:
39
+ chunk = raw.recv(65536)
40
+ except socket.timeout:
41
+ break
42
+ if not chunk:
43
+ break
44
+ chunks.append(chunk)
45
+ raw.close()
46
+ return b"".join(chunks)
47
+
48
+
49
+ def test_an_https_upstream_opens_a_tls_connection(monkeypatch):
50
+ """The connection class follows the upstream's scheme: https opens HTTPSConnection at the upstream's host."""
51
+ opened: list[tuple[str, tuple]] = []
52
+
53
+ class _Recorder:
54
+ def __init__(self, host, port=None, timeout=None, **_kwargs):
55
+ opened.append(("https", (host, port)))
56
+
57
+ def request(self, *args, **kwargs):
58
+ raise OSError("no network in this test")
59
+
60
+ monkeypatch.setattr(http.client, "HTTPSConnection", _Recorder)
61
+ proxy = _serve("https://api.example.test")
62
+ try:
63
+ answer = _post(proxy.server_address[1])
64
+ finally:
65
+ proxy.shutdown()
66
+ assert opened == [("https", ("api.example.test", None))]
67
+ assert answer.startswith(b"HTTP/1.1 502")
68
+
69
+
70
+ def test_an_http_upstream_keeps_a_plain_connection(monkeypatch):
71
+ opened: list[str] = []
72
+
73
+ class _Recorder:
74
+ def __init__(self, host, port=None, timeout=None, **_kwargs):
75
+ opened.append("http")
76
+
77
+ def request(self, *args, **kwargs):
78
+ raise OSError("no network in this test")
79
+
80
+ monkeypatch.setattr(http.client, "HTTPConnection", _Recorder)
81
+ proxy = _serve("http://127.0.0.1:1")
82
+ try:
83
+ _post(proxy.server_address[1])
84
+ finally:
85
+ proxy.shutdown()
86
+ assert opened == ["http"]
87
+
88
+
89
+ def test_a_config_refuses_an_upstream_without_a_scheme():
90
+ with pytest.raises(ValueError, match="http or https"):
91
+ ServeConfig(upstream="api.example.test", listen_port=0)
@@ -0,0 +1,175 @@
1
+ """Import tooling works in the standalone, standard-library-only client."""
2
+
3
+ import fcntl
4
+ import io
5
+ import json
6
+ import subprocess
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ import pytest
11
+
12
+ from reef_client.record_import import import_records_file, record_batches
13
+
14
+
15
+ def imported(record_id, payload=None):
16
+ return {
17
+ "agent_record_id": record_id,
18
+ "request_type": "inference",
19
+ "payload": payload or {"text": record_id},
20
+ }
21
+
22
+
23
+ def write_records(path, count):
24
+ path.write_bytes(
25
+ b"".join(
26
+ json.dumps(imported(str(index))).encode() + b"\n" for index in range(count)
27
+ )
28
+ )
29
+
30
+
31
+ def test_batches_bound_bytes_count_and_preserve_resume_offsets():
32
+ rows = [
33
+ json.dumps(
34
+ imported(str(index), {"text": "汉字" * index}), ensure_ascii=False
35
+ ).encode()
36
+ for index in range(8)
37
+ ]
38
+ data = b"\n\n".join(rows) + b"\n"
39
+ source = io.BytesIO(data)
40
+ batches = list(record_batches(source, batch_size=3, max_bytes=400))
41
+ assert sum(count for _, _, count in batches) == 8
42
+ assert all(len(body) <= 400 and count <= 3 for body, _, count in batches)
43
+ _, first_offset, _ = batches[0]
44
+ source.seek(first_offset)
45
+ resumed = list(record_batches(source, batch_size=3, max_bytes=400))
46
+ assert resumed == batches[1:]
47
+ ids = [
48
+ item["agent_record_id"]
49
+ for body, _, _ in batches
50
+ for item in json.loads(body)["records"]
51
+ ]
52
+ assert ids == [str(index) for index in range(8)]
53
+ with pytest.raises(ValueError, match="exceeds"):
54
+ list(record_batches(io.BytesIO(b"x" * 401), batch_size=3, max_bytes=400))
55
+ with pytest.raises(ValueError, match="invalid JSONL"):
56
+ list(record_batches(io.BytesIO(b"not json\n"), batch_size=3, max_bytes=400))
57
+
58
+
59
+ def test_import_rejects_concurrent_checkpoint_use(tmp_path):
60
+ source = tmp_path / "records.jsonl"
61
+ write_records(source, 1)
62
+ progress = tmp_path / "progress.json"
63
+ with progress.with_name(progress.name + ".lock").open("w") as lock:
64
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
65
+ with pytest.raises(ValueError, match="another importer"):
66
+ import_records_file(
67
+ source,
68
+ url="http://localhost:8900",
69
+ scenario="s",
70
+ progress_path=progress,
71
+ )
72
+
73
+
74
+ def test_import_command_works_without_site_packages(tmp_path):
75
+ # Copying the dependency-free package is a supported harness deployment.
76
+ import shutil
77
+
78
+ root = Path(__file__).resolve().parents[1]
79
+ shutil.copytree(
80
+ root / "reef_client",
81
+ tmp_path / "reef_client",
82
+ ignore=shutil.ignore_patterns("__pycache__"),
83
+ )
84
+ result = subprocess.run(
85
+ [sys.executable, "-S", "-m", "reef_client", "import", "--help"],
86
+ cwd=tmp_path,
87
+ text=True,
88
+ capture_output=True,
89
+ )
90
+ assert result.returncode == 0, result.stderr
91
+ assert "reef-client import" in result.stdout
92
+ assert "JSONL" in result.stdout
93
+ assert "--progress" in result.stdout
94
+ assert "--max-batch-bytes" in result.stdout
95
+
96
+
97
+ def test_standalone_command_uploads_and_resumes_without_server_dependencies(tmp_path):
98
+ import os
99
+ import shutil
100
+ import threading
101
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
102
+
103
+ root = Path(__file__).resolve().parents[1]
104
+ shutil.copytree(
105
+ root / "reef_client",
106
+ tmp_path / "reef_client",
107
+ ignore=shutil.ignore_patterns("__pycache__"),
108
+ )
109
+ source = tmp_path / "records.jsonl"
110
+ write_records(source, 5)
111
+ received = []
112
+
113
+ class Handler(BaseHTTPRequestHandler):
114
+ protocol_version = "HTTP/1.1"
115
+
116
+ def do_POST(self):
117
+ assert self.path == "/reef/records/batch"
118
+ assert self.headers["Authorization"] == "Bearer fixture-token"
119
+ assert self.headers["x-reef-scenario"] == "s"
120
+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
121
+ received.append(body["records"])
122
+ payload = json.dumps(
123
+ {
124
+ "records": [
125
+ {
126
+ "agent_record_id": item["agent_record_id"],
127
+ "request_type": item["request_type"],
128
+ "scenario": "s",
129
+ }
130
+ for item in body["records"]
131
+ ]
132
+ }
133
+ ).encode()
134
+ self.send_response(200)
135
+ self.send_header("Content-Type", "application/json")
136
+ self.send_header("Content-Length", str(len(payload)))
137
+ self.end_headers()
138
+ self.wfile.write(payload)
139
+
140
+ def log_message(self, format, *args):
141
+ pass
142
+
143
+ with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
144
+ worker = threading.Thread(target=server.serve_forever)
145
+ worker.start()
146
+ try:
147
+ command = [
148
+ sys.executable,
149
+ "-S",
150
+ "-m",
151
+ "reef_client",
152
+ "import",
153
+ str(source),
154
+ "--url",
155
+ f"http://127.0.0.1:{server.server_port}",
156
+ "--scenario",
157
+ "s",
158
+ "--batch-size",
159
+ "2",
160
+ ]
161
+ for _ in range(2):
162
+ result = subprocess.run(
163
+ command,
164
+ cwd=tmp_path,
165
+ text=True,
166
+ capture_output=True,
167
+ env={**os.environ, "REEF_TOKEN": "fixture-token"},
168
+ timeout=10,
169
+ )
170
+ assert result.returncode == 0, result.stderr
171
+ assert "5 records acknowledged" in result.stdout
172
+ assert [len(batch) for batch in received] == [2, 2, 1]
173
+ finally:
174
+ server.shutdown()
175
+ worker.join(timeout=5)
@@ -1,46 +0,0 @@
1
- # reef_client
2
-
3
- Stdlib-only client SDK for the [Reef](https://github.com/Human-Agent-Society/reef) protocol. `reef_client` is a client of
4
- Reef's HTTP wire protocol, not of the `reef` package: it never imports `reef`
5
- and has no dependencies, so external harnesses can install it or copy it into
6
- environments that cannot take the `reef` wheel's dependencies.
7
-
8
- The distribution is `reef-client` ([`pyproject.toml`](pyproject.toml)); the
9
- import package is the inner [`reef_client/`](reef_client) directory:
10
-
11
- - [`client.py`](reef_client/client.py) is `ReefClient`, the
12
- ask/observe/report loop every example shares (see the
13
- [Reef docs](https://github.com/Human-Agent-Society/reef/blob/main/docs/reference/reef-client.md)),
14
- plus the harness update channel reads: `harness_versions` (the version
15
- catalog with gate metrics) and `harness_pull` (write one served tree, head
16
- or version-addressed, into a directory).
17
- - [`skill.py`](reef_client/skill.py) fetches and syncs the scenario's served
18
- skill file (`fetch_skill`/`sync_skill`);
19
- - [`sse.py`](reef_client/sse.py) converts between buffered chat completions
20
- and OpenAI-style SSE chunk streams in both directions
21
- (`synthesize_sse_events` / `SSEAccumulator`).
22
- - [`serve.py`](reef_client/serve.py) is serve mode: a local sidecar that
23
- agents treat as their model endpoint (`python -m reef_client.serve`),
24
- owning session stamping, trajectory capture, receipt collection, and SSE
25
- passthrough/synthesis so reef-oblivious agents need no SDK. See the
26
- [reference](https://github.com/Human-Agent-Society/reef/blob/main/docs/reference/reef-client.md#serve-mode-a-local-proxy-for-reef-oblivious-agents).
27
-
28
- The client and skill helpers are re-exported at the package root:
29
- `from reef_client import ReefClient, fetch_skill, sync_skill`. Import the
30
- `sse`/`serve` submodules directly.
31
-
32
- ## Install
33
-
34
- ```bash
35
- pip install reef-client
36
- ```
37
-
38
- For development:
39
-
40
- ```bash
41
- git clone https://github.com/Human-Agent-Society/reef-client && cd reef-client
42
- pip install -e .
43
- ```
44
-
45
- The package is standard library only — copying the inner `reef_client/`
46
- directory into your harness works too.
File without changes
File without changes