qql-protocol 0.5.0

Qdrant REST protocol surface for QQL: closed result IR, strict OpenAPI response parsing, schema and telemetry
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
use std::collections::HashMap;
use std::fmt::Write as _;

use serde::ser::{SerializeMap, Serializer};
use serde::{Deserialize, Serialize};

use qql_plan::{
    PlanFacetValue, PlanGroupId, PlanPointId, PlanShardKey, PlanVectorStruct, QuotaConfig,
};

use crate::schema::CollectionInfo;

use crate::telemetry::{PhaseTimings, ServerTelemetry, ServerUsage};

/// Single-statement execution outcome: status, operation label, message, data,
/// and optional server telemetry.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ExecResponse {
    /// Whether the statement succeeded.
    pub ok: bool,
    /// Operation label (e.g. `QUERY`, `UPSERT`, `PARSE`) for this result.
    pub operation: String,
    /// Human-readable summary or error text.
    pub message: String,
    /// Typed payload (search hits, count, facet entries, …), when the
    /// operation returns data.
    pub data: Option<ExecData>,
    /// Server telemetry (`time` + hardware/inference `usage`) when the
    /// backend reported it. `None` where the route/transport carries none
    /// (batch items, collection DDL over gRPC, mocks without timing).
    /// `skip_serializing_if` keeps the pre-telemetry JSON shape byte-identical
    /// when no telemetry was reported.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub telemetry: Option<ServerTelemetry>,
}

/// Canonical cross-SDK execution result. Every `client.execute(…)` call
/// returns this shape regardless of input type (string / Stmt / array).
#[derive(Debug, Clone, Serialize)]
pub struct ExecutionReport {
    /// Whether every statement succeeded (`failed == 0`).
    pub ok: bool,
    /// One `ExecResponse` per statement, in execution order.
    pub results: Vec<ExecResponse>,
    /// Number of successful statements.
    pub succeeded: usize,
    /// Number of failed statements.
    pub failed: usize,
    /// Report-level telemetry totals (server times summed, hardware counters
    /// summed, per-model tokens summed). `None` when no response reported
    /// telemetry; omitted from the serialized shape.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub telemetry: Option<ServerTelemetry>,
}

impl ExecutionReport {
    /// Create from a collection of `ExecResponse`s. `ok` is `failed == 0`;
    /// `telemetry` aggregates the per-response telemetry (see
    /// [`ServerTelemetry::aggregate`]).
    pub fn from_results(results: Vec<ExecResponse>) -> Self {
        let succeeded = results.iter().filter(|r| r.ok).count();
        let failed = results.len() - succeeded;
        let telemetry =
            ServerTelemetry::aggregate(results.iter().filter_map(|r| r.telemetry.as_ref()));
        Self {
            ok: failed == 0,
            results,
            succeeded,
            failed,
            telemetry,
        }
    }

    /// Convenience wrapper for a single `ExecResponse`.
    pub fn single(resp: ExecResponse) -> Self {
        let ok = resp.ok;
        let telemetry = resp.telemetry.clone();
        Self {
            ok,
            results: vec![resp],
            succeeded: if ok { 1 } else { 0 },
            failed: if ok { 0 } else { 1 },
            telemetry,
        }
    }

    /// Return the first statement response, if present.
    pub fn first(&self) -> Option<&ExecResponse> {
        self.results.first()
    }

    /// Return typed search hits of statement `stmt`.
    pub fn hits(&self, stmt: usize) -> Option<Vec<SearchHit>> {
        self.results.get(stmt).and_then(|r| r.hits())
    }

    /// Return point IDs from statement `stmt`.
    pub fn ids(&self, stmt: usize) -> Vec<u64> {
        self.results.get(stmt).map(|r| r.ids()).unwrap_or_default()
    }

    /// Return the count integer from statement `stmt`.
    pub fn count(&self, stmt: usize) -> Option<u64> {
        self.results.get(stmt).and_then(|r| r.count())
    }

    /// Return facet entries as `(value, count)` pairs from statement `stmt`.
    pub fn facet(&self, stmt: usize) -> Option<Vec<(PlanFacetValue, u64)>> {
        self.results.get(stmt).and_then(|r| r.facet())
    }

    /// Return the count integer from the first statement.
    pub fn first_count(&self) -> Option<u64> {
        self.count(0)
    }

    /// Return the search hits from the first statement.
    pub fn first_hits(&self) -> Option<Vec<SearchHit>> {
        self.hits(0)
    }

    /// Return the point IDs from the first statement.
    pub fn first_ids(&self) -> Vec<u64> {
        self.ids(0)
    }

    /// Return the facet pairs from the first statement.
    pub fn first_facet(&self) -> Option<Vec<(PlanFacetValue, u64)>> {
        self.facet(0)
    }
}

/// Structured `EXPLAIN ANALYZE` report: the static plan summary plus the
/// measured execution. JSON-serializable; returned by the runtime's
/// `Executor::explain_analyze`.
#[derive(Debug, Clone, Serialize)]
pub struct AnalyzeReport {
    /// Whether the analyzed statement succeeded (errors surface as `Err`).
    pub ok: bool,
    /// Static plan summary — the same tree `Executor::explain` renders,
    /// captured before execution.
    pub plan: String,
    /// Per-phase client timings (milliseconds).
    pub phases: PhaseTimings,
    /// Total server time in seconds (summed per-response `time`); `None`
    /// when the backend reported none.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub server_time_s: Option<f64>,
    /// Merged hardware/inference usage; `None` when the backend reported none.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage: Option<ServerUsage>,
    /// The statement's execution response(s), in order (one entry: analyze
    /// is single-statement, like Postgres `EXPLAIN ANALYZE`).
    pub results: Vec<ExecResponse>,
}

/// Controls batch-execution behaviour when a statement fails.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum OnError {
    /// Halt immediately on the first error (default).
    #[default]
    Stop,
    /// Continue executing remaining statements, collecting error
    /// responses alongside successes.
    Continue,
}

/// Normalize a backend f32 score to f64 **once, at ingestion**, through its
/// shortest round-trip decimal (`0.95f32` becomes `0.95f64`, not
/// `0.949999988079071`).
///
/// Every transport parses scores through this helper (REST `parse_hit` via
/// `score_from_wire`, gRPC `scored_point_to_hit`, edge
/// `from_edge_scored_point_to_hit`, cross-rerank dispatch), so the stored
/// value already carries the shortest decimal and plain
/// `Serialize`/`pythonize` emit it identically everywhere — JSON text,
/// `Value`, and the Python `ScoredPoint.score` getter agree with no custom
/// serializer. The mapping is monotonic over finite values, so sort order
/// under `partial_cmp` is unchanged.
///
/// The shortest decimal renders into a stack-resident `ScoreBuf` through
/// the same std float formatter as `to_string`, so the decimal is identical
/// without the per-hit `String` allocation; parsing it back as f64 yields
/// the same value the old `v.to_string().parse()` round-trip produced.
///
/// (`ryu::Buffer` was measured first and rejected: on exact ties such as
/// `0.494140625f32` it rounds to even — `"0.49414062"` — while std rounds
/// away — `"0.49414063"`. Same-renderer output is identical by construction.)
pub fn score_f64(v: f32) -> f64 {
    let mut buf = ScoreBuf::new();
    // Infallible in practice: the longest f32 `Display` (47 chars, plus a
    // sign) fits the buffer with room to spare. A failed write falls back
    // to the plain widening rather than risk a truncated decimal.
    if write!(buf, "{v}").is_err() {
        return v as f64;
    }
    buf.as_str().parse().unwrap_or(v as f64)
}

/// Stack-resident decimal scratch for [`score_f64`]: `write!` renders the
/// f32 through std's `Display` into inline bytes — no allocator in the path.
/// 64 bytes covers the longest f32 `Display` (47 chars: subnormal plain
/// notation like `0.000…001`, plus a sign).
struct ScoreBuf {
    buf: [u8; 64],
    len: usize,
}

impl ScoreBuf {
    fn new() -> Self {
        Self {
            buf: [0; 64],
            len: 0,
        }
    }

    fn as_str(&self) -> &str {
        // `Display` for f32 emits ASCII only, so the collected bytes are
        // always valid UTF-8; fall back to empty (which fails `parse` and
        // takes the `unwrap_or` plain widening) rather than panicking.
        std::str::from_utf8(&self.buf[..self.len]).unwrap_or("")
    }
}

impl std::fmt::Write for ScoreBuf {
    fn write_str(&mut self, s: &str) -> std::fmt::Result {
        let bytes = s.as_bytes();
        let end = self.len + bytes.len();
        if end > self.buf.len() {
            return Err(std::fmt::Error);
        }
        self.buf[self.len..end].copy_from_slice(bytes);
        self.len = end;
        Ok(())
    }
}

/// Normalize a JSON-decoded wire score to the stored f64 in one step.
///
/// REST decodes every JSON number as f64, so the wire decimal narrows to f32
/// and then shortest-expands through [`score_f64`]; fusing both halves here
/// keeps that double conversion at exactly one call site instead of inline
/// at every `parse_hit`.
///
/// The sole caller is [`crate::rest`], which is the REST boundary.
pub fn score_from_wire(v: f64) -> f64 {
    score_f64(v as f32)
}

/// Normalized search hit returned inside `ExecResponse` data.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SearchHit {
    /// Point ID (integer or string/UUID).
    pub id: PlanPointId,
    /// Similarity or rerank score, rounded once at ingestion via
    /// [`score_f64`] so it holds the shortest round-trip decimal (`0.95`,
    /// not `0.949999988079071`): Qdrant's own JSON text and the native Python
    /// `ScoredPoint.score` getter both use that form, so the JSON report view
    /// and the typed view agree with plain `Serialize` (no custom
    /// `serialize_with`).
    ///
    /// Deliberate asymmetry with [`PlanVectorStruct`]: scalar scores are
    /// human-read values worth normalizing, while `vector` stays `Vec<f32>`
    /// passthrough — exact decimal equality on 128-dim vectors is
    /// meaningless, and doubling their memory for cosmetics is indefensible.
    pub score: f64,
    /// Point payload when requested via `WITH PAYLOAD`.
    pub payload: Option<HashMap<String, serde_json::Value>>,
    /// Source collection. Populated by cross-collection operations (e.g.
    /// CROSS RERANK) so results are unambiguous when multiple collections
    /// share the same point id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub collection: Option<String>,
    /// Vector(s) returned when requested via `WITH VECTOR`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vector: Option<PlanVectorStruct>,
}

/// Grouped query result: one group key with its ordered hits.
///
/// Serializes to Qdrant's group shape `{"id": …, "hits": […]}` so report JSON
/// and SDK `.groups()` consumers read the same field names as the backend.
/// `Deserialize` mirrors it for wire round-trips.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GroupedSearchResult {
    /// Group key value as returned by Qdrant.
    #[serde(rename = "id")]
    pub group_id: PlanGroupId,
    /// Search hits in this group, in backend order.
    pub hits: Vec<SearchHit>,
}

/// One facet entry: value + occurrence count.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FacetHit {
    /// Facet value as returned by Qdrant.
    pub value: PlanFacetValue,
    /// Number of points carrying this value.
    pub count: u64,
}

/// Transport-neutral typed payload of one operation result. Closed by
/// construction: every backend response shape the transports can produce has a
/// variant here — there is no JSON passthrough.
///
/// Serialization emits the report JSON shapes SDK consumers already read:
/// `Hits` → array of [`SearchHit`], `Groups` → `{"groups": [{"id", "hits"}]}`,
/// `Count` → `{"count": n}`, `Facet` → array of `{"value": …, "count": n}`,
/// `Mutation { affected: Some(n) }` → `{"count": n}`,
/// `Mutation { affected: None }` → `null`,
/// `Collections` → `{"collections": ["name", …]}`,
/// `Collection` → the [`CollectionInfo`] object,
/// `ShardKeys` → `{"shard_keys": [key, …]}`,
/// `Quotas` → the [`QuotaConfig`] object.
// `CollectionInfo` is the largest variant (nested vector/index schema); the
// enum stays cloneable and is not hot-path cloned, so boxing it would only add
// indirection to the public IR shape.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, PartialEq)]
pub enum ExecData {
    /// Query / scroll / retrieve hits, in backend order.
    Hits(Vec<SearchHit>),
    /// Grouped query results (`QUERY … GROUP BY`).
    Groups(Vec<GroupedSearchResult>),
    /// COUNT result.
    Count(u64),
    /// FACET entries.
    Facet(Vec<FacetHit>),
    /// Write-op outcome: `affected: Some(n)` for upsert (n points written),
    /// `None` for status-only mutations (delete, payload/vector updates).
    Mutation {
        /// Number of points written, when the operation reports one.
        affected: Option<u64>,
    },
    /// Collection names (`SHOW COLLECTIONS`).
    Collections(Vec<String>),
    /// Collection metadata (`SHOW COLLECTION`).
    Collection(CollectionInfo),
    /// Custom shard keys (`SHOW SHARD KEYS`).
    ShardKeys(Vec<PlanShardKey>),
    /// Cluster-wide quota configuration (`SHOW QUOTAS` / `SET QUOTA`).
    Quotas(QuotaConfig),
}

impl Serialize for ExecData {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            ExecData::Hits(hits) => hits.serialize(serializer),
            ExecData::Groups(groups) => {
                let mut map = serializer.serialize_map(Some(1))?;
                map.serialize_entry("groups", groups)?;
                map.end()
            }
            ExecData::Count(count) => {
                let mut map = serializer.serialize_map(Some(1))?;
                map.serialize_entry("count", count)?;
                map.end()
            }
            ExecData::Facet(hits) => hits.serialize(serializer),
            ExecData::Mutation {
                affected: Some(count),
            } => {
                let mut map = serializer.serialize_map(Some(1))?;
                map.serialize_entry("count", count)?;
                map.end()
            }
            ExecData::Mutation { affected: None } => serializer.serialize_none(),
            ExecData::Collections(collections) => {
                let mut map = serializer.serialize_map(Some(1))?;
                map.serialize_entry("collections", collections)?;
                map.end()
            }
            ExecData::Collection(info) => info.serialize(serializer),
            ExecData::ShardKeys(keys) => {
                let mut map = serializer.serialize_map(Some(1))?;
                map.serialize_entry("shard_keys", keys)?;
                map.end()
            }
            ExecData::Quotas(config) => config.serialize(serializer),
        }
    }
}

impl ExecData {
    /// Borrow hits when this is a [`ExecData::Hits`] payload. A query that
    /// found nothing still yields `Some(&[])`, matching the pre-typing
    /// `hits()` contract.
    pub fn hits(&self) -> Option<&[SearchHit]> {
        match self {
            ExecData::Hits(hits) => Some(hits),
            _ => None,
        }
    }

    /// Borrow grouped results when this is an [`ExecData::Groups`] payload.
    pub fn groups(&self) -> Option<&[GroupedSearchResult]> {
        match self {
            ExecData::Groups(groups) => Some(groups),
            _ => None,
        }
    }

    /// The integer when this is a [`ExecData::Count`] payload, or the affected
    /// point count of an upsert [`ExecData::Mutation`].
    pub fn count(&self) -> Option<u64> {
        match self {
            ExecData::Count(count) => Some(*count),
            ExecData::Mutation { affected } => *affected,
            _ => None,
        }
    }

    /// The affected-point count of an [`ExecData::Mutation`]: `Some(Some(n))`
    /// for an upsert, `Some(None)` for a status-only write, `None` otherwise.
    pub fn mutation_affected(&self) -> Option<Option<u64>> {
        match self {
            ExecData::Mutation { affected } => Some(*affected),
            _ => None,
        }
    }

    /// Borrow facet entries when this is a [`ExecData::Facet`] payload.
    pub fn facet(&self) -> Option<&[FacetHit]> {
        match self {
            ExecData::Facet(hits) => Some(hits),
            _ => None,
        }
    }

    /// Borrow collection names when this is a [`ExecData::Collections`] payload.
    pub fn collections(&self) -> Option<&[String]> {
        match self {
            ExecData::Collections(collections) => Some(collections),
            _ => None,
        }
    }

    /// Borrow collection metadata when this is an [`ExecData::Collection`] payload.
    pub fn collection(&self) -> Option<&CollectionInfo> {
        match self {
            ExecData::Collection(info) => Some(info),
            _ => None,
        }
    }

    /// Borrow custom shard keys when this is an [`ExecData::ShardKeys`] payload.
    pub fn shard_keys(&self) -> Option<&[PlanShardKey]> {
        match self {
            ExecData::ShardKeys(keys) => Some(keys),
            _ => None,
        }
    }

    /// Borrow the quota configuration when this is a [`ExecData::Quotas`] payload.
    pub fn quotas(&self) -> Option<&QuotaConfig> {
        match self {
            ExecData::Quotas(config) => Some(config),
            _ => None,
        }
    }

    /// Whether the payload carries no records: empty
    /// `Hits`/`Groups`/`Facet`/`Collections`/`ShardKeys`. `Count`, `Mutation`,
    /// `Collection`, and `Quotas` are never empty (a zero count or an
    /// unlimited quota config is a result).
    pub fn is_empty(&self) -> bool {
        match self {
            ExecData::Hits(hits) => hits.is_empty(),
            ExecData::Groups(groups) => groups.is_empty(),
            ExecData::Count(_)
            | ExecData::Mutation { .. }
            | ExecData::Collection(_)
            | ExecData::Quotas(_) => false,
            ExecData::Facet(hits) => hits.is_empty(),
            ExecData::Collections(collections) => collections.is_empty(),
            ExecData::ShardKeys(keys) => keys.is_empty(),
        }
    }
}

/// Typed backend response: data + telemetry, no transport JSON envelope.
#[derive(Debug, Clone, Serialize)]
pub struct BackendResponse {
    /// Typed operation payload.
    pub data: ExecData,
    /// Server telemetry extracted from the transport envelope, when present.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub telemetry: Option<ServerTelemetry>,
}

impl ExecResponse {
    /// Borrow the typed search hits if this response contains hits data.
    pub fn hits_ref(&self) -> Option<&[SearchHit]> {
        self.data.as_ref().and_then(ExecData::hits)
    }

    /// Typed search hits: cloned from the native typed payload. Non-hits
    /// payloads (counts, facets, status envelopes) yield `None`.
    pub fn hits(&self) -> Option<Vec<SearchHit>> {
        self.hits_ref().map(<[SearchHit]>::to_vec)
    }

    /// Return point IDs as u64 from hits or scroll results.
    pub fn ids(&self) -> Vec<u64> {
        let Some(hits) = self.hits_ref() else {
            return Vec::new();
        };
        hits.iter()
            .filter_map(|hit| match &hit.id {
                PlanPointId::Number(id) => Some(*id),
                PlanPointId::String(id) => id.parse().ok(),
            })
            .collect()
    }

    /// Return the count from a COUNT response, if present.
    pub fn count(&self) -> Option<u64> {
        self.data.as_ref().and_then(ExecData::count)
    }

    /// Return facet entries as `(value, count)` pairs, if present.
    pub fn facet(&self) -> Option<Vec<(PlanFacetValue, u64)>> {
        let entries = self.data.as_ref()?.facet()?;
        Some(
            entries
                .iter()
                .map(|entry| (entry.value.clone(), entry.count))
                .collect(),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Scores are rounded once at ingestion ([`score_f64`]), so the stored
    /// f64 already holds the shortest decimal — plain `Serialize` emits it
    /// (`0.95`, not `0.949999988079071`), keeping the JSON report view and
    /// every native view (`pythonize`, `ScoredPoint.score`) in agreement.
    #[test]
    fn score_f64_rounds_once_at_ingestion() {
        assert_eq!(score_f64(0.95f32), 0.95f64);
        let hit = SearchHit {
            id: PlanPointId::Number(1),
            score: score_f64(0.95f32),
            payload: None,
            collection: None,
            vector: None,
        };
        let value = serde_json::to_value(&hit).expect("hit serializes");
        assert_eq!(value["score"], serde_json::json!(0.95));
    }

    /// The stack-buffer shortest repr must stay byte-identical to the old
    /// heap round-trip: pin a table of tricky values (short decimals,
    /// exponent boundaries, subnormals, extremes, non-finite) against
    /// `to_string().parse()`. NaN compares unequal to itself, so it asserts
    /// NaN-ness on both sides.
    #[test]
    fn score_f64_matches_heap_round_trip() {
        for v in [
            0.95f32,
            0.75,
            0.1,
            0.99,
            1.0,
            -1.0,
            0.0,
            -0.0,
            1e-5,
            1e-4,
            1e21,
            12345.67,
            0.30000004,
            f32::MIN_POSITIVE,
            f32::EPSILON,
            3.4028235e38,
            1.1754944e-38,
            1e-45,
            2.5e-7,
            std::f32::consts::PI,
            100.0,
            f32::INFINITY,
            f32::NEG_INFINITY,
        ] {
            let expected: f64 = v.to_string().parse().unwrap_or(v as f64);
            assert_eq!(score_f64(v), expected, "score_f64({v}) diverged");
        }
        assert!(score_f64(f32::NAN).is_nan());
        let expected: f64 = f32::NAN.to_string().parse().unwrap_or(f32::NAN as f64);
        assert!(expected.is_nan());
    }

    /// The wire decimal normalizes once: the exact f32 expansion
    /// `0.949999988079071` narrows back to the same stored `0.95`.
    #[test]
    fn score_from_wire_narrows_once() {
        assert_eq!(super::score_from_wire(0.95), 0.95f64);
        assert_eq!(super::score_from_wire(0.949999988079071), 0.95f64);
    }
}