hugpy-queue 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hugpy_queue-0.1.0/PKG-INFO +155 -0
- hugpy_queue-0.1.0/README.md +147 -0
- hugpy_queue-0.1.0/pyproject.toml +22 -0
- hugpy_queue-0.1.0/setup.cfg +4 -0
- hugpy_queue-0.1.0/src/hugpy_queue/__init__.py +1 -0
- hugpy_queue-0.1.0/src/hugpy_queue/__main__.py +5 -0
- hugpy_queue-0.1.0/src/hugpy_queue/calls.py +70 -0
- hugpy_queue-0.1.0/src/hugpy_queue/cli.py +81 -0
- hugpy_queue-0.1.0/src/hugpy_queue/core_sql.py +62 -0
- hugpy_queue-0.1.0/src/hugpy_queue/door.py +305 -0
- hugpy_queue-0.1.0/src/hugpy_queue/imports/__init__.py +37 -0
- hugpy_queue-0.1.0/src/hugpy_queue/imports/constants.py +47 -0
- hugpy_queue-0.1.0/src/hugpy_queue/rows.py +205 -0
- hugpy_queue-0.1.0/src/hugpy_queue/store.py +166 -0
- hugpy_queue-0.1.0/src/hugpy_queue/system/__init__.py +19 -0
- hugpy_queue-0.1.0/src/hugpy_queue/system/system.py +170 -0
- hugpy_queue-0.1.0/src/hugpy_queue.egg-info/PKG-INFO +155 -0
- hugpy_queue-0.1.0/src/hugpy_queue.egg-info/SOURCES.txt +20 -0
- hugpy_queue-0.1.0/src/hugpy_queue.egg-info/dependency_links.txt +1 -0
- hugpy_queue-0.1.0/src/hugpy_queue.egg-info/entry_points.txt +2 -0
- hugpy_queue-0.1.0/src/hugpy_queue.egg-info/requires.txt +1 -0
- hugpy_queue-0.1.0/src/hugpy_queue.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hugpy-queue
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: The queue of a Hugpy worker: the front door, a record of every call, and the stages each call passes
|
|
5
|
+
Requires-Python: >=3.11
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: hugpy-utilities<0.2,>=0.1.0
|
|
8
|
+
|
|
9
|
+
# hugpy-queue
|
|
10
|
+
|
|
11
|
+
The queue of a Hugpy worker: the front door every request comes in through, a record of every call, and the
|
|
12
|
+
stages each call passes on its way to an answer.
|
|
13
|
+
|
|
14
|
+
A Hugpy worker is made of four parts, each with its own service, account and database:
|
|
15
|
+
|
|
16
|
+
| Part | Package | What it answers |
|
|
17
|
+
|---|---|---|
|
|
18
|
+
| Discovery | `hugpy-discovery` | where a model is stored |
|
|
19
|
+
| Resources | `hugpy-resources` | where a model is loaded |
|
|
20
|
+
| Engines | `hugpy-engine` | what a model is doing and what it needs |
|
|
21
|
+
| Queue | `hugpy-queue` | what a call is and what it has |
|
|
22
|
+
|
|
23
|
+
`hugpy-wrapper` is the bundle that installs all four and connects their databases.
|
|
24
|
+
|
|
25
|
+
## What it does
|
|
26
|
+
|
|
27
|
+
- **Front door.** It listens on one address and takes every request for the worker. Each request is put on record
|
|
28
|
+
with its method, route, status, time and size.
|
|
29
|
+
- **Calls.** Every `POST` is a call. It gets a row saying what it is and what it has, and one row for each stage
|
|
30
|
+
it passes.
|
|
31
|
+
- **Hand-off.** The call is passed on to `hugpy-resources`, and the reply is passed back to the caller as it
|
|
32
|
+
comes, so a streamed reply still arrives piece by piece.
|
|
33
|
+
- **Health.** `GET /health` answers for the whole worker: the queue under its own name, and the health of the part
|
|
34
|
+
behind it as that part gave it.
|
|
35
|
+
|
|
36
|
+
Who may call is decided by `hugpy-resources`. The queue passes every header on unchanged, and names a caller from
|
|
37
|
+
another machine in `X-Forwarded-For`, so the caller is asked for its key exactly as it would be at that door.
|
|
38
|
+
|
|
39
|
+
## Install
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
pip install hugpy-queue
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Python 3.11 or later. The only dependency is `hugpy-utilities`.
|
|
46
|
+
|
|
47
|
+
To run it as a service of the host (Linux with systemd, as root):
|
|
48
|
+
|
|
49
|
+
```sh
|
|
50
|
+
sudo hugpy-queue system install
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
This makes the account `hugpy-queue`, the folder `/var/lib/hugpy/queue`, the database `queue.sqlite3` and the unit
|
|
54
|
+
`hugpy-queue.service`, then starts it. `sudo hugpy-queue system status` shows its state, and
|
|
55
|
+
`sudo hugpy-queue system uninstall` stops and removes the unit; the record and the settings are kept.
|
|
56
|
+
|
|
57
|
+
## Use
|
|
58
|
+
|
|
59
|
+
Send a call to the door the same way it would be sent to the worker:
|
|
60
|
+
|
|
61
|
+
```sh
|
|
62
|
+
curl http://127.0.0.1:15203/v1/chat/completions \
|
|
63
|
+
-H 'content-type: application/json' \
|
|
64
|
+
-d '{"model": "MODEL", "messages": [{"role": "user", "content": "hello"}]}'
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
The reply carries a `queue_id`: the number of the call's row.
|
|
68
|
+
|
|
69
|
+
### Commands
|
|
70
|
+
|
|
71
|
+
| Command | What it does |
|
|
72
|
+
|---|---|
|
|
73
|
+
| `hugpy-queue serve` | run the front door in the foreground (the service runs this) |
|
|
74
|
+
| `hugpy-queue calls` | the latest calls and the stages each passed |
|
|
75
|
+
| `hugpy-queue door` | what has been asked of the door, by route and status |
|
|
76
|
+
| `hugpy-queue settings` | every setting, its value, and where the database is |
|
|
77
|
+
| `hugpy-queue set NAME VALUE` | save one setting |
|
|
78
|
+
| `sudo hugpy-queue system install \| status \| uninstall` | the service of the host |
|
|
79
|
+
| `sudo hugpy-queue system set NAME VALUE` | save one setting and restart the service on it |
|
|
80
|
+
|
|
81
|
+
### The queue's own reads
|
|
82
|
+
|
|
83
|
+
These are answered by the queue itself and are not passed on:
|
|
84
|
+
|
|
85
|
+
| Route | What it returns |
|
|
86
|
+
|---|---|
|
|
87
|
+
| `GET /health` | the worker's health: the queue, and the part behind it |
|
|
88
|
+
| `GET /_queue/health` | the queue alone: its version, where it hands calls, how many are in flight |
|
|
89
|
+
| `GET /_queue/calls?limit=N` | the latest calls with their stages (20 by default, 500 at most) |
|
|
90
|
+
| `GET /_queue/door` | requests by method, route and status, with counts and times |
|
|
91
|
+
| `GET /_queue/stages` | the order of stages |
|
|
92
|
+
|
|
93
|
+
Every other request is passed on to `hugpy-resources`.
|
|
94
|
+
|
|
95
|
+
## Settings
|
|
96
|
+
|
|
97
|
+
| Setting | Default | What it is |
|
|
98
|
+
|---|---|---|
|
|
99
|
+
| `host` | `127.0.0.1` | the address the door listens on |
|
|
100
|
+
| `port` | `15203` | the port the door listens on |
|
|
101
|
+
| `wrapper_url` | `http://127.0.0.1:15202` | where a call is handed: the address of `hugpy-resources` |
|
|
102
|
+
|
|
103
|
+
A saved setting is a row of the `settings` table of the queue's database.
|
|
104
|
+
|
|
105
|
+
Two environment variables say where its data is kept:
|
|
106
|
+
|
|
107
|
+
| Variable | What it sets |
|
|
108
|
+
|---|---|
|
|
109
|
+
| `HUGPY_DATA_DIR` | the data directory shared by the Hugpy tools of a host (the service uses `/var/lib/hugpy`; a person's own default is `~/.local/share/hugpy`) |
|
|
110
|
+
| `HUGPY_QUEUE_STATE` | the queue's own folder (default: `queue` under the data directory) |
|
|
111
|
+
|
|
112
|
+
## The order of stages
|
|
113
|
+
|
|
114
|
+
A call passes these stages in order. Sorting only predicts; running acts.
|
|
115
|
+
|
|
116
|
+
| No. | Stage | Owner | Phase | What it is |
|
|
117
|
+
|---|---|---|---|---|
|
|
118
|
+
| 10 | `received` | queue | sort | recorded: what it is |
|
|
119
|
+
| 20 | `engine_range` | engine | sort | time-to-processed range from tokens in and out; impossible placements out |
|
|
120
|
+
| 30 | `reap_prediction` | discovery | sort | seconds to place the model on a worker drive |
|
|
121
|
+
| 40 | `evict_prediction` | resources | sort | seconds to make room in memory; finishes the sort |
|
|
122
|
+
| 50 | `turn` | queue | run | this row is next |
|
|
123
|
+
| 60 | `accommodate` | discovery | run | the model placed on a worker drive |
|
|
124
|
+
| 70 | `evict` | resources | run | room made |
|
|
125
|
+
| 80 | `load` | resources | run | the engine loads |
|
|
126
|
+
| 90 | `intake` | engine | run | the engine takes the call |
|
|
127
|
+
| 100 | `done` | queue | run | answered |
|
|
128
|
+
| 110 | `responded` | queue | run | the reply written to the caller |
|
|
129
|
+
|
|
130
|
+
The order is data: it is the `stage_order` table, and `GET /_queue/stages` returns it.
|
|
131
|
+
|
|
132
|
+
## What is recorded
|
|
133
|
+
|
|
134
|
+
The database is `queue.sqlite3` in the queue's folder. One thread of the queue's own process writes it; nothing else
|
|
135
|
+
does.
|
|
136
|
+
|
|
137
|
+
| Table or view | What it holds |
|
|
138
|
+
|---|---|
|
|
139
|
+
| `calls` | every call: what it is and what it has |
|
|
140
|
+
| `call_stages` | a row for each stage a call passed, with when it started and finished |
|
|
141
|
+
| `call_times` | view: each call with its times |
|
|
142
|
+
| `front_door` | every request at the door |
|
|
143
|
+
| `front_door_hours` | answered reads, counted by hour |
|
|
144
|
+
| `front_door_routes` | view: requests by method, route and status |
|
|
145
|
+
| `stage_order` | the order of stages |
|
|
146
|
+
| `settings` | the saved settings |
|
|
147
|
+
|
|
148
|
+
An answered read keeps its own `front_door` row for two minutes. It is then counted into its hour in
|
|
149
|
+
`front_door_hours` and the row is removed.
|
|
150
|
+
|
|
151
|
+
## Limits of this release
|
|
152
|
+
|
|
153
|
+
The queue does not sort calls or decide whose turn it is yet. A call is handed to `hugpy-resources` whole, and
|
|
154
|
+
`hugpy-resources` still does stages 20 to 90 itself. That hand-off is on record as one stage row, `handed`, from the
|
|
155
|
+
moment the call is sent until the answer begins. Each stage moves to its owner's door as that door is made.
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
# hugpy-queue
|
|
2
|
+
|
|
3
|
+
The queue of a Hugpy worker: the front door every request comes in through, a record of every call, and the
|
|
4
|
+
stages each call passes on its way to an answer.
|
|
5
|
+
|
|
6
|
+
A Hugpy worker is made of four parts, each with its own service, account and database:
|
|
7
|
+
|
|
8
|
+
| Part | Package | What it answers |
|
|
9
|
+
|---|---|---|
|
|
10
|
+
| Discovery | `hugpy-discovery` | where a model is stored |
|
|
11
|
+
| Resources | `hugpy-resources` | where a model is loaded |
|
|
12
|
+
| Engines | `hugpy-engine` | what a model is doing and what it needs |
|
|
13
|
+
| Queue | `hugpy-queue` | what a call is and what it has |
|
|
14
|
+
|
|
15
|
+
`hugpy-wrapper` is the bundle that installs all four and connects their databases.
|
|
16
|
+
|
|
17
|
+
## What it does
|
|
18
|
+
|
|
19
|
+
- **Front door.** It listens on one address and takes every request for the worker. Each request is put on record
|
|
20
|
+
with its method, route, status, time and size.
|
|
21
|
+
- **Calls.** Every `POST` is a call. It gets a row saying what it is and what it has, and one row for each stage
|
|
22
|
+
it passes.
|
|
23
|
+
- **Hand-off.** The call is passed on to `hugpy-resources`, and the reply is passed back to the caller as it
|
|
24
|
+
comes, so a streamed reply still arrives piece by piece.
|
|
25
|
+
- **Health.** `GET /health` answers for the whole worker: the queue under its own name, and the health of the part
|
|
26
|
+
behind it as that part gave it.
|
|
27
|
+
|
|
28
|
+
Who may call is decided by `hugpy-resources`. The queue passes every header on unchanged, and names a caller from
|
|
29
|
+
another machine in `X-Forwarded-For`, so the caller is asked for its key exactly as it would be at that door.
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
pip install hugpy-queue
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Python 3.11 or later. The only dependency is `hugpy-utilities`.
|
|
38
|
+
|
|
39
|
+
To run it as a service of the host (Linux with systemd, as root):
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
sudo hugpy-queue system install
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
This makes the account `hugpy-queue`, the folder `/var/lib/hugpy/queue`, the database `queue.sqlite3` and the unit
|
|
46
|
+
`hugpy-queue.service`, then starts it. `sudo hugpy-queue system status` shows its state, and
|
|
47
|
+
`sudo hugpy-queue system uninstall` stops and removes the unit; the record and the settings are kept.
|
|
48
|
+
|
|
49
|
+
## Use
|
|
50
|
+
|
|
51
|
+
Send a call to the door the same way it would be sent to the worker:
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
curl http://127.0.0.1:15203/v1/chat/completions \
|
|
55
|
+
-H 'content-type: application/json' \
|
|
56
|
+
-d '{"model": "MODEL", "messages": [{"role": "user", "content": "hello"}]}'
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
The reply carries a `queue_id`: the number of the call's row.
|
|
60
|
+
|
|
61
|
+
### Commands
|
|
62
|
+
|
|
63
|
+
| Command | What it does |
|
|
64
|
+
|---|---|
|
|
65
|
+
| `hugpy-queue serve` | run the front door in the foreground (the service runs this) |
|
|
66
|
+
| `hugpy-queue calls` | the latest calls and the stages each passed |
|
|
67
|
+
| `hugpy-queue door` | what has been asked of the door, by route and status |
|
|
68
|
+
| `hugpy-queue settings` | every setting, its value, and where the database is |
|
|
69
|
+
| `hugpy-queue set NAME VALUE` | save one setting |
|
|
70
|
+
| `sudo hugpy-queue system install \| status \| uninstall` | the service of the host |
|
|
71
|
+
| `sudo hugpy-queue system set NAME VALUE` | save one setting and restart the service on it |
|
|
72
|
+
|
|
73
|
+
### The queue's own reads
|
|
74
|
+
|
|
75
|
+
These are answered by the queue itself and are not passed on:
|
|
76
|
+
|
|
77
|
+
| Route | What it returns |
|
|
78
|
+
|---|---|
|
|
79
|
+
| `GET /health` | the worker's health: the queue, and the part behind it |
|
|
80
|
+
| `GET /_queue/health` | the queue alone: its version, where it hands calls, how many are in flight |
|
|
81
|
+
| `GET /_queue/calls?limit=N` | the latest calls with their stages (20 by default, 500 at most) |
|
|
82
|
+
| `GET /_queue/door` | requests by method, route and status, with counts and times |
|
|
83
|
+
| `GET /_queue/stages` | the order of stages |
|
|
84
|
+
|
|
85
|
+
Every other request is passed on to `hugpy-resources`.
|
|
86
|
+
|
|
87
|
+
## Settings
|
|
88
|
+
|
|
89
|
+
| Setting | Default | What it is |
|
|
90
|
+
|---|---|---|
|
|
91
|
+
| `host` | `127.0.0.1` | the address the door listens on |
|
|
92
|
+
| `port` | `15203` | the port the door listens on |
|
|
93
|
+
| `wrapper_url` | `http://127.0.0.1:15202` | where a call is handed: the address of `hugpy-resources` |
|
|
94
|
+
|
|
95
|
+
A saved setting is a row of the `settings` table of the queue's database.
|
|
96
|
+
|
|
97
|
+
Two environment variables say where its data is kept:
|
|
98
|
+
|
|
99
|
+
| Variable | What it sets |
|
|
100
|
+
|---|---|
|
|
101
|
+
| `HUGPY_DATA_DIR` | the data directory shared by the Hugpy tools of a host (the service uses `/var/lib/hugpy`; a person's own default is `~/.local/share/hugpy`) |
|
|
102
|
+
| `HUGPY_QUEUE_STATE` | the queue's own folder (default: `queue` under the data directory) |
|
|
103
|
+
|
|
104
|
+
## The order of stages
|
|
105
|
+
|
|
106
|
+
A call passes these stages in order. Sorting only predicts; running acts.
|
|
107
|
+
|
|
108
|
+
| No. | Stage | Owner | Phase | What it is |
|
|
109
|
+
|---|---|---|---|---|
|
|
110
|
+
| 10 | `received` | queue | sort | recorded: what it is |
|
|
111
|
+
| 20 | `engine_range` | engine | sort | time-to-processed range from tokens in and out; impossible placements out |
|
|
112
|
+
| 30 | `reap_prediction` | discovery | sort | seconds to place the model on a worker drive |
|
|
113
|
+
| 40 | `evict_prediction` | resources | sort | seconds to make room in memory; finishes the sort |
|
|
114
|
+
| 50 | `turn` | queue | run | this row is next |
|
|
115
|
+
| 60 | `accommodate` | discovery | run | the model placed on a worker drive |
|
|
116
|
+
| 70 | `evict` | resources | run | room made |
|
|
117
|
+
| 80 | `load` | resources | run | the engine loads |
|
|
118
|
+
| 90 | `intake` | engine | run | the engine takes the call |
|
|
119
|
+
| 100 | `done` | queue | run | answered |
|
|
120
|
+
| 110 | `responded` | queue | run | the reply written to the caller |
|
|
121
|
+
|
|
122
|
+
The order is data: it is the `stage_order` table, and `GET /_queue/stages` returns it.
|
|
123
|
+
|
|
124
|
+
## What is recorded
|
|
125
|
+
|
|
126
|
+
The database is `queue.sqlite3` in the queue's folder. One thread of the queue's own process writes it; nothing else
|
|
127
|
+
does.
|
|
128
|
+
|
|
129
|
+
| Table or view | What it holds |
|
|
130
|
+
|---|---|
|
|
131
|
+
| `calls` | every call: what it is and what it has |
|
|
132
|
+
| `call_stages` | a row for each stage a call passed, with when it started and finished |
|
|
133
|
+
| `call_times` | view: each call with its times |
|
|
134
|
+
| `front_door` | every request at the door |
|
|
135
|
+
| `front_door_hours` | answered reads, counted by hour |
|
|
136
|
+
| `front_door_routes` | view: requests by method, route and status |
|
|
137
|
+
| `stage_order` | the order of stages |
|
|
138
|
+
| `settings` | the saved settings |
|
|
139
|
+
|
|
140
|
+
An answered read keeps its own `front_door` row for two minutes. It is then counted into its hour in
|
|
141
|
+
`front_door_hours` and the row is removed.
|
|
142
|
+
|
|
143
|
+
## Limits of this release
|
|
144
|
+
|
|
145
|
+
The queue does not sort calls or decide whose turn it is yet. A call is handed to `hugpy-resources` whole, and
|
|
146
|
+
`hugpy-resources` still does stages 20 to 90 itself. That hand-off is on record as one stage row, `handed`, from the
|
|
147
|
+
moment the call is sent until the answer begins. Each stage moves to its owner's door as that door is made.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "hugpy-queue"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "The queue of a Hugpy worker: the front door, a record of every call, and the stages each call passes"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
# hugpy_utilities is the one function library (the service helpers and the SQLite connection come from it).
|
|
12
|
+
# hugpy-resources, hugpy-engine and hugpy-discovery are not dependencies: each is a part of its own, asked over its door.
|
|
13
|
+
dependencies = ["hugpy-utilities>=0.1.0,<0.2"]
|
|
14
|
+
|
|
15
|
+
[project.scripts]
|
|
16
|
+
hugpy-queue = "hugpy_queue.cli:main"
|
|
17
|
+
|
|
18
|
+
[tool.setuptools]
|
|
19
|
+
package-dir = {"" = "src"}
|
|
20
|
+
|
|
21
|
+
[tool.setuptools.packages.find]
|
|
22
|
+
where = ["src"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""hugpy-queue: the queue of a Hugpy worker: the front door, a record of every call, and its stages (README.md)."""
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""A call's row and the rows of its stages: what the queue writes as a call passes through its hands."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from .imports import json, time
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def fields(body: bytes) -> dict:
|
|
8
|
+
"""What the queue reads of a call's body: the model as named, whether it streams, its cap on tokens."""
|
|
9
|
+
try:
|
|
10
|
+
doc = json.loads(body) if body else {}
|
|
11
|
+
except ValueError:
|
|
12
|
+
return {}
|
|
13
|
+
if not isinstance(doc, dict):
|
|
14
|
+
return {}
|
|
15
|
+
cap = doc.get("max_tokens", doc.get("max_completion_tokens"))
|
|
16
|
+
return {"model": doc.get("model") if isinstance(doc.get("model"), str) else None,
|
|
17
|
+
"stream": int(bool(doc.get("stream"))) if "stream" in doc else None,
|
|
18
|
+
"max_tokens": cap if isinstance(cap, int) else None}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def received(conn, at: float, endpoint: str, read: dict, caller: str, body: bytes) -> int:
|
|
22
|
+
"""Stage 10: the call is recorded as it arrived. Returns its id."""
|
|
23
|
+
call_id = conn.execute(
|
|
24
|
+
"INSERT INTO calls (arrived_at, endpoint, model, stream, max_tokens, caller, bytes_in, body) "
|
|
25
|
+
"VALUES (?,?,?,?,?,?,?,?)",
|
|
26
|
+
(at, endpoint, read.get("model"), read.get("stream"), read.get("max_tokens"), caller, len(body), body)).lastrowid
|
|
27
|
+
conn.execute("INSERT INTO call_stages (call_id, stage_no, stage, owner, started_at, finished_at) "
|
|
28
|
+
"VALUES (?, 10, 'received', 'queue', ?, ?)", (call_id, at, time.time()))
|
|
29
|
+
return call_id
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def handed(conn, call_id: int, to: str, at: float, note: str) -> None:
|
|
33
|
+
"""The call leaves the queue's hands for a part that does several stages itself."""
|
|
34
|
+
conn.execute("UPDATE calls SET state = 'handed', handed_to = ? WHERE id = ?", (to, call_id))
|
|
35
|
+
conn.execute("INSERT INTO call_stages (call_id, stage, owner, started_at, note) VALUES (?, 'handed', ?, ?, ?)",
|
|
36
|
+
(call_id, to, at, note))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def answered(conn, call_id: int, at: float, status, ref, error) -> None:
|
|
40
|
+
"""Stage 100: the part it was handed to has answered (or could not be reached)."""
|
|
41
|
+
conn.execute("UPDATE call_stages SET finished_at = ? WHERE call_id = ? AND stage = 'handed' AND finished_at IS NULL",
|
|
42
|
+
(at, call_id))
|
|
43
|
+
ok = status is not None and status < 500 and not error
|
|
44
|
+
conn.execute("UPDATE calls SET state = ?, kind = ?, handed_ref = ?, status = ?, done_at = ?, error = ? WHERE id = ?",
|
|
45
|
+
("done" if ok else "failed",
|
|
46
|
+
"call" if ref else "refused" if status is not None and status >= 400 else "command",
|
|
47
|
+
ref, status, at, error, call_id))
|
|
48
|
+
conn.execute("INSERT INTO call_stages (call_id, stage_no, stage, owner, started_at, finished_at) "
|
|
49
|
+
"VALUES (?, 100, 'done', 'queue', ?, ?)", (call_id, at, at))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def responded(conn, call_id: int, began: float, at: float, bytes_out: int, error, bytes_back=None, verified=None) -> None:
|
|
53
|
+
"""Stage 110: the reply is written to the caller (or the caller had gone). The body is held no longer.
|
|
54
|
+
`verified`: all that the part said it would send came back, and all of it was written to the caller."""
|
|
55
|
+
conn.execute("UPDATE calls SET responded_at = ?, bytes_out = ?, bytes_back = ?, verified = ?, body = NULL, "
|
|
56
|
+
"error = COALESCE(error, ?), state = CASE WHEN ? IS NULL THEN state ELSE 'failed' END WHERE id = ?",
|
|
57
|
+
(at, bytes_out, bytes_back, verified, error, error, call_id))
|
|
58
|
+
conn.execute("INSERT INTO call_stages (call_id, stage_no, stage, owner, started_at, finished_at, note) "
|
|
59
|
+
"VALUES (?, 110, 'responded', 'queue', ?, ?, ?)", (call_id, began, at, error))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def left_from_before(conn) -> int:
|
|
63
|
+
"""Calls a process before this one left in flight: it ended with them, and they say so."""
|
|
64
|
+
now = time.time()
|
|
65
|
+
count = conn.execute("UPDATE calls SET state = 'failed', body = NULL, done_at = COALESCE(done_at, ?), "
|
|
66
|
+
"error = COALESCE(error, 'the queue stopped while it was in flight') "
|
|
67
|
+
"WHERE state IN ('received', 'handed')", (now,)).rowcount
|
|
68
|
+
conn.execute("UPDATE call_stages SET finished_at = ?, note = COALESCE(note || '; ', '') || 'the queue stopped' "
|
|
69
|
+
"WHERE finished_at IS NULL", (now,))
|
|
70
|
+
return count
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""`hugpy-queue`: serve | calls | door | settings | set | system."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from . import store
|
|
5
|
+
from .imports import DEFAULTS, QUEUE_DB, TOOL, argparse, os, sqlite3, sys, time
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _clock(at) -> str:
|
|
9
|
+
return time.strftime("%H:%M:%S", time.localtime(at)) if at else "-"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _calls(args) -> int:
|
|
13
|
+
conn = store.reader()
|
|
14
|
+
try:
|
|
15
|
+
for call in conn.execute("SELECT * FROM call_times ORDER BY id DESC LIMIT ?", (args.limit,)).fetchall():
|
|
16
|
+
took = "-" if call["total_s"] is None else f"{call['total_s']:.2f}s"
|
|
17
|
+
proof = {1: "verified", 0: "NOT verified"}.get(call["verified"], "")
|
|
18
|
+
print(f"{call['id']:>6} {_clock(call['arrived_at'])} {call['state']:<8} {str(call['status'] or '-'):<4} {proof:<12} "
|
|
19
|
+
f"{took:>9} {call['kind'] or '-':<8} {call['endpoint']} {call['model'] or ''}"
|
|
20
|
+
+ (f" -> {call['handed_to']} {call['handed_ref']}" if call["handed_ref"] else ""))
|
|
21
|
+
for stage in conn.execute("SELECT * FROM call_stages WHERE call_id = ? ORDER BY started_at, id", (call["id"],)):
|
|
22
|
+
lasted = "" if stage["finished_at"] is None else f"{stage['finished_at'] - stage['started_at']:.3f}s"
|
|
23
|
+
print(f" {str(stage['stage_no'] or ''):>3} {stage['stage']:<10} {stage['owner']:<8} "
|
|
24
|
+
f"{_clock(stage['started_at'])} {lasted:>9} {stage['note'] or ''}")
|
|
25
|
+
finally:
|
|
26
|
+
conn.close()
|
|
27
|
+
return 0
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _door(_args) -> int:
|
|
31
|
+
conn = store.reader()
|
|
32
|
+
try:
|
|
33
|
+
for row in conn.execute("SELECT * FROM front_door_routes ORDER BY requests DESC").fetchall():
|
|
34
|
+
print(f"{row['requests']:>8} {row['method'] or '-':<7} {str(row['status'] or '-'):<4} "
|
|
35
|
+
f"{(row['avg_ms'] or 0):>9.1f} ms {row['route']}")
|
|
36
|
+
finally:
|
|
37
|
+
conn.close()
|
|
38
|
+
return 0
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _settings(_args) -> int:
|
|
42
|
+
found = store.settings()
|
|
43
|
+
for name in DEFAULTS:
|
|
44
|
+
print(f"{name:<12} {found[name]}" + ("" if found[name] != DEFAULTS[name] else " (default)"))
|
|
45
|
+
print(f"{'database':<12} {QUEUE_DB}")
|
|
46
|
+
return 0
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _set(args) -> int:
|
|
50
|
+
try:
|
|
51
|
+
store.save_setting(args.name, args.value, by=f"{TOOL} set")
|
|
52
|
+
except KeyError as exc:
|
|
53
|
+
raise SystemExit(str(exc.args[0]))
|
|
54
|
+
print(f"{args.name} = {args.value} (the service reads it when it next starts)")
|
|
55
|
+
return 0
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def main(argv=None) -> int:
|
|
59
|
+
argv = sys.argv[1:] if argv is None else list(argv)
|
|
60
|
+
if argv[:1] == ["system"]:
|
|
61
|
+
from .system import main as system_main
|
|
62
|
+
return system_main(argv[1:], given=os.environ.get("HUGPY_DATA_DIR"))
|
|
63
|
+
parser = argparse.ArgumentParser(prog=TOOL, description="The queue: the front door, every call and its stages")
|
|
64
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
65
|
+
sub.add_parser("serve", help="the front door (the service runs this)")
|
|
66
|
+
shown = sub.add_parser("calls", help="the latest calls and their stages")
|
|
67
|
+
shown.add_argument("--limit", type=int, default=10)
|
|
68
|
+
sub.add_parser("door", help="what is asked of the door, a route and status")
|
|
69
|
+
sub.add_parser("settings", help="every setting and its value")
|
|
70
|
+
one = sub.add_parser("set", help="save one setting")
|
|
71
|
+
one.add_argument("name")
|
|
72
|
+
one.add_argument("value")
|
|
73
|
+
sub.add_parser("system", help="install | status | uninstall: this tool as a service of the host")
|
|
74
|
+
args = parser.parse_args(argv)
|
|
75
|
+
if args.command == "serve":
|
|
76
|
+
from .door import serve
|
|
77
|
+
return serve()
|
|
78
|
+
try:
|
|
79
|
+
return {"calls": _calls, "door": _door, "settings": _settings, "set": _set}[args.command](args)
|
|
80
|
+
except sqlite3.OperationalError as exc:
|
|
81
|
+
raise SystemExit(f"{QUEUE_DB}: {exc} (is the service installed? sudo {TOOL} system install)")
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""The core statements of queue: one named query for each derivation this part owns.
|
|
2
|
+
|
|
3
|
+
Each is a SELECT that takes no call as input and answers for every model as things stand. `views(conn)`
|
|
4
|
+
makes them temporary views of a connection, under these names, in this order (a later one reads an earlier).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
# Q1 call_units: the model a call is for, as a unit. The queue's own row has the model as the caller named it; which unit that is (the quant chosen, a person's approved fallbacks) is still resolved in the wrapper (queue/rows.py choose, auto_quant, resolve: about 150 lines) and is on the wrapper's row
|
|
8
|
+
CALL_UNITS_SQL = """
|
|
9
|
+
SELECT c.id AS call_id, c.arrived_at, c.endpoint, c.model AS named, c.state, c.kind,
|
|
10
|
+
q.id AS wrapper_id, q.key, q.variation, COALESCE(NULLIF(q.engine, ''), u.engine) AS engine,
|
|
11
|
+
COALESCE(q.tokens_in, 0) AS tokens_in, COALESCE(c.max_tokens, q.tokens_out_hi) AS output_top
|
|
12
|
+
FROM main.calls c
|
|
13
|
+
LEFT JOIN w.queue q ON c.handed_to = 'wrapper'
|
|
14
|
+
AND q.id = CAST(replace(c.handed_ref, rtrim(c.handed_ref, '0123456789'), '') AS INTEGER)
|
|
15
|
+
LEFT JOIN w.units_mat u ON u.key = q.key AND u.variation = q.variation
|
|
16
|
+
WHERE c.endpoint LIKE '/v1/%'
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
# Q2 model_readiness: the readiness of all three components for every model, with no call. accommodated Discovery: its files are whole where its route loads it from resident wrapper: it is in the resources (a load that is ready and not ended) engine_here engines: its engine can start o
|
|
20
|
+
MODEL_READINESS_SQL = """
|
|
21
|
+
SELECT u.key, u.variation, u.engine,
|
|
22
|
+
COALESCE(du.route_present, 0) AS accommodated, du.route_role AS loaded_from,
|
|
23
|
+
EXISTS (SELECT 1 FROM w.load_runs r WHERE r.key = u.key AND r.variation = u.variation
|
|
24
|
+
AND r.state = 'ready' AND r.ended_at IS NULL) AS resident,
|
|
25
|
+
EXISTS (SELECT 1 FROM w.load_runs r WHERE r.key = u.key AND r.variation = u.variation
|
|
26
|
+
AND r.state = 'requested' AND r.ended_at IS NULL) AS loading,
|
|
27
|
+
COALESCE(en.ready, 0) AS engine_here, en.why AS engine_why,
|
|
28
|
+
EXISTS (SELECT 1 FROM w.load_runs r JOIN e.starts s ON s.pid = r.pid AND s.port = r.port
|
|
29
|
+
WHERE r.key = u.key AND r.variation = u.variation AND r.state = 'ready' AND r.ended_at IS NULL
|
|
30
|
+
AND s.ready_at IS NOT NULL AND s.stopped_at IS NULL) AS engine_up
|
|
31
|
+
FROM w.units_mat u
|
|
32
|
+
LEFT JOIN d.api_units_v1 du ON du.key = u.key AND du.variation = u.variation
|
|
33
|
+
LEFT JOIN e.engines en ON en.engine = u.engine
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
# Q3 call_readiness: for any call in the queue, whether all three are ready for it, and the stage still wanted (the operator's order, stage_order: 60 accommodate, 70 evict and 80 load, 90 intake).
|
|
37
|
+
CALL_READINESS_SQL = """
|
|
38
|
+
SELECT c.call_id, c.arrived_at, c.named, c.key, c.variation, c.state,
|
|
39
|
+
m.accommodated, m.resident, m.engine_here, m.engine_up,
|
|
40
|
+
(m.accommodated AND m.resident AND m.engine_up) AS ready,
|
|
41
|
+
CASE WHEN c.key IS NULL THEN 'not a model this worker has'
|
|
42
|
+
WHEN NOT m.engine_here THEN 'none: its engine cannot start here (' || COALESCE(m.engine_why, 'no reason on record') || ')'
|
|
43
|
+
WHEN NOT m.accommodated THEN '60 accommodate (Discovery)'
|
|
44
|
+
WHEN NOT m.resident THEN CASE WHEN m.loading THEN '80 load (under way)' ELSE '70 evict, 80 load (wrapper)' END
|
|
45
|
+
WHEN NOT m.engine_up THEN '80 load: no engine on record for it'
|
|
46
|
+
ELSE '90 intake (engines)' END AS wanted
|
|
47
|
+
FROM call_units c LEFT JOIN model_readiness m ON m.key = c.key AND m.variation = c.variation
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
CORE = {
|
|
51
|
+
'call_units': CALL_UNITS_SQL,
|
|
52
|
+
'model_readiness': MODEL_READINESS_SQL,
|
|
53
|
+
'call_readiness': CALL_READINESS_SQL,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def views(conn) -> list:
|
|
58
|
+
"""Make every core statement a temporary view of `conn`; the names made."""
|
|
59
|
+
for name, sql in CORE.items():
|
|
60
|
+
conn.execute(f"DROP VIEW IF EXISTS temp.{name}")
|
|
61
|
+
conn.execute(f"CREATE TEMP VIEW {name} AS {sql}")
|
|
62
|
+
return list(CORE)
|