Spaces:
Running

Shoraky commited on
Commit
2ba563f
·
1 Parent(s): cb83a8a

Align interval metrics by frame

Browse files
app.py CHANGED
@@ -1039,23 +1039,20 @@ def results(session_id: UUID, request: Request):
1039
  "right_heel_height": ("Right Heel Height", "cm"),
1040
  }
1041
  full_interval_metrics = []
1042
- metric_frames = {}
1043
- for frame_text, frame_data in full_interval.items():
1044
- if not isinstance(frame_data, dict):
1045
- continue
1046
- try:
1047
- frame_number = int(frame_text) - start
1048
- except (TypeError, ValueError):
1049
- continue
1050
- if frame_number < 0 or frame_number >= max(0, end - start + 1):
1051
- continue
1052
- for key, (metric_name, unit) in telemetry_names.items():
1053
- value = frame_data.get(key)
1054
  if isinstance(value, (int, float)) and math.isfinite(value):
1055
- metric_frames.setdefault(key, []).append({"frame": frame_number, "value": value})
1056
- for key, values in metric_frames.items():
1057
- if values:
1058
- full_interval_metrics.append({"name": telemetry_names[key][0], "unit": telemetry_names[key][1], "values": values})
 
 
1059
  clips = [{"cameraId": camera_id,
1060
  "url": f"/storage/{session_id}/videos/{filename}",
1061
  "poster": f"/storage/{session_id}/posters/camera_{camera_id}.webp"}
 
1039
  "right_heel_height": ("Right Heel Height", "cm"),
1040
  }
1041
  full_interval_metrics = []
1042
+ for key, (metric_name, unit) in telemetry_names.items():
1043
+ values = []
1044
+ has_measurement = False
1045
+ for frame_number in range(max(0, end - start + 1)):
1046
+ absolute_frame = start + frame_number
1047
+ frame_data = full_interval.get(str(absolute_frame), {})
1048
+ value = frame_data.get(key) if isinstance(frame_data, dict) else None
 
 
 
 
 
1049
  if isinstance(value, (int, float)) and math.isfinite(value):
1050
+ has_measurement = True
1051
+ else:
1052
+ value = None
1053
+ values.append({"frame": frame_number, "value": value})
1054
+ if has_measurement:
1055
+ full_interval_metrics.append({"name": metric_name, "unit": unit, "values": values})
1056
  clips = [{"cameraId": camera_id,
1057
  "url": f"/storage/{session_id}/videos/{filename}",
1058
  "poster": f"/storage/{session_id}/posters/camera_{camera_id}.webp"}
tests/admin-review-author.test.ts DELETED
@@ -1,80 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { spawn } from "node:child_process";
3
- import { once } from "node:events";
4
- import { createServer } from "node:http";
5
- import type { AddressInfo } from "node:net";
6
- import { test } from "node:test";
7
-
8
- test("admin action edits attribute changed feedback to the editor", { timeout: 30_000 }, async () => {
9
- const adminId = "11111111-1111-4111-8111-111111111111";
10
- const ownerId = "22222222-2222-4222-8222-222222222222";
11
- const sessionId = "33333333-3333-4333-8333-333333333333";
12
- const actionId = "44444444-4444-4444-8444-444444444444";
13
- const user = { id: adminId, email: "admin@example.com", email_confirmed_at: new Date().toISOString(), user_metadata: {} };
14
- const savedReviews: Array<Record<string, unknown>> = [];
15
- let oldNotes = ["Original feedback"];
16
- const upstream = createServer(async (req, res) => {
17
- const url = new URL(req.url!, "http://stub");
18
- res.setHeader("Content-Type", "application/json");
19
- if (url.pathname === "/auth/v1/user") return res.end(JSON.stringify(user));
20
- if (url.pathname === "/rest/v1/users") return res.end(JSON.stringify({ user_id: adminId, account_role: "admin" }));
21
- if (url.pathname === "/rest/v1/sessions") return res.end(JSON.stringify({ status: "completed" }));
22
- if (url.pathname === "/rest/v1/annotations" && req.method === "GET") {
23
- return res.end(JSON.stringify({ user_id: ownerId, score: 5, annotations_notes: oldNotes.map((note) => ({ note })) }));
24
- }
25
- if (url.pathname === "/rest/v1/rpc/save_action_review") {
26
- const chunks: Buffer[] = [];
27
- for await (const chunk of req) chunks.push(Buffer.from(chunk));
28
- const body = JSON.parse(Buffer.concat(chunks).toString()) as Record<string, unknown>;
29
- savedReviews.push(body);
30
- oldNotes = body.p_notes as string[];
31
- return res.end("null");
32
- }
33
- if (url.pathname === `/api/sessions/${sessionId}/actions/${actionId}` && req.method === "PATCH") return res.end("{}");
34
- res.statusCode = 404;
35
- return res.end(JSON.stringify({ error: "Unexpected mock request", path: url.pathname }));
36
- });
37
- upstream.listen(0, "127.0.0.1");
38
- await once(upstream, "listening");
39
- const portProbe = createServer();
40
- portProbe.listen(0, "127.0.0.1");
41
- await once(portProbe, "listening");
42
- const port = (portProbe.address() as AddressInfo).port;
43
- await new Promise<void>((resolve) => portProbe.close(() => resolve()));
44
- const origin = `http://127.0.0.1:${port}`;
45
- const upstreamOrigin = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`;
46
- const child = spawn(process.execPath, ["--import", "tsx", "src/server.ts"], {
47
- env: { ...process.env, NODE_ENV: "test", PORT: String(port), FRONTEND_URL: origin, BACKEND_URL: origin,
48
- ANALYSIS_API_URL: upstreamOrigin, SUPABASE_URL: upstreamOrigin,
49
- SUPABASE_ANON_KEY: "test-anon", SUPABASE_SERVICE_ROLE_KEY: "test-service", ANALYSIS_PROXY_SECRET: "x".repeat(32) },
50
- stdio: ["ignore", "pipe", "pipe"],
51
- });
52
- try {
53
- await new Promise<void>((resolve, reject) => {
54
- child.stdout.on("data", (data) => { if (String(data).includes("API listening")) resolve(); });
55
- child.once("exit", (code) => reject(new Error(`API exited: ${code}`)));
56
- child.once("error", reject);
57
- });
58
- const save = (notes: string[]) => fetch(`${origin}/api/admin/sessions/${sessionId}/actions/${actionId}`, {
59
- method: "PATCH", signal: AbortSignal.timeout(10000),
60
- headers: { Cookie: "sp_access=access", Origin: origin, "Content-Type": "application/json" },
61
- body: JSON.stringify({ startFrame: 0, endFrame: 10, type: "Shoot", score: 5, notes }),
62
- });
63
- assert.equal((await save(["Original feedback"])).status, 200);
64
- assert.equal(savedReviews.length, 0, "an action-only edit must preserve the previous feedback author");
65
- assert.equal((await save(["Updated feedback"])).status, 200);
66
- assert.equal(savedReviews.length, 1);
67
- assert.equal(savedReviews[0].p_user_id, adminId);
68
- assert.deepEqual(savedReviews[0].p_notes, ["Updated feedback"]);
69
- assert.equal(savedReviews[0].p_session_id, sessionId);
70
- assert.equal(savedReviews[0].p_action_id, actionId);
71
- } finally {
72
- if (child.exitCode === null && child.signalCode === null) {
73
- const exited = once(child, "exit");
74
- child.kill();
75
- await exited;
76
- }
77
- upstream.closeAllConnections();
78
- await new Promise<void>((resolve) => upstream.close(() => resolve()));
79
- }
80
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/agent-chat.test.ts DELETED
@@ -1,283 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { spawn } from "node:child_process";
3
- import { once } from "node:events";
4
- import { createServer, type IncomingHttpHeaders } from "node:http";
5
- import type { AddressInfo } from "node:net";
6
- import { test } from "node:test";
7
-
8
- test("action chat sends measurements and annotated references on every message and preserves access checks", { timeout: 30_000 }, async () => {
9
- const owner = "11111111-1111-4111-8111-111111111111";
10
- const other = "22222222-2222-4222-8222-222222222222";
11
- const sessionId = "33333333-3333-4333-8333-333333333333";
12
- const actionId = "44444444-4444-4444-8444-444444444444";
13
- const otherActionId = "55555555-5555-4555-8555-555555555555";
14
- const referenceSessionId = "77777777-7777-4777-8777-777777777777";
15
- const foreignSessionId = "88888888-8888-4888-8888-888888888888";
16
- const analytics = { foot_region: "Toe", active_foot_speed: 1232.04, standing_foot_contact_seconds: 0,
17
- ball_speed: 1303.31, touch_frame: 766, minimum_knee_angle: null, future_metric: false };
18
- const measured = { id: actionId, label: "Pass", rawAnalytics: analytics,
19
- inActionMetrics: Object.entries(analytics).map(([name, value]) => ({ name, value, unit: name === "active_foot_speed" ? "cm/s" : "" })) };
20
- const otherMeasured = { id: otherActionId, label: "Shoot", rawAnalytics: { ball_speed: 1303.31, active_foot_speed: 1232.04 },
21
- inActionMetrics: [{ name: "Ball Speed", value: 1303.31, unit: "cm/s" }, { name: "Active Foot Speed", value: 1232.04, unit: "cm/s" }] };
22
- let role = "user";
23
- let sessionOwner = owner;
24
- let resultsAvailable = true;
25
- let analysisStatus = 200;
26
- let analysisReads = 0;
27
- let analysisHeaders: IncomingHttpHeaders = {};
28
- let savedFeedbackAvailable = false;
29
- let referencesAvailable = true;
30
- let annotationsFail = false;
31
- let referenceResultsAvailable = true;
32
- let referenceReads = 0;
33
- let mutations = 0;
34
- const referenceAnalytics = { active_foot: "left", ball_speed: 1303.31, active_foot_speed: 1232.04, standing_foot_contact_seconds: 0, touch_frame: 999999 };
35
- const offsets: Record<string, number> = { "00-blank": 0, "02-reference": 0, "00-foreign": 5, "03-reference": 300,
36
- "04-reference": 200, "05-reference": 100, "06-reference": 50, "07-reference": 20, "08-reference": 10, "zz-late": 1, "zz-wrong-report": 0 };
37
- const referenceUsers = new Set<string>();
38
- const reference = (id: string, type = "Pass", userId = owner, score: number | null = 7, notes = ["Reference coach note."]) => ({
39
- action_id: id, score, annotations_notes: notes.map((note) => ({ note })),
40
- actions: { action_id: id, session_id: userId === owner ? referenceSessionId : foreignSessionId, type,
41
- sessions: { user_id: userId, players: { gender: "female", bdate: "2000-01-01", height: 170, weight: 65, position: "Forward" } } },
42
- });
43
- const examples = [reference(actionId), reference("00-foreign", "Pass", other, null), reference("shoot-reference", "Shoot"),
44
- reference("00-blank", "Pass", owner, null, [" "]), reference("01-empty"), reference("01-missing"),
45
- reference("02-reference", "Pass", owner, 0, []), reference("03-reference", "Pass", owner, null),
46
- ...Array.from({ length: 5 }, (_, index) => reference(`${String(index + 4).padStart(2, "0")}-reference`)),
47
- ...Array.from({ length: 110 }, (_, index) => reference(`far-${String(index).padStart(3, "0")}`)),
48
- reference("zz-late", "Pass", other, 0), reference("zz-no-common"), reference("zz-wrong-report")];
49
- const referenceReport = (item: ReturnType<typeof reference>) => {
50
- const rawAnalytics: Record<string, unknown> = item.action_id === "01-empty" ? {} : item.action_id === "zz-no-common" ? { unrelated_metric: 42 }
51
- : { ...referenceAnalytics, active_foot_speed: referenceAnalytics.active_foot_speed + (offsets[item.action_id] ?? 500) };
52
- return { id: item.action_id, label: item.action_id === "zz-wrong-report" ? "Shoot" : item.actions.type, rawAnalytics,
53
- inActionMetrics: Object.entries(rawAnalytics).map(([name, value]) => ({ name, value, unit: "" })) };
54
- };
55
- type Reference = { session_id: string; action_id: string; action_type: string; player: { gender: string }; score: number | null; notes: string[];
56
- results: { metrics: unknown[]; analytics: unknown } };
57
- type ChatPayload = { actions: unknown[]; message: string; history: unknown[];
58
- context: { action?: { action_id: string; results: { metrics: unknown[]; analytics: unknown }; references: Reference[]; feedback: string[]; annotations: unknown }; actions?: unknown[] } };
59
- const chats: ChatPayload[] = [];
60
- const generations: { actions: { action_id: string; references: Reference[] }[] }[] = [];
61
- let generationOverride: unknown;
62
- const upstream = createServer(async (req, res) => {
63
- const url = new URL(req.url!, "http://stub");
64
- res.setHeader("Content-Type", "application/json");
65
- if (url.pathname === "/auth/v1/user") return res.end(JSON.stringify({ id: owner, email: "test@example.com" }));
66
- if (url.pathname === `/api/sessions/${sessionId}`) {
67
- analysisReads++;
68
- analysisHeaders = req.headers;
69
- res.statusCode = analysisStatus;
70
- return res.end(JSON.stringify({ id: sessionId, actions: resultsAvailable ? [otherMeasured, measured] : [] }));
71
- }
72
- if ([`/api/sessions/${referenceSessionId}`, `/api/sessions/${foreignSessionId}`].includes(url.pathname)) {
73
- referenceReads++;
74
- const id = url.pathname.split("/").at(-1);
75
- const expectedOwner = id === referenceSessionId ? owner : other;
76
- referenceUsers.add(String(req.headers["x-sporalize-user-id"]));
77
- if (req.headers["x-sporalize-user-id"] !== expectedOwner) {
78
- res.statusCode = 403;
79
- return res.end("{}");
80
- }
81
- res.statusCode = referenceResultsAvailable ? 200 : 503;
82
- return res.end(JSON.stringify({ id, actions: examples.filter((item) => item.action_id !== "01-missing" && item.actions.session_id === id).map(referenceReport) }));
83
- }
84
- if (url.pathname === "/api/chat") {
85
- let body = "";
86
- for await (const chunk of req) body += chunk;
87
- chats.push(JSON.parse(body));
88
- return res.end(JSON.stringify({ reply: "Measured coaching reply." }));
89
- }
90
- if (url.pathname === "/api/session/generate") {
91
- let body = "";
92
- for await (const chunk of req) body += chunk;
93
- const input = JSON.parse(body);
94
- generations.push(input);
95
- return res.end(JSON.stringify(generationOverride ?? { actions: input.actions.map((action: { action_id: string }) => ({ action_id: action.action_id, feedback: ["Generated feedback."] })), session_feedback: ["Session summary."] }));
96
- }
97
- const table = url.pathname.split("/").at(-1);
98
- if (req.method !== "GET") { mutations++; return res.end("[]"); }
99
- if (table === "annotations" && annotationsFail) {
100
- res.statusCode = 400;
101
- return res.end(JSON.stringify({ message: "Annotations unavailable." }));
102
- }
103
- let rows: Record<string, unknown>[] = table === "users" ? [{ user_id: owner, account_role: role }]
104
- : table === "users_subscriptions" ? [{ user_id: owner, subscription_id: "plan", startdate: "2000-01-01", enddate: "2099-01-01", plan: { subscription_id: "plan" } }]
105
- : table === "sessions" ? [{ session_id: sessionId, user_id: sessionOwner, name: "Practice", players: { fname: "Player", gender: "male", bdate: "2000-01-01" } }]
106
- : table === "actions" ? [actionId, otherActionId].map((id) => ({ action_id: id, session_id: sessionId, type: id === actionId ? "Pass" : "Shoot", start_frame: 750, end_frame: 780,
107
- annotations: [{ score: 7, annotations_notes: [{ note: "Coach note." }] }] }))
108
- : table === "annotations" ? referencesAvailable ? examples : []
109
- : table === "actions_feedbacks" ? savedFeedbackAvailable ? [{ action_id: actionId, feedback: "Saved action evaluation." }] : []
110
- : table === "sessions_feedbacks" ? [{ session_id: sessionId, feedback: "Saved session evaluation." }] : [];
111
- const value = (row: Record<string, unknown>, key: string): unknown => key.split(".").reduce<unknown>((item, part) => (item as Record<string, unknown> | undefined)?.[part], row);
112
- for (const [key, filter] of url.searchParams) {
113
- if (filter.startsWith("eq.")) rows = rows.filter((row) => String(value(row, key)) === filter.slice(3));
114
- if (filter.startsWith("neq.")) rows = rows.filter((row) => String(value(row, key)) !== filter.slice(4));
115
- }
116
- if (url.searchParams.get("order") === "action_id.asc") rows = [...rows].sort((a, b) => String(a.action_id).localeCompare(String(b.action_id)));
117
- const from = Number(url.searchParams.get("offset") ?? 0);
118
- const limit = Number(url.searchParams.get("limit") ?? rows.length);
119
- res.end(JSON.stringify(rows.slice(from, from + limit)));
120
- });
121
- upstream.listen(0, "127.0.0.1");
122
- await once(upstream, "listening");
123
- const upstreamOrigin = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`;
124
- const portProbe = createServer();
125
- portProbe.listen(0, "127.0.0.1");
126
- await once(portProbe, "listening");
127
- const port = (portProbe.address() as AddressInfo).port;
128
- await new Promise<void>((resolve) => portProbe.close(() => resolve()));
129
- const origin = `http://127.0.0.1:${port}`;
130
- const child = spawn(process.execPath, ["--import", "tsx", "src/server.ts"], {
131
- env: { ...process.env, NODE_ENV: "test", PORT: String(port), FRONTEND_URL: origin, BACKEND_URL: origin,
132
- SUPABASE_URL: upstreamOrigin, SUPABASE_ANON_KEY: "test-anon", SUPABASE_SERVICE_ROLE_KEY: "test-service",
133
- ANALYSIS_API_URL: upstreamOrigin, ANALYSIS_PROXY_SECRET: "x".repeat(32),
134
- AGENT_API_URL: upstreamOrigin, AGENT_API_KEY: "a".repeat(32), HF_TOKEN: "" },
135
- stdio: ["ignore", "pipe", "pipe"],
136
- });
137
- try {
138
- let stderr = "";
139
- child.stderr.on("data", (data) => { stderr += String(data); });
140
- await new Promise<void>((resolve, reject) => {
141
- child.stdout.on("data", (data) => { if (String(data).includes("API listening")) resolve(); });
142
- child.once("exit", (code) => reject(new Error(`API exited: ${code}\n${stderr}`)));
143
- child.once("error", reject);
144
- });
145
- const request = (input: Record<string, unknown>, authenticated = true) => fetch(`${origin}/api/agent/chat`, {
146
- method: "POST", signal: AbortSignal.timeout(10000),
147
- headers: { "Content-Type": "application/json", Origin: origin, ...(authenticated ? { Cookie: "sp_access=access" } : {}) },
148
- body: JSON.stringify({ message: "Explain these measurements.", ...input }),
149
- });
150
- const selected = { sessionId, actionId };
151
- assert.equal((await request(selected, false)).status, 401);
152
- assert.equal(analysisReads, 0);
153
- assert.equal((await request(selected)).status, 200);
154
- assert.equal(analysisReads, 1);
155
- assert.deepEqual(chats[0].context.action?.results, { metrics: measured.inActionMetrics, analytics });
156
- assert.deepEqual(chats[0].context.action?.feedback, []);
157
- const expectedReferences = ["zz-late", "00-foreign", "08-reference", "07-reference", "06-reference"];
158
- assert.deepEqual(chats[0].context.action?.references.map((item) => item.action_id), expectedReferences);
159
- assert.ok(chats[0].context.action?.references.every((item) => item.action_type === "Pass" && item.player.gender === "female"));
160
- const nearest = referenceReport(examples.find((item) => item.action_id === "zz-late")!);
161
- assert.deepEqual(chats[0].context.action?.references[0].results, { metrics: nearest.inActionMetrics, analytics: nearest.rawAnalytics });
162
- assert.equal(chats[0].context.action?.references[0].session_id, foreignSessionId, "comparisons include other accounts with their real session IDs");
163
- assert.equal(chats[0].context.action?.references[0].score, 0);
164
- assert.equal(chats[0].context.action?.references[1].score, null);
165
- assert.deepEqual(chats[0].context.action?.references[0].notes, ["Reference coach note."]);
166
- assert.equal(referenceReads, 2, "each session is fetched once across all candidate pages");
167
- assert.deepEqual(referenceUsers, new Set([owner, other]));
168
- assert.deepEqual(chats[0].context.action?.annotations, [{ score: 7, annotations_notes: [{ note: "Coach note." }] }]);
169
- assert.equal(analysisHeaders["x-sporalize-user-id"], owner);
170
- assert.equal(analysisHeaders["x-sporalize-proxy-secret"], "x".repeat(32));
171
- assert.equal(analysisHeaders["x-sporalize-admin"], undefined);
172
-
173
- analytics.ball_speed = 1500.123456;
174
- measured.inActionMetrics.find((metric) => metric.name === "ball_speed")!.value = analytics.ball_speed;
175
- savedFeedbackAvailable = true;
176
- referenceAnalytics.ball_speed = 1400.75;
177
- const history = [{ role: "user", content: "Explain these measurements." }, { role: "assistant", content: "Previous reply." }];
178
- assert.equal((await request({ ...selected, message: "What changed?", history })).status, 200);
179
- assert.equal(analysisReads, 2);
180
- assert.deepEqual(chats[1].context.action?.results, { metrics: measured.inActionMetrics, analytics });
181
- assert.deepEqual(chats[1].context.action?.feedback, ["Saved action evaluation."]);
182
- const updatedNearest = referenceReport(examples.find((item) => item.action_id === "zz-late")!);
183
- assert.deepEqual(chats[1].context.action?.references[0].results, { metrics: updatedNearest.inActionMetrics, analytics: updatedNearest.rawAnalytics });
184
- assert.equal(referenceReads, 4, "each message gets current reference measurements");
185
- assert.deepEqual(chats[1].history, history);
186
- assert.equal((await request({ sessionId, actionId: otherActionId })).status, 200);
187
- assert.deepEqual(chats[2].context.action?.results, { metrics: otherMeasured.inActionMetrics, analytics: otherMeasured.rawAnalytics });
188
- assert.deepEqual(chats[2].context.action?.references.map((item) => item.action_id), ["shoot-reference"]);
189
-
190
- const chatCount = chats.length;
191
- const readCount = analysisReads;
192
- sessionOwner = other;
193
- assert.equal((await request(selected)).status, 404);
194
- assert.equal(analysisReads, readCount, "unauthorized requests must not load measurements");
195
- assert.equal(chats.length, chatCount);
196
- role = "admin";
197
- assert.equal((await request(selected)).status, 200);
198
- assert.equal(analysisHeaders["x-sporalize-admin"], "true");
199
- assert.equal(analysisHeaders["x-sporalize-user-id"], owner);
200
- assert.deepEqual(chats.at(-1)?.context.action?.results, { metrics: measured.inActionMetrics, analytics });
201
- role = "user";
202
- sessionOwner = owner;
203
-
204
- referencesAvailable = false;
205
- assert.equal((await request(selected)).status, 200);
206
- assert.deepEqual(chats.at(-1)?.context.action?.references, []);
207
- referencesAvailable = true;
208
- referenceResultsAvailable = false;
209
- const readsBeforeMissing = referenceReads;
210
- assert.equal((await request(selected)).status, 200);
211
- assert.deepEqual(chats.at(-1)?.context.action?.references, []);
212
- assert.equal(referenceReads, readsBeforeMissing + 2, "unavailable reference results are not retried for each candidate page");
213
- referenceResultsAvailable = true;
214
- const chatsBeforeFailure = chats.length;
215
- annotationsFail = true;
216
- assert.equal((await request(selected)).status, 500);
217
- assert.equal(chats.length, chatsBeforeFailure, "a DB failure must not be presented as an empty search");
218
- annotationsFail = false;
219
-
220
- const successfulChats = chats.length;
221
- resultsAvailable = false;
222
- assert.equal((await request(selected)).status, 404);
223
- analysisStatus = 503;
224
- assert.equal((await request(selected)).status, 500);
225
- assert.equal(chats.length, successfulChats, "missing results must not produce an ungrounded reply");
226
- const failedReads = analysisReads;
227
- assert.equal((await request({ actionId })).status, 400);
228
- assert.equal((await request({ ...selected, actionId: "66666666-6666-4666-8666-666666666666" })).status, 404);
229
- assert.equal(analysisReads, failedReads);
230
- assert.equal((await request({ sessionId })).status, 200);
231
- assert.equal((await request({})).status, 200);
232
- assert.equal(analysisReads, failedReads, "general and session chats do not need action measurements");
233
- assert.equal(chats.at(-1)?.context.action, undefined);
234
- assert.equal(mutations, 0, "chat must not save or replace feedback");
235
-
236
- analysisStatus = 200;
237
- resultsAvailable = true;
238
- Object.assign(process.env, { FRONTEND_URL: origin, BACKEND_URL: origin, SUPABASE_URL: upstreamOrigin,
239
- SUPABASE_ANON_KEY: "test-anon", SUPABASE_SERVICE_ROLE_KEY: "test-service", ANALYSIS_API_URL: upstreamOrigin,
240
- ANALYSIS_PROXY_SECRET: "x".repeat(32), AGENT_API_URL: upstreamOrigin, AGENT_API_KEY: "a".repeat(32), HF_TOKEN: "" });
241
- const { createClient } = await import("@supabase/supabase-js");
242
- const { actionDistance, generateSessionFeedback } = await import("../src/agent-session.js");
243
- const sample = (rawAnalytics: Record<string, unknown>) => ({ id: "sample", label: "Pass", rawAnalytics });
244
- assert.equal(actionDistance(sample({ speed: 0, touch_frame: 1 }), sample({ speed: 0, touch_frame: 9999 })), 0);
245
- assert.equal(actionDistance(sample({ missing: null, flag: false, region: "Toe" }), sample({ speed: 0 })), null);
246
- assert.equal(actionDistance(sample({ speed: 10 }), sample({ speed: "10" })), null);
247
- assert.equal(actionDistance(sample({ speed: 10 }), sample({ unrelated: 10 })), null);
248
- assert.ok(actionDistance(sample({ speed: 1000, angle: 100 }), sample({ speed: 1010, angle: 101 }))!
249
- < actionDistance(sample({ speed: 1000, angle: 100 }), sample({ speed: 1000 }))!, "missing values must not outrank complete close measurements");
250
- assert.equal(actionDistance(sample({ ball_speed: 10, touch_frame: 1 }), sample({ ball_speed: 9999, touch_frame: 9999 })), null);
251
- assert.equal(actionDistance(sample({ active_foot_speed: 10, ball_speed: 10, touch_frame: 1 }), { id: "metric", label: "Pass",
252
- inActionMetrics: [{ name: "Active Foot Speed", value: 10 }, { name: "Ball Speed", value: 9999 }, { name: "Touch Frame", value: 9999 }] }), 0);
253
- const db = createClient(upstreamOrigin, "test-service", { auth: { persistSession: false } });
254
- const readsBeforeGeneration = referenceReads;
255
- await generateSessionFeedback(db, sessionId, owner);
256
- assert.equal(referenceReads - readsBeforeGeneration, 2, "all actions in a generation share reference session downloads");
257
- assert.deepEqual(generations[0].actions.find((item) => item.action_id === actionId)?.references.map((item) => item.action_id), expectedReferences);
258
- assert.deepEqual(generations[0].actions.find((item) => item.action_id === otherActionId)?.references.map((item) => item.action_id), ["shoot-reference"]);
259
- assert.equal(mutations, 6, "automatic generation still persists feedback for both actions and the session");
260
- await generateSessionFeedback(db, sessionId, owner);
261
- assert.equal(referenceReads - readsBeforeGeneration, 4, "a new generation fetches fresh reference measurements");
262
- const mutationsBeforeInvalid = mutations;
263
- for (const invalid of [
264
- { actions: [{ action_id: "foreign-action", feedback: ["Bad."] }, { action_id: otherActionId, feedback: ["Good."] }], session_feedback: ["Summary."] },
265
- { actions: [{ action_id: actionId, feedback: ["Bad."] }, { action_id: actionId, feedback: ["Duplicate."] }], session_feedback: ["Summary."] },
266
- { actions: [{ action_id: actionId, feedback: ["Bad."] }], session_feedback: ["Summary."] },
267
- { actions: [{ action_id: actionId, feedback: ["Bad."] }, { action_id: otherActionId, feedback: [" "] }], session_feedback: ["Summary."] },
268
- ]) {
269
- generationOverride = invalid;
270
- await assert.rejects(generateSessionFeedback(db, sessionId, owner), /Agent generation failed/);
271
- assert.equal(mutations, mutationsBeforeInvalid, "invalid agent output cannot change stored feedback");
272
- }
273
- generationOverride = undefined;
274
- } finally {
275
- if (child.exitCode === null && child.signalCode === null) {
276
- const exited = once(child, "exit");
277
- child.kill();
278
- await exited;
279
- }
280
- upstream.closeAllConnections();
281
- await new Promise<void>((resolve) => upstream.close(() => resolve()));
282
- }
283
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/analysis-admin.test.ts DELETED
@@ -1,70 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { createServer } from "node:http";
3
- import type { AddressInfo } from "node:net";
4
- import { test } from "node:test";
5
- import express from "express";
6
- import type { SupabaseClient } from "@supabase/supabase-js";
7
-
8
- test("an administrator can start analysis for another user's player", async () => {
9
- Object.assign(process.env, {
10
- NODE_ENV: "test",
11
- FRONTEND_URL: "http://127.0.0.1:3000",
12
- BACKEND_URL: "http://127.0.0.1:4000",
13
- ANALYSIS_PROXY_SECRET: "test-analysis-proxy-secret-32-chars",
14
- SUPABASE_URL: "http://127.0.0.1:54321",
15
- SUPABASE_ANON_KEY: "test-anon-key",
16
- SUPABASE_SERVICE_ROLE_KEY: "test-service-role-key",
17
- });
18
- const { analysisRouter } = await import("../src/analysis.js");
19
- const adminId = "11111111-1111-4111-8111-111111111111";
20
- const ownerId = "22222222-2222-4222-8222-222222222222";
21
- const playerId = "33333333-3333-4333-8333-333333333333";
22
- const clientId = "44444444-4444-4444-8444-444444444444";
23
- const filters: [string, string][] = [];
24
- const rpcCalls: { name: string; args: Record<string, unknown> }[] = [];
25
- const db = {
26
- from(table: string) {
27
- assert.equal(table, "players");
28
- const query = {
29
- select() { return query; },
30
- eq(column: string, value: string) { filters.push([column, value]); return query; },
31
- async maybeSingle() { return { data: { player_id: playerId, user_id: ownerId }, error: null }; },
32
- };
33
- return query;
34
- },
35
- async rpc(name: string, args: Record<string, unknown>) {
36
- rpcCalls.push({ name, args });
37
- return { error: null };
38
- },
39
- } as unknown as SupabaseClient;
40
- const secret = "test-analysis-proxy-secret-32-chars";
41
- const app = express();
42
- app.use("/internal/analysis", analysisRouter(db, secret));
43
- const server = createServer(app);
44
- await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
45
- try {
46
- const port = (server.address() as AddressInfo).port;
47
- const response = await fetch(`http://127.0.0.1:${port}/internal/analysis`, {
48
- method: "POST",
49
- headers: {
50
- "content-type": "application/json",
51
- "x-sporalize-proxy-secret": secret,
52
- "x-sporalize-user-id": adminId,
53
- "x-sporalize-admin": "true",
54
- },
55
- body: JSON.stringify({ clientId, playerId, name: "Admin analysis" }),
56
- });
57
- assert.equal(response.status, 200);
58
- assert.deepEqual(await response.json(), {
59
- session_id: clientId, player_id: playerId, user_id: ownerId,
60
- by_admin: true, actor_is_admin: true,
61
- });
62
- assert.deepEqual(filters, [["player_id", playerId]]);
63
- assert.deepEqual(rpcCalls, [{ name: "admin_create_analysis_session", args: {
64
- p_session_id: clientId, p_user_id: ownerId, p_player_id: playerId,
65
- p_name: "Admin analysis", p_path: `sessions/${clientId}`, p_by_admin: true,
66
- } }]);
67
- } finally {
68
- await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
69
- }
70
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/read-batches.test.ts DELETED
@@ -1,22 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { test } from "node:test";
3
- import { readBatches } from "../src/read-batches.js";
4
-
5
- test("caps concurrent reads, keeps result order and includes the final partial batch", async () => {
6
- let active = 0;
7
- let peak = 0;
8
- const input = Array.from({ length: 23 }, (_, index) => index);
9
- const output = await readBatches(input, async (batch) => {
10
- peak = Math.max(peak, ++active);
11
- await new Promise((resolve) => setTimeout(resolve, batch[0] % 2 ? 1 : 5));
12
- active--;
13
- return batch;
14
- }, 5, 3);
15
- assert.equal(peak, 3);
16
- assert.deepEqual(output, input);
17
- });
18
-
19
- test("does not query empty input or return incomplete results after failure", async () => {
20
- assert.deepEqual(await readBatches([], () => { throw new Error("should not run"); }), []);
21
- await assert.rejects(readBatches([1, 2], async () => { throw new Error("DB unavailable"); }), /DB unavailable/);
22
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/read-pages.test.ts DELETED
@@ -1,23 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { test } from "node:test";
3
- import { readPages } from "../src/read-pages.js";
4
-
5
- test("reads beyond the upstream row cap with inclusive, ordered ranges", async () => {
6
- const input = Array.from({ length: 1203 }, (_, index) => index);
7
- const ranges: number[][] = [];
8
- const rows = await readPages(async (from, to) => {
9
- ranges.push([from, to]);
10
- return input.slice(from, to + 1);
11
- });
12
- assert.deepEqual(rows, input);
13
- assert.deepEqual(ranges, [[0, 499], [500, 999], [1000, 1499]]);
14
- });
15
-
16
- test("handles empty and exact page boundaries, and propagates failure", async () => {
17
- assert.deepEqual(await readPages(async () => []), []);
18
- let calls = 0;
19
- assert.deepEqual(await readPages(async (from) => { calls++; return from ? [] : [1, 2]; }, 2), [1, 2]);
20
- assert.equal(calls, 2);
21
- await assert.rejects(readPages(async () => { throw new Error("offline"); }), /offline/);
22
- await assert.rejects(readPages(async () => [], 0), /Invalid page size/);
23
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/single-flight.test.ts DELETED
@@ -1,22 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { test } from "node:test";
3
- import { singleFlight } from "../src/single-flight.js";
4
-
5
- test("shares concurrent validation, isolates tokens, and revalidates after completion", async () => {
6
- let calls = 0;
7
- const run = singleFlight(async (token: string) => { calls++; return token; });
8
- const first = run("one");
9
- assert.equal(first, run("one"));
10
- assert.notEqual(first, run("two"));
11
- assert.equal(await first, "one");
12
- assert.equal(calls, 2);
13
- await run("one");
14
- assert.equal(calls, 3);
15
- });
16
-
17
- test("does not retain failed validation", async () => {
18
- let calls = 0;
19
- const run = singleFlight(async () => { if (++calls === 1) throw new Error("network"); return "verified"; });
20
- await assert.rejects(run("token"), /network/);
21
- assert.equal(await run("token"), "verified");
22
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_admin_analysis.py DELETED
@@ -1,51 +0,0 @@
1
- import asyncio
2
- from io import BytesIO
3
- import unittest
4
- from unittest.mock import patch
5
- from uuid import UUID
6
-
7
- from fastapi import UploadFile
8
- from starlette.requests import Request
9
-
10
- import app as analysis_app
11
-
12
-
13
- class StopBeforeUpload(Exception):
14
- pass
15
-
16
-
17
- class AdminAnalysisTest(unittest.TestCase):
18
- def test_begin_analysis_forwards_admin_identity_to_internal_backend(self):
19
- user_id = "11111111-1111-4111-8111-111111111111"
20
- client_id = UUID("22222222-2222-4222-8222-222222222222")
21
- player_id = "33333333-3333-4333-8333-333333333333"
22
- for is_admin in (False, True):
23
- with self.subTest(is_admin=is_admin):
24
- request = Request({"type": "http", "method": "POST", "path": "/api/analyze", "headers": []})
25
- request.state.user_id = user_id
26
- request.state.is_admin = is_admin
27
- actions = UploadFile(BytesIO(b"{}"), filename="actions.json")
28
- calibration = UploadFile(BytesIO(b"data"), filename="calibration.npz")
29
- with patch.object(analysis_app, "backend", side_effect=StopBeforeUpload) as backend:
30
- with self.assertRaises(StopBeforeUpload):
31
- asyncio.run(analysis_app.analyze(
32
- request, playerId=player_id, clientId=client_id,
33
- videoOrders=[1, 2], videos=[], videoDriveLinks=["first", "second"],
34
- actionsJson=actions, calibration=calibration, sessionName="Admin session",
35
- ))
36
- backend.assert_called_once_with("", user_id, "POST", {
37
- "clientId": str(client_id), "playerId": player_id, "name": "Admin session",
38
- }, is_admin=is_admin)
39
-
40
- def test_admin_session_lookup_forwards_admin_identity(self):
41
- session_id = "44444444-4444-4444-8444-444444444444"
42
- admin_id = "11111111-1111-4111-8111-111111111111"
43
- other_owner = "22222222-2222-4222-8222-222222222222"
44
- with patch.object(analysis_app, "backend", return_value={"user_id": other_owner}) as backend:
45
- self.assertEqual(analysis_app.owned_session_row(session_id, admin_id, is_admin=True),
46
- {"user_id": other_owner})
47
- backend.assert_called_once_with(f"/{session_id}", admin_id, is_admin=True)
48
-
49
-
50
- if __name__ == "__main__":
51
- unittest.main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_start.py DELETED
@@ -1,54 +0,0 @@
1
- import unittest
2
- from unittest.mock import MagicMock, Mock, patch
3
-
4
- import start
5
-
6
-
7
- class StartupTest(unittest.TestCase):
8
- def test_waits_for_analysis_health_before_accepting_requests(self):
9
- process = Mock()
10
- process.poll.return_value = None
11
- response = MagicMock()
12
- response.__enter__.return_value.status = 200
13
- response.__enter__.return_value.read.return_value = b'{"ok": true}'
14
- with patch.object(start, "urlopen", side_effect=[OSError("not listening"), response]) as probe, \
15
- patch.object(start.time, "sleep") as sleep:
16
- self.assertTrue(start.wait_for_analysis(process, lambda: False))
17
- self.assertEqual(probe.call_count, 2)
18
- sleep.assert_called_once_with(0.5)
19
-
20
- def test_exits_without_starting_node_if_analysis_fails(self):
21
- analysis = Mock()
22
- analysis.poll.return_value = 3
23
- analysis.returncode = 3
24
- with patch.object(start.subprocess, "Popen", return_value=analysis) as spawn, \
25
- patch.object(start, "load_dotenv"), patch.object(start.signal, "signal"):
26
- self.assertEqual(start.main(), 1)
27
- spawn.assert_called_once()
28
-
29
- def test_times_out_if_analysis_never_becomes_ready(self):
30
- analysis = Mock()
31
- analysis.poll.return_value = None
32
- with patch.object(start, "urlopen", side_effect=OSError("not listening")), \
33
- patch.object(start.time, "monotonic", side_effect=[0, 2]), \
34
- patch.object(start.time, "sleep") as sleep:
35
- self.assertFalse(start.wait_for_analysis(analysis, lambda: False, timeout_seconds=1))
36
- sleep.assert_not_called()
37
-
38
- def test_starts_node_after_analysis_is_ready(self):
39
- analysis = Mock()
40
- analysis.poll.return_value = None
41
- node = Mock()
42
- node.poll.return_value = 2
43
- node.returncode = 2
44
- with patch.object(start.subprocess, "Popen", side_effect=[analysis, node]) as spawn, \
45
- patch.object(start, "load_dotenv"), patch.object(start.signal, "signal"), \
46
- patch.object(start, "wait_for_analysis", side_effect=lambda *_: spawn.call_count == 1) as readiness:
47
- self.assertEqual(start.main(), 2)
48
- self.assertEqual(spawn.call_count, 2)
49
- self.assertEqual(spawn.call_args_list[1].args[0], ["node", "dist/server.js"])
50
- readiness.assert_called_once()
51
-
52
-
53
- if __name__ == "__main__":
54
- unittest.main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_storage_listing.py DELETED
@@ -1,42 +0,0 @@
1
- import unittest
2
- import httpx
3
- from unittest.mock import Mock
4
- from huggingface_hub import RepoFile, RepoFolder
5
- from huggingface_hub.errors import RemoteEntryNotFoundError
6
- from storage_listing import session_files, session_folder_exists
7
-
8
-
9
- class StorageListingTest(unittest.TestCase):
10
- def test_lists_only_requested_folder_and_excludes_directories(self):
11
- api = Mock()
12
- api.list_repo_tree.return_value = [
13
- RepoFile(path="sessions/one/videos/camera_1.mp4", size=1, oid="a"),
14
- RepoFolder(path="sessions/one/videos/subdir", oid="b"),
15
- ]
16
- self.assertEqual(session_files(api, "repo", "sessions/one/videos"),
17
- ["sessions/one/videos/camera_1.mp4"])
18
- api.list_repo_tree.assert_called_once_with(
19
- repo_id="repo", repo_type="dataset", path_in_repo="sessions/one/videos",
20
- recursive=False, expand=False)
21
- api.list_repo_files.assert_not_called()
22
-
23
- def test_missing_folder_is_empty_but_other_errors_propagate(self):
24
- api = Mock()
25
- api.list_repo_tree.side_effect = RemoteEntryNotFoundError(
26
- "missing", response=httpx.Response(404, request=httpx.Request("GET", "https://example.com/tree")))
27
- self.assertEqual(session_files(api, "repo", "folder"), [])
28
- api.list_repo_tree.side_effect = RuntimeError("unavailable")
29
- with self.assertRaises(RuntimeError):
30
- session_files(api, "repo", "folder")
31
-
32
- def test_deletion_checks_only_the_session_path(self):
33
- api = Mock()
34
- api.get_paths_info.return_value = []
35
- self.assertFalse(session_folder_exists(api, "repo", "sessions/one"))
36
- api.get_paths_info.assert_called_once_with(
37
- repo_id="repo", repo_type="dataset", paths=["sessions/one"])
38
- api.list_repo_files.assert_not_called()
39
-
40
-
41
- if __name__ == "__main__":
42
- unittest.main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_video_stream.py DELETED
@@ -1,120 +0,0 @@
1
- import unittest
2
- from unittest.mock import AsyncMock, patch
3
- from uuid import UUID
4
-
5
- import httpx
6
- from fastapi import HTTPException
7
- from starlette.requests import Request
8
-
9
- import video_stream
10
-
11
-
12
- class ProbeStream(httpx.AsyncByteStream):
13
- def __init__(self):
14
- self.reads = 0
15
- self.closed = False
16
-
17
- async def __aiter__(self):
18
- for chunk in (b"first", b"second"):
19
- self.reads += 1
20
- yield chunk
21
-
22
- async def aclose(self):
23
- self.closed = True
24
-
25
-
26
- def request(method="GET", headers=None):
27
- return Request({"type": "http", "method": method, "path": "/storage/test/videos/camera_1.mp4",
28
- "headers": [(key.encode(), value.encode()) for key, value in (headers or {}).items()]})
29
-
30
-
31
- class VideoStreamingTest(unittest.IsolatedAsyncioTestCase):
32
- async def test_streams_ranges_lazily_and_closes_after_client_cancels(self):
33
- body = ProbeStream()
34
- seen = []
35
-
36
- def handler(req):
37
- seen.append(req)
38
- return httpx.Response(206, headers={"Content-Range": "bytes 0-10/1000000", "Content-Length": "11",
39
- "Accept-Ranges": "bytes", "Content-Type": "video/mp4"}, stream=body)
40
-
41
- client = httpx.AsyncClient(transport=httpx.MockTransport(handler))
42
- with patch.object(video_stream.httpx, "AsyncClient", return_value=client):
43
- response = await video_stream.video_response(request(headers={"range": "bytes=0-10", "cookie": "private-cookie"}),
44
- "test/storage", "sessions/id/videos/camera_1.mp4", "storage-token")
45
- self.assertEqual(body.reads, 0)
46
- self.assertEqual(response.status_code, 206)
47
- self.assertEqual(response.headers["content-range"], "bytes 0-10/1000000")
48
- self.assertEqual(seen[0].headers["range"], "bytes=0-10")
49
- self.assertNotIn("cookie", seen[0].headers)
50
- self.assertEqual(await anext(response.body_iterator), b"first")
51
- await response.body_iterator.aclose()
52
- await response.background()
53
- self.assertEqual(body.reads, 1)
54
- self.assertTrue(body.closed)
55
- self.assertTrue(client.is_closed)
56
-
57
- async def test_cdn_redirect_strips_authorization_and_keeps_range(self):
58
- seen = []
59
-
60
- def handler(req):
61
- seen.append(req)
62
- if req.url.host == "huggingface.co":
63
- return httpx.Response(302, headers={"Location": "https://cdn.example/video?signature=test"})
64
- return httpx.Response(206, headers={"Content-Range": "bytes 0-1/10"}, stream=ProbeStream())
65
-
66
- client = httpx.AsyncClient(transport=httpx.MockTransport(handler), follow_redirects=True)
67
- with patch.object(video_stream.httpx, "AsyncClient", return_value=client):
68
- response = await video_stream.video_response(request(headers={"range": "bytes=0-1"}),
69
- "test/storage", "video.mp4", "storage-token")
70
- self.assertEqual(seen[0].headers["authorization"], "Bearer storage-token")
71
- self.assertNotIn("authorization", seen[1].headers)
72
- self.assertEqual(seen[1].headers["range"], "bytes=0-1")
73
- await response.background()
74
-
75
- async def test_head_preserves_size_without_reading_video(self):
76
- body = ProbeStream()
77
- client = httpx.AsyncClient(transport=httpx.MockTransport(lambda req: httpx.Response(
78
- 200, headers={"Content-Length": "1000000", "Accept-Ranges": "bytes"}, stream=body)))
79
- with patch.object(video_stream.httpx, "AsyncClient", return_value=client):
80
- response = await video_stream.video_response(request("HEAD"), "test/storage", "video.mp4", "token")
81
- self.assertEqual(response.headers["content-length"], "1000000")
82
- self.assertEqual(response.body, b"")
83
- self.assertEqual(body.reads, 0)
84
- self.assertTrue(client.is_closed)
85
-
86
- async def test_invalid_range_keeps_total_size_and_omits_storage_error_body(self):
87
- client = httpx.AsyncClient(transport=httpx.MockTransport(lambda req: httpx.Response(
88
- 416, headers={"Content-Range": "bytes */100", "Content-Length": "100"}, stream=ProbeStream())))
89
- with patch.object(video_stream.httpx, "AsyncClient", return_value=client):
90
- response = await video_stream.video_response(request(headers={"range": "bytes=999-"}), "test/storage", "video.mp4", "token")
91
- self.assertEqual(response.status_code, 416)
92
- self.assertEqual(response.headers["content-range"], "bytes */100")
93
- self.assertEqual(response.headers["content-length"], "0")
94
- self.assertTrue(client.is_closed)
95
-
96
- async def test_upstream_errors_close_connections_and_hide_storage_details(self):
97
- for status, expected in ((404, 404), (401, 502), (503, 502)):
98
- with self.subTest(status=status):
99
- client = httpx.AsyncClient(transport=httpx.MockTransport(lambda req: httpx.Response(status, stream=ProbeStream())))
100
- with patch.object(video_stream.httpx, "AsyncClient", return_value=client):
101
- with self.assertRaises(HTTPException) as error:
102
- await video_stream.video_response(request(), "test/storage", "video.mp4", "private-token")
103
- self.assertEqual(error.exception.status_code, expected)
104
- self.assertNotIn("private-token", error.exception.detail)
105
- self.assertTrue(client.is_closed)
106
-
107
- async def test_video_route_checks_ownership_before_streaming(self):
108
- import app as analysis_app
109
- req = request()
110
- req.state.user_id = "11111111-1111-4111-8111-111111111111"
111
- req.state.is_admin = False
112
- with patch.object(analysis_app, "session_row", side_effect=HTTPException(404, "Session not found")), \
113
- patch.object(analysis_app, "video_response", new_callable=AsyncMock) as stream:
114
- with self.assertRaises(HTTPException):
115
- await analysis_app.video(UUID("22222222-2222-4222-8222-222222222222"), "camera_1.mp4", req)
116
- stream.assert_not_called()
117
-
118
-
119
- if __name__ == "__main__":
120
- unittest.main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/video-session.test.ts DELETED
@@ -1,58 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { createServer } from "node:http";
3
- import type { AddressInfo } from "node:net";
4
- import { test } from "node:test";
5
- import express from "express";
6
- import type { SupabaseClient } from "@supabase/supabase-js";
7
-
8
- test("media lookups skip timing data while retaining session ownership checks", async () => {
9
- Object.assign(process.env, {
10
- NODE_ENV: "test", FRONTEND_URL: "http://127.0.0.1:3000", BACKEND_URL: "http://127.0.0.1:4000",
11
- ANALYSIS_PROXY_SECRET: "test-analysis-proxy-secret-32-chars", SUPABASE_URL: "http://127.0.0.1:54321",
12
- SUPABASE_ANON_KEY: "test-anon-key", SUPABASE_SERVICE_ROLE_KEY: "test-service-role-key",
13
- });
14
- const { analysisRouter } = await import("../src/analysis.js");
15
- const sessionId = "11111111-1111-4111-8111-111111111111";
16
- const userId = "22222222-2222-4222-8222-222222222222";
17
- const times = [{ action_id: sessionId, start_time_seconds: 1, end_time_seconds: 2 }];
18
- const filters: [string, string][] = [];
19
- const tables: string[] = [];
20
- let owned = true;
21
- const db = {
22
- from(table: string) {
23
- tables.push(table);
24
- const query = {
25
- select() { return query; },
26
- eq(column: string, value: string) { filters.push([column, value]); return query; },
27
- async maybeSingle() { return { data: owned ? { session_id: sessionId, user_id: userId } : null, error: null }; },
28
- then(resolve: (value: unknown) => void) { return Promise.resolve({ data: times, error: null }).then(resolve); },
29
- };
30
- return query;
31
- },
32
- } as unknown as SupabaseClient;
33
- const app = express();
34
- const secret = process.env.ANALYSIS_PROXY_SECRET!;
35
- app.use("/internal/analysis", analysisRouter(db, secret));
36
- const server = createServer(app);
37
- await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
38
- const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/internal/analysis/${sessionId}`;
39
- const headers = { "x-sporalize-proxy-secret": secret, "x-sporalize-user-id": userId };
40
- try {
41
- const media = await fetch(`${url}?playbackTimes=false`, { headers });
42
- assert.equal(media.status, 200);
43
- assert.deepEqual(tables, ["sessions"]);
44
- assert.ok(filters.some(([column, value]) => column === "user_id" && value === userId));
45
- tables.length = 0;
46
- const results = await fetch(url, { headers });
47
- assert.equal(results.status, 200);
48
- assert.deepEqual((await results.json()).action_times, times);
49
- assert.deepEqual(tables, ["sessions", "actions"]);
50
- owned = false;
51
- tables.length = 0;
52
- const denied = await fetch(`${url}?playbackTimes=false`, { headers });
53
- assert.equal(denied.status, 404);
54
- assert.deepEqual(tables, ["sessions"]);
55
- } finally {
56
- await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
57
- }
58
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/workspace-performance.test.ts DELETED
@@ -1,143 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { spawn } from "node:child_process";
3
- import { once } from "node:events";
4
- import { createServer } from "node:http";
5
- import type { AddressInfo } from "node:net";
6
- import { test } from "node:test";
7
-
8
- test("optimized workspace reads preserve authorization, scores and fresh permission checks", { timeout: 30_000 }, async () => {
9
- const owner = "11111111-1111-4111-8111-111111111111";
10
- const other = "22222222-2222-4222-8222-222222222222";
11
- const playerId = "33333333-3333-4333-8333-333333333333";
12
- const otherPlayerId = "44444444-4444-4444-8444-444444444444";
13
- const calls: { method: string; url: URL }[] = [];
14
- let role = "user";
15
- let revoked = false;
16
- let authUnavailable = false;
17
- let failActions = false;
18
- const user = { id: owner, email: "test@example.com", email_confirmed_at: new Date().toISOString(), user_metadata: {} };
19
- const plan = { subscription_id: "plan", plan: "Pro", price: 10, player_limit: 5, session_limit: 10 };
20
- const player = { player_id: playerId, user_id: owner, fname: "Own", lname: "Player", bdate: "2000-01-01", gender: "male", image_path: null };
21
- const sessions = [
22
- { session_id: "s1", player_id: playerId, user_id: owner, created_at: "2026-01-02T00:00:00Z", status: "completed", name: "Own session", player },
23
- { session_id: "s2", player_id: otherPlayerId, user_id: other, created_at: "2026-01-01T00:00:00Z", status: "completed", name: "Other session", player: { fname: "Other" } },
24
- ];
25
- const actions = [
26
- { action_id: "a1", session_id: "s1", type: "Pass", annotation: { score: 7 } },
27
- { action_id: "a2", session_id: "s1", type: "Pass", annotation: null },
28
- { action_id: "a3", session_id: "s2", type: "Pass", annotation: { score: 10 } },
29
- ];
30
- const upstream = createServer((req, res) => {
31
- const url = new URL(req.url!, "http://stub");
32
- calls.push({ method: req.method!, url });
33
- res.setHeader("Content-Type", "application/json");
34
- if (url.pathname === "/auth/v1/user") {
35
- if (authUnavailable) { res.statusCode = 503; return res.end(JSON.stringify({ message: "Temporarily unavailable" })); }
36
- res.statusCode = revoked ? 401 : 200;
37
- return res.end(JSON.stringify(revoked ? { message: "Revoked" } : user));
38
- }
39
- if (url.pathname === "/auth/v1/token") {
40
- return res.end(JSON.stringify({ user, access_token: "access", refresh_token: "refresh", expires_in: 3600, token_type: "bearer" }));
41
- }
42
- const table = url.pathname.split("/").at(-1);
43
- if (table === "actions" && failActions) {
44
- res.statusCode = 400;
45
- return res.end(JSON.stringify({ message: "Unavailable" }));
46
- }
47
- let rows: Record<string, unknown>[] = table === "users" ? [{ user_id: owner, email: user.email, account_role: role }]
48
- : table === "users_subscriptions" ? [{ user_id: owner, subscription_id: "plan", startdate: "2000-01-01", enddate: "2099-01-01", num_players: 1, num_sessions: 1, plan }]
49
- : table === "players" ? [player, { player_id: otherPlayerId, user_id: other, fname: "Other" }]
50
- : table === "sessions" ? sessions : table === "actions" ? actions : [];
51
- for (const [key, filter] of url.searchParams) {
52
- if (filter.startsWith("eq.")) rows = rows.filter((row) => String(row[key]) === filter.slice(3));
53
- if (filter.startsWith("in.(")) {
54
- const values = filter.slice(4, -1).split(",");
55
- rows = rows.filter((row) => values.includes(String(row[key])));
56
- }
57
- }
58
- const from = Number(url.searchParams.get("offset") ?? 0);
59
- const limit = Number(url.searchParams.get("limit") ?? rows.length);
60
- res.end(JSON.stringify(rows.slice(from, from + limit)));
61
- });
62
- upstream.listen(0, "127.0.0.1");
63
- await once(upstream, "listening");
64
- const portProbe = createServer();
65
- portProbe.listen(0, "127.0.0.1");
66
- await once(portProbe, "listening");
67
- const port = (portProbe.address() as AddressInfo).port;
68
- await new Promise<void>((resolve) => portProbe.close(() => resolve()));
69
- const origin = `http://127.0.0.1:${port}`;
70
- const child = spawn(process.execPath, ["--import", "tsx", "src/server.ts"], {
71
- env: { ...process.env, NODE_ENV: "test", PORT: String(port), FRONTEND_URL: origin, BACKEND_URL: origin,
72
- SUPABASE_URL: `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`,
73
- SUPABASE_ANON_KEY: "test-anon", SUPABASE_SERVICE_ROLE_KEY: "test-service", ANALYSIS_PROXY_SECRET: "x".repeat(32) },
74
- stdio: ["ignore", "pipe", "pipe"],
75
- });
76
- try {
77
- await new Promise<void>((resolve, reject) => {
78
- child.stdout.on("data", (data) => { if (String(data).includes("API listening")) resolve(); });
79
- child.once("exit", (code) => reject(new Error(`API exited: ${code}`)));
80
- child.once("error", reject);
81
- });
82
- const request = (path: string, init: RequestInit = {}) => fetch(`${origin}${path}`, {
83
- ...init, signal: AbortSignal.timeout(10000), headers: { Cookie: "sp_access=access", Origin: origin, ...init.headers },
84
- }).catch((error) => { throw new Error(`Request failed: ${path}`, { cause: error }); });
85
- assert.equal((await fetch(`${origin}/api/players-overview`)).status, 401);
86
- authUnavailable = true;
87
- const outage = await request("/api/auth/me", { headers: { Cookie: "sp_access=access; sp_refresh=refresh" } });
88
- assert.equal(outage.status, 500);
89
- assert.equal(outage.headers.get("set-cookie"), null, "an outage must preserve session cookies");
90
- assert.equal(calls.some((call) => call.url.pathname === "/auth/v1/token"), false, "an outage must not rotate refresh tokens");
91
- authUnavailable = false;
92
- const meStart = calls.length;
93
- const me = await (await request("/api/auth/me")).json();
94
- assert.equal(me.access.active, true);
95
- assert.equal(me.access.subscription.plan, "Pro");
96
- assert.equal(calls.length - meStart, 3); // auth + role + joined assignment/plan
97
- const rosterResponse = await request("/api/players-overview");
98
- assert.equal(rosterResponse.status, 200);
99
- const roster = (await rosterResponse.json()).players;
100
- assert.equal(roster.length, 1);
101
- assert.equal(roster[0].scores.overall, 70);
102
- assert.equal(roster[0].actionCount, 2);
103
- assert.equal(roster[0].scores.scoredActions, 1);
104
- const list = (await (await request("/api/sessions-overview")).json()).sessions;
105
- assert.equal(list.length, 1);
106
- assert.equal(list[0].playerName, "Own Player");
107
- assert.equal(list[0].actionBreakdown.Pass, 2);
108
- const detail = await (await request(`/api/players-overview/${playerId}`)).json();
109
- assert.equal(detail.scores.overall, 70);
110
- assert.equal(detail.playerCount, 1);
111
- assert.equal((await request(`/api/players-overview/${otherPlayerId}`)).status, 404);
112
- const billing = await (await request("/api/plan-billing")).json();
113
- assert.equal(billing.subscription.name, "Pro");
114
- assert.equal(billing.usage.sessions, 1);
115
- assert.ok(!calls.some(({ url }) => url.pathname.endsWith("/annotations")));
116
- const login = await request("/api/auth/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email: user.email, password: "password123" }) });
117
- assert.equal(login.status, 200);
118
- assert.ok(!calls.some(({ method }) => method === "PATCH"));
119
- role = "admin";
120
- const adminPlayers = await (await request("/api/admin/players")).json();
121
- assert.equal(adminPlayers.players.find((row: { player_id: string }) => row.player_id === playerId).sessionCount, 1);
122
- const adminSessions = await (await request("/api/admin/sessions")).json();
123
- assert.equal(adminSessions.sessions.find((row: { session_id: string }) => row.session_id === "s1").actionCount, 2);
124
- const adminUsers = await (await request("/api/admin/users")).json();
125
- assert.equal(adminUsers.users[0].dataCounts.sessions, 1);
126
- const adminRows = (await (await request("/api/players-overview")).json()).players;
127
- assert.equal(adminRows.length, 2);
128
- role = "user";
129
- assert.equal((await (await request("/api/players-overview")).json()).players.length, 1);
130
- failActions = true;
131
- assert.equal((await request("/api/sessions-overview")).status, 500);
132
- revoked = true;
133
- assert.equal((await request("/api/sessions-overview")).status, 401);
134
- } finally {
135
- if (child.exitCode === null && child.signalCode === null) {
136
- const exited = once(child, "exit");
137
- child.kill();
138
- await exited;
139
- }
140
- upstream.closeAllConnections();
141
- await new Promise<void>((resolve) => upstream.close(() => resolve()));
142
- }
143
- });