tuneio 2.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. tuneio/__init__.py +2 -0
  2. tuneio/__main__.py +3 -0
  3. tuneio/_version.py +2 -0
  4. tuneio/artifacts.py +55 -0
  5. tuneio/baseline.py +160 -0
  6. tuneio/benchmarking.py +434 -0
  7. tuneio/cache.py +2 -0
  8. tuneio/cli.py +575 -0
  9. tuneio/comparison.py +106 -0
  10. tuneio/console.py +151 -0
  11. tuneio/core/__init__.py +10 -0
  12. tuneio/core/cache.py +223 -0
  13. tuneio/core/contracts.py +14 -0
  14. tuneio/core/controller.py +90 -0
  15. tuneio/core/engine.py +64 -0
  16. tuneio/core/insights.py +146 -0
  17. tuneio/core/metrics.py +83 -0
  18. tuneio/core/monitoring.py +26 -0
  19. tuneio/dashboard.html +114 -0
  20. tuneio/database.py +64 -0
  21. tuneio/demo.py +51 -0
  22. tuneio/discovery.py +294 -0
  23. tuneio/main.py +147 -0
  24. tuneio/metrics.py +2 -0
  25. tuneio/monitor.py +248 -0
  26. tuneio/optimization.py +109 -0
  27. tuneio/product.css +4 -0
  28. tuneio/product_config.py +189 -0
  29. tuneio/product_dashboard.html +46 -0
  30. tuneio/product_ui.js +62 -0
  31. tuneio/proxy.py +393 -0
  32. tuneio/qualification_fixture.py +84 -0
  33. tuneio/qualification_server.py +57 -0
  34. tuneio/quality.py +29 -0
  35. tuneio/release.py +92 -0
  36. tuneio/reporting.py +24 -0
  37. tuneio/response_cache.py +297 -0
  38. tuneio/scenario_presets.json +200 -0
  39. tuneio/scenarios.py +314 -0
  40. tuneio/schemas.py +53 -0
  41. tuneio/session.py +124 -0
  42. tuneio/storage.py +465 -0
  43. tuneio/terminal.py +667 -0
  44. tuneio/terminal_reports.py +271 -0
  45. tuneio/terminal_ui.py +288 -0
  46. tuneio/workflow.js +109 -0
  47. tuneio-2.1.0.dist-info/METADATA +83 -0
  48. tuneio-2.1.0.dist-info/RECORD +52 -0
  49. tuneio-2.1.0.dist-info/WHEEL +5 -0
  50. tuneio-2.1.0.dist-info/entry_points.txt +2 -0
  51. tuneio-2.1.0.dist-info/licenses/LICENSE +21 -0
  52. tuneio-2.1.0.dist-info/top_level.txt +1 -0
tuneio/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ """Local API monitoring and explicit adaptive caching."""
2
+ from ._version import __version__
tuneio/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import entrypoint
2
+
3
+ entrypoint()
tuneio/_version.py ADDED
@@ -0,0 +1,2 @@
1
+ """Single source for candidate, CLI, application and telemetry versions."""
2
+ __version__ = '2.1.0'
tuneio/artifacts.py ADDED
@@ -0,0 +1,55 @@
1
+ """Bounded JSON artifacts, published only after all bytes are written."""
2
+ import json
3
+ import math
4
+ import os
5
+ from pathlib import Path
6
+ from tempfile import NamedTemporaryFile
7
+
8
+
9
+ def read_json(path, limit):
10
+ with Path(path).open('rb') as handle:
11
+ raw = handle.read(limit + 1)
12
+ if len(raw) > limit:
13
+ raise ValueError('Evidence exceeds size limit')
14
+
15
+ def unique(pairs):
16
+ result = dict(pairs)
17
+ if len(result) != len(pairs):
18
+ raise ValueError('Duplicate evidence field')
19
+ return result
20
+
21
+ def finite(value):
22
+ number = float(value)
23
+ if not math.isfinite(number):
24
+ raise ValueError('Non-finite evidence number')
25
+ return number
26
+
27
+ try:
28
+ data = json.loads(raw, object_pairs_hook=unique, parse_constant=finite, parse_float=finite)
29
+ except RecursionError:
30
+ raise ValueError('Evidence nesting exceeds parser limits') from None
31
+ if not isinstance(data, dict):
32
+ raise ValueError('Expected a JSON object')
33
+ return data, raw
34
+
35
+
36
+ def write_new(path, data, *, limit=32 * 1024 * 1024):
37
+ path = Path(path)
38
+ temp = None
39
+ try:
40
+ with NamedTemporaryFile(dir=path.parent, delete=False) as stream:
41
+ temp = Path(stream.name)
42
+ for part in json.JSONEncoder(indent=2, allow_nan=False).iterencode(data):
43
+ stream.write(part.encode('utf-8'))
44
+ if stream.tell() >= limit:
45
+ raise ValueError('Export exceeds size limit')
46
+ stream.write(b'\n')
47
+ stream.flush()
48
+ os.fsync(stream.fileno())
49
+ if os.name == 'nt':
50
+ os.rename(temp, path) # On Windows this refuses an existing destination.
51
+ else:
52
+ os.link(temp, path)
53
+ finally:
54
+ if temp is not None:
55
+ temp.unlink(missing_ok=True)
tuneio/baseline.py ADDED
@@ -0,0 +1,160 @@
1
+ """Capture passive evidence or run an explicitly approved read workload."""
2
+ from datetime import datetime, timezone
3
+ import hashlib
4
+ import json
5
+ from pathlib import Path
6
+ import re
7
+ import sys
8
+ from time import monotonic, sleep
9
+ import uuid
10
+
11
+ from ._version import __version__
12
+ from .core.metrics import percentile
13
+ from .scenarios import Scenario, path_check
14
+ from .storage import config_identity, source_digest
15
+
16
+
17
+ def plan(config, route, requests, delay_ms, timeout, environment, window, *, optimized=False, warmup=0):
18
+ if not 1 <= window <= 3600:
19
+ raise ValueError('Window must be 1-3600 seconds')
20
+ if not route:
21
+ return None
22
+ # Only simple concrete paths. Credentials, query strings, and request bodies are outside this workload.
23
+ if (len(route) > 1024 or not re.fullmatch(r'/(?:[A-Za-z0-9_.~-]+(?:/[A-Za-z0-9_.~-]+)*)?', route)
24
+ or set(route.split('/')) & {'.', '..'}):
25
+ raise ValueError('Use a concrete GET path without query, fragment or dot segments')
26
+ path_check(route)
27
+ parts = route.split('/')
28
+ candidates = [operation.path for operation in config.operations if operation.method == 'GET'
29
+ and len(operation.path.split('/')) == len(parts)
30
+ and all(a == b or a == '*' for a, b in zip(operation.path.split('/'), parts))]
31
+ if not candidates:
32
+ raise ValueError('Select a path matching a configured GET operation')
33
+ modes = ('adaptive', 'cache') if optimized else ('observe', 'off')
34
+ if config.mode not in modes or environment not in ('local', 'staging'):
35
+ raise ValueError('Use observe/off for baseline, cache/adaptive for optimized, and --environment local or staging')
36
+ if not (1 <= requests and 0 <= warmup and requests + warmup <= 20 and 100 <= delay_ms <= 1000 and 1 <= timeout <= 5
37
+ and (requests + warmup) * (timeout * 1000 + delay_ms) <= 90000):
38
+ raise ValueError('Workload exceeds limits: 1-20 requests, 100-1000 ms delay, 1-5 s timeout, 90 s total')
39
+ return dict(method='GET', operation=min(candidates, key=lambda value: value.count('*')), path=route,
40
+ requests=requests, delay_ms=delay_ms, timeout_seconds=timeout, concurrency=1,
41
+ environment=environment, expected_status=200)
42
+
43
+
44
+ def digest(value):
45
+ return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
46
+
47
+
48
+ def snapshots(query, session, identity, window):
49
+ metrics = query('GET', f'/_autotuner/metrics?window={window}')
50
+ insights = query('GET', f'/_autotuner/insights?window={window}')
51
+ status = query('GET', '/_autotuner/status')
52
+ if (any(item.get('session_id') != session for item in (metrics, insights, status))
53
+ or insights.get('config_digest') != identity or status.get('config_digest') != identity):
54
+ raise ValueError('Proxy session or configuration changed during capture')
55
+ return dict(metrics=metrics, insights=insights, resources={key: status.get(key) for key in
56
+ ('runtime', 'cache', 'storage', 'limits', 'uptime_seconds')})
57
+
58
+
59
+ def run_workload(query, workload, session, identifier):
60
+ step = dict(
61
+ name='Read', method='GET', path=workload['path'], repeat=workload['requests'],
62
+ timeout_seconds=workload['timeout_seconds'], expect_status=workload['expected_status'])
63
+ matched = 'app_state_digest' in workload
64
+ if matched:
65
+ step['fingerprint_response'] = True
66
+ warmup = workload.get('warmup', 0)
67
+ steps = [dict(step, name='Warmup', repeat=warmup), step] if warmup else [step]
68
+ scenario = Scenario.model_validate(dict(name='Read baseline', delay_ms=workload['delay_ms'], steps=steps))
69
+ prefix = '/_autotuner/scenarios/'
70
+ deadline = monotonic() + 100
71
+
72
+ def poll(report):
73
+ while report.get('state') == 'running' and monotonic() < deadline:
74
+ sleep(.25)
75
+ report = query('GET', prefix + 'jobs/' + identifier)
76
+ return report
77
+
78
+ def stop():
79
+ return query('POST', prefix + 'stop', {'run_id': identifier})
80
+
81
+ try:
82
+ report = poll(query('POST', prefix + 'run', dict(scenario=scenario.model_dump(exclude_unset=True),
83
+ allow_writes=False, run_id=identifier, expected_session_id=session)))
84
+ if report.get('state') == 'running':
85
+ report = stop()
86
+ except KeyboardInterrupt:
87
+ report = poll(stop())
88
+ if report.get('run_id') != identifier or report.get('state') not in (
89
+ 'completed', 'failed', 'stopped', 'interrupted', 'runtime_limit', 'running'):
90
+ raise ValueError('Unexpected workload report')
91
+ measured = report['results'][warmup:]
92
+ columns = ('status', 'duration_ms', 'passed', 'reason')
93
+ if matched:
94
+ columns += ('response_sha256', 'cache')
95
+ rows = [{key: row.get(key) for key in columns} for row in measured]
96
+ durations = [row['duration_ms'] for row in rows if row['duration_ms'] is not None]
97
+ elapsed = report['finished_at'] - report['started_at'] if report['finished_at'] is not None else None
98
+ if measured and matched and measured[0].get('start_offset') is not None and measured[-1].get('end_offset') is not None:
99
+ elapsed = measured[-1]['end_offset'] - measured[0]['start_offset']
100
+ return dict(state='stop_requested' if report['state'] == 'running' else report['state'], samples=rows,
101
+ completed=len(rows), errors=sum(not row['passed'] for row in rows),
102
+ mean_ms=sum(durations) / len(durations) if durations else None,
103
+ p50_ms=percentile(durations, .5), p95_ms=percentile(durations, .95), p99_ms=percentile(durations, .99),
104
+ elapsed_seconds=elapsed, requests_per_second=len(rows) / elapsed if elapsed and elapsed > 0 else None,
105
+ warmup_completed=min(warmup, len(report['results'])))
106
+
107
+
108
+ def capture(args, config, query):
109
+ identity, redacted = config_identity(config)
110
+ optimized = args.stage == 'optimized'
111
+ if (optimized or args.warmup or args.app_state is not None) and not args.get:
112
+ raise ValueError('Use an explicit --get path for a matched capture')
113
+ if (optimized or args.warmup) and not args.app_state:
114
+ raise ValueError('Give both captures an application revision and test-data identifier with --app-state')
115
+ workload = plan(config, args.get, args.requests, args.delay_ms, args.timeout, args.environment, args.window,
116
+ optimized=optimized, warmup=args.warmup)
117
+ if args.app_state is not None:
118
+ if not args.app_state.strip() or len(args.app_state) > 200:
119
+ raise ValueError('Use a nonempty application-state identifier up to 200 characters')
120
+ workload.update(app_state_digest=digest(args.app_state), warmup=args.warmup)
121
+ if args.apply is not None and workload is None:
122
+ raise ValueError('--apply requires an active GET workload')
123
+ if workload:
124
+ token = digest([identity, workload, args.stage, args.window, str(Path(args.output).resolve())])
125
+ if args.apply is None:
126
+ return dict(schema_version=1, written=False, proxy=config.listen, upstream=config.upstream,
127
+ workload=workload, stage=args.stage, review_token=token), 0
128
+ if args.apply != token:
129
+ raise ValueError('Baseline preview changed. Review it again before applying')
130
+ status = query('GET', '/_autotuner/status')
131
+ session = status.get('session_id')
132
+ if not status.get('running') or not session or status.get('config_digest') != identity:
133
+ raise ValueError('Start the proxy with the same selected configuration before capturing a baseline')
134
+ identifier = str(uuid.uuid4())
135
+ record = dict(schema_version=1, baseline_id=identifier, session_id=session, config_digest=identity,
136
+ config=redacted, tool_version=__version__, proxy_version=status.get('tool_version'),
137
+ client_source_sha256=source_digest(), proxy_source_sha256=status.get('source_sha256'), stage=args.stage,
138
+ comparison_context=digest(config.model_dump(exclude={'mode','cache'})),
139
+ captured_at=datetime.now(timezone.utc).isoformat(),
140
+ kind='active' if workload else 'passive', window_seconds=args.window, state='incomplete',
141
+ sampling_note='Proxy metrics and insights are separate rolling snapshots and may include other traffic. '
142
+ 'Workload timings measure only the explicit scenario at the proxy boundary.')
143
+ with Path(args.output).open('x', encoding='utf-8') as file:
144
+ if workload:
145
+ record['workload'] = {key: value for key, value in workload.items() if key != 'path'}
146
+ record['workload_digest'] = digest(workload)
147
+ file.write(json.dumps(record, indent=2) + '\n')
148
+ file.flush()
149
+ try:
150
+ if workload:
151
+ print(f'Baseline run {identifier}. Stop with Ctrl+C.', file=sys.stderr)
152
+ record['active_result'] = run_workload(query, workload, session, identifier)
153
+ record.update(snapshots(query, session, identity, args.window))
154
+ record['state'] = record.get('active_result', {}).get('state', 'completed')
155
+ finally:
156
+ file.seek(0)
157
+ file.write(json.dumps(record, indent=2) + '\n')
158
+ file.truncate()
159
+ return dict(schema_version=1, written=True, output=args.output, baseline_id=identifier,
160
+ state=record['state'], findings=len(record['insights']['findings'])), (0 if record['state'] == 'completed' else 3)