diff --git a/docs/omegallm/README.md b/docs/omegallm/README.md index c42716c..06f10a5 100644 --- a/docs/omegallm/README.md +++ b/docs/omegallm/README.md @@ -137,6 +137,38 @@ Never commit the data or the `.bin` and `.ck` files. Every receipt in the table with `sh tests/omegallm/core-receipts.sh`; set `CORE`, `BUILD`, `DATA` or `WORK` to override the defaults. The exit codes are listed in CONTRACT ยง7. +## Serve (DRA-119) + +```sh +ollm serve PORT CK MERGES [MAXCONN] # AArch64 Linux only; prints "PORT n" once listening +``` + +`serve.om` (aarch64 builds only; gb10 and the x86 targets get `noserve.om`, which exits 2) answers +OpenAI-style chat requests on 127.0.0.1:PORT with omega-mv's `seed/net/http.om` and +`seed/json/{json,jsonw}.om`, vendored byte for byte from omega-mv `e5b32567` into +`native/omegallm/net/`. `build.sh` checks their sha256 (`NET_PIN_MISMATCH`, exit 3) and puts `om2` +first. One connection at a time and one request per connection (`Connection: close`), so a pooled +idle client cannot hold the listener; 10 s head and 60 s body deadlines. + +- `GET /health` โ†’ `{"status":"ok","in_flight":0}`; `GET /v1/models` โ†’ one model, `ollm`. +- `POST /v1/chat/completions`: `messages` (string or null content), `max_tokens` or + `max_completion_tokens` (1 to 999999), `temperature` (0 to 2, no exponent; 0 is argmax), `seed`, + `stream`, `stream_options.include_usage`, `n` = 1; other members are ignored (`tools`, `model`). + JSON or SSE (`data:` chunks: role, content, finish, optional usage, `[DONE]`). +- Interim template, until DRA-123 fixes a shared one: `role: content\n` per message, then + `assistant: `, at most 4000 bytes. The context is token 0 plus its encoding; when that reaches T + the answer is 400 `context_length_exceeded`. Output is at most min(max_tokens, T โˆ’ prompt tokens) + tokens drawn with `sample`'s step (`osstep`), so the same SEED and TEMPMILLI give `sample`'s + bytes. Bytes are sent as UTF-8; an ill-formed sequence becomes U+FFFD. +- Refusals are JSON `{"error":{...}}`: 400 (`invalid_json`, `invalid_request`, + `context_length_exceeded`), 404, 405, and 413 for a body over 983040 bytes (the JSON parser's + limit), refused at the head. +- stdout gets one line per response: `C status prompt_tokens completion_tokens finish ms`. + +`tests/omegallm/serve-check.sh` starts the server under taskset/nice/bwrap, referees it with +`serve-check.py` (27 checks; the content oracle is the same binary's `sample`, decoded with +Python's `errors="replace"`) and stops the PIDs it started. Receipts: `evidence/OMEGALLM/serve/`. + ## iMac `tests/omegallm/efi-receipts.sh` leaves the boot image at `$WORK/ollm.img` (`scratch-efi/ollm.img`; diff --git a/evidence/OMEGALLM/serve/allen-chat.txt b/evidence/OMEGALLM/serve/allen-chat.txt new file mode 100644 index 0000000..56dd9e4 --- /dev/null +++ b/evidence/OMEGALLM/serve/allen-chat.txt @@ -0,0 +1,69 @@ +== POST /allen/api/chat: What is Omega? +event: start +data: {"model":"qwen3.6-35b-a3b-fp8","queued_ms":0,"remembered":false} + +event: meta +data: {"source":"cold"} + +data: "" + +data: "\"" + +data: "I" + +data: " am" + +data: " O" + +data: "kay" + +data: "." + +data: " I" + +data: " am" + +event: done +data: {"prompt_tokens":43,"completion_tokens":8,"finish":"length","upstream_ttft_ms":2088,"upstream_ms":11421,"source":"cold","tool_rounds":0} + +== curl rc=0 +== POST /allen/api/chat: Tell me a story. +event: start +data: {"model":"qwen3.6-35b-a3b-fp8","queued_ms":0,"remembered":false} + +event: meta +data: {"source":"cold"} + +data: "" + +data: "\"" + +data: "What" + +data: " kind" + +data: " of" + +data: " story" + +data: " do" + +data: " you" + +data: " want" + +event: done +data: {"prompt_tokens":42,"completion_tokens":8,"finish":"length","upstream_ttft_ms":843,"upstream_ms":7754,"source":"cold","tool_rounds":0} + +== curl rc=0 +--- ollm.log +PORT 18292 +C 200 0 0 0 0 +C 200 43 8 2 11420 +C 200 0 0 0 0 +C 200 42 8 2 7754 +--- allen.log +allen-chat listening on 127.0.0.1:18293, upstream 127.0.0.1:18292, cap 2, system prompt sha256 3d718b5b7cf53fa633fd02e92d92451536efd79312b2edb3030a2a8e3af7cd66, console off +launchers 3662509 3664641 servers 3662517 3664645 +after: 0 0 +rc=0 diff --git a/evidence/OMEGALLM/serve/allen-chat/allen.log b/evidence/OMEGALLM/serve/allen-chat/allen.log new file mode 100644 index 0000000..27d05ba --- /dev/null +++ b/evidence/OMEGALLM/serve/allen-chat/allen.log @@ -0,0 +1 @@ +allen-chat listening on 127.0.0.1:18293, upstream 127.0.0.1:18292, cap 2, system prompt sha256 3d718b5b7cf53fa633fd02e92d92451536efd79312b2edb3030a2a8e3af7cd66, console off diff --git a/evidence/OMEGALLM/serve/allen-chat/chat.txt b/evidence/OMEGALLM/serve/allen-chat/chat.txt new file mode 100644 index 0000000..c13340f --- /dev/null +++ b/evidence/OMEGALLM/serve/allen-chat/chat.txt @@ -0,0 +1,58 @@ +== POST /allen/api/chat: What is Omega? +event: start +data: {"model":"qwen3.6-35b-a3b-fp8","queued_ms":0,"remembered":false} + +event: meta +data: {"source":"cold"} + +data: "" + +data: "\"" + +data: "I" + +data: " am" + +data: " O" + +data: "kay" + +data: "." + +data: " I" + +data: " am" + +event: done +data: {"prompt_tokens":43,"completion_tokens":8,"finish":"length","upstream_ttft_ms":2088,"upstream_ms":11421,"source":"cold","tool_rounds":0} + +== curl rc=0 +== POST /allen/api/chat: Tell me a story. +event: start +data: {"model":"qwen3.6-35b-a3b-fp8","queued_ms":0,"remembered":false} + +event: meta +data: {"source":"cold"} + +data: "" + +data: "\"" + +data: "What" + +data: " kind" + +data: " of" + +data: " story" + +data: " do" + +data: " you" + +data: " want" + +event: done +data: {"prompt_tokens":42,"completion_tokens":8,"finish":"length","upstream_ttft_ms":843,"upstream_ms":7754,"source":"cold","tool_rounds":0} + +== curl rc=0 diff --git a/evidence/OMEGALLM/serve/allen-chat/ollm.log b/evidence/OMEGALLM/serve/allen-chat/ollm.log new file mode 100644 index 0000000..432b3d1 --- /dev/null +++ b/evidence/OMEGALLM/serve/allen-chat/ollm.log @@ -0,0 +1,5 @@ +PORT 18292 +C 200 0 0 0 0 +C 200 43 8 2 11420 +C 200 0 0 0 0 +C 200 42 8 2 7754 diff --git a/evidence/OMEGALLM/serve/allen-chat/pids.txt b/evidence/OMEGALLM/serve/allen-chat/pids.txt new file mode 100644 index 0000000..768060b --- /dev/null +++ b/evidence/OMEGALLM/serve/allen-chat/pids.txt @@ -0,0 +1,2 @@ +launchers 3662509 3664641 servers 3662517 3664645 +after: 0 0 diff --git a/evidence/OMEGALLM/serve/allen-chat/system.txt b/evidence/OMEGALLM/serve/allen-chat/system.txt new file mode 100644 index 0000000..499a37e --- /dev/null +++ b/evidence/OMEGALLM/serve/allen-chat/system.txt @@ -0,0 +1 @@ +You are Allen. diff --git a/evidence/OMEGALLM/serve/build.txt b/evidence/OMEGALLM/serve/build.txt new file mode 100644 index 0000000..51d193f --- /dev/null +++ b/evidence/OMEGALLM/serve/build.txt @@ -0,0 +1,5 @@ +aarch64 BUILD_OK 318573b6cc65bb6dbb0e63ab23c0afffdc45eab10823ccf5d1a98433842f113d /dev/shm/hive/OwnModelCoord/m71-aarch64/ollm source_sha256 154ec3985cb9f1e0718dc0b3905d84dc0da2fbbea65c52aa5fcd3fb00e673e5a +gb10 BUILD_OK 54c1f122872430b5a4ff81677329d6ecb760b1c6f90ecd0128c8ebae836971f4 /dev/shm/hive/OwnModelCoord/m71-gb10/ollm-gb10 source_sha256 1b4f1682b5b7bb57410a658c914f446f6ebf365d9f446fe9e07531d9d1eb569a +x86efi BUILD_OK d4b03fabc4f73c7be1e365075851d404d8bf54e78c3ab3b323fc9135622946ed /dev/shm/hive/OwnModelCoord/m71-x86efi/ollm.efi source_sha256 e273bae1cc4e24b6876953a71f03363119c5a53acdcc277faedaff17047cb028 +x86linux NOT_RUN: omc pin be8c5130 not present on the Spark +keepalive-negctl ka-ollm 657b4936c1cd4af48ed6de00d44dbde8ed5abd880a801454146c0fe1f29e3b87 (the previous keep-alive build, source 2b3a5643) diff --git a/evidence/OMEGALLM/serve/check.txt b/evidence/OMEGALLM/serve/check.txt new file mode 100644 index 0000000..5cbde09 --- /dev/null +++ b/evidence/OMEGALLM/serve/check.txt @@ -0,0 +1,31 @@ +PASS health 200 b'{"status":"ok","in_flight":0}' +PASS models 200 ['ollm'] +PASS chat_json_t0 200 usage={'prompt_tokens': 17, 'completion_tokens': 12, 'total_tokens': 29} finish=length s=5.37 content='"I am here to help you."\nOme' oracle='"I am here to help you."\nOme' +PASS chat_sse_t0 200 events=15 done=True usage=[{'prompt_tokens': 17, 'completion_tokens': 12, 'total_tokens': 29}] text='"I am here to help you."\nOme' +PASS chat_json_t800 200 usage={'prompt_tokens': 17, 'completion_tokens': 12, 'total_tokens': 29} finish=length s=5.25 content='"Because I want to go to the park with' oracle='"Because I want to go to the park with' +PASS chat_sse_t800 200 events=15 done=True usage=[{'prompt_tokens': 17, 'completion_tokens': 12, 'total_tokens': 29}] text='"Because I want to go to the park with' +PASS allen_chat_shape 200 b'{"id":"chatcmpl-ollm-5","object":"chat.completion","created":1793999561,"model":"ollm","choices":[{"index":0,"message":{"role":"assistant","content":"\\"I will help"},"finish_reason":"length"}],"usage"' +PASS refuse_context 400 context_length_exceeded 'prompt is 2453 tokens including the start token; the context window is 256 tokens, so no room is left for output' +PASS refuse_template_bytes 400 invalid_request 'the chat template is over 4000 bytes' +PASS refuse_bad_json 400 invalid_json 'request body is not valid JSON (RFC 8259) or has over 65532 JSON tokens' +PASS refuse_not_object 400 invalid_request 'the request must be a JSON object' +PASS refuse_trailing 400 invalid_json 'request body is not valid JSON (RFC 8259) or has over 65532 JSON tokens' +PASS refuse_empty_messages 400 invalid_request 'messages must be a non-empty array of objects' +PASS refuse_array_content 400 invalid_request 'message content must be a string or null' +PASS refuse_no_role 400 invalid_request 'message role must be a string of at most 32 bytes' +PASS refuse_neg_temp 400 invalid_request 'temperature must be a number from 0 to 2 without exponent' +PASS refuse_hot_temp 400 invalid_request 'temperature must be a number from 0 to 2 without exponent' +PASS refuse_zero_max 400 invalid_request 'max_tokens must be an integer from 1 to 999999' +PASS refuse_n2 400 invalid_request 'only n = 1 is supported' +PASS refuse_stream_str 400 invalid_request 'stream must be true or false' +PASS refuse_exp_temp 400 invalid_request 'temperature must be a number from 0 to 2 without exponent' +PASS refuse_404 404 b'{"error":{"message":"no such path; routes: GET /health, GET /v1/models, POST /v1/chat/completions","type":"invalid_request_error","param":null,"code":"not_found"}}' +PASS refuse_405 405 b'{"error":{"message":"method not allowed on this path","type":"invalid_request_error","param":null,"code":"method_not_allowed"}}' +PASS refuse_413 b'HTTP/1.1 413 Content Too Large\r\nContent-Type: application/json\r\nContent-Length: 132\r\nConnection: close\r\n\r\n{"error":{"mes' +PASS held_conn_not_blocking Connection='close' next=200 in 0.000s +PASS silent_conn_dropped next=200 after 10.005s +PASS alive_after_negatives 200 +SUMMARY pass=27 fail=0 +bind_loopback_only 1 LISTEN 0 16 127.0.0.1:18291 0.0.0.0:* users:(("ollm",pid=95106,fd=3)) +SERVE_CHECK PASS +rc=0 diff --git a/evidence/OMEGALLM/serve/check/env.txt b/evidence/OMEGALLM/serve/check/env.txt new file mode 100644 index 0000000..962b43b --- /dev/null +++ b/evidence/OMEGALLM/serve/check/env.txt @@ -0,0 +1,7 @@ +date 2026-11-06T21:12:05Z +host spark-b87b aarch64 +ollm 318573b6cc65bb6dbb0e63ab23c0afffdc45eab10823ccf5d1a98433842f113d /dev/shm/hive/OwnModelCoord/m71-aarch64/ollm +ck a53ced7265818c8f6197449315e9ca4082721665022fec4f81d4538e8d6c2d0f /tmp/gk/r10/run/ck60000.bin +merges 73a29baf97619a746a21232c403bf08af71a76e48b3b2cde6d64dab766083882 /home/drakestapleton/handoffs/omega-llm-20261101/v1-data/merges4096.bin +referee 097733a013603a332f33394be0694bf95308f09c5de329545022f09ad3fff3fc /home/drakestapleton/work/hive/OwnModelCoord/aien-train/tests/omegallm/serve-check.py +stopped launcher=95103 server=95106 diff --git a/evidence/OMEGALLM/serve/check/listen.txt b/evidence/OMEGALLM/serve/check/listen.txt new file mode 100644 index 0000000..e03d233 --- /dev/null +++ b/evidence/OMEGALLM/serve/check/listen.txt @@ -0,0 +1 @@ +LISTEN 0 16 127.0.0.1:18291 0.0.0.0:* users:(("ollm",pid=95106,fd=3)) diff --git a/evidence/OMEGALLM/serve/check/referee.txt b/evidence/OMEGALLM/serve/check/referee.txt new file mode 100644 index 0000000..919a21e --- /dev/null +++ b/evidence/OMEGALLM/serve/check/referee.txt @@ -0,0 +1,30 @@ +PASS health 200 b'{"status":"ok","in_flight":0}' +PASS models 200 ['ollm'] +PASS chat_json_t0 200 usage={'prompt_tokens': 17, 'completion_tokens': 12, 'total_tokens': 29} finish=length s=5.37 content='"I am here to help you."\nOme' oracle='"I am here to help you."\nOme' +PASS chat_sse_t0 200 events=15 done=True usage=[{'prompt_tokens': 17, 'completion_tokens': 12, 'total_tokens': 29}] text='"I am here to help you."\nOme' +PASS chat_json_t800 200 usage={'prompt_tokens': 17, 'completion_tokens': 12, 'total_tokens': 29} finish=length s=5.25 content='"Because I want to go to the park with' oracle='"Because I want to go to the park with' +PASS chat_sse_t800 200 events=15 done=True usage=[{'prompt_tokens': 17, 'completion_tokens': 12, 'total_tokens': 29}] text='"Because I want to go to the park with' +PASS allen_chat_shape 200 b'{"id":"chatcmpl-ollm-5","object":"chat.completion","created":1793999561,"model":"ollm","choices":[{"index":0,"message":{"role":"assistant","content":"\\"I will help"},"finish_reason":"length"}],"usage"' +PASS refuse_context 400 context_length_exceeded 'prompt is 2453 tokens including the start token; the context window is 256 tokens, so no room is left for output' +PASS refuse_template_bytes 400 invalid_request 'the chat template is over 4000 bytes' +PASS refuse_bad_json 400 invalid_json 'request body is not valid JSON (RFC 8259) or has over 65532 JSON tokens' +PASS refuse_not_object 400 invalid_request 'the request must be a JSON object' +PASS refuse_trailing 400 invalid_json 'request body is not valid JSON (RFC 8259) or has over 65532 JSON tokens' +PASS refuse_empty_messages 400 invalid_request 'messages must be a non-empty array of objects' +PASS refuse_array_content 400 invalid_request 'message content must be a string or null' +PASS refuse_no_role 400 invalid_request 'message role must be a string of at most 32 bytes' +PASS refuse_neg_temp 400 invalid_request 'temperature must be a number from 0 to 2 without exponent' +PASS refuse_hot_temp 400 invalid_request 'temperature must be a number from 0 to 2 without exponent' +PASS refuse_zero_max 400 invalid_request 'max_tokens must be an integer from 1 to 999999' +PASS refuse_n2 400 invalid_request 'only n = 1 is supported' +PASS refuse_stream_str 400 invalid_request 'stream must be true or false' +PASS refuse_exp_temp 400 invalid_request 'temperature must be a number from 0 to 2 without exponent' +PASS refuse_404 404 b'{"error":{"message":"no such path; routes: GET /health, GET /v1/models, POST /v1/chat/completions","type":"invalid_request_error","param":null,"code":"not_found"}}' +PASS refuse_405 405 b'{"error":{"message":"method not allowed on this path","type":"invalid_request_error","param":null,"code":"method_not_allowed"}}' +PASS refuse_413 b'HTTP/1.1 413 Content Too Large\r\nContent-Type: application/json\r\nContent-Length: 132\r\nConnection: close\r\n\r\n{"error":{"mes' +PASS held_conn_not_blocking Connection='close' next=200 in 0.000s +PASS silent_conn_dropped next=200 after 10.005s +PASS alive_after_negatives 200 +SUMMARY pass=27 fail=0 +bind_loopback_only 1 LISTEN 0 16 127.0.0.1:18291 0.0.0.0:* users:(("ollm",pid=95106,fd=3)) +SERVE_CHECK PASS diff --git a/evidence/OMEGALLM/serve/check/server.log b/evidence/OMEGALLM/serve/check/server.log new file mode 100644 index 0000000..aa436b1 --- /dev/null +++ b/evidence/OMEGALLM/serve/check/server.log @@ -0,0 +1,29 @@ +PORT 18291 +C 200 0 0 0 0 +C 200 0 0 0 0 +C 200 17 12 2 5374 +C 200 17 12 2 5388 +C 200 17 12 2 5251 +C 200 17 12 2 5175 +C 200 22 4 2 1803 +C 400 2453 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 404 0 0 0 0 +C 405 0 0 0 0 +C 413 0 0 0 0 +C 200 0 0 0 0 +C 200 0 0 0 0 +C 200 0 0 0 0 +C 200 0 0 0 0 diff --git a/evidence/OMEGALLM/serve/negctl-keepalive.txt b/evidence/OMEGALLM/serve/negctl-keepalive.txt new file mode 100644 index 0000000..855739e --- /dev/null +++ b/evidence/OMEGALLM/serve/negctl-keepalive.txt @@ -0,0 +1,46 @@ +PASS health 200 b'{"status":"ok","in_flight":0}' +PASS models 200 ['ollm'] +PASS chat_json_t0 200 usage={'prompt_tokens': 17, 'completion_tokens': 12, 'total_tokens': 29} finish=length s=6.52 content='"I am here to help you."\nOme' oracle='"I am here to help you."\nOme' +PASS chat_sse_t0 200 events=15 done=True usage=[{'prompt_tokens': 17, 'completion_tokens': 12, 'total_tokens': 29}] text='"I am here to help you."\nOme' +PASS chat_json_t800 200 usage={'prompt_tokens': 17, 'completion_tokens': 12, 'total_tokens': 29} finish=length s=7.83 content='"Because I want to go to the park with' oracle='"Because I want to go to the park with' +PASS chat_sse_t800 200 events=15 done=True usage=[{'prompt_tokens': 17, 'completion_tokens': 12, 'total_tokens': 29}] text='"Because I want to go to the park with' +PASS allen_chat_shape 200 b'{"id":"chatcmpl-ollm-5","object":"chat.completion","created":1793998200,"model":"ollm","choices":[{"index":0,"message":{"role":"assistant","content":"\\"I will help"},"finish_reason":"length"}],"usage"' +PASS refuse_context 400 context_length_exceeded 'prompt is 2453 tokens including the start token; the context window is 256 tokens, so no room is left for output' +PASS refuse_template_bytes 400 invalid_request 'the chat template is over 4000 bytes' +PASS refuse_bad_json 400 invalid_json 'request body is not valid JSON (RFC 8259) or has over 65532 JSON tokens' +PASS refuse_not_object 400 invalid_request 'the request must be a JSON object' +PASS refuse_trailing 400 invalid_json 'request body is not valid JSON (RFC 8259) or has over 65532 JSON tokens' +PASS refuse_empty_messages 400 invalid_request 'messages must be a non-empty array of objects' +PASS refuse_array_content 400 invalid_request 'message content must be a string or null' +PASS refuse_no_role 400 invalid_request 'message role must be a string of at most 32 bytes' +PASS refuse_neg_temp 400 invalid_request 'temperature must be a number from 0 to 2 without exponent' +PASS refuse_hot_temp 400 invalid_request 'temperature must be a number from 0 to 2 without exponent' +PASS refuse_zero_max 400 invalid_request 'max_tokens must be an integer from 1 to 999999' +PASS refuse_n2 400 invalid_request 'only n = 1 is supported' +PASS refuse_stream_str 400 invalid_request 'stream must be true or false' +PASS refuse_exp_temp 400 invalid_request 'temperature must be a number from 0 to 2 without exponent' +PASS refuse_404 404 b'{"error":{"message":"no such path; routes: GET /health, GET /v1/models, POST /v1/chat/completions","type":"invalid_request_error","param":null,"code":"not_found"}}' +PASS refuse_405 405 b'{"error":{"message":"method not allowed on this path","type":"invalid_request_error","param":null,"code":"method_not_allowed"}}' +PASS refuse_413 b'HTTP/1.1 413 Content Too Large\r\nContent-Type: application/json\r\nContent-Length: 132\r\nConnection: close\r\n\r\n{"error":{"mes' +Traceback (most recent call last): + File "/home/drakestapleton/work/hive/OwnModelCoord/aien-train/tests/omegallm/serve-check.py", line 173, in + st, ct, out, _ = call("GET", "/health", timeout=5) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/home/drakestapleton/work/hive/OwnModelCoord/aien-train/tests/omegallm/serve-check.py", line 34, in call + r = c.getresponse() + ^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/http/client.py", line 1457, in getresponse + response.begin() + File "/usr/lib/python3.12/http/client.py", line 336, in begin + version, status, reason = self._read_status() + ^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/http/client.py", line 297, in _read_status + line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1") + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/socket.py", line 707, in readinto + return self._sock.recv_into(b) + ^^^^^^^^^^^^^^^^^^^^^^^ +TimeoutError: timed out +bind_loopback_only 1 LISTEN 0 16 127.0.0.1:18291 0.0.0.0:* users:(("ka-ollm",pid=3641568,fd=3)) +SERVE_CHECK FAIL +rc=1 diff --git a/evidence/OMEGALLM/serve/negctl-keepalive/env.txt b/evidence/OMEGALLM/serve/negctl-keepalive/env.txt new file mode 100644 index 0000000..3b48520 --- /dev/null +++ b/evidence/OMEGALLM/serve/negctl-keepalive/env.txt @@ -0,0 +1,7 @@ +date 2026-11-06T20:49:12Z +host spark-b87b aarch64 +ollm 657b4936c1cd4af48ed6de00d44dbde8ed5abd880a801454146c0fe1f29e3b87 /dev/shm/hive/OwnModelCoord/ka-ollm +ck a53ced7265818c8f6197449315e9ca4082721665022fec4f81d4538e8d6c2d0f /tmp/gk/r10/run/ck60000.bin +merges 73a29baf97619a746a21232c403bf08af71a76e48b3b2cde6d64dab766083882 /home/drakestapleton/handoffs/omega-llm-20261101/v1-data/merges4096.bin +referee 097733a013603a332f33394be0694bf95308f09c5de329545022f09ad3fff3fc /home/drakestapleton/work/hive/OwnModelCoord/aien-train/tests/omegallm/serve-check.py +stopped launcher=3641565 server=3641568 diff --git a/evidence/OMEGALLM/serve/negctl-keepalive/listen.txt b/evidence/OMEGALLM/serve/negctl-keepalive/listen.txt new file mode 100644 index 0000000..5b89b11 --- /dev/null +++ b/evidence/OMEGALLM/serve/negctl-keepalive/listen.txt @@ -0,0 +1 @@ +LISTEN 0 16 127.0.0.1:18291 0.0.0.0:* users:(("ka-ollm",pid=3641568,fd=3)) diff --git a/evidence/OMEGALLM/serve/negctl-keepalive/referee.txt b/evidence/OMEGALLM/serve/negctl-keepalive/referee.txt new file mode 100644 index 0000000..f7d94cf --- /dev/null +++ b/evidence/OMEGALLM/serve/negctl-keepalive/referee.txt @@ -0,0 +1,26 @@ +PASS health 200 b'{"status":"ok","in_flight":0}' +PASS models 200 ['ollm'] +PASS chat_json_t0 200 usage={'prompt_tokens': 17, 'completion_tokens': 12, 'total_tokens': 29} finish=length s=6.52 content='"I am here to help you."\nOme' oracle='"I am here to help you."\nOme' +PASS chat_sse_t0 200 events=15 done=True usage=[{'prompt_tokens': 17, 'completion_tokens': 12, 'total_tokens': 29}] text='"I am here to help you."\nOme' +PASS chat_json_t800 200 usage={'prompt_tokens': 17, 'completion_tokens': 12, 'total_tokens': 29} finish=length s=7.83 content='"Because I want to go to the park with' oracle='"Because I want to go to the park with' +PASS chat_sse_t800 200 events=15 done=True usage=[{'prompt_tokens': 17, 'completion_tokens': 12, 'total_tokens': 29}] text='"Because I want to go to the park with' +PASS allen_chat_shape 200 b'{"id":"chatcmpl-ollm-5","object":"chat.completion","created":1793998200,"model":"ollm","choices":[{"index":0,"message":{"role":"assistant","content":"\\"I will help"},"finish_reason":"length"}],"usage"' +PASS refuse_context 400 context_length_exceeded 'prompt is 2453 tokens including the start token; the context window is 256 tokens, so no room is left for output' +PASS refuse_template_bytes 400 invalid_request 'the chat template is over 4000 bytes' +PASS refuse_bad_json 400 invalid_json 'request body is not valid JSON (RFC 8259) or has over 65532 JSON tokens' +PASS refuse_not_object 400 invalid_request 'the request must be a JSON object' +PASS refuse_trailing 400 invalid_json 'request body is not valid JSON (RFC 8259) or has over 65532 JSON tokens' +PASS refuse_empty_messages 400 invalid_request 'messages must be a non-empty array of objects' +PASS refuse_array_content 400 invalid_request 'message content must be a string or null' +PASS refuse_no_role 400 invalid_request 'message role must be a string of at most 32 bytes' +PASS refuse_neg_temp 400 invalid_request 'temperature must be a number from 0 to 2 without exponent' +PASS refuse_hot_temp 400 invalid_request 'temperature must be a number from 0 to 2 without exponent' +PASS refuse_zero_max 400 invalid_request 'max_tokens must be an integer from 1 to 999999' +PASS refuse_n2 400 invalid_request 'only n = 1 is supported' +PASS refuse_stream_str 400 invalid_request 'stream must be true or false' +PASS refuse_exp_temp 400 invalid_request 'temperature must be a number from 0 to 2 without exponent' +PASS refuse_404 404 b'{"error":{"message":"no such path; routes: GET /health, GET /v1/models, POST /v1/chat/completions","type":"invalid_request_error","param":null,"code":"not_found"}}' +PASS refuse_405 405 b'{"error":{"message":"method not allowed on this path","type":"invalid_request_error","param":null,"code":"method_not_allowed"}}' +PASS refuse_413 b'HTTP/1.1 413 Content Too Large\r\nContent-Type: application/json\r\nContent-Length: 132\r\nConnection: close\r\n\r\n{"error":{"mes' +bind_loopback_only 1 LISTEN 0 16 127.0.0.1:18291 0.0.0.0:* users:(("ka-ollm",pid=3641568,fd=3)) +SERVE_CHECK FAIL diff --git a/evidence/OMEGALLM/serve/negctl-keepalive/server.log b/evidence/OMEGALLM/serve/negctl-keepalive/server.log new file mode 100644 index 0000000..11a0411 --- /dev/null +++ b/evidence/OMEGALLM/serve/negctl-keepalive/server.log @@ -0,0 +1,28 @@ +PORT 18291 +C 200 0 0 0 0 +C 200 0 0 0 0 +C 200 17 12 2 6523 +C 200 17 12 2 7313 +C 200 17 12 2 7825 +C 200 17 12 2 6381 +C 200 22 4 2 3627 +C 200 0 0 0 0 +C 400 2453 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 400 0 0 0 0 +C 404 0 0 0 0 +C 405 0 0 0 0 +C 413 0 0 0 0 +C 200 0 0 0 0 +C 200 0 0 0 0 diff --git a/evidence/OMEGALLM/tune/README.md b/evidence/OMEGALLM/tune/README.md index 93371d6..22508a7 100644 --- a/evidence/OMEGALLM/tune/README.md +++ b/evidence/OMEGALLM/tune/README.md @@ -15,3 +15,8 @@ closes), tune keeps the weights (eval loss and bpb equal), resets the step, zero fine-tuning then lowers eval loss (4.901318 to 4.816743 nats after 20 steps), resume is bit-identical, tune is deterministic, bad TOTAL, argument count and a truncated checkpoint are refused with no output, and a build with the moment reset removed is caught. + +Rerun after merging `ollm serve` (aien-train#71, branch `feat/ollm-serve-http`): the same command on +the merged aarch64 build, `ollm` sha256 `318573b6cc65bb6dbb0e63ab23c0afffdc45eab10823ccf5d1a98433842f113d` +(source `154ec398`), Spark cores 8-9 in bwrap, exit 0, TUNE_PASS, output in `check-merged-serve.txt` +(MEASURED, 2026-11-06). diff --git a/evidence/OMEGALLM/tune/check-merged-serve.txt b/evidence/OMEGALLM/tune/check-merged-serve.txt new file mode 100644 index 0000000..4dd386a --- /dev/null +++ b/evidence/OMEGALLM/tune/check-merged-serve.txt @@ -0,0 +1,25 @@ +ollm_sha256=318573b6cc65bb6dbb0e63ab23c0afffdc45eab10823ccf5d1a98433842f113d +data_sha256=0d96a4ff68ad6d4b6f1f30f713b18d5184912ba8dd389f86aa7710db079abcb0 +PASS init: I 119104 +PASS train base 0..30 rc: 0 +PASS train past TOTAL makes no step (why tune exists): 0 +PASS checkpoint unchanged past TOTAL: 0 +PASS tune: U 119104 +PASS weights kept (eval loss and bpb equal): 4 4901318 7071108 +PASS step reset: 0 +PASS Adam m and v zeroed: 0 +PASS control: base checkpoint moments nonzero (1899279 bytes) +PASS fine-tune 0..20 rc: 0 +PASS fine-tune saves: T 10,T 20, +PASS fine-tune resume 0..10..20 bit-identical to 0..20: 0 +PASS fine-tune changed the weights +PASS fine-tune lowered eval loss (micro-nats 4901318 to 4816743) +PASS tune deterministic: 0 +PASS TOTAL 0 refused: 12 +PASS TOTAL 1000000 refused: 12 +PASS argument count refused: 2 +PASS truncated checkpoint refused: 10 +PASS refused tune wrote no output +PASS negative control: one moment-reset line to remove: 1 +PASS negative control caught: moments not reset (1899279 nonzero bytes) +TUNE_PASS diff --git a/native/omegallm/bpe.om b/native/omegallm/bpe.om index 127d084..0825393 100644 --- a/native/omegallm/bpe.om +++ b/native/omegallm/bpe.om @@ -23,6 +23,8 @@ const BQPMSK ulong 1048575 const BQNCAP ulong 4194304 const BQLCAP ulong 1099511627776 global obtk ulong 4096 +global obo uchar 4096 +global obon ulong 1 global obm uchar 15384 global bqma ushort 4096 global bqmb ushort 4096 @@ -779,7 +781,8 @@ end put bqv 0 v end -note write the decoded bytes of token t to stdout (mode 0) or to output 0 (mode 1) +note write the decoded bytes of token t to stdout (mode 0), to output 0 (mode 1) or to the capture +note buffer obo (mode 2, serve.om; bytes past obo's 4096 are dropped, so callers check obtlen first) fn bpexp t ulong mode ulong to void put bqsk 0 ushort t sp = ulong 1 @@ -793,7 +796,15 @@ if lt x 256 if eq mode 0 oputc x else +if eq mode 1 owbyte 0 x +else +n = get obon 0 +if lt n 4096 +put obo n uchar x +put obon 0 add n 1 +end +end end else put bqsk sp get bqmb x @@ -887,6 +898,12 @@ fn obtput t ulong to void bpexp t 0 end +note the decoded bytes of token t into obo[0 .. obon[0]) (serve.om) +fn obtcap t ulong to void +put obon 0 0 +bpexp t 2 +end + note section 8: encode argument ai (at most 4000 bytes, CONTRACT 7.2; longer exit 2) into obtk; note returns the token count fn obprompt ai ulong to ulong @@ -894,6 +911,11 @@ n = oargp ai if gt n 4000 exit 2 end +ret obpenc n +end + +note encode oarg[0 .. n), n <= 4000, into obtk; returns the token count (obprompt, serve.om) +fn obpenc n ulong to ulong i = ulong 0 m = ulong 0 while lt i n bound 4097 diff --git a/native/omegallm/cli.om b/native/omegallm/cli.om index e5d2dfa..349ffda 100644 --- a/native/omegallm/cli.om +++ b/native/omegallm/cli.om @@ -5,8 +5,8 @@ note Command words are matched as little-endian u64 packings of their bytes (Wol note FromDigits[Reverse[ToCharacterCode[w]],256]): prep 1885696624, init 1953066601, note grad 1684107879, train 474214396532, eval 1818326629, base 1702060386, sample 111516417089907, note gcheck 118074647274343, mathck 118074698391917, adamck 118074781033569; v1: bpefit -note 127996038312034, bpeenc 109325798699106, bpedec 109287127216226 (bpe.om). Fine-tune: -note tune 1701737844. +note 127996038312034, bpeenc 109325798699106, bpedec 109287127216226 (bpe.om); serve 435778905459 +note (serve.om on aarch64, noserve.om elsewhere). Fine-tune: tune 1701737844. note Exit codes: 0 ok; 2 usage; 10-15 checkpoint refusals (ckpt.om); 20 data file shorter than note T + 1 bytes; 21 data over 2^25 bytes or OFFS not exactly 8 B bytes; 22 an OFFS offset with note o + T >= N; 23 eval W = 0 or W T + 1 > M; 24 prep story over 999999 bytes; 40 gcheck over @@ -79,6 +79,10 @@ if eq w 118074781033569 cmdadamck ret 0 end +if eq w 435778905459 +cmdserve +ret 0 +end if eq w 1701737844 cmdtune ret 0 @@ -345,13 +349,8 @@ ocpush ulong get oarg i end end for g ulong nn -lf = ofwd 0 -olast -c = ulong 0 -if eq tm 0 -c = oargmax -else -c = odraw st div f64 tm 1000.0 +c = osstep st tm +if ne tm 0 st = add st 11400714819323198485 end if eq c 0 @@ -367,6 +366,17 @@ end oflush end +note one sampling step (cmdsamp, serve.om): the next token from the logits at the last context +note position, argmax when TEMPMILLI tm is 0, else a draw with the splitmix64 stream state st. +fn osstep st ulong tm ulong to ulong +lf = ofwd 0 +olast +if eq tm 0 +ret oargmax +end +ret odraw st div f64 tm 1000.0 +end + note logits of the last context position into TMP[0..V) (oa) fn olast to void d = get og 2 diff --git a/native/omegallm/net/http.om b/native/omegallm/net/http.om new file mode 100644 index 0000000..a653055 --- /dev/null +++ b/native/omegallm/net/http.om @@ -0,0 +1,2463 @@ +note seed/net/http.om -- bounded HTTP/1.1 server and client in seeded Omega (omega-mv #788). +note Library unit: it has no `om2` line, no `fn main` and no globals. An application composes +note { printf 'om2\n'; cat seed/net/http.om app.om; } | omc +note (JSON users add seed/json/json.om in the same cat). Names: functions h*, consts H*, texts h*. +note Contract, framing rules, error values and ownership: seed/net/README.md. +note +note A connection is two caller-owned arrays: +note cs = new ulong HCSLEN 0 state (fd, buffer cursors, deadlines, framing, header index) +note io = new uchar N 0 one byte array split by hinit into a read region io[0, HRCAP), +note a write region io[HWB, HWB+HWCAP) and a transport region +note io[HTB, HTB+HTL) (empty for plain TCP; reserved for TLS) +note Header and target offsets stored in cs are absolute offsets into io and stay valid until the +note next hreqrd / hrsprd on the same cs. +note +note Results: a long. Nonnegative is success. Negative is minus a Linux errno (-11, -104, ...), +note or one of the HE* protocol values below (-400 .. -505), or HETIME (-110) at a deadline. +note +note ---- state slots of cs +const HFD ulong 0 +const HRLEN ulong 1 +const HRPOS ulong 2 +const HDL ulong 3 +const HIDLE ulong 4 +const HKEEP ulong 5 +const HBMODE ulong 6 +const HBREM ulong 7 +const HCST ulong 8 +const HMEM ulong 9 +const HBCAP ulong 10 +const HBGOT ulong 11 +const HVER ulong 12 +const HSTAT ulong 13 +const HMOFF ulong 14 +const HMLEN ulong 15 +const HTOFF ulong 16 +const HTLEN ulong 17 +const HHN ulong 18 +const HHMAX ulong 19 +const HHEADMX ulong 20 +const HWLEN ulong 21 +const HNMSG ulong 22 +const HMAXMSG ulong 23 +const HHEND ulong 24 +const HISHEAD ulong 25 +const HWMODE ulong 26 +const HEXPECT ulong 27 +const HFLAGS ulong 28 +const HCLV ulong 29 +const HOPEN ulong 30 +const HHDLV ulong 31 +const HSERVER ulong 32 +const HSTART ulong 33 +const HSCAN ulong 34 +const HRCAP ulong 35 +const HWB ulong 36 +const HWCAP ulong 37 +const HTB ulong 38 +const HTL ulong 39 +const HXPORT ulong 40 +const HWBODY ulong 41 +const HWDROP ulong 42 +const HWOUT ulong 43 +const HWCL ulong 44 +const HOMODE ulong 45 +const HSCODE ulong 46 +const HTRN ulong 47 +const HHOSTN ulong 48 +const HBDLV ulong 49 +const HFINAL ulong 50 +const HFRM ulong 51 +const HFRMAX ulong 52 +const HBSC ulong 53 +note header i (0 <= i < HHN): cs[HHX+4i] name offset, +1 name length, +2 value offset, +3 value length +const HHX ulong 64 +const HHSLOTS ulong 64 +const HCSLEN ulong 320 +note ---- results +const HEINVAL long -22 +const HENOSUP long -95 +const HETIME long -110 +const HEBAD long -400 +const HEEXP long -417 +const HEBIG long -413 +const HEHEAD long -431 +const HETRUNC long -499 +const HETE long -501 +const HEVER long -505 +note ---- SSE reader: ss = new ulong HSSLEN 0, lb = new uchar N 0 (N >= 256) +note lb[0, 64) event type, lb[64, 128) last event id, lb[128, ...) data and the line being read +const HSLINE ulong 0 +const HSDLEN ulong 1 +const HSELEN ulong 2 +const HSILEN ulong 3 +const HSRETRY ulong 4 +const HSRDY ulong 5 +const HSCR ulong 6 +const HSBOM ulong 7 +const HSNEV ulong 8 +note HSVO / HSVL: value offset and length of the field line being applied (scratch) +const HSVO ulong 9 +const HSVL ulong 10 +const HSSLEN ulong 16 +const HSIDB ulong 64 +const HSDB ulong 128 +const HSFCAP ulong 64 +note ---- byte strings (lowercase ones are compared case-insensitively) +text hvhttp "HTTP/" +text hv11 "HTTP/1.1" +text hnclen "content-length" +text hnte "transfer-encoding" +text hnconn "connection" +text hnhost "host" +text hnexp "expect" +text hvchunk "chunked" +text hvclose "close" +text hvkeep "keep-alive" +text hv100c "100-continue" +text hmhead "HEAD" +text hmconn "CONNECT" +text hoclen "Content-Length: " +text hote "Transfer-Encoding: chunked" +text hocls "Connection: close" +text ho100 "HTTP/1.1 100 Continue" +text hoctype "Content-Type" +text hocache "Cache-Control" +text hvnoca "no-cache" +text hvevst "text/event-stream" +text hsdata "data: " +text hsevent "event: " +text hsid "id: " +text hsretry "retry: " +text hfdata "data" +text hfevent "event" +text hfid "id" +text hfretry "retry" +text hr100 "Continue" +text hr101 "Switching Protocols" +text hr200 "OK" +text hr201 "Created" +text hr202 "Accepted" +text hr204 "No Content" +text hr206 "Partial Content" +text hr301 "Moved Permanently" +text hr302 "Found" +text hr304 "Not Modified" +text hr400 "Bad Request" +text hr401 "Unauthorized" +text hr403 "Forbidden" +text hr404 "Not Found" +text hr405 "Method Not Allowed" +text hr408 "Request Timeout" +text hr409 "Conflict" +text hr411 "Length Required" +text hr413 "Content Too Large" +text hr414 "URI Too Long" +text hr415 "Unsupported Media Type" +text hr417 "Expectation Failed" +text hr422 "Unprocessable Content" +text hr429 "Too Many Requests" +text hr431 "Request Header Fields Too Large" +text hr500 "Internal Server Error" +text hr501 "Not Implemented" +text hr502 "Bad Gateway" +text hr503 "Service Unavailable" +text hr504 "Gateway Timeout" +text hr505 "HTTP Version Not Supported" +note ======== small helpers +fn hmin a ulong b ulong to ulong +if lt a b +ret a +end +ret b +end +fn hfe a long b long to long +note first error: a when a is negative, else b +if lt a 0 +ret a +end +ret b +end +fn hlow c uchar to uchar +if and ge c 65 le c 90 +ret add c 32 +end +ret c +end +fn hws c uchar to bool +ret or eq c 32 eq c 9 +end +note htchar: RFC 9110 tchar +fn htchar c uchar to bool +if and ge c 97 le c 122 +ret true +end +if and ge c 65 le c 90 +ret true +end +if and ge c 48 le c 57 +ret true +end +if or or or eq c 33 eq c 35 eq c 36 eq c 37 +ret true +end +if or or or eq c 38 eq c 39 eq c 42 eq c 43 +ret true +end +if or or or eq c 45 eq c 46 eq c 94 eq c 95 +ret true +end +ret or or eq c 96 eq c 124 eq c 126 +end +note hvch: a field-value byte: HTAB, SP, VCHAR or obs-text (0x80-0xff); never CR, LF, NUL, DEL +fn hvch c uchar to bool +if eq c 9 +ret true +end +ret and ge c 32 ne c 127 +end +fn hvall a view uchar * to bool +for b ulong 65536 +s = mul b 65536 +if ge s len a +ret true +end +m = hmin sub len a s 65536 +for i ulong m +if not hvch get a add s i +ret false +end +end +end +ret true +end +fn htok a view uchar * to bool +n = len a +if or eq n 0 gt n 64 +ret false +end +for i ulong n +if not htchar get a i +ret false +end +end +ret true +end +fn htarg a view uchar * to bool +n = len a +if or eq n 0 gt n 8192 +ret false +end +for i ulong n +c = get a i +if or lt c 33 gt c 126 +ret false +end +end +ret true +end +fn hdigits a view uchar * to bool +n = len a +if or eq n 0 gt n 19 +ret false +end +for i ulong n +c = get a i +if or lt c 48 gt c 57 +ret false +end +end +ret true +end +fn hdecv a view uchar * to ulong +note the value of 1..19 checked decimal digits (hdigits first) +v = ulong 0 +for i ulong len a +v = add mul v 10 ulong sub get a i 48 +end +ret v +end +fn hieq a view uchar * t view uchar * to bool +note ASCII case-insensitive equality; t is lowercase +n = len a +if ne n len t +ret false +end +for i ulong n +if ne hlow get a i get t i +ret false +end +end +ret true +end +fn heq a view uchar * t view uchar * to bool +n = len a +if ne n len t +ret false +end +for i ulong n +if ne get a i get t i +ret false +end +end +ret true +end +note hcopy: d[0, len s) = s; blocks of 65536 keep every loop under the 1000000-pass guard +fn hcopy d edit uchar * s view uchar * to void +n = len s +for b ulong 65536 +st = mul b 65536 +if ge st n +break +end +m = hmin sub n st 65536 +for i ulong m +put d add st i get s add st i +end +end +end +note hmove: a[dt, dt+n) = a[sr, sr+n) with dt <= sr (forward copy) +fn hmove a edit uchar * dt ulong sr ulong n ulong to void +for b ulong 65536 +st = mul b 65536 +if ge st n +break +end +m = hmin sub n st 65536 +for i ulong m +put a add dt add st i get a add sr add st i +end +end +end +fn hhexv c uchar to ulong +if and ge c 48 le c 57 +ret ulong sub c 48 +end +if and ge c 97 le c 102 +ret ulong sub c 87 +end +if and ge c 65 le c 70 +ret ulong sub c 55 +end +ret 16 +end +fn hhexd v ulong to uchar +if lt v 10 +ret uchar add v 48 +end +ret uchar add v 87 +end +note ======== transport boundary: the only functions that call recv, send and waitio on a connection +note hwait: wait for events ev on the connection; interval = min(idle, deadline - now) +fn hwait cs edit ulong * ev int to long +fd = int get cs HFD +for it ulong 4096 +iv = long -1 +if ne get cs HIDLE 0 +iv = long get cs HIDLE +end +dl = get cs HDL +if ne dl 0 +now = ulong monons +if ge now dl +ret HETIME +end +rm = long sub dl now +if or lt iv 0 lt rm iv +iv = rm +end +end +r = waitio fd ev iv +if eq r 0 +ret HETIME +end +if ne r -4 +ret r +end +end +ret HETIME +end +note hrecvio: at most n bytes into io[off, off+n); count, 0 at end of stream, or negative +fn hrecvio cs edit ulong * io edit uchar * off ulong n ulong to long +if ne get cs HMEM 0 +ret 0 +end +if ne get cs HXPORT 0 +ret HENOSUP +end +fd = int get cs HFD +for it ulong 4096 +r = recv fd io off n 64 +if eq r -11 +w = hwait cs 1 +if lt w 0 +ret w +end +continue +end +if ne r -4 +ret r +end +end +ret HETIME +end +note hrecvd: at most len d bytes straight into the caller's array d +fn hrecvd cs edit ulong * io edit uchar * d edit uchar * to long +if ne get cs HMEM 0 +ret 0 +end +if ne get cs HXPORT 0 +ret HENOSUP +end +fd = int get cs HFD +for it ulong 4096 +r = recv fd d 0 len d 64 +if eq r -11 +w = hwait cs 1 +if lt w 0 +ret w +end +continue +end +if ne r -4 +ret r +end +end +ret HETIME +end +note hsendio: send all of io[off, off+n); 0 or negative +fn hsendio cs edit ulong * io edit uchar * off ulong n ulong to long +if ne get cs HMEM 0 +ret -9 +end +if ne get cs HXPORT 0 +ret HENOSUP +end +fd = int get cs HFD +e = add off n +p = off +for it ulong 4194304 +if ge p e +ret 0 +end +r = send fd io p sub e p 64 +if gt r 0 +p = add p ulong r +continue +end +if eq r -11 +w = hwait cs 4 +if lt w 0 +ret w +end +continue +end +if eq r 0 +ret -32 +end +if ne r -4 +ret r +end +end +ret HETIME +end +note ======== connection setup +note hinit: take ownership of fd (hclose closes it); fd < 0 selects memory mode (no I/O; tests). +note role 1 = server (reads requests, writes responses), 0 = client. +fn hinit cs edit ulong * io edit uchar * fd int role ulong to long +if lt len cs HCSLEN +ret HEINVAL +end +if or lt len io 512 gt len io 16777216 +ret HEINVAL +end +if gt role 1 +ret HEINVAL +end +for i ulong HCSLEN +put cs i 0 +end +if lt fd 0 +put cs HMEM 1 +else +put cs HFD ulong fd +put cs HOPEN 1 +end +put cs HSERVER role +put cs HBCAP 1048576 +put cs HHMAX HHSLOTS +put cs HMAXMSG 1000 +put cs HIDLE 30000000000 +put cs HHDLV 30000000000 +put cs HBDLV 60000000000 +put cs HFRMAX 65536 +put cs HKEEP 1 +w = hmin div len io 4 65536 +if lt w 256 +w = 256 +end +ret hlayout cs len io w +end +fn hlayout cs edit ulong * n ulong w ulong to long +r = sub n w +put cs HRCAP r +put cs HWB r +put cs HWCAP w +put cs HTB n +put cs HTL 0 +put cs HHEADMX hmin 16384 div r 2 +ret 0 +end +note hsetw: change the write region capacity (256 .. 65536) before any I/O on cs +fn hsetw cs edit ulong * io edit uchar * w ulong to long +if or ne get cs HRLEN 0 ne get cs HWLEN 0 +ret HEINVAL +end +if or lt w 256 gt w 65536 +ret HEINVAL +end +if lt len io add w 512 +ret HEINVAL +end +ret hlayout cs len io w +end +note hsettmo: idle = longest single wait in ns (0 = none); hdl = deadline for reading one +note message head, counted from the start of hreqrd / hrsprd (0 = none). Negative means 0. +fn hsettmo cs edit ulong * idle long hdl long to void +put cs HIDLE 0 +if gt idle 0 +put cs HIDLE ulong idle +end +put cs HHDLV 0 +if gt hdl 0 +put cs HHDLV ulong hdl +end +end +note hsetbdl: interval armed as the deadline (HDL) for a message's body reads and the response +note writes when its head has been read, and for a request's writes when hreqst starts it +note (0 = none). The default is 60 s; a long-lived stream (SSE) sets its own with hsetdl. +fn hsetbdl cs edit ulong * iv long to void +put cs HBDLV 0 +if gt iv 0 +put cs HBDLV ulong iv +end +end +fn hbdl cs edit ulong * to ulong +if eq get cs HBDLV 0 +ret 0 +end +ret add ulong monons get cs HBDLV +end +note hsetdl: absolute deadline now + iv for the following body reads and writes (0 clears) +fn hsetdl cs edit ulong * iv long to void +put cs HDL 0 +if gt iv 0 +put cs HDL add ulong monons ulong iv +end +end +fn hclose cs edit ulong * to long +if eq get cs HOPEN 1 +put cs HOPEN 0 +put cs HKEEP 0 +ret fclose int get cs HFD +end +ret 0 +end +note hmemld: memory mode only; the read region holds exactly src (a whole test message) +fn hmemld cs edit ulong * io edit uchar * src view uchar * to long +if eq get cs HMEM 0 +ret HEINVAL +end +if gt len src get cs HRCAP +ret HEBIG +end +hcopy part io 0 len src src +put cs HRLEN len src +put cs HRPOS 0 +ret 0 +end +note ======== sockets (IPv4 or Unix); every descriptor is O_NONBLOCK and close-on-exec +fn haddr4 a edit uchar * ip uint port ulong to long +if lt len a 16 +ret HEINVAL +end +if gt port 65535 +ret HEINVAL +end +for i ulong 16 +put a i 0 +end +put a 0 2 +put a 2 uchar shr port 8 +put a 3 uchar and port 255 +put a 4 uchar shr ip 24 +put a 5 uchar and shr ip 16 255 +put a 6 uchar and shr ip 8 255 +put a 7 uchar and ip 255 +ret 0 +end +fn hport a view uchar * to ulong +ret or shl ulong get a 2 8 ulong get a 3 +end +fn hfam a view uchar * to int +ret int or ulong get a 0 shl ulong get a 1 8 +end +fn hnodel fd int to long +one = new uchar 4 0 +put one 0 1 +ret sockopt fd 6 1 one 0 4 +end +note hlisten: socket, SO_REUSEADDR, bind a (exactly the sockaddr bytes), listen, and write the +note bound address back into a (so port 0 reports the ephemeral port). Returns the listening fd. +fn hlisten a edit uchar * backlog int to long +one = new uchar 4 0 +put one 0 1 +fd = socknew hfam a 526337 0 +if lt fd 0 +ret fd +end +r = sockopt int fd 1 2 one 0 4 +if eq r 0 +r = bind int fd a 0 len a +end +if eq r 0 +r = listen int fd backlog +end +if eq r 0 +k = sockname int fd a 0 len a +if lt k 0 +r = k +end +end +if ne r 0 +c = fclose int fd +ret r +end +ret fd +end +note haccept: wait at most tmo ns (negative = forever) for a connection; returns its fd +fn haccept lfd int tmo long to long +w = waitio lfd 1 tmo +if eq w 0 +ret HETIME +end +if lt w 0 +ret w +end +c = accept lfd 526336 +if lt c 0 +ret c +end +q = hnodel int c +ret c +end +note hdial: nonblocking connect bounded by tmo ns; returns the connected fd or closes it +fn hdial a view uchar * tmo long to long +fd = socknew hfam a 526337 0 +if lt fd 0 +ret fd +end +r = connect int fd a 0 len a +if eq r -115 +w = waitio int fd 4 tmo +if le w 0 +c = fclose int fd +if eq w 0 +ret HETIME +end +ret w +end +r = connect int fd a 0 len a +if eq r -106 +r = 0 +end +end +if ne r 0 +c = fclose int fd +ret r +end +q = hnodel int fd +ret fd +end +note ======== reading a message head +note hbegin: drop the consumed bytes of the previous message, reset per-message state, arm the +note head deadline +fn hbegin cs edit ulong * io edit uchar * to void +p = get cs HRPOS +n = get cs HRLEN +if gt p 0 +hmove io 0 p sub n p +put cs HRLEN sub n p +put cs HRPOS 0 +end +if gt get cs HHEADMX hmin 65536 div get cs HRCAP 2 +put cs HHEADMX hmin 65536 div get cs HRCAP 2 +end +if gt get cs HHMAX HHSLOTS +put cs HHMAX HHSLOTS +end +put cs HSTART 0 +put cs HSCAN 0 +put cs HHN 0 +put cs HFLAGS 0 +put cs HCLV 0 +put cs HBMODE 0 +put cs HBREM 0 +put cs HCST 0 +put cs HBGOT 0 +put cs HEXPECT 0 +put cs HHEND 0 +put cs HSTAT 0 +put cs HVER 0 +put cs HTRN 0 +put cs HHOSTN 0 +put cs HMOFF 0 +put cs HMLEN 0 +put cs HTOFF 0 +put cs HTLEN 0 +put cs HKEEP 1 +put cs HFINAL 0 +put cs HFRM 0 +put cs HBSC 0 +put cs HDL 0 +if ne get cs HHDLV 0 +put cs HDL add ulong monons get cs HHDLV +end +end +note hskipcr: a server ignores empty lines (CRLF) before a request line (RFC 9112 2.2) +fn hskipcr cs edit ulong * io edit uchar * to void +for it ulong 999999 +st = get cs HSTART +if gt add st 2 get cs HRLEN +break +end +if ne get io st 13 +break +end +if ne get io add st 1 10 +break +end +put cs HSTART add st 2 +end +end +note hscan: look for CRLF CRLF in io[HSTART, min(HRLEN, HHEADMX)); end offset, 0 = need more, +note HEBAD for a bare LF or a CR not followed by LF +fn hscan cs edit ulong * io edit uchar * to long +st = get cs HSTART +lim = hmin get cs HRLEN get cs HHEADMX +i = get cs HSCAN +if lt i st +i = st +end +while lt i lim bound 999999 +c = get io i +if eq c 10 +if eq i st +ret HEBAD +end +if ne get io sub i 1 13 +ret HEBAD +end +if ge i add st 3 +if and eq get io sub i 2 10 eq get io sub i 3 13 +put cs HSCAN add i 1 +ret long add i 1 +end +end +end +if eq c 13 +if ge add i 1 get cs HRLEN +put cs HSCAN i +ret 0 +end +if ne get io add i 1 10 +ret HEBAD +end +end +i = add i 1 +end +put cs HSCAN i +ret 0 +end +fn hhead cs edit ulong * io edit uchar * to long +for it ulong 1000000 +if eq get cs HSERVER 1 +hskipcr cs io +end +e = hscan cs io +if lt e 0 +ret e +end +if gt e 0 +ret hparse cs io ulong e +end +n = get cs HRLEN +if ge n get cs HHEADMX +ret HEHEAD +end +if ge n get cs HRCAP +ret HEHEAD +end +k = hrecvio cs io n sub get cs HRCAP n +if lt k 0 +ret k +end +if eq k 0 +if eq n get cs HSTART +ret 0 +end +ret HETRUNC +end +put cs HRLEN add n ulong k +end +ret HEHEAD +end +note hcr: the first CR in a[p, e) (the head scan guarantees CR LF pairs), or e +fn hcr a view uchar * p ulong e ulong to ulong +i = p +while lt i e bound 999999 +if eq get a i 13 +ret i +end +i = add i 1 +end +ret e +end +fn hparse cs edit ulong * io edit uchar * e ulong to long +p = get cs HSTART +x = hcr io p e +r = long 0 +if eq get cs HSERVER 1 +r = hreql cs io p x +else +r = hstatl cs io p x +end +if lt r 0 +ret r +end +p = add x 2 +lim = sub e 2 +for it ulong 65536 +if ge p lim +break +end +x = hcr io p lim +r = hfield cs io p x +if lt r 0 +ret r +end +p = add x 2 +end +r = hsem cs io +if lt r 0 +ret r +end +put cs HHEND e +put cs HRPOS e +put cs HDL hbdl cs +ret 1 +end +note hreqm: method = 1..32 tchar then SP; returns its length +fn hreqm a view uchar * p ulong x ulong to long +i = p +while and lt i x htchar get a i bound 999999 +i = add i 1 +end +ml = sub i p +if or eq ml 0 gt ml 32 +ret HEBAD +end +if ne get a i 32 +ret HEBAD +end +ret long ml +end +note hreqt: request-target = 1..8192 bytes 0x21-0x7e then SP; returns its length +fn hreqt a view uchar * t ulong x ulong to long +j = t +while and lt j x and ge get a j 33 le get a j 126 bound 999999 +j = add j 1 +end +tl = sub j t +if or eq tl 0 gt tl 8192 +ret HEBAD +end +if ne get a j 32 +ret HEBAD +end +ret long tl +end +note hver: exactly HTTP/1.1 (1) or HTTP/1.0 (0); another HTTP/d.d is HEVER, anything else HEBAD +fn hver a view uchar * k ulong to long +for i ulong 5 +if ne get a add k i get hvhttp i +ret HEBAD +end +end +mj = get a add k 5 +dt = get a add k 6 +mn = get a add k 7 +if or or lt mj 48 gt mj 57 ne dt 46 +ret HEBAD +end +if or lt mn 48 gt mn 57 +ret HEBAD +end +if ne mj 49 +ret HEVER +end +if eq mn 48 +ret 0 +end +if eq mn 49 +ret 1 +end +ret HEVER +end +fn hreql cs edit ulong * io edit uchar * p ulong x ulong to long +ml = hreqm io p x +if lt ml 0 +ret ml +end +t = add p add ulong ml 1 +tl = hreqt io t x +if lt tl 0 +ret tl +end +k = add t add ulong tl 1 +if ne sub x k 8 +ret HEBAD +end +v = hver io k +if lt v 0 +ret v +end +put cs HVER ulong v +put cs HMOFF p +put cs HMLEN ulong ml +put cs HTOFF t +put cs HTLEN ulong tl +ret htform cs io +end +note htform: origin-form (/...), asterisk-form (*), authority-form (CONNECT only) or +note absolute-form (scheme://...) +fn htform cs edit ulong * io edit uchar * to long +t = get cs HTOFF +tl = get cs HTLEN +c = get io t +if eq c 47 +ret 0 +end +if and eq tl 1 eq c 42 +ret 0 +end +if heq view part io get cs HMOFF get cs HMLEN hmconn +ret 0 +end +ret hscheme view part io t tl +end +fn hscheme a view uchar * to long +n = len a +if lt n 4 +ret HEBAD +end +c = hlow get a 0 +if or lt c 97 gt c 122 +ret HEBAD +end +for i ulong n +if gt i 0 +c = hlow get a i +if eq c 58 +if gt add i 3 n +ret HEBAD +end +if and eq get a add i 1 47 eq get a add i 2 47 +ret 0 +end +ret HEBAD +end +if not hschc c +ret HEBAD +end +end +end +ret HEBAD +end +note hschc: a scheme byte after the first (lowercased): ALPHA, DIGIT, + - . +fn hschc c uchar to bool +if and ge c 97 le c 122 +ret true +end +if and ge c 48 le c 57 +ret true +end +ret or or eq c 43 eq c 45 eq c 46 +end +note hstatl: HTTP/1.x SP 3DIGIT SP reason; status 100..599 +fn hstatl cs edit ulong * io edit uchar * p ulong x ulong to long +if lt sub x p 8 +ret HEBAD +end +v = hver io p +if lt v 0 +ret v +end +if lt sub x p 13 +ret HEBAD +end +if or ne get io add p 8 32 ne get io add p 12 32 +ret HEBAD +end +c = ulong 0 +for i ulong 3 +d = get io add p add 9 i +if or lt d 48 gt d 57 +ret HEBAD +end +c = add mul c 10 ulong sub d 48 +end +if or lt c 100 gt c 599 +ret HEBAD +end +r = add p 13 +if not hvall view part io r sub x r +ret HEBAD +end +put cs HVER ulong v +put cs HSTAT c +put cs HMOFF r +put cs HMLEN sub x r +ret 0 +end +note hfvalid: a field line: tchar name, ':' with no space before it, field-value bytes; +note returns the colon index. A leading SP or HTAB (obs-fold) is HEBAD. +fn hfvalid a view uchar * to long +n = len a +if eq n 0 +ret HEBAD +end +if hws get a 0 +ret HEBAD +end +c = n +for i ulong n +if not htchar get a i +c = i +break +end +end +if or eq c 0 eq c n +ret HEBAD +end +if ne get a c 58 +ret HEBAD +end +k = add c 1 +if not hvall view part a k sub n k +ret HEBAD +end +ret long c +end +fn hfield cs edit ulong * io edit uchar * p ulong x ulong to long +co = hfvalid view part io p sub x p +if lt co 0 +ret co +end +n = get cs HHN +if or ge n get cs HHMAX ge n HHSLOTS +ret HEHEAD +end +b = add HHX mul n 4 +put cs b p +put cs add b 1 ulong co +put cs HHN add n 1 +put cs add b 2 add add p ulong co 1 +ret hftrim cs io b x +end +note hftrim: header slot b's value starts at get cs b+2 and ends before x; drop leading and +note trailing SP / HTAB +fn hftrim cs edit ulong * io edit uchar * b ulong x ulong to long +s = get cs add b 2 +while and lt s x hws get io s bound 999999 +s = add s 1 +end +ve = x +while and gt ve s hws get io sub ve 1 bound 999999 +ve = sub ve 1 +end +put cs add b 2 s +put cs add b 3 sub ve s +ret 0 +end +note ======== header semantics and message framing (RFC 9112 6.1-6.3) +fn hsem cs edit ulong * io edit uchar * to long +n = get cs HHN +for i ulong n +r = hsem1 cs io i +if lt r 0 +ret r +end +end +ret hframe cs +end +fn hsem1 cs edit ulong * io edit uchar * i ulong to long +b = add HHX mul i 4 +no = get cs b +nl = get cs add b 1 +vo = get cs add b 2 +vl = get cs add b 3 +if hieq view part io no nl hnclen +ret hsemcl cs io vo vl +end +if hieq view part io no nl hnte +ret hsemte cs io vo vl +end +if hieq view part io no nl hnconn +ret hsemco cs io vo vl +end +if hieq view part io no nl hnhost +put cs HHOSTN add get cs HHOSTN 1 +ret 0 +end +if hieq view part io no nl hnexp +ret hsemex cs io vo vl +end +ret 0 +end +note Content-Length: 1..19 digits, exactly one field line (a repeated or list value is ambiguous) +fn hsemcl cs edit ulong * io edit uchar * vo ulong vl ulong to long +if ne and get cs HFLAGS 1 0 +ret HEBAD +end +put cs HFLAGS or get cs HFLAGS 1 +if not hdigits view part io vo vl +ret HEBAD +end +put cs HCLV hdecv view part io vo vl +ret 0 +end +note Transfer-Encoding: exactly one field line whose value is chunked; any other coding is HETE +fn hsemte cs edit ulong * io edit uchar * vo ulong vl ulong to long +if ne and get cs HFLAGS 2 0 +ret HEBAD +end +put cs HFLAGS or get cs HFLAGS 2 +if not hieq view part io vo vl hvchunk +ret HETE +end +ret 0 +end +note Connection: comma list; close (flag 4) and keep-alive (flag 8) are recognised +fn hsemco cs edit ulong * io edit uchar * vo ulong vl ulong to long +p = vo +e = add vo vl +for it ulong 999999 +if gt p e +break +end +q = p +while and lt q e ne get io q 44 bound 999999 +q = add q 1 +end +r = hcotok cs io p q +p = add q 1 +end +ret 0 +end +note hcotok: the list element io[a, q) without SP / HTAB; sets flag 4 (close) or 8 (keep-alive) +fn hcotok cs edit ulong * io edit uchar * a ulong q ulong to long +s = a +while and lt s q hws get io s bound 999999 +s = add s 1 +end +z = q +while and gt z s hws get io sub z 1 bound 999999 +z = sub z 1 +end +if hieq view part io s sub z s hvclose +put cs HFLAGS or get cs HFLAGS 4 +end +if hieq view part io s sub z s hvkeep +put cs HFLAGS or get cs HFLAGS 8 +end +ret 0 +end +note Expect (server, HTTP/1.1 only): 100-continue is honoured on the first body read; others HEEXP +fn hsemex cs edit ulong * io edit uchar * vo ulong vl ulong to long +if or ne get cs HSERVER 1 ne get cs HVER 1 +ret 0 +end +if not hieq view part io vo vl hv100c +ret HEEXP +end +put cs HEXPECT 1 +ret 0 +end +fn hframe cs edit ulong * to long +f = get cs HFLAGS +cl = ne and f 1 0 +te = ne and f 2 0 +if and cl te +ret HEBAD +end +if and te eq get cs HVER 0 +ret HEBAD +end +srv = eq get cs HSERVER 1 +if and srv eq get cs HVER 1 +if ne get cs HHOSTN 1 +ret HEBAD +end +end +put cs HKEEP 0 +if and eq get cs HVER 1 eq and f 4 0 +put cs HKEEP 1 +end +if srv +if ge add get cs HNMSG 1 get cs HMAXMSG +put cs HKEEP 0 +end +ret hfrsrv cs +end +ret hfrcli cs +end +fn hfrsrv cs edit ulong * to long +f = get cs HFLAGS +if ne and f 2 0 +put cs HBMODE 2 +ret 0 +end +if ne and f 1 0 +v = get cs HCLV +if gt v get cs HBCAP +put cs HKEEP 0 +ret HEBIG +end +if gt v 0 +put cs HBMODE 1 +put cs HBREM v +end +end +ret 0 +end +fn hfrcli cs edit ulong * to long +s = get cs HSTAT +f = get cs HFLAGS +if eq s 101 +put cs HKEEP 0 +end +if or or eq get cs HISHEAD 1 lt s 200 or eq s 204 eq s 304 +ret 0 +end +if ne and f 2 0 +put cs HBMODE 2 +ret 0 +end +if ne and f 1 0 +v = get cs HCLV +if gt v get cs HBCAP +put cs HKEEP 0 +ret HEBIG +end +if gt v 0 +put cs HBMODE 1 +put cs HBREM v +end +ret 0 +end +put cs HBMODE 3 +put cs HKEEP 0 +ret 0 +end +note ======== public head readers +note hreqrd (server): 1 = a request head was read, 0 = the peer closed between requests, negative = +note error (a value <= -400 is the status to answer with hrsperr before closing) +fn hreqrd cs edit ulong * io edit uchar * to long +if and eq get cs HOPEN 0 eq get cs HMEM 0 +ret -9 +end +hbegin cs io +put cs HISHEAD 0 +r = hhead cs io +if le r 0 +ret r +end +if heq view part io get cs HMOFF get cs HMLEN hmhead +put cs HISHEAD 1 +end +ret 1 +end +note hrsprd (client): the final status (101, or 200..599; 1xx interim responses are skipped) +fn hrsprd cs edit ulong * io edit uchar * to long +if and eq get cs HOPEN 0 eq get cs HMEM 0 +ret -9 +end +for it ulong 16 +hbegin cs io +r = hhead cs io +if eq r 0 +ret HETRUNC +end +if lt r 0 +ret r +end +s = get cs HSTAT +if or ge s 200 eq s 101 +ret long s +end +put cs HRPOS get cs HHEND +end +ret HEBAD +end +note header accessors: hhfind returns the index of the first field named nm (any case), or -1 +fn hhfind cs edit ulong * io edit uchar * nm view uchar * to long +n = get cs HHN +for i ulong n +b = add HHX mul i 4 +if hieqm view part io get cs b get cs add b 1 nm +ret long i +end +end +ret -1 +end +note hieqm: case-insensitive equality of two arbitrary byte strings +fn hieqm a view uchar * t view uchar * to bool +n = len a +if ne n len t +ret false +end +for i ulong n +if ne hlow get a i hlow get t i +ret false +end +end +ret true +end +fn hhvoff cs edit ulong * i ulong to ulong +ret get cs add HHX add mul i 4 2 +end +fn hhvlen cs edit ulong * i ulong to ulong +ret get cs add HHX add mul i 4 3 +end +fn hhnoff cs edit ulong * i ulong to ulong +ret get cs add HHX mul i 4 +end +fn hhnlen cs edit ulong * i ulong to ulong +ret get cs add HHX add mul i 4 1 +end +note hismeth: the request method equals m exactly; hispath: the target before '?' equals pa +fn hismeth cs edit ulong * io edit uchar * m view uchar * to bool +ret heq view part io get cs HMOFF get cs HMLEN m +end +fn hplen cs edit ulong * io edit uchar * to ulong +t = get cs HTOFF +n = get cs HTLEN +for i ulong n +if eq get io add t i 63 +ret i +end +end +ret n +end +fn hispath cs edit ulong * io edit uchar * pa view uchar * to bool +n = hplen cs io +ret heq view part io get cs HTOFF n pa +end +note ======== body reading +note hbodyrd: next decoded body bytes into d[0, r); 0 = end of body; negative = error. +note Content-Length, chunked and (client) close-delimited framing; HBCAP bounds the total. +fn hbodyrd cs edit ulong * io edit uchar * d edit uchar * to long +m = get cs HBMODE +if eq m 0 +ret 0 +end +if eq len d 0 +ret HEINVAL +end +if eq get cs HEXPECT 1 +put cs HEXPECT 2 +r = hsend100 cs io +if lt r 0 +ret r +end +end +if eq m 1 +ret hbdlen cs io d +end +if eq m 3 +ret hbdcls cs io d +end +ret hbdchk cs io d +end +fn hsend100 cs edit ulong * io edit uchar * to long +if or ne get cs HFINAL 0 ne get cs HMEM 0 +ret 0 +end +b = get cs HWB +n = len ho100 +hcopy part io b n ho100 +put io add b n 13 +put io add b add n 1 10 +put io add b add n 2 13 +put io add b add n 3 10 +ret hsendio cs io b add n 4 +end +note hbcopy: move buffered bytes io[HRPOS, ...) into d (at most len d) +fn hbcopy cs edit ulong * io edit uchar * d edit uchar * to ulong +p = get cs HRPOS +n = hmin sub get cs HRLEN p len d +hcopy part d 0 n view part io p n +put cs HRPOS add p n +ret n +end +fn hbdlen cs edit ulong * io edit uchar * d edit uchar * to long +rm = get cs HBREM +if eq rm 0 +ret 0 +end +k = hmin rm len d +n = ulong 0 +if gt get cs HRLEN get cs HRPOS +n = hbcopy cs io part d 0 k +else +r = hrecvd cs io part d 0 k +if lt r 0 +ret r +end +if eq r 0 +ret HETRUNC +end +n = ulong r +end +put cs HBREM sub rm n +put cs HBGOT add get cs HBGOT n +ret long n +end +fn hbdcls cs edit ulong * io edit uchar * d edit uchar * to long +if eq get cs HCST 4 +ret 0 +end +got = get cs HBGOT +cap = get cs HBCAP +k = hmin len d add sub cap got 1 +n = ulong 0 +if gt get cs HRLEN get cs HRPOS +n = hbcopy cs io part d 0 k +else +r = hrecvd cs io part d 0 k +if lt r 0 +ret r +end +if eq r 0 +put cs HCST 4 +ret 0 +end +n = ulong r +end +if gt add got n cap +ret HEBIG +end +put cs HBGOT add got n +ret long n +end +note chunked states (HCST): 0 size line, 1 data, 2 CRLF after data, 3 trailer lines, 4 done +fn hbdchk cs edit ulong * io edit uchar * d edit uchar * to long +for it ulong 1000000 +st = get cs HCST +if eq st 4 +ret 0 +end +if eq st 1 +ret hbdcdat cs io d +end +r = long 0 +if eq st 0 +r = hbdcsz cs io +end +if eq st 2 +r = hbdccr cs io +end +if eq st 3 +r = hbdctr cs io +end +if lt r 0 +ret r +end +end +ret HEBAD +end +fn hbdcdat cs edit ulong * io edit uchar * d edit uchar * to long +rm = get cs HBREM +k = hmin rm len d +n = ulong 0 +if gt get cs HRLEN get cs HRPOS +n = hbcopy cs io part d 0 k +else +r = hrecvd cs io part d 0 k +if lt r 0 +ret r +end +if eq r 0 +ret HETRUNC +end +n = ulong r +end +put cs HBREM sub rm n +put cs HBGOT add get cs HBGOT n +if eq rm n +put cs HCST 2 +end +ret long n +end +note hfrchk: count n framing bytes (chunk-size lines, CRLF after chunk data, trailer lines and +note the final empty line); more than HFRMAX + 8 * decoded bytes is HEBIG +fn hfrchk cs edit ulong * n ulong to long +f = add get cs HFRM n +put cs HFRM f +if gt f add get cs HFRMAX mul get cs HBGOT 8 +put cs HKEEP 0 +ret HEBIG +end +ret 0 +end +fn hbdcsz cs edit ulong * io edit uchar * to long +x = hbline cs io +if lt x 0 +ret x +end +p = get cs HRPOS +v = hchsz view part io p sub ulong x p +if lt v 0 +ret v +end +put cs HRPOS add ulong x 2 +r = hfrchk cs sub add ulong x 2 p +if lt r 0 +ret r +end +if eq v 0 +put cs HCST 3 +ret 0 +end +if gt add get cs HBGOT ulong v get cs HBCAP +put cs HKEEP 0 +ret HEBIG +end +put cs HBREM ulong v +put cs HCST 1 +ret 0 +end +fn hbdccr cs edit ulong * io edit uchar * to long +r = hneed cs io 2 +if lt r 0 +ret r +end +p = get cs HRPOS +if or ne get io p 13 ne get io add p 1 10 +ret HEBAD +end +r = hfrchk cs 2 +if lt r 0 +ret r +end +put cs HRPOS add p 2 +put cs HCST 0 +ret 0 +end +fn hbdctr cs edit ulong * io edit uchar * to long +x = hbline cs io +if lt x 0 +ret x +end +p = get cs HRPOS +r = hfrchk cs sub add ulong x 2 p +if lt r 0 +ret r +end +if eq ulong x p +put cs HRPOS add p 2 +put cs HCST 4 +ret 0 +end +co = hfvalid view part io p sub ulong x p +if lt co 0 +ret co +end +put cs HTRN add get cs HTRN 1 +if gt get cs HTRN get cs HHMAX +ret HEHEAD +end +put cs HRPOS add ulong x 2 +ret 0 +end +note hchsz: chunk-size = 1..15 hex digits, then nothing or ';' and field-value bytes (extensions, +note ignored); no whitespace before ';' +fn hchsz a view uchar * to long +n = len a +v = ulong 0 +c = n +for i ulong n +h = hhexv get a i +if eq h 16 +c = i +break +end +if ge i 15 +ret HEBAD +end +v = add mul v 16 h +end +if eq c 0 +ret HEBAD +end +if lt c n +if ne get a c 59 +ret HEBAD +end +if not hvall view part a c sub n c +ret HEBAD +end +end +ret long v +end +note hbline: the CR index of the CRLF line starting at HRPOS (at most HHEADMX bytes), reading more +note as needed +fn hbline cs edit ulong * io edit uchar * to long +for it ulong 1000000 +p = get cs HRPOS +n = get cs HRLEN +lim = hmin n add p get cs HHEADMX +i = add p get cs HBSC +while lt i lim bound 999999 +c = get io i +if eq c 10 +ret HEBAD +end +if eq c 13 +if ge add i 1 n +put cs HBSC sub i p +break +end +if ne get io add i 1 10 +ret HEBAD +end +put cs HBSC 0 +ret long i +end +i = add i 1 +end +put cs HBSC sub i p +if ge sub n p get cs HHEADMX +ret HEHEAD +end +r = hmore cs io +if lt r 0 +ret r +end +end +ret HEHEAD +end +note hcompact: move unread body bytes down to HHEND (the head stays in place) +fn hcompact cs edit ulong * io edit uchar * to void +b = get cs HHEND +p = get cs HRPOS +if gt p b +n = get cs HRLEN +hmove io b p sub n p +put cs HRLEN sub n sub p b +put cs HRPOS b +end +end +fn hmore cs edit ulong * io edit uchar * to long +hcompact cs io +n = get cs HRLEN +cap = get cs HRCAP +if ge n cap +ret HEHEAD +end +k = hrecvio cs io n sub cap n +if lt k 0 +ret k +end +if eq k 0 +ret HETRUNC +end +put cs HRLEN add n ulong k +ret k +end +fn hneed cs edit ulong * io edit uchar * k ulong to long +for it ulong 1000000 +if ge sub get cs HRLEN get cs HRPOS k +ret 0 +end +r = hmore cs io +if lt r 0 +ret r +end +end +ret HETRUNC +end +note hbodyall: the whole body into d; the length, or HEBIG when it does not fit in d +fn hbodyall cs edit ulong * io edit uchar * d edit uchar * to long +pb = new uchar 1 0 +got = ulong 0 +for it ulong 16777216 +if ge got len d +r = hbodyrd cs io pb +if gt r 0 +put cs HKEEP 0 +ret HEBIG +end +if lt r 0 +ret r +end +ret long got +end +r = hbodyrd cs io part d got sub len d got +if lt r 0 +ret r +end +if eq r 0 +ret long got +end +got = add got ulong r +end +ret HEBIG +end +note ======== writing (one write region, flushed to the transport when full or on demand) +note HWMODE 0: raw bytes from HWB. HWMODE 1: chunked body; io[HWB, HWB+10) is reserved for the +note chunk-size line, so a flush sends one chunk without copying. +fn hwreset cs edit ulong * to void +put cs HWLEN 0 +put cs HWMODE 0 +put cs HWBODY 0 +put cs HWDROP 0 +put cs HWOUT 0 +put cs HWCL 0 +put cs HOMODE 0 +end +fn hwcap cs edit ulong * to ulong +if eq get cs HWMODE 1 +ret sub get cs HWCAP 2 +end +ret get cs HWCAP +end +fn hhexpre io edit uchar * b ulong v ulong to ulong +put io add b 8 13 +put io add b 9 10 +i = ulong 8 +x = v +for it ulong 8 +i = sub i 1 +put io add b i hhexd and x 15 +x = shr x 4 +if eq x 0 +ret i +end +end +ret i +end +fn hflush cs edit ulong * io edit uchar * to long +n = get cs HWLEN +b = get cs HWB +if eq get cs HWMODE 1 +if le n 10 +ret 0 +end +s = hhexpre io b sub n 10 +put io add b n 13 +put io add b add n 1 10 +put cs HWLEN 10 +ret hsendio cs io add b s sub add n 2 s +end +if eq n 0 +ret 0 +end +put cs HWLEN 0 +ret hsendio cs io b n +end +note hovercl: n more body bytes would pass the declared Content-Length (mode 0 after hhend) +fn hovercl cs edit ulong * n ulong to bool +if or ne get cs HWBODY 1 ne get cs HOMODE 0 +ret false +end +ret gt add get cs HWOUT n get cs HWCL +end +note hput: append s (body bytes after hhend are framed and counted; dropped for HEAD/204/304). +note A Content-Length body refuses bytes past clen before any is buffered (HEINVAL, closing). +fn hput cs edit ulong * io edit uchar * s view uchar * to long +if eq get cs HWBODY 1 +if hovercl cs len s +put cs HKEEP 0 +ret HEINVAL +end +put cs HWOUT add get cs HWOUT len s +if eq get cs HWDROP 1 +ret 0 +end +end +off = ulong 0 +for it ulong 16777216 +if ge off len s +ret 0 +end +w = get cs HWLEN +if ge w hwcap cs +r = hflush cs io +if lt r 0 +ret r +end +continue +end +k = hmin sub hwcap cs w sub len s off +w = add get cs HWB w +hcopy part io w k view part s off k +put cs HWLEN add get cs HWLEN k +off = add off k +end +ret HEINVAL +end +fn hputb cs edit ulong * io edit uchar * c uchar to long +if eq get cs HWBODY 1 +if hovercl cs 1 +put cs HKEEP 0 +ret HEINVAL +end +put cs HWOUT add get cs HWOUT 1 +if eq get cs HWDROP 1 +ret 0 +end +end +if ge get cs HWLEN hwcap cs +r = hflush cs io +if lt r 0 +ret r +end +end +w = get cs HWLEN +put io add get cs HWB w c +put cs HWLEN add w 1 +ret 0 +end +fn hcrlf cs edit ulong * io edit uchar * to long +r = hputb cs io 13 +ret hfe r hputb cs io 10 +end +fn hdec cs edit ulong * io edit uchar * v ulong to long +d = new uchar 20 0 +i = ulong 20 +x = v +for it ulong 20 +i = sub i 1 +put d i uchar add rem x 10 48 +x = div x 10 +if eq x 0 +break +end +end +ret hput cs io view part d i sub 20 i +end +note hrspst (server): start a response: status line with the standard reason phrase +fn hrspst cs edit ulong * io edit uchar * code ulong to long +if or lt code 100 gt code 599 +ret HEINVAL +end +hwreset cs +put cs HSCODE code +if ge code 200 +put cs HFINAL 1 +end +r = hput cs io hv11 +r = hfe r hputb cs io 32 +r = hfe r hdec cs io code +r = hfe r hputb cs io 32 +r = hfe r hreason cs io code +ret hfe r hcrlf cs io +end +fn hreason cs edit ulong * io edit uchar * code ulong to long +if lt code 300 +ret hreas2 cs io code +end +if lt code 420 +ret hreas4 cs io code +end +ret hreas5 cs io code +end +fn hreas2 cs edit ulong * io edit uchar * code ulong to long +if eq code 100 +ret hput cs io hr100 +end +if eq code 101 +ret hput cs io hr101 +end +if eq code 200 +ret hput cs io hr200 +end +if eq code 201 +ret hput cs io hr201 +end +if eq code 202 +ret hput cs io hr202 +end +if eq code 204 +ret hput cs io hr204 +end +if eq code 206 +ret hput cs io hr206 +end +ret 0 +end +fn hreas4 cs edit ulong * io edit uchar * code ulong to long +if eq code 301 +ret hput cs io hr301 +end +if eq code 302 +ret hput cs io hr302 +end +if eq code 304 +ret hput cs io hr304 +end +if eq code 400 +ret hput cs io hr400 +end +if eq code 401 +ret hput cs io hr401 +end +if eq code 403 +ret hput cs io hr403 +end +if eq code 404 +ret hput cs io hr404 +end +if eq code 405 +ret hput cs io hr405 +end +if eq code 408 +ret hput cs io hr408 +end +if eq code 409 +ret hput cs io hr409 +end +if eq code 411 +ret hput cs io hr411 +end +if eq code 413 +ret hput cs io hr413 +end +if eq code 414 +ret hput cs io hr414 +end +if eq code 415 +ret hput cs io hr415 +end +if eq code 417 +ret hput cs io hr417 +end +ret 0 +end +fn hreas5 cs edit ulong * io edit uchar * code ulong to long +if eq code 422 +ret hput cs io hr422 +end +if eq code 429 +ret hput cs io hr429 +end +if eq code 431 +ret hput cs io hr431 +end +if eq code 500 +ret hput cs io hr500 +end +if eq code 501 +ret hput cs io hr501 +end +if eq code 502 +ret hput cs io hr502 +end +if eq code 503 +ret hput cs io hr503 +end +if eq code 504 +ret hput cs io hr504 +end +if eq code 505 +ret hput cs io hr505 +end +ret 0 +end +note hreqst + hreqtg (client): request line `m SP t SP HTTP/1.1`; HEAD is remembered for framing +fn hreqst cs edit ulong * io edit uchar * m view uchar * to long +if not htok m +ret HEINVAL +end +hwreset cs +hsetdl cs long get cs HBDLV +put cs HISHEAD 0 +if heq m hmhead +put cs HISHEAD 1 +end +put cs HNMSG add get cs HNMSG 1 +r = hput cs io m +ret hfe r hputb cs io 32 +end +fn hreqtg cs edit ulong * io edit uchar * t view uchar * to long +if not htarg t +ret HEINVAL +end +r = hput cs io t +r = hfe r hputb cs io 32 +r = hfe r hput cs io hv11 +ret hfe r hcrlf cs io +end +note hhname + hhval / hhnum: one header field. Framing fields (Content-Length, +note Transfer-Encoding, Connection) are refused: hhend writes them. Values must be field-value +note bytes without leading or trailing whitespace (no CR, LF or NUL: no header injection). +fn hhname cs edit ulong * io edit uchar * nm view uchar * to long +if not htok nm +ret HEINVAL +end +if or or hieqm nm hnclen hieqm nm hnte hieqm nm hnconn +ret HEINVAL +end +r = hput cs io nm +r = hfe r hputb cs io 58 +ret hfe r hputb cs io 32 +end +fn hhval cs edit ulong * io edit uchar * v view uchar * to long +n = len v +if not hvall v +ret HEINVAL +end +if gt n 0 +if or hws get v 0 hws get v sub n 1 +ret HEINVAL +end +end +r = hput cs io v +ret hfe r hcrlf cs io +end +fn hhnum cs edit ulong * io edit uchar * v ulong to long +r = hdec cs io v +ret hfe r hcrlf cs io +end +note hhend: framing and the end of the head. mode 0 = Content-Length clen, 1 = chunked, +note 2 = close-delimited (server only). A server answering HTTP/1.0 turns chunked into 2; 1xx, +note 204 and 304 get no framing field and no body; a HEAD response keeps its framing fields and +note drops the body bytes. put cs HKEEP 0 before hhend to close after this message. +fn hhend cs edit ulong * io edit uchar * mode ulong clen ulong to long +if gt mode 2 +ret HEINVAL +end +srv = eq get cs HSERVER 1 +m = mode +nob = false +if srv +s = get cs HSCODE +if or or lt s 200 eq s 204 eq s 304 +nob = true +end +if and eq m 1 eq get cs HVER 0 +m = 2 +end +else +if eq m 2 +ret HEINVAL +end +end +r = long 0 +if nob +m = 0 +else +r = hhfram cs io m clen +end +if eq m 2 +put cs HKEEP 0 +end +if eq get cs HKEEP 0 +r = hfe r hput cs io hocls +r = hfe r hcrlf cs io +end +r = hfe r hcrlf cs io +if lt r 0 +ret r +end +put cs HOMODE m +put cs HWCL clen +put cs HWBODY 1 +put cs HWOUT 0 +if or nob and srv eq get cs HISHEAD 1 +put cs HWDROP 1 +end +if and eq m 1 eq get cs HWDROP 0 +r = hflush cs io +put cs HWMODE 1 +put cs HWLEN 10 +end +ret r +end +fn hhfram cs edit ulong * io edit uchar * m ulong clen ulong to long +if eq m 1 +r = hput cs io hote +ret hfe r hcrlf cs io +end +if eq m 0 +if or gt clen 0 eq get cs HSERVER 1 +r = hput cs io hoclen +r = hfe r hdec cs io clen +ret hfe r hcrlf cs io +end +end +ret 0 +end +note hwfin: flush, end the chunked body, check a Content-Length body was exactly clen bytes +fn hwfin cs edit ulong * io edit uchar * to long +r = hflush cs io +if lt r 0 +put cs HKEEP 0 +ret r +end +drop = eq get cs HWDROP 1 +m = get cs HOMODE +put cs HWBODY 0 +put cs HWMODE 0 +put cs HWLEN 0 +if and eq m 1 not drop +b = get cs HWB +put io b 48 +put io add b 1 13 +put io add b 2 10 +put io add b 3 13 +put io add b 4 10 +r = hsendio cs io b 5 +end +if and eq m 0 not drop +if ne get cs HWOUT get cs HWCL +put cs HKEEP 0 +ret HEINVAL +end +end +if eq get cs HSERVER 1 +put cs HNMSG add get cs HNMSG 1 +end +if lt r 0 +put cs HKEEP 0 +end +ret r +end +note hreject: answer a failed hreqrd result r. HEBAD .. HEVER answer with that status, HETIME +note with 408; any other value (peer gone, socket error) sends nothing. The connection must +note then be closed (HKEEP is 0). Returns the send result or 0. +fn hreject cs edit ulong * io edit uchar * r long to long +put cs HKEEP 0 +if eq r HETIME +ret hrsperr cs io 408 +end +if or eq r HEBAD eq r HEBIG +ret hrsperr cs io ulong neg r +end +if or or eq r HEHEAD eq r HEEXP or eq r HETE eq r HEVER +ret hrsperr cs io ulong neg r +end +ret 0 +end +note hrsperr: a complete empty error response that closes the connection +fn hrsperr cs edit ulong * io edit uchar * code ulong to long +put cs HKEEP 0 +ret hrspempty cs io code +end +note hrspempty: a complete response with an empty body; the connection stays reusable when +note the request allowed it (hnext still closes when the request body was left unread) +fn hrspempty cs edit ulong * io edit uchar * code ulong to long +r = hrspst cs io code +r = hfe r hhend cs io 0 0 +ret hfe r hwfin cs io +end +note hnext: 1 when the connection may carry another message (keep-alive, body fully read, +note response finished, under HMAXMSG), else 0: the caller closes it +fn hnext cs edit ulong * io edit uchar * to long +if eq get cs HKEEP 0 +ret 0 +end +if eq get cs HWBODY 1 +ret 0 +end +m = get cs HBMODE +if and eq m 1 ne get cs HBREM 0 +ret 0 +end +if and eq m 2 ne get cs HCST 4 +ret 0 +end +if eq m 3 +ret 0 +end +if ge get cs HNMSG get cs HMAXMSG +ret 0 +end +ret 1 +end +note ======== server-sent events: writing (one event per chunk) +fn hrspsse cs edit ulong * io edit uchar * to long +r = hrspst cs io 200 +r = hfe r hhname cs io hoctype +r = hfe r hhval cs io hvevst +r = hfe r hhname cs io hocache +r = hfe r hhval cs io hvnoca +ret hfe r hhend cs io 1 0 +end +fn hsseok a view uchar * to bool +n = len a +for i ulong n +c = get a i +if or or eq c 10 eq c 13 eq c 0 +ret false +end +end +ret true +end +fn hsseln1 cs edit ulong * io edit uchar * v view uchar * to long +r = hput cs io v +ret hfe r hputb cs io 10 +end +fn hsseevt cs edit ulong * io edit uchar * v view uchar * to long +if not hsseok v +ret HEINVAL +end +r = hput cs io hsevent +ret hfe r hsseln1 cs io v +end +fn hsseid cs edit ulong * io edit uchar * v view uchar * to long +if not hsseok v +ret HEINVAL +end +r = hput cs io hsid +ret hfe r hsseln1 cs io v +end +fn hsseret cs edit ulong * io edit uchar * v view uchar * to long +if not hdigits v +ret HEINVAL +end +r = hput cs io hsretry +ret hfe r hsseln1 cs io v +end +fn hssecmt cs edit ulong * io edit uchar * v view uchar * to long +if not hsseok v +ret HEINVAL +end +r = hputb cs io 58 +r = hfe r hputb cs io 32 +ret hfe r hsseln1 cs io v +end +note hlnend: index of the first CR or LF in a at or after p, or len a +fn hlnend a view uchar * p ulong to ulong +n = len a +for b ulong 65536 +s = add p mul b 65536 +if ge s n +ret n +end +m = hmin sub n s 65536 +for i ulong m +c = get a add s i +if or eq c 10 eq c 13 +ret add s i +end +end +end +ret n +end +note hssedat: one `data: ` line per line of v (CR, LF and CRLF all end a line) +fn hssedat cs edit ulong * io edit uchar * v view uchar * to long +n = len v +p = ulong 0 +r = long 0 +for it ulong 16777216 +q = hlnend v p +r = hfe r hput cs io hsdata +r = hfe r hput cs io view part v p sub q p +r = hfe r hputb cs io 10 +if ge q n +ret r +end +p = add q 1 +if eq get v q 13 +if lt p n +if eq get v p 10 +p = add p 1 +end +end +end +end +ret r +end +fn hsseend cs edit ulong * io edit uchar * to long +r = hputb cs io 10 +ret hfe r hflush cs io +end +note ======== server-sent events: incremental reader (WHATWG HTML 9.2.6) +fn hsseinit ss edit ulong * to long +if lt len ss HSSLEN +ret HEINVAL +end +for i ulong HSSLEN +put ss i 0 +end +ret 0 +end +note hssefeed: consume src; returns the bytes consumed. When an event completes it stops right +note after the dispatching line with get ss HSRDY = 1: type lb[0, HSELEN) (empty = message), +note id lb[64, 64+HSILEN), data lb[128, 128+HSDLEN). Call hssenext, then feed the rest. +fn hssefeed ss edit ulong * lb edit uchar * src view uchar * to long +if ne get ss HSRDY 0 +ret HEINVAL +end +if lt len lb 256 +ret HEINVAL +end +n = len src +i = ulong 0 +for it ulong 4194304 +if ge i n +ret long n +end +r = hssebyte ss lb get src i +i = add i 1 +if lt r 0 +ret r +end +if gt r 0 +ret long i +end +end +ret long i +end +note hssebyte: one stream byte; 1 = an event is ready, 0 = continue, negative = error +fn hssebyte ss edit ulong * lb edit uchar * c uchar to long +if eq c 10 +if eq get ss HSCR 1 +put ss HSCR 0 +ret 0 +end +ret hssleol ss lb +end +put ss HSCR 0 +if eq c 13 +put ss HSCR 1 +ret hssleol ss lb +end +w = add add HSDB get ss HSDLEN get ss HSLINE +if ge w len lb +ret HEBIG +end +put lb w c +put ss HSLINE add get ss HSLINE 1 +ret 0 +end +fn hssleol ss edit ulong * lb edit uchar * to long +r = hsseline ss lb +if lt r 0 +ret r +end +if ne get ss HSRDY 0 +ret 1 +end +ret 0 +end +fn hssenext ss edit ulong * to void +put ss HSRDY 0 +put ss HSDLEN 0 +put ss HSELEN 0 +end +fn hssedis ss edit ulong * to long +n = get ss HSDLEN +if eq n 0 +put ss HSELEN 0 +ret 0 +end +put ss HSDLEN sub n 1 +put ss HSRDY 1 +put ss HSNEV add get ss HSNEV 1 +ret 0 +end +note hssebom: strip one U+FEFF (EF BB BF) from the first line of the stream; the new length +fn hssebom ss edit ulong * lb edit uchar * s ulong l ulong to ulong +if ne get ss HSBOM 0 +ret l +end +put ss HSBOM 1 +if lt l 3 +ret l +end +if and and eq get lb s 239 eq get lb add s 1 187 eq get lb add s 2 191 +hmove lb s add s 3 sub l 3 +ret sub l 3 +end +ret l +end +fn hsseline ss edit ulong * lb edit uchar * to long +s = add HSDB get ss HSDLEN +l = hssebom ss lb s get ss HSLINE +put ss HSLINE 0 +if eq l 0 +ret hssedis ss +end +c = l +for i ulong l +if eq get lb add s i 58 +c = i +break +end +end +if eq c 0 +ret 0 +end +vo = c +if lt c l +vo = add c 1 +if lt vo l +if eq get lb add s vo 32 +vo = add vo 1 +end +end +end +put ss HSVO vo +put ss HSVL sub l vo +ret hssefv ss lb s c +end +note hssefv: apply field lb[s, s+c) with value lb[s+vo, s+vo+vl), vo and vl from ss +fn hssefv ss edit ulong * lb edit uchar * s ulong c ulong to long +vo = get ss HSVO +vl = get ss HSVL +if heq view part lb s c hfdata +hmove lb s add s vo vl +put lb add s vl 10 +put ss HSDLEN add get ss HSDLEN add vl 1 +ret 0 +end +if heq view part lb s c hfevent +if gt vl HSFCAP +ret HEHEAD +end +hmove lb 0 add s vo vl +put ss HSELEN vl +ret 0 +end +if heq view part lb s c hfid +if not hsseok view part lb add s vo vl +ret 0 +end +if gt vl HSFCAP +ret HEHEAD +end +hmove lb HSIDB add s vo vl +put ss HSILEN vl +ret 0 +end +if heq view part lb s c hfretry +if hdigits view part lb add s vo vl +put ss HSRETRY hdecv view part lb add s vo vl +end +end +ret 0 +end diff --git a/native/omegallm/net/json.om b/native/omegallm/net/json.om new file mode 100644 index 0000000..99c5dcb --- /dev/null +++ b/native/omegallm/net/json.om @@ -0,0 +1,1247 @@ +note seed/json/json.om: strict RFC 8259 JSON reader for seeded Omega (omega-mv #788). Contract: README.md. +note Composition: an OM-2 unit built by the caller, `{ printf 'om2\n'; cat seed/json/json.om [seed/json/jsonw.om +note [seed/json/jsonf.om]] app.om; }`. The unit has no globals, no texts and no host words: the caller owns +note every array. Names: functions js_*, constants js*; locals are short. +note Tape: a caller `uint` array. Cells 0..15 are the header (jsh* below); token t occupies the four cells from +note 16 + 4t: [0] type | number flags << 4 | child count << 8, [1] first byte offset, [2] byte span, +note [3] match index for a container begin or end, decoded byte length for a key or string, 0 otherwise. +note Every value is checked; nothing is rounded: a number token is its source lexeme. + +const jsnone ulong 4294967295 +const jsbads ulong 4294967294 +const jsth ulong 16 +const jsts ulong 4 +const jstmax ulong 16777215 +const jsmaxn ulong 983040 +const jsdcap ulong 65535 +const jsmagic ulong 788 + +note token types +const jsobj ulong 1 +const jsobje ulong 2 +const jsarr ulong 3 +const jsarre ulong 4 +const jskey ulong 5 +const jsstr ulong 6 +const jsnum ulong 7 +const jstrue ulong 8 +const jsfalse ulong 9 +const jsnull ulong 10 + +note number flags (token cell 0, bits 4..6) +const jsfneg ulong 1 +const jsffrac ulong 2 +const jsfexp ulong 4 + +note reader refusal codes; js_parse returns minus the code +const jseeof ulong 1 +const jsesyn ulong 2 +const jsetrl ulong 3 +const jsedep ulong 4 +const jsesiz ulong 5 +const jseutf ulong 6 +const jsesur ulong 7 +const jsectl ulong 8 +const jseesc ulong 9 +const jsenum ulong 10 +const jsetok ulong 11 +const jselit ulong 12 +const jsearg ulong 13 + +note header cells +const jshok ulong 0 +const jshn ulong 1 +const jshpos ulong 2 +const jshnt ulong 3 +const jshcur ulong 4 +const jshdep ulong 5 +const jsherr ulong 6 +const jshepos ulong 7 +const jshdlim ulong 8 +const jshmaxd ulong 9 +const jshdtot ulong 10 +const jshdmax ulong 11 +const jshcap ulong 12 +const jshsl ulong 13 +const jshslim ulong 14 +const jshmagc ulong 15 + +note ======== header and token cells ======== + +fn js_hg tape edit uint * i ulong to ulong +ret ulong get tape i +end + +fn js_hs tape edit uint * i ulong v ulong to void +put tape i uint v +end + +fn js_fail tape edit uint * code ulong q ulong to void +if eq get tape jsherr 0 +put tape jsherr uint code +put tape jshepos uint q +end +end + +fn js_okst tape edit uint * st ulong to ulong +if ne get tape jsherr 0 +ret 3 +end +ret st +end + +note js_cntinc: a key counts as an object member, any value directly inside an array as an element +fn js_cntinc tape edit uint * ty ulong to void +cur = js_hg tape jshcur +if eq cur 0 +ret +end +if or eq ty jsobje eq ty jsarre +ret +end +b = add jsth mul sub cur 1 jsts +ct = and ulong get tape b 15 +if or eq ty jskey eq ct jsarr +put tape b add get tape b 256 +end +end + +fn js_tok tape edit uint * ty ulong q ulong w ulong to ulong +t = js_hg tape jshnt +if ge t js_hg tape jshcap +js_fail tape jsetok q +ret jsnone +end +b = add jsth mul t jsts +put tape b uint ty +put tape add b 1 uint q +put tape add b 2 uint w +put tape add b 3 0 +js_hs tape jshnt add t 1 +js_cntinc tape ty +ret t +end + +note ======== limits and entry ======== + +note js_init: size limit 1..983040 bytes, depth limit 1..65535; the tape must hold the header and one token. +fn js_init tape edit uint * slim ulong dlim ulong to long +if lt len tape add jsth jsts +ret neg long jsearg +end +if or eq slim 0 gt slim jsmaxn +ret neg long jsearg +end +if or eq dlim 0 gt dlim jsdcap +ret neg long jsearg +end +for i ulong jsth +put tape i 0 +end +c = div sub len tape jsth jsts +if gt c jstmax +c = jstmax +end +js_hs tape jshslim slim +js_hs tape jshdlim dlim +js_hs tape jshcap c +js_hs tape jshmagc jsmagic +ret 0 +end + +fn js_reset tape edit uint * n ulong to void +js_hs tape jshok 0 +js_hs tape jshn n +js_hs tape jshpos 0 +js_hs tape jshnt 0 +js_hs tape jshcur 0 +js_hs tape jshdep 0 +js_hs tape jsherr 0 +js_hs tape jshepos 0 +js_hs tape jshmaxd 0 +js_hs tape jshdtot 0 +js_hs tape jshdmax 0 +js_hs tape jshsl 0 +end + +fn js_result tape edit uint * to long +e = js_hg tape jsherr +if ne e 0 +js_hs tape jshnt 0 +js_hs tape jshok 0 +ret neg long e +end +js_hs tape jshok 1 +ret long js_hg tape jshnt +end + +note js_parse: n bytes of src. Returns the token count, or minus a refusal code (tape then holds no tokens). +note Loop bound: every step consumes at least one distinct input byte (a token's first byte, a closing byte +note or a comma) or ends the parse, so steps <= n + 1 <= 983041 < 999999. +fn js_parse src view uchar * tape edit uint * n ulong to long +if lt len tape add jsth jsts +ret neg long jsearg +end +if ne js_hg tape jshmagc jsmagic +ret neg long jsearg +end +if gt n len src +ret neg long jsearg +end +js_reset tape n +if gt n js_hg tape jshslim +js_fail tape jsesiz js_hg tape jshslim +ret js_result tape +end +st = ulong 0 +while lt st 3 bound 999999 +st = js_step src tape st +end +ret js_result tape +end + +note states: 0 value expected, 1 after a value, 2 member key expected, 3 finished or refused +fn js_step src view uchar * tape edit uint * st ulong to ulong +js_ws src tape +if eq st 1 +ret js_after src tape +end +p = js_hg tape jshpos +if ge p js_hg tape jshn +js_fail tape jseeof p +ret 3 +end +if eq st 2 +ret js_keyst src tape +end +ret js_value src tape +end + +fn js_ws src view uchar * tape edit uint * to void +p = js_hg tape jshpos +n = js_hg tape jshn +while lt p n bound 999999 +c = get src p +if and ne c 32 and ne c 9 and ne c 10 ne c 13 +break +end +p = add p 1 +end +js_hs tape jshpos p +end + +fn js_at src view uchar * tape edit uint * q ulong c uchar to bool +if ge q js_hg tape jshn +ret false +end +ret eq get src q c +end + +fn js_value src view uchar * tape edit uint * to ulong +p = js_hg tape jshpos +c = get src p +if eq c 123 +ret js_open src tape jsobj +end +if eq c 91 +ret js_open src tape jsarr +end +if eq c 34 +js_string src tape jsstr +ret js_okst tape 1 +end +if or eq c 45 and ge c 48 le c 57 +js_number src tape +ret js_okst tape 1 +end +if eq c 116 +js_lit src tape 0 +ret js_okst tape 1 +end +if eq c 102 +js_lit src tape 1 +ret js_okst tape 1 +end +if eq c 110 +js_lit src tape 2 +ret js_okst tape 1 +end +js_fail tape jsesyn p +ret 3 +end + +fn js_after src view uchar * tape edit uint * to ulong +d = js_hg tape jshdep +p = js_hg tape jshpos +n = js_hg tape jshn +if eq d 0 +if lt p n +js_fail tape jsetrl p +end +ret 3 +end +if ge p n +js_fail tape jseeof p +ret 3 +end +c = get src p +b = add jsth mul sub js_hg tape jshcur 1 jsts +bt = and ulong get tape b 15 +if eq c 44 +js_hs tape jshpos add p 1 +if eq bt jsobj +ret 2 +end +ret 0 +end +if and eq bt jsobj eq c 125 +js_close tape jsobje +ret js_okst tape 1 +end +if and eq bt jsarr eq c 93 +js_close tape jsarre +ret js_okst tape 1 +end +js_fail tape jsesyn p +ret 3 +end + +fn js_keyst src view uchar * tape edit uint * to ulong +p = js_hg tape jshpos +if ne get src p 34 +js_fail tape jsesyn p +ret 3 +end +js_string src tape jskey +if ne get tape jsherr 0 +ret 3 +end +js_ws src tape +q = js_hg tape jshpos +if ge q js_hg tape jshn +js_fail tape jseeof q +ret 3 +end +if ne get src q 58 +js_fail tape jsesyn q +ret 3 +end +js_hs tape jshpos add q 1 +ret 0 +end + +note ======== containers ======== + +note js_open: cell 3 of an open container keeps the enclosing open container (+1) until it closes. +fn js_open src view uchar * tape edit uint * ty ulong to ulong +p = js_hg tape jshpos +d = js_hg tape jshdep +if ge d js_hg tape jshdlim +js_fail tape jsedep p +ret 3 +end +t = js_tok tape ty p 1 +if eq t jsnone +ret 3 +end +put tape add add jsth mul t jsts 3 uint js_hg tape jshcur +js_hs tape jshcur add t 1 +d = add d 1 +js_hs tape jshdep d +if gt d js_hg tape jshmaxd +js_hs tape jshmaxd d +end +js_hs tape jshpos add p 1 +js_ws src tape +e = uchar 93 +if eq ty jsobj +e = uchar 125 +end +q = js_hg tape jshpos +if js_at src tape q e +js_close tape add ty 1 +ret js_okst tape 1 +end +if eq ty jsobj +ret 2 +end +ret 0 +end + +fn js_close tape edit uint * ety ulong to void +p = js_hg tape jshpos +cur = js_hg tape jshcur +b = add jsth mul sub cur 1 jsts +js_hs tape jshcur ulong get tape add b 3 +js_hs tape jshdep sub js_hg tape jshdep 1 +e = js_tok tape ety p 1 +if eq e jsnone +ret +end +put tape add b 3 uint e +put tape add add jsth mul e jsts 3 uint sub cur 1 +put tape add b 2 uint add sub p ulong get tape add b 1 1 +js_hs tape jshpos add p 1 +end + +note ======== literals and numbers ======== + +note js_litb: byte i of literal k (0 true, 1 false, 2 null) +fn js_litb k ulong i ulong to uchar +if eq k 0 +if eq i 0 +ret 116 +end +if eq i 1 +ret 114 +end +if eq i 2 +ret 117 +end +ret 101 +end +if eq k 1 +if eq i 0 +ret 102 +end +if eq i 1 +ret 97 +end +if eq i 2 +ret 108 +end +if eq i 3 +ret 115 +end +ret 101 +end +if eq i 0 +ret 110 +end +if eq i 1 +ret 117 +end +ret 108 +end + +fn js_litn k ulong to ulong +if eq k 1 +ret 5 +end +ret 4 +end + +fn js_lit src view uchar * tape edit uint * k ulong to void +p = js_hg tape jshpos +n = js_hg tape jshn +m = js_litn k +for i ulong m +q = add p i +if ge q n +js_fail tape jseeof n +ret +end +if ne get src q js_litb k i +js_fail tape jselit q +ret +end +end +t = js_tok tape add k 8 p m +js_hs tape jshpos add p m +end + +fn js_isdig src view uchar * tape edit uint * q ulong to bool +if ge q js_hg tape jshn +ret false +end +c = get src q +ret and ge c 48 le c 57 +end + +fn js_digits src view uchar * tape edit uint * q ulong to ulong +p = q +while js_isdig src tape p bound 999999 +p = add p 1 +end +ret p +end + +note js_number: RFC 8259 section 6 grammar; a leading zero followed by a digit is refused as a number +fn js_number src view uchar * tape edit uint * to void +s = js_hg tape jshpos +p = s +f = ulong 0 +if js_at src tape p 45 +f = jsfneg +p = add p 1 +end +if not js_isdig src tape p +js_fail tape jsenum p +ret +end +if js_at src tape p 48 +p = add p 1 +if js_isdig src tape p +js_fail tape jsenum p +ret +end +else +p = js_digits src tape p +end +if js_at src tape p 46 +p = add p 1 +if not js_isdig src tape p +js_fail tape jsenum p +ret +end +p = js_digits src tape p +f = or f jsffrac +end +if or js_at src tape p 101 js_at src tape p 69 +p = add p 1 +if or js_at src tape p 43 js_at src tape p 45 +p = add p 1 +end +if not js_isdig src tape p +js_fail tape jsenum p +ret +end +p = js_digits src tape p +f = or f jsfexp +end +t = js_tok tape jsnum s sub p s +if ne t jsnone +put tape add jsth mul t jsts uint or jsnum shl f 4 +end +js_hs tape jshpos p +end + +note ======== strings ======== + +note js_u8st: RFC 3629 section 4 well-formed UTF-8 as a state machine. State 0 expects a lead byte; +note 1, 2, 3 expect that many continuation bytes 80..BF; 4 after E0 expects A0..BF; 5 after ED expects +note 80..9F; 6 after F0 expects 90..BF; 7 after F4 expects 80..8F. 9 is refusal (overlong, surrogate, +note above U+10FFFF, stray continuation, C0, C1, F5..FF). +fn js_u8st s ulong c uchar to ulong +if eq s 0 +if lt c 128 +ret 0 +end +if lt c 194 +ret 9 +end +if lt c 224 +ret 1 +end +if eq c 224 +ret 4 +end +if eq c 237 +ret 5 +end +if lt c 240 +ret 2 +end +if eq c 240 +ret 6 +end +if lt c 244 +ret 3 +end +if eq c 244 +ret 7 +end +ret 9 +end +lo = uchar 128 +hi = uchar 191 +if eq s 4 +lo = uchar 160 +end +if eq s 5 +hi = uchar 159 +end +if eq s 6 +lo = uchar 144 +end +if eq s 7 +hi = uchar 143 +end +if or lt c lo gt c hi +ret 9 +end +if eq s 1 +ret 0 +end +if or eq s 2 or eq s 4 eq s 5 +ret 1 +end +ret 2 +end + +fn js_hexv c uchar to ulong +if and ge c 48 le c 57 +ret ulong sub c 48 +end +if and ge c 97 le c 102 +ret ulong sub c 87 +end +if and ge c 65 le c 70 +ret ulong sub c 55 +end +ret 16 +end + +fn js_cplen v ulong to ulong +if lt v 128 +ret 1 +end +if lt v 2048 +ret 2 +end +if lt v 65536 +ret 3 +end +ret 4 +end + +fn js_esc1 c uchar to bool +if or eq c 34 eq c 92 +ret true +end +if or eq c 47 eq c 98 +ret true +end +if or eq c 102 eq c 110 +ret true +end +ret or eq c 114 eq c 116 +end + +fn js_dadd tape edit uint * k ulong to void +js_hs tape jshsl add js_hg tape jshsl k +end + +fn js_hex4 src view uchar * tape edit uint * q ulong to ulong +n = js_hg tape jshn +v = ulong 0 +for i ulong 4 +r = add q i +if ge r n +js_fail tape jseeof n +ret jsnone +end +h = js_hexv get src r +if eq h 16 +js_fail tape jseesc r +ret jsnone +end +v = or shl v 4 h +end +ret v +end + +note js_uesc: p is the backslash of \uXXXX. A high surrogate must be followed at once by \u and a low +note surrogate; a lone low surrogate, or a high one without its low half, is refused (RFC 8259 section 8.2). +fn js_uesc src view uchar * tape edit uint * p ulong to ulong +h = js_hex4 src tape add p 2 +if eq h jsnone +ret jsnone +end +q = add p 6 +if and ge h 56320 le h 57343 +js_fail tape jsesur p +ret jsnone +end +if or lt h 55296 gt h 56319 +js_dadd tape js_cplen h +ret q +end +if not and js_at src tape q 92 js_at src tape add q 1 117 +if ge q js_hg tape jshn +js_fail tape jseeof q +ret jsnone +end +js_fail tape jsesur p +ret jsnone +end +l = js_hex4 src tape add q 2 +if eq l jsnone +ret jsnone +end +if or lt l 56320 gt l 57343 +js_fail tape jsesur q +ret jsnone +end +js_dadd tape 4 +ret add q 6 +end + +fn js_escape src view uchar * tape edit uint * p ulong to ulong +q = add p 1 +if ge q js_hg tape jshn +js_fail tape jseeof q +ret jsnone +end +c = get src q +if eq c 117 +ret js_uesc src tape p +end +if not js_esc1 c +js_fail tape jseesc q +ret jsnone +end +js_dadd tape 1 +ret add q 1 +end + +fn js_strtok tape edit uint * ty ulong s ulong e ulong to void +t = js_tok tape ty s sub e s +js_hs tape jshpos e +if eq t jsnone +ret +end +l = js_hg tape jshsl +put tape add add jsth mul t jsts 3 uint l +js_hs tape jshdtot add js_hg tape jshdtot l +if gt l js_hg tape jshdmax +js_hs tape jshdmax l +end +end + +note js_string: validates one string and records its decoded length; bytes are decoded later by js_sget. +note Each pass advances p by at least one byte, so passes <= n <= 983040. +fn js_string src view uchar * tape edit uint * ty ulong to void +s = js_hg tape jshpos +n = js_hg tape jshn +js_hs tape jshsl 0 +p = add s 1 +st = ulong 0 +while lt p n bound 999999 +c = get src p +if or ne st 0 ge c 128 +st = js_u8st st c +if eq st 9 +js_fail tape jseutf p +ret +end +js_dadd tape 1 +p = add p 1 +continue +end +if eq c 34 +js_strtok tape ty s add p 1 +ret +end +if lt c 32 +js_fail tape jsectl p +ret +end +if eq c 92 +p = js_escape src tape p +if eq p jsnone +ret +end +continue +end +js_dadd tape 1 +p = add p 1 +end +js_fail tape jseeof n +end + +note ======== public tape accessors (read only) ======== + +fn js_ok tape view uint * to bool +if lt len tape add jsth jsts +ret false +end +ret eq get tape jshok 1 +end + +fn js_ntok tape view uint * to ulong +if not js_ok tape +ret 0 +end +ret ulong get tape jshnt +end + +fn js_err tape view uint * to ulong +if lt len tape jsth +ret jsearg +end +ret ulong get tape jsherr +end + +fn js_epos tape view uint * to ulong +if lt len tape jsth +ret 0 +end +ret ulong get tape jshepos +end + +fn js_maxdep tape view uint * to ulong +if not js_ok tape +ret 0 +end +ret ulong get tape jshmaxd +end + +note js_dtotal: decoded bytes of every key and string; js_dmax: the longest one (sizes for js_sget buffers) +fn js_dtotal tape view uint * to ulong +if not js_ok tape +ret 0 +end +ret ulong get tape jshdtot +end + +fn js_dmax tape view uint * to ulong +if not js_ok tape +ret 0 +end +ret ulong get tape jshdmax +end + +fn js_cell tape view uint * t ulong i ulong to ulong +if not js_ok tape +ret 0 +end +if ge t ulong get tape jshnt +ret 0 +end +ret ulong get tape add add jsth mul t jsts i +end + +fn js_type tape view uint * t ulong to ulong +ret and js_cell tape t 0 15 +end + +fn js_nflags tape view uint * t ulong to ulong +ret and shr js_cell tape t 0 4 7 +end + +note js_nkids: members of an object, elements of an array +fn js_nkids tape view uint * t ulong to ulong +ty = js_type tape t +if or eq ty jsobj eq ty jsarr +ret shr js_cell tape t 0 8 +end +ret 0 +end + +fn js_off tape view uint * t ulong to ulong +ret js_cell tape t 1 +end + +fn js_span tape view uint * t ulong to ulong +ret js_cell tape t 2 +end + +fn js_match tape view uint * t ulong to ulong +ty = js_type tape t +if and ge ty jsobj le ty jsarre +ret js_cell tape t 3 +end +ret jsnone +end + +fn js_slen tape view uint * t ulong to ulong +ty = js_type tape t +if or eq ty jskey eq ty jsstr +ret js_cell tape t 3 +end +ret 0 +end + +note js_last: the last token of the value starting at t (its end token for a container) +fn js_last tape view uint * t ulong to ulong +ty = js_type tape t +if or eq ty jsobj eq ty jsarr +ret js_cell tape t 3 +end +ret t +end + +note js_first: first member key of an object or first element of an array, jsnone when empty or not one +fn js_first tape view uint * t ulong to ulong +if eq js_nkids tape t 0 +ret jsnone +end +ret add t 1 +end + +note js_enext: the element after array element e; js_mnext: the key after member key k; jsnone at the end +fn js_enext tape view uint * e ulong to ulong +n = add js_last tape e 1 +ty = js_type tape n +if or eq ty 0 or eq ty jsobje eq ty jsarre +ret jsnone +end +ret n +end + +fn js_mnext tape view uint * k ulong to ulong +if ne js_type tape k jskey +ret jsnone +end +n = add js_last tape add k 1 1 +if ne js_type tape n jskey +ret jsnone +end +ret n +end + +note ======== strings from the source (off is a key or string token's offset) ======== + +fn js_slim src view uchar * off ulong to ulong +n = len src +m = add off add jsmaxn 2 +if gt n m +ret m +end +ret n +end + +fn js_atv src view uchar * q ulong c uchar to bool +if ge q len src +ret false +end +ret eq get src q c +end + +fn js_hex4s src view uchar * q ulong to ulong +if gt add q 4 len src +ret jsnone +end +v = ulong 0 +for i ulong 4 +h = js_hexv get src add q i +if eq h 16 +ret jsnone +end +v = or shl v 4 h +end +ret v +end + +fn js_esv c uchar to ulong +if or eq c 34 or eq c 92 eq c 47 +ret ulong c +end +if eq c 98 +ret 8 +end +if eq c 102 +ret 12 +end +if eq c 110 +ret 10 +end +if eq c 114 +ret 13 +end +if eq c 116 +ret 9 +end +ret jsnone +end + +note js_ecp: the code point of the escape whose backslash is at p; jsnone for a malformed escape, +note jsbads for a surrogate that is not one well-formed pair +fn js_ecp src view uchar * p ulong to ulong +q = add p 1 +if ge q len src +ret jsnone +end +c = get src q +if ne c 117 +ret js_esv c +end +h = js_hex4s src add p 2 +if eq h jsnone +ret jsnone +end +if and ge h 56320 le h 57343 +ret jsbads +end +if or lt h 55296 gt h 56319 +ret h +end +r = add p 6 +if not js_atv src r 92 +ret jsbads +end +if not js_atv src add r 1 117 +ret jsbads +end +l = js_hex4s src add r 2 +if eq l jsnone +ret jsnone +end +if or lt l 56320 gt l 57343 +ret jsbads +end +ret add 65536 add shl sub h 55296 10 sub l 56320 +end + +note js_elen: source bytes of the escape at p whose code point is cp +fn js_elen src view uchar * p ulong cp ulong to ulong +if ne get src add p 1 117 +ret 2 +end +if ge cp 65536 +ret 12 +end +ret 6 +end + +note js_putcp: UTF-8 encoding of cp at w; returns the next w, or jsnone when it does not fit +fn js_putcp ob edit uchar * w ulong cp ulong to ulong +k = js_cplen cp +if gt add w k len ob +ret jsnone +end +if eq k 1 +put ob w uchar cp +ret add w 1 +end +if eq k 2 +put ob w uchar or 192 shr cp 6 +put ob add w 1 uchar or 128 and cp 63 +ret add w 2 +end +if eq k 3 +put ob w uchar or 224 shr cp 12 +put ob add w 1 uchar or 128 and shr cp 6 63 +put ob add w 2 uchar or 128 and cp 63 +ret add w 3 +end +put ob w uchar or 240 shr cp 18 +put ob add w 1 uchar or 128 and shr cp 12 63 +put ob add w 2 uchar or 128 and shr cp 6 63 +put ob add w 3 uchar or 128 and cp 63 +ret add w 4 +end + +note js_sgesc: decode the escape at src[p] into ob at w; the next w, or minus a code +fn js_sgesc src view uchar * p ulong ob edit uchar * w ulong to long +cp = js_ecp src p +if eq cp jsnone +ret neg long jseesc +end +if eq cp jsbads +ret neg long jsesur +end +r = js_putcp ob w cp +if eq r jsnone +ret neg long jsearg +end +ret long r +end + +note js_sget: decode the string whose opening quote is src[off] into ob[0..); returns the byte count or minus +note a code (jsearg: ob too small or off not a quote). It re-checks UTF-8, controls, escapes and surrogates. +fn js_sget src view uchar * off ulong ob edit uchar * to long +if ge off js_slim src off +ret neg long jsearg +end +if ne get src off 34 +ret neg long jsearg +end +p = add off 1 +w = ulong 0 +st = ulong 0 +while lt p js_slim src off bound 999999 +c = get src p +if and eq st 0 eq c 34 +ret long w +end +if and eq st 0 eq c 92 +r = js_sgesc src p ob w +if lt r 0 +ret r +end +w = ulong r +p = add p js_elen src p js_ecp src p +continue +end +if and eq st 0 lt c 32 +ret neg long jsectl +end +st = js_u8st st c +if eq st 9 +ret neg long jseutf +end +if ge w len ob +ret neg long jsearg +end +put ob w c +w = add w 1 +p = add p 1 +end +ret neg long jseeof +end + +note js_cpeq: whether key[k ..] starts with the UTF-8 encoding of cp; the next k, or jsnone +fn js_cpeq key view uchar * k ulong cp ulong to ulong +tmp = new uchar 4 0 +m = js_putcp tmp 0 cp +if gt m sub len key k +ret jsnone +end +for i ulong m +if ne get key add k i get tmp i +ret jsnone +end +end +ret add k m +end + +note js_streq: whether the decoded string at src[off] equals the bytes of key exactly +fn js_streq src view uchar * off ulong key view uchar * to bool +if ge off js_slim src off +ret false +end +if ne get src off 34 +ret false +end +p = add off 1 +k = ulong 0 +while lt p js_slim src off bound 999999 +c = get src p +if eq c 34 +ret eq k len key +end +if ne c 92 +if ge k len key +ret false +end +if ne get key k c +ret false +end +k = add k 1 +p = add p 1 +continue +end +cp = js_ecp src p +if ge cp jsbads +ret false +end +k = js_cpeq key k cp +if eq k jsnone +ret false +end +p = add p js_elen src p cp +end +ret false +end + +note ======== integers from a number lexeme at src[off] (exact; no rounding) ======== + +note js_ovf10: whether m * 10 + d exceeds 18446744073709551615 +fn js_ovf10 m ulong d ulong to bool +if gt m 1844674407370955161 +ret true +end +if lt m 1844674407370955161 +ret false +end +ret gt d 5 +end + +note js_ilex: 0 not an integer lexeme (fraction or exponent present, or no digit), 1 integer whose +note magnitude fits ulong, 2 integer whose magnitude exceeds 18446744073709551615 +fn js_ilex src view uchar * off ulong to ulong +n = js_slim src off +p = off +if js_atv src p 45 +p = add p 1 +end +m = ulong 0 +ovf = false +k = ulong 0 +while lt p n bound 999999 +c = get src p +if or lt c 48 gt c 57 +break +end +d = ulong sub c 48 +if js_ovf10 m d +ovf = true +else +m = add mul m 10 d +end +k = add k 1 +p = add p 1 +end +if eq k 0 +ret 0 +end +if lt p n +c = get src p +if or eq c 46 or eq c 101 eq c 69 +ret 0 +end +end +if ovf +ret 2 +end +ret 1 +end + +fn js_imag src view uchar * off ulong to ulong +n = js_slim src off +p = off +if js_atv src p 45 +p = add p 1 +end +m = ulong 0 +while lt p n bound 25 +c = get src p +if or lt c 48 gt c 57 +break +end +m = add mul m 10 ulong sub c 48 +p = add p 1 +end +ret m +end + +fn js_isu src view uchar * off ulong to bool +if ne js_ilex src off 1 +ret false +end +ret not js_atv src off 45 +end + +fn js_tou src view uchar * off ulong to ulong +if not js_isu src off +ret 0 +end +ret js_imag src off +end + +fn js_isl src view uchar * off ulong to bool +if ne js_ilex src off 1 +ret false +end +m = js_imag src off +if js_atv src off 45 +ret le m 9223372036854775808 +end +ret le m 9223372036854775807 +end + +fn js_tol src view uchar * off ulong to long +if not js_isl src off +ret 0 +end +m = js_imag src off +if not js_atv src off 45 +ret long m +end +if eq m 9223372036854775808 +ret long -9223372036854775808 +end +ret neg long m +end diff --git a/native/omegallm/net/jsonw.om b/native/omegallm/net/jsonw.om new file mode 100644 index 0000000..9f7bf11 --- /dev/null +++ b/native/omegallm/net/jsonw.om @@ -0,0 +1,671 @@ +note seed/json/jsonw.om: strict JSON writer for seeded Omega (omega-mv #788). Needs json.om before it. README.md. +note The caller owns one `uchar` output array ob. Its first 1040 bytes are the writer state; the JSON text is +note ob[1040 .. 1040 + js_wlen ob). State bytes: 0..7 text length (little-endian), 8 error code, 9 flags +note (1 inside a string, 2 that string is a member key, 4 the root value is complete), 10 UTF-8 state of the +note string being written, 11..12 depth (little-endian), 16 + d - 1 level d: 1 object, 2 array, 4 has an item, +note 8 a key was written and its value is due. Every call checks the state, so only RFC 8259 text can come +note out; a refused call writes nothing more and its code sticks until js_winit. + +const jswh ulong 1040 +const jswdcap ulong 1024 +const jswerr ulong 8 +const jswflg ulong 9 +const jswu8 ulong 10 + +note writer refusal codes; js_wdone returns minus the code +const jswesp ulong 21 +const jswest ulong 22 +const jsweut ulong 23 +const jswenm ulong 24 +const jswedp ulong 25 +const jswearg ulong 26 +const jswesrc ulong 27 + +note ======== state ======== + +fn js_winit ob edit uchar * to long +if le len ob jswh +ret neg long jswearg +end +for i ulong jswh +put ob i 0 +end +ret 0 +end + +fn js_wlen ob view uchar * to ulong +if le len ob jswh +ret 0 +end +v = ulong 0 +for i ulong 8 +v = or v shl ulong get ob i mul i 8 +end +ret v +end + +fn js_wsetn ob edit uchar * v ulong to void +for i ulong 8 +put ob i uchar and shr v mul i 8 255 +end +end + +fn js_werr ob view uchar * to ulong +if le len ob jswh +ret jswearg +end +ret ulong get ob jswerr +end + +fn js_wfail ob edit uchar * code ulong to void +if eq get ob jswerr 0 +put ob jswerr uchar code +end +end + +fn js_wdep ob edit uchar * to ulong +ret or ulong get ob 11 shl ulong get ob 12 8 +end + +fn js_wsdep ob edit uchar * d ulong to void +put ob 11 uchar and d 255 +put ob 12 uchar shr d 8 +end + +fn js_wb ob edit uchar * c uchar to void +if ne get ob jswerr 0 +ret +end +n = js_wlen ob +q = add jswh n +if ge q len ob +js_wfail ob jswesp +ret +end +put ob q c +js_wsetn ob add n 1 +end + +note js_wpre: before a value. Refuses a value where a member key is due, a second root value, and any +note value inside a string; writes the comma between array elements. +fn js_wpre ob edit uchar * to bool +if ne get ob jswerr 0 +ret false +end +f = get ob jswflg +if ne and f 1 0 +js_wfail ob jswest +ret false +end +d = js_wdep ob +if eq d 0 +if ne and f 4 0 +js_wfail ob jswest +ret false +end +ret true +end +l = get ob add 15 d +if eq and l 1 1 +if eq and l 8 0 +js_wfail ob jswest +ret false +end +ret true +end +if ne and l 4 0 +js_wb ob 44 +end +ret eq get ob jswerr 0 +end + +fn js_wpost ob edit uchar * to void +d = js_wdep ob +if eq d 0 +put ob jswflg or get ob jswflg 4 +ret +end +i = add 15 d +put ob i and or get ob i 4 247 +end + +fn js_wiskey ob edit uchar * to bool +d = js_wdep ob +if eq d 0 +ret false +end +l = get ob add 15 d +ret and eq and l 1 1 eq and l 8 0 +end + +fn js_wkpre ob edit uchar * to bool +if ne get ob jswerr 0 +ret false +end +if ne and get ob jswflg 1 0 +js_wfail ob jswest +ret false +end +if not js_wiskey ob +js_wfail ob jswest +ret false +end +if ne and get ob add 15 js_wdep ob 4 0 +js_wb ob 44 +end +ret eq get ob jswerr 0 +end + +note ======== containers ======== + +fn js_wopen ob edit uchar * kind ulong to void +if not js_wpre ob +ret +end +d = js_wdep ob +if ge d jswdcap +js_wfail ob jswedp +ret +end +if eq kind 1 +js_wb ob 123 +else +js_wb ob 91 +end +if ne get ob jswerr 0 +ret +end +d = add d 1 +js_wsdep ob d +put ob add 15 d uchar kind +end + +fn js_wclose ob edit uchar * kind ulong to void +if ne get ob jswerr 0 +ret +end +if ne and get ob jswflg 1 0 +js_wfail ob jswest +ret +end +d = js_wdep ob +if eq d 0 +js_wfail ob jswest +ret +end +l = ulong get ob add 15 d +if ne and l 3 kind +js_wfail ob jswest +ret +end +if ne and l 8 0 +js_wfail ob jswest +ret +end +if eq kind 1 +js_wb ob 125 +else +js_wb ob 93 +end +if ne get ob jswerr 0 +ret +end +put ob add 15 d 0 +js_wsdep ob sub d 1 +js_wpost ob +end + +fn js_wobj ob edit uchar * to void +js_wopen ob 1 +end + +fn js_wobje ob edit uchar * to void +js_wclose ob 1 +end + +fn js_warr ob edit uchar * to void +js_wopen ob 2 +end + +fn js_warre ob edit uchar * to void +js_wclose ob 2 +end + +note ======== scalars ======== + +fn js_wlit ob edit uchar * k ulong to void +if not js_wpre ob +ret +end +for i ulong js_litn k +js_wb ob js_litb k i +end +js_wpost ob +end + +fn js_wnull ob edit uchar * to void +js_wlit ob 2 +end + +fn js_wbool ob edit uchar * b bool to void +if b +js_wlit ob 0 +else +js_wlit ob 1 +end +end + +fn js_wdig ob edit uchar * m ulong to void +tmp = new uchar 20 0 +k = ulong 0 +v = m +for i ulong 20 +put tmp k uchar add rem v 10 48 +k = add k 1 +v = div v 10 +if eq v 0 +break +end +end +while gt k 0 bound 21 +k = sub k 1 +js_wb ob get tmp k +end +end + +fn js_wulong ob edit uchar * v ulong to void +if not js_wpre ob +ret +end +js_wdig ob v +js_wpost ob +end + +fn js_wlong ob edit uchar * v long to void +if not js_wpre ob +ret +end +if lt v 0 +js_wb ob 45 +js_wdig ob add ulong neg add v 1 1 +else +js_wdig ob ulong v +end +js_wpost ob +end + +note js_numend: end of the RFC 8259 number lexeme starting at s[p], within s[p .. e); jsnone when none starts there +fn js_isb s view uchar * q ulong e ulong c uchar to bool +if ge q e +ret false +end +ret eq get s q c +end + +fn js_digend s view uchar * p ulong e ulong to ulong +q = p +while lt q e bound 999999 +c = get s q +if or lt c 48 gt c 57 +break +end +q = add q 1 +end +ret q +end + +fn js_numend s view uchar * p ulong e ulong to ulong +q = p +if js_isb s q e 45 +q = add q 1 +end +r = js_digend s q e +if eq r q +ret jsnone +end +if and eq get s q 48 gt sub r q 1 +ret jsnone +end +q = r +if js_isb s q e 46 +r = js_digend s add q 1 e +if eq r add q 1 +ret jsnone +end +q = r +end +if or js_isb s q e 101 js_isb s q e 69 +q = add q 1 +if or js_isb s q e 43 js_isb s q e 45 +q = add q 1 +end +r = js_digend s q e +if eq r q +ret jsnone +end +q = r +end +ret q +end + +fn js_wcopy ob edit uchar * s view uchar * p ulong e ulong to void +for i ulong sub e p +js_wb ob get s add p i +end +end + +note js_wnumb: s[off .. off + n) must be exactly one number lexeme; it is written byte for byte +fn js_wnumb ob edit uchar * s view uchar * off ulong n ulong to void +if ne get ob jswerr 0 +ret +end +if or gt n jsmaxn gt n len s +js_wfail ob jswearg +ret +end +if gt off sub len s n +js_wfail ob jswearg +ret +end +e = add off n +if ne js_numend s off e e +js_wfail ob jswenm +ret +end +if not js_wpre ob +ret +end +js_wcopy ob s off e +js_wpost ob +end + +note js_wlex: the number lexeme that starts at src[off] (a parsed number token's offset), unchanged +fn js_wlex ob edit uchar * src view uchar * off ulong to void +if ne get ob jswerr 0 +ret +end +e = js_numend src off js_slim src off +if eq e jsnone +js_wfail ob jswenm +ret +end +if not js_wpre ob +ret +end +js_wcopy ob src off e +js_wpost ob +end + +note ======== strings ======== + +fn js_hexd v uchar to uchar +if lt v 10 +ret add v 48 +end +ret add v 87 +end + +note js_wesc: RFC 8259 section 7 escaping of one ASCII byte: quote, backslash and U+0000..U+001F only, +note with the two-character forms for b f n r t and \u00xx (lowercase hex) for the other controls. +fn js_wesc ob edit uchar * c uchar to void +if eq c 34 +js_wb ob 92 +js_wb ob 34 +ret +end +if eq c 92 +js_wb ob 92 +js_wb ob 92 +ret +end +if ge c 32 +js_wb ob c +ret +end +js_wb ob 92 +if eq c 8 +js_wb ob 98 +ret +end +if eq c 12 +js_wb ob 102 +ret +end +if eq c 10 +js_wb ob 110 +ret +end +if eq c 13 +js_wb ob 114 +ret +end +if eq c 9 +js_wb ob 116 +ret +end +js_wb ob 117 +js_wb ob 48 +js_wb ob 48 +js_wb ob js_hexd shr c 4 +js_wb ob js_hexd and c 15 +end + +note js_wsbeg / js_wsb / js_wsend stream one string of raw UTF-8 bytes. It is a member key when the +note innermost open container is an object whose next item is a key, otherwise a value. +fn js_wsbeg ob edit uchar * to void +if ne get ob jswerr 0 +ret +end +if ne and get ob jswflg 1 0 +js_wfail ob jswest +ret +end +if js_wiskey ob +if not js_wkpre ob +ret +end +js_wb ob 34 +put ob jswflg or get ob jswflg 3 +else +if not js_wpre ob +ret +end +js_wb ob 34 +put ob jswflg or get ob jswflg 1 +end +put ob jswu8 0 +end + +fn js_wsb ob edit uchar * c uchar to void +if ne get ob jswerr 0 +ret +end +if eq and get ob jswflg 1 0 +js_wfail ob jswest +ret +end +s = ulong get ob jswu8 +if or ne s 0 ge c 128 +s = js_u8st s c +if eq s 9 +js_wfail ob jsweut +ret +end +put ob jswu8 uchar s +js_wb ob c +ret +end +js_wesc ob c +end + +fn js_wsend ob edit uchar * to void +if ne get ob jswerr 0 +ret +end +f = get ob jswflg +if eq and f 1 0 +js_wfail ob jswest +ret +end +if ne get ob jswu8 0 +js_wfail ob jsweut +ret +end +js_wb ob 34 +if ne get ob jswerr 0 +ret +end +put ob jswflg and f 252 +if ne and f 2 0 +js_wb ob 58 +i = add 15 js_wdep ob +put ob i or get ob i 8 +ret +end +js_wpost ob +end + +note js_wsbuf: the string s[off .. off + n) of raw UTF-8 bytes (n <= 983040) +fn js_wsbuf ob edit uchar * s view uchar * off ulong n ulong to void +if ne get ob jswerr 0 +ret +end +if or gt n jsmaxn gt n len s +js_wfail ob jswearg +ret +end +if gt off sub len s n +js_wfail ob jswearg +ret +end +js_wsbeg ob +for i ulong n +js_wsb ob get s add off i +end +js_wsend ob +end + +note js_wsesc: write the escape at src[p] as raw UTF-8 string bytes; the next p, or jsnone after a refusal +fn js_wsesc ob edit uchar * src view uchar * p ulong to ulong +tmp = new uchar 4 0 +cp = js_ecp src p +if ge cp jsbads +js_wfail ob jswesrc +ret jsnone +end +m = js_putcp tmp 0 cp +for i ulong m +js_wsb ob get tmp i +end +ret add p js_elen src p cp +end + +note js_wsrc: re-encode the JSON string whose opening quote is src[off] (a parsed key or string token) +fn js_wsrc ob edit uchar * src view uchar * off ulong to void +if ne get ob jswerr 0 +ret +end +if not js_atv src off 34 +js_wfail ob jswesrc +ret +end +js_wsbeg ob +p = add off 1 +while lt p js_slim src off bound 999999 +if ne get ob jswerr 0 +ret +end +c = get src p +if and eq get ob jswu8 0 eq c 34 +js_wsend ob +ret +end +if and eq get ob jswu8 0 eq c 92 +p = js_wsesc ob src p +if eq p jsnone +ret +end +continue +end +if and eq get ob jswu8 0 lt c 32 +js_wfail ob jswesrc +ret +end +js_wsb ob c +p = add p 1 +end +js_wfail ob jswesrc +end + +note ======== tape tokens and completion ======== + +note js_wtok: write one parsed token, given its type (js_type) and offset (js_off). A key token must land +note where a key is due and a string token where a value is due. +fn js_wtok ob edit uchar * src view uchar * ty ulong off ulong to void +if ne get ob jswerr 0 +ret +end +if eq ty jsobj +js_wobj ob +ret +end +if eq ty jsobje +js_wobje ob +ret +end +if eq ty jsarr +js_warr ob +ret +end +if eq ty jsarre +js_warre ob +ret +end +if or eq ty jskey eq ty jsstr +isk = js_wiskey ob +if and eq ty jskey not isk +js_wfail ob jswest +ret +end +if and eq ty jsstr isk +js_wfail ob jswest +ret +end +js_wsrc ob src off +ret +end +if eq ty jsnum +js_wlex ob src off +ret +end +if and ge ty jstrue le ty jsnull +js_wlit ob sub ty 8 +ret +end +js_wfail ob jswest +end + +note js_wdone: the text length when exactly one complete root value was written, else minus a code +fn js_wdone ob edit uchar * to long +if le len ob jswh +ret neg long jswearg +end +e = ulong get ob jswerr +if ne e 0 +ret neg long e +end +f = get ob jswflg +d = js_wdep ob +bad = ne and f 1 0 +if ne d 0 +bad = true +end +if eq and f 4 0 +bad = true +end +if bad +js_wfail ob jswest +ret neg long jswest +end +ret long js_wlen ob +end diff --git a/native/omegallm/noserve.om b/native/omegallm/noserve.om new file mode 100644 index 0000000..3b550d9 --- /dev/null +++ b/native/omegallm/noserve.om @@ -0,0 +1,6 @@ +note cmdserve for the targets without serve.om (gb10, x86linux, x86efi): serve.om needs the om2 +note profile and omega-mv e5b32567's seed/net/http.om, which build.sh composes on aarch64 only, so +note `ollm serve` refuses here with exit 2. +fn cmdserve to void +exit 2 +end diff --git a/native/omegallm/serve.om b/native/omegallm/serve.om new file mode 100644 index 0000000..83ceb98 --- /dev/null +++ b/native/omegallm/serve.om @@ -0,0 +1,1115 @@ +note SPDX-License-Identifier: AGPL-3.0-only +note omegallm serve.om (aien-train DRA-119): `ollm serve PORT CK MERGES [MAXCONN]`, an +note OpenAI-compatible HTTP/1.1 server for a v1 BPE checkpoint (V > 256) on 127.0.0.1:PORT only. +note aarch64 only: build.sh composes it under one `om2` line after the omega-mv e5b32567 units +note net/http.om, net/json.om and net/jsonw.om (vendored unmodified); the other targets take +note noserve.om. It prints `PORT n`, then serves one connection at a time, one request each +note (Connection: close), until MAXCONN connections (default 1000000) have been served. +note Routes: GET /health {"status":"ok","in_flight":0}; GET /v1/models; POST /v1/chat/completions +note with JSON or SSE (stream true) responses; other paths 404, other methods 405. +note Request: messages (non-empty array of objects with a string role of at most 32 bytes and a +note string or null content), optional max_tokens or max_completion_tokens (1 .. 999999), +note temperature (0 .. 2 without exponent, used to 0.001; default 1), seed (unsigned, default 1), +note stream, stream_options.include_usage and n (only 1). Other members (model, tools, tool_choice) +note are accepted and ignored: this model never calls tools. +note Interim chat template (until DRA-123 fixes one shared template): `role: content\n` for each +note message in order, then `assistant: `; at most 4000 bytes, else 400. The context is token 0 then +note the template's encoding (CT0 tokens, reported as prompt_tokens); CT0 >= T is refused with 400 +note context_length_exceeded. Output runs at most min(max_tokens, T - CT0) tokens, so the T-token +note window never slides (cmdsamp's sampling step osstep, splitmix64 seed stream); a generated +note token 0 ends it with finish_reason stop, the limit with length. Decoded bytes are sent as +note UTF-8: a sequence cut by a token boundary waits for the next token, an ill-formed one (or one +note cut by the end) becomes U+FFFD. One line per routed response (and per 413 at the head) goes +note to stdout: `C status prompt_tokens completion_tokens finish(0 none, 1 stop, 2 length) ms`. +note Exit codes: 2 usage; 27 merges (bpe.om); 71 the port cannot be bound. +note wb layout: raw token bytes [0, 8192), content [8192, 73728), template [73728, 77824), +note message [81920, 82176), response id [82176, 82240). sv slots: 0 stream, 1 max tokens, +note 2 TEMPMILLI, 3 seed state, 4 include_usage, 5 template bytes, 6 CT0, 7 generated, 8 finish, +note 9 request count, 10 created, 11 start ns, 12 raw bytes, 13 content bytes, 14 content sent, +note 16 error code, 19 T, 21 last status. + +text svtjson "application/json" +text svtctyp "Content-Type" +text svphlth "/health" +text svpmods "/v1/models" +text svpchat "/v1/chat/completions" +text svmget "GET" +text svmpost "POST" +text svthlth "{\"status\":\"ok\",\"in_flight\":0}" +text svtmods "{\"object\":\"list\",\"data\":[{\"id\":\"ollm\",\"object\":\"model\",\"created\":0,\"owned_by\":\"aien\"}]}" +text svport "PORT " +text skmsgs "messages" +text skrole "role" +text skcont "content" +text skstrm "stream" +text skmaxt "max_tokens" +text skmaxc "max_completion_tokens" +text sktemp "temperature" +text skseed "seed" +text skopts "stream_options" +text skincl "include_usage" +text skn "n" +text skid "id" +text skobj "object" +text skcrt "created" +text skmodel "model" +text skchoi "choices" +text skidx "index" +text skmsg "message" +text skdelta "delta" +text skfin "finish_reason" +text skusage "usage" +text skpt "prompt_tokens" +text skct "completion_tokens" +text sktt "total_tokens" +text skerr "error" +text sktype "type" +text skcode "code" +text skparam "param" +text svollm "ollm" +text svasst "assistant" +text svcc "chat.completion" +text svccc "chat.completion.chunk" +text svstop "stop" +text svlen "length" +text svinv "invalid_request_error" +text svsrv "server_error" +text svdone "[DONE]" +text svidp "chatcmpl-ollm-" +text svsep ": " +text svnl "\n" +text svaprm "assistant: " +text secjson "invalid_json" +text secreq "invalid_request" +text secctx "context_length_exceeded" +text secbig "request_too_large" +text secnf "not_found" +text secmeth "method_not_allowed" +text secint "internal_error" +text sem1 "request body is not valid JSON (RFC 8259) or has over 65532 JSON tokens" +text sem2 "the request must be a JSON object" +text sem3 "messages must be a non-empty array of objects" +text sem4 "message content must be a string or null" +text sem5 "message role must be a string of at most 32 bytes" +text sem6 "the chat template is over 4000 bytes" +text sem7 "temperature must be a number from 0 to 2 without exponent" +text sem8 "max_tokens must be an integer from 1 to 999999" +text sem9 "seed must be an unsigned integer" +text sem10 "stream must be true or false" +text sem12 "only n = 1 is supported" +text sem13 "the request body is over 983040 bytes" +text sem14 "no such path; routes: GET /health, GET /v1/models, POST /v1/chat/completions" +text sem15 "method not allowed on this path" +text sem16 "response construction failed" +text sem11a "prompt is " +text sem11b " tokens including the start token; the context window is " +text sem11c " tokens, so no room is left for output" + +note ======== small byte helpers over wb + +note svmcat: copy text t into wb at p, at most up to e; the next p +fn svmcat wb edit uchar 82432 p ulong e ulong t view uchar * to ulong +q = p +for i ulong len t +if ge q e +ret q +end +put wb q get t i +q = add q 1 +end +ret q +end + +note svmdec: v in decimal into wb at p (at most 20 digits, up to e); the next p +fn svmdec wb edit uchar 82432 p ulong e ulong v ulong to ulong +d = new uchar 20 0 +i = ulong 20 +x = v +for it ulong 20 +i = sub i 1 +put d i uchar add rem x 10 48 +x = div x 10 +if eq x 0 +break +end +end +q = p +for k ulong sub 20 i +if ge q e +ret q +end +put wb q get d add i k +q = add q 1 +end +ret q +end + +note ======== UTF-8 (RFC 3629 section 4) + +note svu8n: the sequence at a[p], with a[0 .. n) the bytes so far: 1 .. 4 its length when well +note formed; 0 when a[p .. n) is a proper prefix of a well-formed sequence; 8 + k when its maximal +note ill-formed subpart is k bytes (replaced by one U+FFFD) +fn svu8n a view uchar * p ulong n ulong to ulong +c = ulong get a p +if lt c 128 +ret 1 +end +k = svu8k c +if eq k 0 +ret 9 +end +for i ulong sub k 1 +q = add p add i 1 +if ge q n +ret 0 +end +if not svu8ok c i ulong get a q +ret add 9 i +end +end +ret k +end + +note svu8k: the sequence length a lead byte c >= 128 starts, 0 when it starts none +fn svu8k c ulong to ulong +if and ge c 194 le c 223 +ret 2 +end +if and ge c 224 le c 239 +ret 3 +end +if and ge c 240 le c 244 +ret 4 +end +ret 0 +end + +note svu8ok: whether b may be continuation byte i (0 the first) after lead byte c (RFC 3629 table) +fn svu8ok c ulong i ulong b ulong to bool +lo = ulong 128 +hi = ulong 191 +if eq i 0 +if eq c 224 +lo = 160 +end +if eq c 237 +hi = 159 +end +if eq c 240 +lo = 144 +end +if eq c 244 +hi = 143 +end +end +ret and ge b lo le b hi +end + +note svrepl: U+FFFD (EF BF BD) into the content at its end +fn svrepl wb edit uchar 82432 sv edit ulong 64 to void +g = add 8192 get sv 13 +put wb g 239 +put wb add g 1 191 +put wb add g 2 189 +put sv 13 add get sv 13 3 +end + +note svclean: move the complete sequences of the raw bytes wb[0, sv12) to the content; fin 1 also +note replaces a cut tail. The rest moves to the front of the raw bytes. +fn svclean wb edit uchar 82432 sv edit ulong 64 fin ulong to void +rn = get sv 12 +p = ulong 0 +for it ulong add rn 1 +if ge p rn +break +end +r = svu8n wb p rn +if eq r 0 +if eq fin 0 +break +end +svrepl wb sv +p = rn +else +if gt r 8 +svrepl wb sv +p = add p sub r 8 +else +svmove wb add 8192 get sv 13 p r +put sv 13 add get sv 13 r +p = add p r +end +end +end +svmove wb 0 p sub rn p +put sv 12 sub rn p +end + +note svmove: wb[d, d + n) = wb[s, s + n), copying forward (d <= s or the ranges apart) +fn svmove wb edit uchar 82432 d ulong s ulong n ulong to void +for i ulong n +put wb add d i get wb add s i +end +end + +note ======== responses + +fn svstat cs edit ulong 320 io edit uchar 131072 code ulong t view uchar * to long +r = hrspst cs io code +r = hfe r hhname cs io svtctyp +r = hfe r hhval cs io svtjson +r = hfe r hhend cs io 0 len t +r = hfe r hput cs io t +ret hfe r hwfin cs io +end + +note svsend: the writer's text ob[1040, 1040 + n) as a JSON response with status code +fn svsend cs edit ulong 320 io edit uchar 131072 ob edit uchar 409600 code ulong n ulong to long +r = hrspst cs io code +r = hfe r hhname cs io svtctyp +r = hfe r hhval cs io svtjson +r = hfe r hhend cs io 0 n +r = hfe r hput cs io view part ob 1040 n +ret hfe r hwfin cs io +end + +fn svwt ob edit uchar 409600 t view uchar * to void +js_wsbuf ob t 0 len t +end + +note svemsg: the message of error code sv16 into wb[81920 ..); its length +fn svemsg wb edit uchar 82432 sv edit ulong 64 to ulong +e = get sv 16 +b = ulong 81920 +z = ulong 82176 +p = b +if eq e 1 +p = svmcat wb p z sem1 +end +if eq e 2 +p = svmcat wb p z sem2 +end +if eq e 3 +p = svmcat wb p z sem3 +end +if eq e 4 +p = svmcat wb p z sem4 +end +if eq e 5 +p = svmcat wb p z sem5 +end +if eq e 6 +p = svmcat wb p z sem6 +end +if eq e 7 +p = svmcat wb p z sem7 +end +if eq e 8 +p = svmcat wb p z sem8 +end +if eq e 9 +p = svmcat wb p z sem9 +end +if eq e 10 +p = svmcat wb p z sem10 +end +if eq e 11 +p = svmcat wb p z sem11a +p = svmdec wb p z get sv 6 +p = svmcat wb p z sem11b +p = svmdec wb p z get sv 19 +p = svmcat wb p z sem11c +end +if eq e 12 +p = svmcat wb p z sem12 +end +if eq e 13 +p = svmcat wb p z sem13 +end +if eq e 14 +p = svmcat wb p z sem14 +end +if eq e 15 +p = svmcat wb p z sem15 +end +if eq e 16 +p = svmcat wb p z sem16 +end +ret sub p b +end + +fn svecode ob edit uchar 409600 e ulong to void +if eq e 1 +svwt ob secjson +ret +end +if eq e 11 +svwt ob secctx +ret +end +if eq e 13 +svwt ob secbig +ret +end +if eq e 14 +svwt ob secnf +ret +end +if eq e 15 +svwt ob secmeth +ret +end +if eq e 16 +svwt ob secint +ret +end +svwt ob secreq +end + +note svfail: {"error":{"message","type","param":null,"code"}} for error code sv16 with status st +fn svfail cs edit ulong 320 io edit uchar 131072 wb edit uchar 82432 sv edit ulong 64 st ulong to long +ob = new uchar 409600 0 +put sv 21 st +m = svemsg wb sv +x = js_winit ob +js_wobj ob +svwt ob skerr +js_wobj ob +svwt ob skmsg +js_wsbuf ob wb 81920 m +svwt ob sktype +if eq st 500 +svwt ob svsrv +else +svwt ob svinv +end +svwt ob skparam +js_wnull ob +svwt ob skcode +svecode ob get sv 16 +js_wobje ob +js_wobje ob +n = js_wdone ob +if lt n 0 +put cs HKEEP 0 +ret hrsperr cs io 500 +end +ret svsend cs io ob st ulong n +end + +note svhead: {"id", "object" t, "created", "model" opened; the caller adds the rest +fn svhead ob edit uchar 409600 wb edit uchar 82432 sv edit ulong 64 t view uchar * to void +x = js_winit ob +js_wobj ob +svwt ob skid +js_wsbuf ob wb 82176 get sv 15 +svwt ob skobj +svwt ob t +svwt ob skcrt +js_wulong ob get sv 10 +svwt ob skmodel +svwt ob svollm +end + +fn svfr ob edit uchar 409600 sv edit ulong 64 to void +f = get sv 8 +if eq f 1 +svwt ob svstop +ret +end +if eq f 2 +svwt ob svlen +ret +end +js_wnull ob +end + +fn svusage ob edit uchar 409600 sv edit ulong 64 to void +svwt ob skusage +js_wobj ob +svwt ob skpt +js_wulong ob get sv 6 +svwt ob skct +js_wulong ob get sv 7 +svwt ob sktt +js_wulong ob add get sv 6 get sv 7 +js_wobje ob +end + +note svfull: the chat.completion object (stream false) +fn svfull ob edit uchar 409600 wb edit uchar 82432 sv edit ulong 64 to long +svhead ob wb sv svcc +svwt ob skchoi +js_warr ob +js_wobj ob +svwt ob skidx +js_wulong ob 0 +svwt ob skmsg +js_wobj ob +svwt ob skrole +svwt ob svasst +svwt ob skcont +js_wsbuf ob wb 8192 get sv 13 +js_wobje ob +svwt ob skfin +svfr ob sv +js_wobje ob +js_warre ob +svusage ob sv +js_wobje ob +ret js_wdone ob +end + +note svchunk: one chat.completion.chunk; kind 0 the role, 1 the content wb[8192 + sv14, 8192 + sv13), +note 2 the finish reason, 3 usage (empty choices). Sends it as one SSE event. +fn svchunk cs edit ulong 320 io edit uchar 131072 ob edit uchar 409600 wb edit uchar 82432 sv edit ulong 64 kind ulong to long +svhead ob wb sv svccc +svwt ob skchoi +js_warr ob +if ne kind 3 +js_wobj ob +svwt ob skidx +js_wulong ob 0 +svwt ob skdelta +js_wobj ob +if eq kind 0 +svwt ob skrole +svwt ob svasst +svwt ob skcont +note "" as zero bytes of a non-empty text: under omc e5b32567 an empty text passed as a view has a +note wrong length (omega-mv#775, fixed after this pin), and js_wsbuf then refuses it (jswearg) +js_wsbuf ob svasst 0 0 +end +if eq kind 1 +svwt ob skcont +g0 = get sv 14 +js_wsbuf ob wb add 8192 g0 sub get sv 13 g0 +end +js_wobje ob +svwt ob skfin +if eq kind 2 +svfr ob sv +else +js_wnull ob +end +js_wobje ob +end +js_warre ob +if eq kind 3 +svusage ob sv +end +js_wobje ob +n = js_wdone ob +if lt n 0 +ret -5 +end +r = hssedat cs io view part ob 1040 ulong n +ret hfe r hsseend cs io +end + +note ======== request parsing + +note svtemp: the temperature token's lexeme at bd[o, o + n) as TEMPMILLI (digits, optional +note fraction, used to 0.001), or 999999 when it is not a number from 0 to 2 +fn svtemp bd edit uchar 983040 o ulong n ulong to ulong +ip = ulong 0 +fr = ulong 0 +fd = ulong 0 +dot = false +for i ulong n +c = ulong get bd add o i +if eq c 46 +if dot +ret 999999 +end +dot = true +else +if or lt c 48 gt c 57 +ret 999999 +end +if dot +if lt fd 3 +fr = add mul fr 10 sub c 48 +fd = add fd 1 +end +else +if ge ip 100 +ret 999999 +end +ip = add mul ip 10 sub c 48 +end +end +end +for k ulong 3 +if lt fd 3 +fr = mul fr 10 +fd = add fd 1 +end +end +m = add mul ip 1000 fr +if gt m 2000 +ret 999999 +end +ret m +end + +note svpcat: append text t to the template; false when it would pass 4000 bytes +fn svpcat wb edit uchar 82432 sv edit ulong 64 t view uchar * to bool +pl = get sv 5 +if gt add pl len t 4000 +ret false +end +for i ulong len t +put wb add 73728 add pl i get t i +end +put sv 5 add pl len t +ret true +end + +note svpstr: append the decoded string token t (role or content) to the template +fn svpstr bd edit uchar 983040 tp edit uint 262144 t ulong wb edit uchar 82432 sv edit ulong 64 to bool +pl = get sv 5 +if ge pl 4000 +ret false +end +n = js_sget bd js_off tp t part wb add 73728 pl sub 4000 pl +if lt n 0 +ret false +end +put sv 5 add pl ulong n +ret true +end + +note svmsg1: one message object e into the template; 0 or an error code +fn svmsg1 bd edit uchar 983040 tp edit uint 262144 e ulong wb edit uchar 82432 sv edit ulong 64 to ulong +if ne js_type tp e 1 +ret 3 +end +ro = jsnone +co = jsnone +k = js_first tp e +for it ulong js_nkids tp e +if eq k jsnone +break +end +o = js_off tp k +if js_streq bd o skrole +ro = add k 1 +end +if js_streq bd o skcont +co = add k 1 +end +k = js_mnext tp k +end +if eq ro jsnone +ret 5 +end +if or ne js_type tp ro 6 gt js_slen tp ro 32 +ret 5 +end +if eq co jsnone +ret 4 +end +ct = js_type tp co +if and ne ct 6 ne ct 10 +ret 4 +end +if not svpstr bd tp ro wb sv +ret 6 +end +if not svpcat wb sv svsep +ret 6 +end +if eq ct 6 +if not svpstr bd tp co wb sv +ret 6 +end +end +if not svpcat wb sv svnl +ret 6 +end +ret 0 +end + +fn svmsgs bd edit uchar 983040 tp edit uint 262144 a ulong wb edit uchar 82432 sv edit ulong 64 to ulong +if ne js_type tp a 3 +ret 3 +end +n = js_nkids tp a +if eq n 0 +ret 3 +end +e = js_first tp a +for it ulong n +if eq e jsnone +break +end +r = svmsg1 bd tp e wb sv +if ne r 0 +ret r +end +e = js_enext tp e +end +if not svpcat wb sv svaprm +ret 6 +end +ret 0 +end + +note svopts: stream_options value v: include_usage true sets sv4 +fn svopts bd edit uchar 983040 tp edit uint 262144 v ulong sv edit ulong 64 to void +if ne js_type tp v 1 +ret +end +k = js_first tp v +for it ulong js_nkids tp v +if eq k jsnone +break +end +if js_streq bd js_off tp k skincl +if eq js_type tp add k 1 8 +put sv 4 1 +end +end +k = js_mnext tp k +end +end + +note svscal: one scalar member (key token k, value k + 1); 0 or an error code +fn svscal bd edit uchar 983040 tp edit uint 262144 k ulong sv edit ulong 64 to ulong +o = js_off tp k +v = add k 1 +ty = js_type tp v +vo = js_off tp v +if or js_streq bd o skmaxt js_streq bd o skmaxc +if eq ty 10 +ret 0 +end +if or ne ty 7 not js_isu bd vo +ret 8 +end +x = js_tou bd vo +if or eq x 0 gt x 999999 +ret 8 +end +put sv 1 x +ret 0 +end +if js_streq bd o sktemp +if eq ty 10 +ret 0 +end +if ne ty 7 +ret 7 +end +if ne and js_nflags tp v 5 0 +ret 7 +end +m = svtemp bd vo js_span tp v +if gt m 2000 +ret 7 +end +put sv 2 m +ret 0 +end +if js_streq bd o skseed +if eq ty 10 +ret 0 +end +if or ne ty 7 not js_isu bd vo +ret 9 +end +put sv 3 js_tou bd vo +ret 0 +end +if js_streq bd o skstrm +if eq ty 8 +put sv 0 1 +ret 0 +end +if or eq ty 9 eq ty 10 +ret 0 +end +ret 10 +end +if js_streq bd o skn +if eq ty 10 +ret 0 +end +if or ne ty 7 not js_isu bd vo +ret 12 +end +if ne js_tou bd vo 1 +ret 12 +end +ret 0 +end +if js_streq bd o skopts +svopts bd tp v sv +end +ret 0 +end + +note svparse: the request body bd[0, n) into sv and the template; 0 or an error code +fn svparse bd edit uchar 983040 n ulong wb edit uchar 82432 sv edit ulong 64 to ulong +tp = new uint 262144 0 +x = js_init tp 983040 64 +r = js_parse bd tp n +if lt r 0 +ret 1 +end +if ne js_type tp 0 1 +ret 2 +end +put sv 0 0 +put sv 1 999999 +put sv 2 1000 +put sv 3 1 +put sv 4 0 +put sv 5 0 +ma = jsnone +k = js_first tp 0 +for it ulong js_nkids tp 0 +if eq k jsnone +break +end +if js_streq bd js_off tp k skmsgs +ma = add k 1 +else +e = svscal bd tp k sv +if ne e 0 +ret e +end +end +k = js_mnext tp k +end +if eq ma jsnone +ret 3 +end +ret svmsgs bd tp ma wb sv +end + +note ======== generation + +note svgen: sample up to min(sv1, T - CT0) tokens; streams chunks when sv0 is 1. 0, or negative +note when a chunk could not be sent (the client left). +fn svgen cs edit ulong 320 io edit uchar 131072 ob edit uchar 409600 wb edit uchar 82432 sv edit ulong 64 to long +lim = sub get sv 19 get sv 6 +if lt get sv 1 lim +lim = get sv 1 +end +put sv 7 0 +put sv 8 0 +put sv 12 0 +put sv 13 0 +put sv 14 0 +for g ulong lim +if not svtake wb sv +break +end +r = svpend cs io ob wb sv +if lt r 0 +ret r +end +end +if eq get sv 8 0 +put sv 8 2 +end +svclean wb sv 1 +ret svpend cs io ob wb sv +end + +note svtake: one sampled token into the context and the content; false when it ends the output +note (sv8: 1 token 0, 2 the content would pass its 65536 bytes) +fn svtake wb edit uchar 82432 sv edit ulong 64 to bool +c = svdraw sv +if eq c 0 +put sv 8 1 +ret false +end +if not svfits sv c +put sv 8 2 +ret false +end +svcap wb sv c +svclean wb sv 0 +ret true +end + +note svdraw: the next token (cmdsamp's step osstep), advancing the seed stream when sampling +fn svdraw sv edit ulong 64 to ulong +st = get sv 3 +tm = get sv 2 +c = osstep st tm +if ne tm 0 +put sv 3 add st 11400714819323198485 +end +ret c +end + +note svfits: whether token c's bytes fit the raw buffer (8192) and, as up to three content bytes +note each, the content (65536) +fn svfits sv edit ulong 64 c ulong to bool +tl = obtlen c +rn = add get sv 12 tl +gn = add get sv 13 mul rn 3 +ret not or or gt rn 8192 gt tl 4096 gt gn 65536 +end + +note svcap: token c's bytes onto the raw buffer, c onto the context +fn svcap wb edit uchar 82432 sv edit ulong 64 c ulong to void +obtcap c +rn = get sv 12 +for i ulong get obon 0 +put wb add rn i get obo i +end +put sv 12 add rn get obon 0 +ocpush c +put sv 7 add get sv 7 1 +end + +note svpend: when streaming, the content not yet sent as one chunk; 0 or the send error +fn svpend cs edit ulong 320 io edit uchar 131072 ob edit uchar 409600 wb edit uchar 82432 sv edit ulong 64 to long +if or ne get sv 0 1 le get sv 13 get sv 14 +ret 0 +end +r = svchunk cs io ob wb sv 1 +put sv 14 get sv 13 +ret r +end + +note svid: response id chatcmpl-ollm- into wb[82176 ..), its length into sv15 +fn svid wb edit uchar 82432 sv edit ulong 64 to void +put sv 9 add get sv 9 1 +p = svmcat wb 82176 82240 svidp +p = svmdec wb p 82240 get sv 9 +put sv 15 sub p 82176 +end + +fn svlog sv edit ulong 64 to void +oputc 67 +oputc 32 +oputu get sv 21 +oputc 32 +oputu get sv 6 +oputc 32 +oputu get sv 7 +oputc 32 +oputu get sv 8 +oputc 32 +oputu div sub ulong monons get sv 11 1000000 +oputc 10 +oflush +end + +note svchat: POST /v1/chat/completions +fn svchat cs edit ulong 320 io edit uchar 131072 bd edit uchar 983040 wb edit uchar 82432 sv edit ulong 64 to long +note the request's clock and log fields come from svroute (svbeg) +n = hbodyall cs io bd +if lt n 0 +put cs HKEEP 0 +if eq n HEBIG +put sv 16 13 +r = svfail cs io wb sv 413 +svlog sv +ret r +end +put sv 21 400 +svlog sv +ret hrsperr cs io 400 +end +note generation outlasts the 60 s body deadline: only the idle limit applies from here +hsetdl cs 0 +e = svparse bd ulong n wb sv +if ne e 0 +put sv 16 e +r = svfail cs io wb sv 400 +svlog sv +ret r +end +pl = get sv 5 +for i ulong pl +put oarg i get wb add 73728 i +end +np = obpenc pl +put og 9 0 +ocpush 0 +for i ulong np +if lt get og 9 get og 1 +ocpush get obtk i +end +end +put sv 6 add np 1 +if ge get sv 6 get sv 19 +put sv 16 11 +r = svfail cs io wb sv 400 +svlog sv +ret r +end +svid wb sv +put sv 10 ulong div realns 1000000000 +ob = new uchar 409600 0 +put sv 21 200 +if eq get sv 0 1 +r = hrspsse cs io +r = hfe r svchunk cs io ob wb sv 0 +if lt r 0 +svlog sv +ret r +end +r = svgen cs io ob wb sv +if lt r 0 +svlog sv +ret r +end +r = svchunk cs io ob wb sv 2 +if eq get sv 4 1 +r = hfe r svchunk cs io ob wb sv 3 +end +r = hfe r hssedat cs io svdone +r = hfe r hsseend cs io +r = hfe r hwfin cs io +svlog sv +ret r +end +r = svgen cs io ob wb sv +m = svfull ob wb sv +if lt m 0 +put sv 16 16 +r = svfail cs io wb sv 500 +svlog sv +ret r +end +r = svsend cs io ob 200 ulong m +svlog sv +ret r +end + +fn svroute cs edit ulong 320 io edit uchar 131072 bd edit uchar 983040 wb edit uchar 82432 sv edit ulong 64 to long +svbeg sv +if hispath cs io svpchat +if hismeth cs io svmpost +ret svchat cs io bd wb sv +end +ret svend cs io wb sv 15 405 +end +if hispath cs io svphlth +if hismeth cs io svmget +ret svok cs io sv svthlth +end +ret svend cs io wb sv 15 405 +end +if hispath cs io svpmods +if hismeth cs io svmget +ret svok cs io sv svtmods +end +ret svend cs io wb sv 15 405 +end +ret svend cs io wb sv 14 404 +end + +note svbeg: a request's log fields cleared, its clock started +fn svbeg sv edit ulong 64 to void +put sv 11 ulong monons +put sv 6 0 +put sv 7 0 +put sv 8 0 +end + +note svend: error code e with status st, logged +fn svend cs edit ulong 320 io edit uchar 131072 wb edit uchar 82432 sv edit ulong 64 e ulong st ulong to long +put sv 16 e +r = svfail cs io wb sv st +svlog sv +ret r +end + +note svok: the fixed JSON text t with status 200, logged +fn svok cs edit ulong 320 io edit uchar 131072 sv edit ulong 64 t view uchar * to long +put sv 21 200 +r = svstat cs io 200 t +svlog sv +ret r +end + +note svconn: one accepted connection c carries one request, answered with Connection: close. +note Connections are served one at a time, so a kept-alive idle connection would hold the listener: +note allen-chat pools its upstream connection, and its next request queued 30 s behind the pooled +note one (the old idle limit) until this change. The head must arrive within 10 s. +fn svconn c long cs edit ulong 320 io edit uchar 131072 bd edit uchar 983040 wb edit uchar 82432 sv edit ulong 64 to void +r = hinit cs io int c 1 +if lt r 0 +x = hclose cs +ret +end +hsettmo cs 10000000000 10000000000 +hsetbdl cs 60000000000 +note the JSON parser takes at most 983040 bytes (jsmaxn); larger Content-Length is 413 at the head +put cs HBCAP 983040 +r = hreqrd cs io +if eq r HEBIG +put cs HKEEP 0 +svbeg sv +x = svend cs io wb sv 13 413 +end +if and lt r 0 ne r HEBIG +x = hreject cs io r +end +if gt r 0 +put cs HKEEP 0 +x = svroute cs io bd wb sv +end +x = hclose cs +end + +note serve PORT CK MERGES [MAXCONN] +fn cmdserve to void +na = oargc +if and ne na 5 ne na 6 +exit 2 +end +port = oargu 2 +if or eq port 0 gt port 65535 +exit 2 +end +mx = ulong 1000000 +if eq na 6 +mx = oargu 5 +if eq mx 0 +exit 2 +end +end +ockload 3 +v = get og 0 +obload 4 v +cs = new ulong 320 0 +io = new uchar 131072 0 +bd = new uchar 983040 0 +wb = new uchar 82432 0 +sv = new ulong 64 0 +a = new uchar 16 0 +put sv 19 get og 1 +r = haddr4 a 2130706433 port +lf = hlisten a 16 +if lt lf 0 +exit 71 +end +for i ulong len svport +oputc ulong get svport i +end +oputu port +oputc 10 +oflush +nc = ulong 0 +for j ulong 999999999 +c = haccept int lf 60000000000 +if ge c 0 +svconn c cs io bd wb sv +nc = add nc 1 +if ge nc mx +break +end +end +end +x = fclose int lf +end diff --git a/tests/omegallm/build.sh b/tests/omegallm/build.sh index f7e8be3..1e21a6b 100755 --- a/tests/omegallm/build.sh +++ b/tests/omegallm/build.sh @@ -48,6 +48,10 @@ # The pool file (CONTRACT-V3 section 2) follows data.om: lpool.om holds the bank-B globals oww, ogb # and oab on the Linux targets, epool.om one-element placeholders on x86efi (its v3 limit is the # v2 bank-A capacity). +# serve (DRA-119, native/omegallm/serve.om): aarch64 starts with the line `om2` and concatenates +# net/http.om, net/json.om and net/jsonw.om (vendored unmodified from omega-mv e5b32567 seed/net/http.om, +# seed/json/json.om and seed/json/jsonw.om; sha256 below, checked at build) before the ollm units and +# serve.om after them. gb10, x86linux and x86efi take noserve.om, whose cmdserve exits 2. # Mutants (ollm-mut-X, one changed line) plant a defect the checks must catch. Variants (ollm-var-X) # h5 and h7 (two changed lines) set both gcheck steps GCH and GCH2 to 1e-5 (h5) or 1e-7 (h7), the step # sizes that the README's GCH section rejects; r0 (gk.om OKREU 0, one changed line) clears the GEMM FFMA @@ -81,9 +85,22 @@ got=$(sha256sum "$OMC" | cut -d' ' -f1) mkdir -p "$OUT" src=$here/native/omegallm name=ollm +if [ "$TARGET" = aarch64 ]; then + ( cd "$src/net" && sha256sum -c --quiet - ) <<'EOF' || { echo "NET_PIN_MISMATCH" >&2; exit 3; } +aff258ecd3858454056811a5e6fe1f660f9d650a7207d6c41885105110e046a7 http.om +456254fc754ea35103ced480407b24fc1a3896d094b90ae0e9623e7b6594e2d2 json.om +464f649e8207495f5d67fe8795d31e42ea3ccebd9ed547274dab802d4f7c5f21 jsonw.om +EOF + lead=om2 + pre="$src/net/http.om $src/net/json.om $src/net/jsonw.om" post=$src/serve.om +else + pre= post=$src/noserve.om +fi { [ -z "$lead" ] || printf '%s\n' "$lead" - cat "$src/math.om" "$src/data.om" "$src/$pool" "$src/model.om" "$src/adam.om" "$src/ckpt.om" "$src/bpe.om" "$src/cli.om" "$src/$plat" + # shellcheck disable=SC2086 + [ -z "$pre" ] || cat $pre + cat "$src/math.om" "$src/data.om" "$src/$pool" "$src/model.om" "$src/adam.om" "$src/ckpt.om" "$src/bpe.om" "$src/cli.om" "$src/$plat" "$post" [ "$TARGET" = gb10 ] || cat "$src/nogpu.om" } > "$OUT/ollm.om" if [ "$TARGET" = gb10 ]; then diff --git a/tests/omegallm/serve-allen.sh b/tests/omegallm/serve-allen.sh new file mode 100755 index 0000000..c86a437 --- /dev/null +++ b/tests/omegallm/serve-allen.sh @@ -0,0 +1,43 @@ +#!/bin/sh +# Throwaway allen-chat (read-only /opt/allen-chat code) pointed at ollm serve on a spare port. +# ollm on 127.0.0.1:18292, allen-chat on 127.0.0.1:18293. Stops only the PIDs it started. +set -u +S=/dev/shm/hive/OwnModelCoord +OUT=${OUT:-$S/ac} +OLLM=${OLLM:-$S/final-aarch64/ollm} +CK=${CK:-/tmp/gk/r10/run/ck60000.bin} +MERGES=${MERGES:-$HOME/handoffs/omega-llm-20261101/v1-data/merges4096.bin} +WARM=${WARM:-0} +mkdir -p "$OUT" +for p in 18292 18293; do + if [ -n "$(ss -Hltn "sport = :$p")" ]; then echo "PORT_BUSY $p"; exit 3; fi +done +printf 'You are Allen.\n' > "$OUT/system.txt" +BW="bwrap --dev-bind / / --dev /dev --bind /dev/shm /dev/shm --proc /proc --" +taskset -c 8-9 nice -n 10 $BW "$OLLM" serve 18292 "$CK" "$MERGES" > "$OUT/ollm.log" 2>&1 & +L1=$! +i=0; while [ $i -lt 100 ] && ! grep -q '^PORT 18292' "$OUT/ollm.log"; do sleep 0.2; i=$((i+1)); done +taskset -c 8-9 nice -n 10 $BW /usr/bin/python3 -I /opt/allen-chat/allen_chat.py \ + --listen 127.0.0.1:18293 --upstream 127.0.0.1:18292 --system-prompt "$OUT/system.txt" \ + --omc /opt/allen-chat/omc --irwasm /opt/allen-chat/irwasm --max-tokens 8 --temperature 0 \ + --warm-every "$WARM" --regen-per-hour 0 --stats-every 3600 \ + --open-user "Hi." --open-user-anon "Hello." --greeting-remember "Hi." --greeting-anon "Hello." \ + > "$OUT/allen.log" 2>&1 & +L2=$! +i=0; while [ $i -lt 100 ] && ! grep -q 'allen-chat listening' "$OUT/allen.log"; do sleep 0.2; i=$((i+1)); done +sleep "${SETTLE:-1}" +for q in "What is Omega?" "Tell me a story."; do + echo "== POST /allen/api/chat: $q" + curl -sS -m 120 -H 'Content-Type: application/json' \ + -d "{\"messages\":[{\"role\":\"user\",\"content\":\"$q\"}]}" http://127.0.0.1:18293/allen/api/chat + echo "== curl rc=$?" +done > "$OUT/chat.txt" 2>&1 +sleep 1 +P1=$(ss -Hltnp 'sport = :18292' | sed -n 's/.*pid=\([0-9]*\).*/\1/p' | head -1) +P2=$(ss -Hltnp 'sport = :18293' | sed -n 's/.*pid=\([0-9]*\).*/\1/p' | head -1) +echo "launchers $L1 $L2 servers ${P1:-none} ${P2:-none}" > "$OUT/pids.txt" +for p in $P1 $P2 $L1 $L2; do kill "$p" 2>/dev/null; done +wait 2>/dev/null +sleep 1 +echo "after: $(ss -Hltn 'sport = :18292' | wc -l) $(ss -Hltn 'sport = :18293' | wc -l)" >> "$OUT/pids.txt" +cat "$OUT/chat.txt"; echo "--- ollm.log"; cat "$OUT/ollm.log"; echo "--- allen.log"; cat "$OUT/allen.log"; cat "$OUT/pids.txt" diff --git a/tests/omegallm/serve-check.py b/tests/omegallm/serve-check.py new file mode 100755 index 0000000..dfaea38 --- /dev/null +++ b/tests/omegallm/serve-check.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python3 +"""Referee for `ollm serve` (DRA-119, native/omegallm/serve.om). + +Usage: serve-check.py PORT OLLM CK MERGES +Talks to an `ollm serve` already listening on 127.0.0.1:PORT and prints one line per check, +`PASS name detail` or `FAIL name detail`, then `SUMMARY pass=N fail=M`; exit 1 on any FAIL. +The content oracle is the same binary's `sample` command (the CLI's sampler, cmdsamp) on the +interim template, decoded with Python's UTF-8 decoder (errors="replace", the maximal-subpart +U+FFFD practice that serve.om follows). +""" +import http.client +import json +import socket +import subprocess +import sys +import time + +PORT, OLLM, CK, MERGES = int(sys.argv[1]), sys.argv[2], sys.argv[3], sys.argv[4] +HOST = "127.0.0.1" +results = [] + + +def check(name, ok, detail=""): + results.append(ok) + print(("PASS" if ok else "FAIL"), name, detail, flush=True) + + +def call(method, path, body=None, raw=None, timeout=600): + c = http.client.HTTPConnection(HOST, PORT, timeout=timeout) + data = raw if raw is not None else (json.dumps(body).encode() if body is not None else None) + hdr = {"Content-Type": "application/json", "Authorization": "Bearer "} if data is not None else {} + t0 = time.monotonic() + c.request(method, path, body=data, headers=hdr) + r = c.getresponse() + out = r.read() + dt = time.monotonic() - t0 + ctype = r.getheader("Content-Type", "") + c.close() + return r.status, ctype, out, dt + + +def template(msgs): + return "".join(f"{m['role']}: {m.get('content') or ''}\n" for m in msgs) + "assistant: " + + +def oracle(msgs, seed, n, tm): + p = subprocess.run([OLLM, "sample", CK, str(seed), str(n), str(tm), template(msgs), MERGES], + capture_output=True, check=True) + return p.stdout.decode("utf-8", errors="replace") + + +def err_code(out): + try: + e = json.loads(out)["error"] + return e["code"], e["message"], e["type"] + except Exception as x: # noqa: BLE001 - any shape error is a FAIL + return None, repr(x), None + + +def sse(out): + events, done = [], False + for line in out.decode().split("\n"): + if not line.startswith("data: "): + continue + d = line[6:] + if d == "[DONE]": + done = True + continue + events.append(json.loads(d)) + return events, done + + +# --- positive ------------------------------------------------------------------------------- +st, ct, out, _ = call("GET", "/health") +h = json.loads(out) if st == 200 else {} +check("health", st == 200 and h.get("status") == "ok" and h.get("in_flight") == 0, f"{st} {out!r}") + +st, ct, out, _ = call("GET", "/v1/models") +ids = [m["id"] for m in json.loads(out).get("data", [])] if st == 200 else [] +check("models", st == 200 and ids == ["ollm"] and ct.startswith("application/json"), f"{st} {ids}") + +msgs = [{"role": "user", "content": "What is Omega?"}] +for tm, seed, n in ((0, 7, 12), (800, 7, 12)): + req = {"model": "ollm", "messages": msgs, "max_tokens": n, "temperature": tm / 1000, "seed": seed} + st, ct, out, dt = call("POST", "/v1/chat/completions", req) + j = json.loads(out) if st == 200 else {} + ch = (j.get("choices") or [{}])[0] + u = j.get("usage", {}) + content = ch.get("message", {}).get("content") + want = oracle(msgs, seed, n, tm) + ok = (st == 200 and j.get("object") == "chat.completion" and ch.get("finish_reason") in ("stop", "length") + and ch["message"]["role"] == "assistant" and u.get("total_tokens") == u.get("prompt_tokens", 0) + u.get("completion_tokens", 0) + and 1 <= u.get("completion_tokens", 0) <= n and content == want) + check(f"chat_json_t{tm}", ok, f"{st} usage={u} finish={ch.get('finish_reason')} s={dt:.2f} content={content!r} oracle={want!r}") + + req.update(stream=True, stream_options={"include_usage": True}) + st, ct, out, dt = call("POST", "/v1/chat/completions", req) + ev, done = sse(out) if st == 200 else ([], False) + deltas = [e["choices"][0]["delta"] for e in ev if e.get("choices")] + text = "".join(d.get("content", "") for d in deltas) + fins = [e["choices"][0].get("finish_reason") for e in ev if e.get("choices")] + usage = [e["usage"] for e in ev if e.get("usage")] + ok = (st == 200 and ct.startswith("text/event-stream") and done and deltas and deltas[0].get("role") == "assistant" + and all(e.get("object") == "chat.completion.chunk" for e in ev) and fins[-1] == ch.get("finish_reason") + and all(f is None for f in fins[:-1]) and text == content and usage == [u] and ev[-1].get("choices") == []) + check(f"chat_sse_t{tm}", ok, f"{st} events={len(ev)} done={done} usage={usage} text={text!r}") + +# allen-chat's body shapes (/opt/allen-chat/allen_chat.py): system + user, tools, tool_choice none +ac = {"model": "omega", "messages": [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "hi"}], + "max_tokens": 4, "temperature": 0.3, "stream": False, + "tools": [{"type": "function", "function": {"name": "x", "parameters": {"type": "object"}}}], "tool_choice": "none"} +st, ct, out, _ = call("POST", "/v1/chat/completions", ac) +j = json.loads(out) if st == 200 else {} +check("allen_chat_shape", st == 200 and j["choices"][0]["finish_reason"] in ("stop", "length") and "tool_calls" not in j["choices"][0]["message"], f"{st} {out[:200]!r}") + +# --- negative controls ------------------------------------------------------------------------ +long_text = " ".join(f"word{i} omega{i * 7}" for i in range(300))[:3800] +st, ct, out, _ = call("POST", "/v1/chat/completions", {"messages": [{"role": "user", "content": long_text}], "max_tokens": 4}) +code, msg, typ = err_code(out) +check("refuse_context", st == 400 and code == "context_length_exceeded" and "context window is 256" in msg, f"{st} {code} {msg!r}") + +st, ct, out, _ = call("POST", "/v1/chat/completions", {"messages": [{"role": "user", "content": "x" * 4100}]}) +code, msg, typ = err_code(out) +check("refuse_template_bytes", st == 400 and code == "invalid_request" and "4000" in msg, f"{st} {code} {msg!r}") + +for name, raw in (("refuse_bad_json", b"{\"messages\": [}"), ("refuse_not_object", b"[1]"), + ("refuse_trailing", b"{\"messages\":[{\"role\":\"user\",\"content\":\"a\"}]} x")): + st, ct, out, _ = call("POST", "/v1/chat/completions", raw=raw) + code, msg, typ = err_code(out) + check(name, st == 400 and typ == "invalid_request_error", f"{st} {code} {msg!r}") + +bad = [("refuse_empty_messages", {"messages": []}), + ("refuse_array_content", {"messages": [{"role": "user", "content": [{"type": "text", "text": "a"}]}]}), + ("refuse_no_role", {"messages": [{"content": "a"}]}), + ("refuse_neg_temp", {"messages": msgs, "temperature": -1}), + ("refuse_hot_temp", {"messages": msgs, "temperature": 2.5}), + ("refuse_zero_max", {"messages": msgs, "max_tokens": 0}), + ("refuse_n2", {"messages": msgs, "n": 2}), + ("refuse_stream_str", {"messages": msgs, "stream": "yes"})] +for name, body in bad: + st, ct, out, _ = call("POST", "/v1/chat/completions", body) + code, msg, typ = err_code(out) + check(name, st == 400 and code == "invalid_request", f"{st} {code} {msg!r}") + +st, ct, out, _ = call("POST", "/v1/chat/completions", raw=b"{\"messages\":[{\"role\":\"user\",\"content\":\"a\"}],\"temperature\":1e-3}") +code, msg, typ = err_code(out) +check("refuse_exp_temp", st == 400 and code == "invalid_request" and "temperature" in msg, f"{st} {code} {msg!r}") + +st, ct, out, _ = call("GET", "/v1/nope") +check("refuse_404", st == 404 and err_code(out)[0] == "not_found", f"{st} {out!r}") +st, ct, out, _ = call("GET", "/v1/chat/completions") +check("refuse_405", st == 405 and err_code(out)[0] == "method_not_allowed", f"{st} {out!r}") + +s = socket.create_connection((HOST, PORT), timeout=30) +s.sendall(b"POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: 1000000\r\n\r\n") +resp = b"" +while True: + b = s.recv(65536) + if not b: + break + resp += b +s.close() +check("refuse_413", resp.startswith(b"HTTP/1.1 413") and b"request_too_large" in resp, f"{resp[:120]!r}") + +# One request per connection: a client that keeps its connection open (allen-chat pools one) +# must not hold the serial listener; the next client is answered at once. +held = http.client.HTTPConnection(HOST, PORT, timeout=30) +held.request("GET", "/health") +r = held.getresponse() +r.read() +conn_hdr = (r.getheader("Connection") or "").lower() +t0 = time.monotonic() +st, ct, out, _ = call("GET", "/health", timeout=5) +dt = time.monotonic() - t0 +held.close() +check("held_conn_not_blocking", conn_hdr == "close" and st == 200 and dt < 2, + f"Connection={conn_hdr!r} next={st} in {dt:.3f}s") + +# A connection that never sends a head is dropped after the 10 s head deadline. +silent = socket.create_connection((HOST, PORT), timeout=30) +t0 = time.monotonic() +st, ct, out, _ = call("GET", "/health", timeout=30) +dt = time.monotonic() - t0 +silent.close() +check("silent_conn_dropped", st == 200 and 8 < dt < 15, f"next={st} after {dt:.3f}s") + +st, ct, out, _ = call("GET", "/health") +check("alive_after_negatives", st == 200, f"{st}") + +fails = results.count(False) +print(f"SUMMARY pass={results.count(True)} fail={fails}", flush=True) +sys.exit(1 if fails else 0) diff --git a/tests/omegallm/serve-check.sh b/tests/omegallm/serve-check.sh new file mode 100755 index 0000000..fe36f86 --- /dev/null +++ b/tests/omegallm/serve-check.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# serve-check.sh: run `ollm serve` on loopback and referee it with serve-check.py (DRA-119). +# Env: OLLM (an aarch64 build with serve), CK (checkpoint), MERGES (V > 256 merges), PORT (default +# 18291), CORES (taskset list, default 8-9), OUT (receipt directory). The server runs under +# taskset/nice/bwrap; this script stops only the PID it started. Exit 0 only when every check +# passes and the server listened on 127.0.0.1 alone. +set -u +: "${OLLM:?}" "${CK:?}" "${MERGES:?}" "${OUT:?}" +PORT=${PORT:-18291} +CORES=${CORES:-8-9} +here=$(cd "$(dirname "$0")" && pwd) +mkdir -p "$OUT" +bw="bwrap --dev-bind / / --dev /dev --bind /dev/shm /dev/shm --proc /proc --" +{ + echo "date $(date -u +%FT%TZ)" + echo "host $(hostname) $(uname -m)" + echo "ollm $(sha256sum "$OLLM")" + echo "ck $(sha256sum "$CK")" + echo "merges $(sha256sum "$MERGES")" + echo "referee $(sha256sum "$here/serve-check.py")" +} >"$OUT/env.txt" +taskset -c "$CORES" nice -n 10 $bw "$OLLM" serve "$PORT" "$CK" "$MERGES" >"$OUT/server.log" 2>&1 & +pid=$! +i=0 +until grep -q "^PORT $PORT" "$OUT/server.log" 2>/dev/null; do + i=$((i + 1)) + if [ $i -gt 600 ] || ! kill -0 $pid 2>/dev/null; then + echo "SERVE_START_FAIL" + cat "$OUT/server.log" + kill $pid 2>/dev/null + exit 1 + fi + sleep 0.1 +done +ss -Hltnp "sport = :$PORT" >"$OUT/listen.txt" +# bwrap does not pass SIGTERM on: stop the listening ollm too, the one this script started +spid=$(grep -o 'pid=[0-9]*' "$OUT/listen.txt" | head -1 | cut -d= -f2) +[ -n "$spid" ] && [ "$(readlink /proc/$spid/exe)" = "$(readlink -f "$OLLM")" ] || spid= +bind_ok=1 +awk '{print $4}' "$OUT/listen.txt" | grep -qv "^127\.0\.0\.1:$PORT$" && bind_ok=0 +[ -s "$OUT/listen.txt" ] || bind_ok=0 +taskset -c "$CORES" nice -n 10 $bw python3 "$here/serve-check.py" "$PORT" "$OLLM" "$CK" "$MERGES" | tee "$OUT/referee.txt" +rc=$? +grep -q "^SUMMARY pass=[0-9]* fail=0$" "$OUT/referee.txt" || rc=1 +kill $pid +[ -n "$spid" ] && kill $spid +wait $pid 2>/dev/null +echo "stopped launcher=$pid server=${spid:-none}" >>"$OUT/env.txt" +echo "bind_loopback_only $bind_ok $(cat "$OUT/listen.txt")" | tee -a "$OUT/referee.txt" +[ $bind_ok -eq 1 ] || rc=1 +if [ $rc -eq 0 ]; then echo "SERVE_CHECK PASS" | tee -a "$OUT/referee.txt"; else echo "SERVE_CHECK FAIL" | tee -a "$OUT/referee.txt"; fi +exit $rc