streaming-sql-engine 0.1.30__tar.gz → 0.2.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.
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/MANIFEST.in +1 -0
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/PKG-INFO +38 -3
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/README.md +32 -2
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/__init__.py +1 -1
- streaming_sql_engine-0.2.0/app/__init__.py +8 -0
- streaming_sql_engine-0.2.0/app/__main__.py +46 -0
- streaming_sql_engine-0.2.0/app/demo.py +106 -0
- streaming_sql_engine-0.2.0/app/jobs.py +165 -0
- streaming_sql_engine-0.2.0/app/server.py +246 -0
- streaming_sql_engine-0.2.0/app/sources.py +320 -0
- streaming_sql_engine-0.2.0/app/static/app.css +457 -0
- streaming_sql_engine-0.2.0/app/static/app.js +1008 -0
- streaming_sql_engine-0.2.0/app/static/index.html +239 -0
- streaming_sql_engine-0.2.0/app/worker.py +620 -0
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/core/evaluator.py +21 -5
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/core/executor.py +12 -3
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/core/optimizer.py +470 -470
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/core/planner.py +174 -174
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/engine.py +10 -5
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/operators/base.py +520 -586
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/operators/mmap.py +262 -332
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/operators/polars.py +732 -732
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/pyproject.toml +80 -67
- streaming_sql_engine-0.2.0/run_app.py +17 -0
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/storage/__init__.py +4 -2
- streaming_sql_engine-0.2.0/storage/file_index.py +405 -0
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/storage/mmap_index.py +391 -391
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/streaming_sql_engine.egg-info/SOURCES.txt +24 -0
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/core/__init__.py +0 -0
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/core/parser.py +0 -0
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/operators/__init__.py +0 -0
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/polars_utils/__init__.py +0 -0
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/polars_utils/operators.py +0 -0
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/polars_utils/translator.py +0 -0
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/requirements.txt +0 -0
- {streaming_sql_engine-0.1.30 → streaming_sql_engine-0.2.0}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: streaming-sql-engine
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Streaming SQL Engine: Lightweight Cross Data Source Integration for Resource Constraint Environments
|
|
5
5
|
Home-page: https://github.com/Ierofantis/streaming_sql_engine/
|
|
6
6
|
Author: Ierofantis
|
|
@@ -31,6 +31,11 @@ Requires-Dist: psycopg2-binary>=2.9.0; extra == "db"
|
|
|
31
31
|
Requires-Dist: pymysql>=1.0.0; extra == "db"
|
|
32
32
|
Requires-Dist: DBUtils>=3.0.0; extra == "db"
|
|
33
33
|
Requires-Dist: pymongo>=4.0.0; extra == "db"
|
|
34
|
+
Provides-Extra: app
|
|
35
|
+
Requires-Dist: fastapi>=0.100.0; extra == "app"
|
|
36
|
+
Requires-Dist: uvicorn>=0.23.0; extra == "app"
|
|
37
|
+
Requires-Dist: psutil>=5.9.0; extra == "app"
|
|
38
|
+
Requires-Dist: openpyxl>=3.1.0; extra == "app"
|
|
34
39
|
Provides-Extra: dev
|
|
35
40
|
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
36
41
|
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
|
|
@@ -114,6 +119,33 @@ for row in engine.query(query):
|
|
|
114
119
|
|
|
115
120
|
---
|
|
116
121
|
|
|
122
|
+
## File Compare app
|
|
123
|
+
|
|
124
|
+
A local web app on top of the engine: compare two large CSV, TSV, JSONL or Excel files and watch the join run live. Nothing is uploaded; it runs on your machine and opens in your browser.
|
|
125
|
+
|
|
126
|
+
```bash
|
|
127
|
+
pip install "streaming-sql-engine[app]"
|
|
128
|
+
sse-compare # or: python -m streaming_sql_engine.app
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
From a source checkout: `python run_app.py`.
|
|
132
|
+
|
|
133
|
+
1. Pick file A and file B (or generate synthetic demo files).
|
|
134
|
+
2. Confirm the key columns; the app suggests them from column names and sample values.
|
|
135
|
+
3. Choose what to show: rows in both files, rows only in A, rows only in B, or matched rows whose values differ.
|
|
136
|
+
4. Press Run. Rows, throughput and memory update live, the generated SQL is shown, and the result downloads as CSV.
|
|
137
|
+
|
|
138
|
+
The "File index in Rust" strategy (files in any order) and the "Merge in Rust" strategies (files already sorted by the key) use an optional native extension that runs on all cores. It reads CSV and TSV. Build it once from a checkout (needs the Rust toolchain):
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
pip install maturin
|
|
142
|
+
cd native && maturin develop --release
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Each run happens in its own process, so the memory figure is the cost of that run alone. Run the same comparison with the "In-memory hash" strategy to see the difference against the default file index join.
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
|
|
117
149
|
## The Problem: Data Lives Everywhere
|
|
118
150
|
|
|
119
151
|
Modern applications don't store all their data in one place. You might have:
|
|
@@ -501,7 +533,7 @@ query = """
|
|
|
501
533
|
|
|
502
534
|
### 4. MMAP Join (For Large Files)
|
|
503
535
|
|
|
504
|
-
Memory-mapped joins for files larger than RAM
|
|
536
|
+
Memory-mapped joins for files larger than RAM. The `filename` can be a JSONL, CSV or TSV file; join keys are compared as text.
|
|
505
537
|
|
|
506
538
|
```python
|
|
507
539
|
engine = Engine(use_polars=False) # MMAP requires use_polars=False
|
|
@@ -1632,6 +1664,9 @@ For cross-system data integration, the Streaming SQL Engine provides a unique so
|
|
|
1632
1664
|
## Resources
|
|
1633
1665
|
|
|
1634
1666
|
- **PyPI:** `pip install streaming-sql-engine`
|
|
1635
|
-
- **
|
|
1667
|
+
- **Bug Reports:** `"https://github.com/Ierofantis/streaming_sql_engine/issues"`,
|
|
1668
|
+
- **Source":** `"https://github.com/Ierofantis/streaming_sql_engine/"`,
|
|
1669
|
+
- **Documentation":** `"https://github.com/Ierofantis/streaming_sql_engine/blob/master/README.md"`,
|
|
1670
|
+
- **Scientific Paper":** `"https://github.com/Ierofantis/streaming_sql_engine/blob/master/Streaming_SQL_Engine_Paper.pdf"`
|
|
1636
1671
|
|
|
1637
1672
|
---
|
|
@@ -67,6 +67,33 @@ for row in engine.query(query):
|
|
|
67
67
|
|
|
68
68
|
---
|
|
69
69
|
|
|
70
|
+
## File Compare app
|
|
71
|
+
|
|
72
|
+
A local web app on top of the engine: compare two large CSV, TSV, JSONL or Excel files and watch the join run live. Nothing is uploaded; it runs on your machine and opens in your browser.
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
pip install "streaming-sql-engine[app]"
|
|
76
|
+
sse-compare # or: python -m streaming_sql_engine.app
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
From a source checkout: `python run_app.py`.
|
|
80
|
+
|
|
81
|
+
1. Pick file A and file B (or generate synthetic demo files).
|
|
82
|
+
2. Confirm the key columns; the app suggests them from column names and sample values.
|
|
83
|
+
3. Choose what to show: rows in both files, rows only in A, rows only in B, or matched rows whose values differ.
|
|
84
|
+
4. Press Run. Rows, throughput and memory update live, the generated SQL is shown, and the result downloads as CSV.
|
|
85
|
+
|
|
86
|
+
The "File index in Rust" strategy (files in any order) and the "Merge in Rust" strategies (files already sorted by the key) use an optional native extension that runs on all cores. It reads CSV and TSV. Build it once from a checkout (needs the Rust toolchain):
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
pip install maturin
|
|
90
|
+
cd native && maturin develop --release
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Each run happens in its own process, so the memory figure is the cost of that run alone. Run the same comparison with the "In-memory hash" strategy to see the difference against the default file index join.
|
|
94
|
+
|
|
95
|
+
---
|
|
96
|
+
|
|
70
97
|
## The Problem: Data Lives Everywhere
|
|
71
98
|
|
|
72
99
|
Modern applications don't store all their data in one place. You might have:
|
|
@@ -454,7 +481,7 @@ query = """
|
|
|
454
481
|
|
|
455
482
|
### 4. MMAP Join (For Large Files)
|
|
456
483
|
|
|
457
|
-
Memory-mapped joins for files larger than RAM
|
|
484
|
+
Memory-mapped joins for files larger than RAM. The `filename` can be a JSONL, CSV or TSV file; join keys are compared as text.
|
|
458
485
|
|
|
459
486
|
```python
|
|
460
487
|
engine = Engine(use_polars=False) # MMAP requires use_polars=False
|
|
@@ -1585,6 +1612,9 @@ For cross-system data integration, the Streaming SQL Engine provides a unique so
|
|
|
1585
1612
|
## Resources
|
|
1586
1613
|
|
|
1587
1614
|
- **PyPI:** `pip install streaming-sql-engine`
|
|
1588
|
-
- **
|
|
1615
|
+
- **Bug Reports:** `"https://github.com/Ierofantis/streaming_sql_engine/issues"`,
|
|
1616
|
+
- **Source":** `"https://github.com/Ierofantis/streaming_sql_engine/"`,
|
|
1617
|
+
- **Documentation":** `"https://github.com/Ierofantis/streaming_sql_engine/blob/master/README.md"`,
|
|
1618
|
+
- **Scientific Paper":** `"https://github.com/Ierofantis/streaming_sql_engine/blob/master/Streaming_SQL_Engine_Paper.pdf"`
|
|
1589
1619
|
|
|
1590
1620
|
---
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Start the File Compare app: python -m streaming_sql_engine.app
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import socket
|
|
7
|
+
import threading
|
|
8
|
+
import webbrowser
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _free_port(preferred: int) -> int:
|
|
12
|
+
for port in [preferred] + list(range(preferred + 1, preferred + 20)):
|
|
13
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
|
|
14
|
+
try:
|
|
15
|
+
probe.bind(("127.0.0.1", port))
|
|
16
|
+
return port
|
|
17
|
+
except OSError:
|
|
18
|
+
continue
|
|
19
|
+
raise SystemExit(f"No free port between {preferred} and {preferred + 19}. Pass --port.")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def main() -> None:
|
|
23
|
+
parser = argparse.ArgumentParser(description="Compare two large files with the streaming SQL engine.")
|
|
24
|
+
parser.add_argument("--port", type=int, default=8765, help="port to listen on (default 8765)")
|
|
25
|
+
parser.add_argument("--no-browser", action="store_true", help="do not open the browser")
|
|
26
|
+
args = parser.parse_args()
|
|
27
|
+
|
|
28
|
+
try:
|
|
29
|
+
import uvicorn
|
|
30
|
+
from .server import app
|
|
31
|
+
except ImportError as exc:
|
|
32
|
+
raise SystemExit(
|
|
33
|
+
f"The app needs extra packages ({exc.name} is missing). "
|
|
34
|
+
"Install them with: pip install fastapi uvicorn psutil openpyxl"
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
port = _free_port(args.port)
|
|
38
|
+
url = f"http://127.0.0.1:{port}"
|
|
39
|
+
print(f"File Compare is running at {url} (Ctrl+C to stop)")
|
|
40
|
+
if not args.no_browser:
|
|
41
|
+
threading.Timer(0.8, webbrowser.open, args=(url,)).start()
|
|
42
|
+
uvicorn.run(app, host="127.0.0.1", port=port, log_level="warning")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
if __name__ == "__main__":
|
|
46
|
+
main()
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Synthetic demo files for the File Compare app.
|
|
3
|
+
|
|
4
|
+
Writes a shop catalog and a supplier feed that share most products, with a
|
|
5
|
+
known share of missing products and price differences on each side.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import csv
|
|
9
|
+
import math
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Dict
|
|
12
|
+
|
|
13
|
+
from .sources import app_dir
|
|
14
|
+
|
|
15
|
+
BRANDS = ["Aldera", "Brontis", "Calyx", "Dorvik", "Elmar", "Fenwick", "Galdo", "Hestia", "Ionis", "Jurek"]
|
|
16
|
+
CATEGORIES = ["Audio", "Cables", "Storage", "Lighting", "Kitchen", "Garden", "Tools", "Office", "Toys", "Sport"]
|
|
17
|
+
NOUNS = ["Speaker", "Adapter", "Drive", "Lamp", "Kettle", "Hose", "Drill", "Stapler", "Puzzle", "Bottle"]
|
|
18
|
+
SUPPLIERS = ["Nordwind Trading", "Meridian Supply", "Kastro Wholesale"]
|
|
19
|
+
|
|
20
|
+
EAN_BASE = 5_200_000_000_000
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _coprime_step(n: int) -> int:
|
|
24
|
+
step = int(n * 0.6180339887) | 1
|
|
25
|
+
while math.gcd(step, n) != 1:
|
|
26
|
+
step += 2
|
|
27
|
+
return step
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def generate_demo(rows: int, sorted_by_key: bool = False) -> Dict[str, object]:
|
|
31
|
+
"""
|
|
32
|
+
Write demo files with `rows` catalog products and return their paths.
|
|
33
|
+
|
|
34
|
+
Of the catalog: 4% are missing from the feed and 3% have a different
|
|
35
|
+
price there. The feed also carries 2% products the catalog does not have,
|
|
36
|
+
and its rows are in a different order unless `sorted_by_key` is set, in
|
|
37
|
+
which case both files are in key order (what a merge join needs).
|
|
38
|
+
"""
|
|
39
|
+
rows = max(1000, int(rows))
|
|
40
|
+
folder = app_dir("demo")
|
|
41
|
+
catalog = folder / f"catalog_{rows}.csv"
|
|
42
|
+
feed = folder / f"supplier_feed_{'sorted_' if sorted_by_key else ''}{rows}.csv"
|
|
43
|
+
extra = rows // 50
|
|
44
|
+
|
|
45
|
+
if not catalog.exists():
|
|
46
|
+
with open(catalog, "w", newline="", encoding="utf-8") as f:
|
|
47
|
+
w = csv.writer(f)
|
|
48
|
+
w.writerow(["ean", "sku", "name", "brand", "category", "price", "stock"])
|
|
49
|
+
for i in range(rows):
|
|
50
|
+
w.writerow(_catalog_row(i))
|
|
51
|
+
|
|
52
|
+
if not feed.exists():
|
|
53
|
+
total = rows + extra
|
|
54
|
+
step = _coprime_step(total)
|
|
55
|
+
with open(feed, "w", newline="", encoding="utf-8") as f:
|
|
56
|
+
w = csv.writer(f)
|
|
57
|
+
w.writerow(["barcode", "title", "supplier_price", "qty", "supplier"])
|
|
58
|
+
for n in range(total):
|
|
59
|
+
i = n if sorted_by_key else (n * step + 7) % total
|
|
60
|
+
if i < rows and i % 25 == 3:
|
|
61
|
+
continue # catalog product the supplier does not list
|
|
62
|
+
w.writerow(_feed_row(i))
|
|
63
|
+
|
|
64
|
+
return {
|
|
65
|
+
"a": str(catalog),
|
|
66
|
+
"b": str(feed),
|
|
67
|
+
"rows": rows,
|
|
68
|
+
"sorted": sorted_by_key,
|
|
69
|
+
"note": "Synthetic demo data: 4% of catalog products are missing from the feed, "
|
|
70
|
+
"3% have a different price, and the feed has 2% extra products. "
|
|
71
|
+
+ ("Both files are sorted by the key, so merge join works."
|
|
72
|
+
if sorted_by_key else "The feed is in a different order than the catalog."),
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _price(i: int) -> float:
|
|
77
|
+
return round(4.9 + (i * 37 % 19_900) / 100, 2)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _name(i: int) -> str:
|
|
81
|
+
return f"{BRANDS[i % 10]} {NOUNS[(i // 10) % 10]} {100 + i % 900}"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _catalog_row(i: int):
|
|
85
|
+
return [
|
|
86
|
+
EAN_BASE + i,
|
|
87
|
+
f"SKU-{i:08d}",
|
|
88
|
+
_name(i),
|
|
89
|
+
BRANDS[i % 10],
|
|
90
|
+
CATEGORIES[(i // 7) % 10],
|
|
91
|
+
f"{_price(i):.2f}",
|
|
92
|
+
i * 13 % 250,
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _feed_row(i: int):
|
|
97
|
+
price = _price(i)
|
|
98
|
+
if i % 33 == 5:
|
|
99
|
+
price = round(price * 1.08 + 0.5, 2) # supplier changed the price
|
|
100
|
+
return [
|
|
101
|
+
EAN_BASE + i,
|
|
102
|
+
_name(i),
|
|
103
|
+
f"{price:.2f}",
|
|
104
|
+
i * 29 % 400,
|
|
105
|
+
SUPPLIERS[i % 3],
|
|
106
|
+
]
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Job manager: starts comparison workers, collects their events, keeps run history.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
import uuid
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any, Dict, List, Optional
|
|
14
|
+
|
|
15
|
+
from .sources import app_dir
|
|
16
|
+
|
|
17
|
+
# The worker starts with polars masked: the comparison joins do not use it,
|
|
18
|
+
# and importing it would add its footprint to every memory reading.
|
|
19
|
+
_BOOT = (
|
|
20
|
+
"import sys; sys.modules['polars'] = None; "
|
|
21
|
+
"from streaming_sql_engine.app.worker import main; sys.exit(main(sys.argv[1]))"
|
|
22
|
+
)
|
|
23
|
+
_PACKAGE_PARENT = str(Path(__file__).resolve().parents[2])
|
|
24
|
+
_KEEP_ROWS_FOR = 60
|
|
25
|
+
MAX_HISTORY = 30
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Job:
|
|
29
|
+
def __init__(self, job_id: str, spec: Dict[str, Any]):
|
|
30
|
+
self.id = job_id
|
|
31
|
+
self.spec = spec
|
|
32
|
+
self.state = "running"
|
|
33
|
+
self.events: List[Dict[str, Any]] = []
|
|
34
|
+
self.process: Optional[subprocess.Popen] = None
|
|
35
|
+
self.started_at = time.time()
|
|
36
|
+
self.summary: Optional[Dict[str, Any]] = None
|
|
37
|
+
self.lock = threading.Lock()
|
|
38
|
+
|
|
39
|
+
def add(self, event: Dict[str, Any]) -> None:
|
|
40
|
+
with self.lock:
|
|
41
|
+
self.events.append(event)
|
|
42
|
+
# Old ticks keep their numbers but drop their row payloads.
|
|
43
|
+
if len(self.events) > _KEEP_ROWS_FOR:
|
|
44
|
+
self.events[-_KEEP_ROWS_FOR - 1].pop("rows", None)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class JobManager:
|
|
48
|
+
def __init__(self):
|
|
49
|
+
self.jobs: Dict[str, Job] = {}
|
|
50
|
+
self.history: List[Dict[str, Any]] = []
|
|
51
|
+
self.lock = threading.Lock()
|
|
52
|
+
|
|
53
|
+
def running(self) -> Optional[Job]:
|
|
54
|
+
for job in self.jobs.values():
|
|
55
|
+
if job.state == "running":
|
|
56
|
+
return job
|
|
57
|
+
return None
|
|
58
|
+
|
|
59
|
+
def start(self, spec: Dict[str, Any]) -> Job:
|
|
60
|
+
with self.lock:
|
|
61
|
+
if self.running():
|
|
62
|
+
raise RuntimeError("A comparison is already running. Stop it before starting another.")
|
|
63
|
+
job_id = uuid.uuid4().hex[:12]
|
|
64
|
+
run_dir = app_dir("runs")
|
|
65
|
+
spec = dict(spec, output=str(run_dir / f"{job_id}.csv"))
|
|
66
|
+
spec_path = run_dir / f"{job_id}.json"
|
|
67
|
+
spec_path.write_text(json.dumps(spec), encoding="utf-8")
|
|
68
|
+
job = Job(job_id, spec)
|
|
69
|
+
|
|
70
|
+
env = dict(os.environ)
|
|
71
|
+
env["PYTHONPATH"] = _PACKAGE_PARENT + os.pathsep + env.get("PYTHONPATH", "")
|
|
72
|
+
env["PYTHONIOENCODING"] = "utf-8"
|
|
73
|
+
stderr_file = open(run_dir / f"{job_id}.log", "w", encoding="utf-8")
|
|
74
|
+
flags = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0
|
|
75
|
+
job.process = subprocess.Popen(
|
|
76
|
+
[sys.executable, "-c", _BOOT, str(spec_path)],
|
|
77
|
+
stdout=subprocess.PIPE,
|
|
78
|
+
stderr=stderr_file,
|
|
79
|
+
env=env,
|
|
80
|
+
creationflags=flags,
|
|
81
|
+
)
|
|
82
|
+
self.jobs[job_id] = job
|
|
83
|
+
threading.Thread(target=self._read, args=(job, stderr_file), daemon=True).start()
|
|
84
|
+
return job
|
|
85
|
+
|
|
86
|
+
def _read(self, job: Job, stderr_file) -> None:
|
|
87
|
+
start_event: Dict[str, Any] = {}
|
|
88
|
+
last_tick: Dict[str, Any] = {}
|
|
89
|
+
try:
|
|
90
|
+
for raw in job.process.stdout:
|
|
91
|
+
try:
|
|
92
|
+
event = json.loads(raw.decode("utf-8", errors="replace"))
|
|
93
|
+
except ValueError:
|
|
94
|
+
continue
|
|
95
|
+
kind = event.get("type")
|
|
96
|
+
if kind == "start":
|
|
97
|
+
start_event = event
|
|
98
|
+
elif kind == "tick":
|
|
99
|
+
last_tick = event
|
|
100
|
+
elif kind == "done":
|
|
101
|
+
job.state = "done"
|
|
102
|
+
job.summary = self._summarize(job, start_event, event, "done")
|
|
103
|
+
event["run"] = job.summary
|
|
104
|
+
elif kind == "error":
|
|
105
|
+
job.state = "error"
|
|
106
|
+
job.add(event)
|
|
107
|
+
finally:
|
|
108
|
+
code = job.process.wait()
|
|
109
|
+
stderr_file.close()
|
|
110
|
+
if job.state == "running":
|
|
111
|
+
# The worker ended without a done or error message.
|
|
112
|
+
job.state = "error"
|
|
113
|
+
detail = self._log_tail(job)
|
|
114
|
+
job.add({"type": "error",
|
|
115
|
+
"message": f"The comparison process stopped unexpectedly (exit code {code}). {detail}".strip()})
|
|
116
|
+
if job.state == "cancelled":
|
|
117
|
+
job.summary = self._summarize(job, start_event, last_tick, "cancelled")
|
|
118
|
+
job.add({"type": "cancelled", "run": job.summary})
|
|
119
|
+
if job.summary:
|
|
120
|
+
with self.lock:
|
|
121
|
+
self.history.insert(0, job.summary)
|
|
122
|
+
del self.history[MAX_HISTORY:]
|
|
123
|
+
|
|
124
|
+
def _log_tail(self, job: Job) -> str:
|
|
125
|
+
try:
|
|
126
|
+
lines = (app_dir("runs") / f"{job.id}.log").read_text(encoding="utf-8").strip().splitlines()
|
|
127
|
+
return lines[-1] if lines else ""
|
|
128
|
+
except OSError:
|
|
129
|
+
return ""
|
|
130
|
+
|
|
131
|
+
def _summarize(self, job: Job, start: Dict[str, Any], last: Dict[str, Any], state: str) -> Dict[str, Any]:
|
|
132
|
+
elapsed = last.get("elapsed", 0) or 0
|
|
133
|
+
probe_rows = last.get("probe_rows", 0)
|
|
134
|
+
return {
|
|
135
|
+
"id": job.id,
|
|
136
|
+
"state": state,
|
|
137
|
+
"started_at": job.started_at,
|
|
138
|
+
"mode": job.spec["mode"],
|
|
139
|
+
"strategy": job.spec["strategy"],
|
|
140
|
+
"strategy_label": start.get("strategy_label", job.spec["strategy"]),
|
|
141
|
+
"a": Path(job.spec["a"]["path"]).name,
|
|
142
|
+
"b": Path(job.spec["b"]["path"]).name,
|
|
143
|
+
"elapsed": elapsed,
|
|
144
|
+
"probe_rows": probe_rows,
|
|
145
|
+
"build_rows": last.get("build_rows", 0),
|
|
146
|
+
"joined": last.get("joined", 0),
|
|
147
|
+
"out": last.get("out", 0),
|
|
148
|
+
"peak": last.get("peak", 0),
|
|
149
|
+
"baseline": start.get("baseline", 0),
|
|
150
|
+
"rows_per_sec": round((probe_rows + last.get("build_rows", 0)) / elapsed) if elapsed else 0,
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
def cancel(self, job_id: str) -> bool:
|
|
154
|
+
job = self.jobs.get(job_id)
|
|
155
|
+
if not job or job.state != "running":
|
|
156
|
+
return False
|
|
157
|
+
job.state = "cancelled"
|
|
158
|
+
job.process.terminate()
|
|
159
|
+
return True
|
|
160
|
+
|
|
161
|
+
def shutdown(self) -> None:
|
|
162
|
+
for job in self.jobs.values():
|
|
163
|
+
if job.state == "running":
|
|
164
|
+
job.state = "cancelled"
|
|
165
|
+
job.process.terminate()
|