result_parser.py 23.5 KB
Newer Older
1
2
3
4
"""Parse quic-interop-runner result.json files."""

import json
import re
5
from abc import ABC, abstractmethod
6
7
8
from dataclasses import dataclass
from datetime import datetime, timedelta
from enum import Enum
9
from functools import cached_property
10
from itertools import chain
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from pathlib import Path
from typing import Literal, Optional, TypedDict, Union, cast

DETAILS_RE = re.compile(r"(?P<avg>\d+) \(± (?P<var>\d+)\) (?P<unit>\w+)")


class RawTest(TypedDict):
    """A test description as parsed from result.json."""

    name: str
    desc: str


RawTestResultResult = Union[Literal["succeeded"], Literal["failed"]]


class RawTestResult(TypedDict):
    """A test result as parsed from result.json."""

30
31
    #: deprecated
    name: str
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
    abbr: str
    result: RawTestResultResult


class RawMeasurement(TypedDict):
    """A measurement result as parsed from result.json."""

    #: deprecated
    name: str
    abbr: str
    result: RawTestResultResult
    details: str


class RawResult(TypedDict):
    """The unmodified content of result.json."""

    start_time: float
    end_time: float
    log_dir: str
    servers: list[str]
    clients: list[str]
    urls: dict[str, str]
    tests: dict[str, RawTest]
    quic_draft: int
    quic_version: str
    results: list[list[RawTestResult]]
    measurements: list[list[RawMeasurement]]


class ImplementationRole(Enum):
    """The role of an implementation."""

    SERVER = "server"
    CLIENT = "client"
    BOTH = "both"


@dataclass(frozen=True)
class Implementation:
    """An server and/or client implementation with metadata."""

    name: str
    url: str
    role: ImplementationRole


@dataclass(frozen=True)
class TestDescription:
    """The description of a test."""

    abbr: str
    name: str
    desc: str

87
88
89
90
91
    def to_raw(self) -> RawTest:
        """Convert to a raw test description."""

        return {"name": self.name, "desc": self.desc}

92

93
@dataclass(frozen=True)  # type: ignore
94
95
class _ExtendedTestResultMixin(ABC):
    result: RawTestResultResult
96
97
98
    server: Implementation
    client: Implementation
    test: TestDescription
99
    _base_log_dir: Path
100
101
102
103
104
105
106
107
108
109
110
111
112

    @property
    def succeeded(self) -> bool:
        """True if the test succeeded."""

        return self.result == "succeeded"

    @property
    def combination(self) -> str:
        """Return a combination of server and client as string."""

        return f"{self.server.name}_{self.client.name}"

113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
    @property
    def log_dir_for_test(self) -> Path:
        """Return the log dir for this test."""

        return self._base_log_dir / self.combination / self.test.name

    @cached_property
    def iteration_log_dirs(self) -> list[Path]:
        """Return a list of log dirs for each test iteration."""
        iterations = sorted(
            iterdir
            for iterdir in self.log_dir_for_test.iterdir()
            if iterdir.is_dir() and iterdir.name.isnumeric()
        )
        iteration_nums = [int(iterdir.name) for iterdir in iterations]

        for index, cur_num in enumerate(iteration_nums):
            if index + 1 != cur_num:
                raise AssertionError(
132
133
                    f"Expected the {index}th iteration directory "
                    f"to be named {index} instead of {cur_num}."
134
135
136
137
138
139
                )

        return iterations

    @property
    def num_iterations(self) -> int:
140
        """Return the number of test iterations found for this test case."""
141
142
        return len(self.iteration_log_dirs)

143
144
145
146
    @abstractmethod
    def to_raw(self):
        """Convert to a raw result."""

147
148
149
150
151

@dataclass(frozen=True)
class ExtendedTestResult(_ExtendedTestResultMixin):
    """Test result with more information."""

152
153
154
155
    def to_raw(self) -> RawTestResult:
        """Return a raw measurement result."""

        return RawTestResult(
156
            name=self.test.name,
157
            abbr=self.test.abbr,
158
            result=self.result,
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

@dataclass(frozen=True)
class ExtendedMeasurementResult(_ExtendedTestResultMixin):
    """Measurement result with more information."""

    details: str

    @property
    def _details_match(self) -> re.Match:
        assert self.succeeded, "Can't parse details, because test did not succeed."
        match = DETAILS_RE.match(self.details)
        assert match, (
            f"Measurement details `{self.details}` do not match pattern "
            f"in test {self.test.abbr} for combination {self.combination}."
        )

        return match

    @property
    def avg(self) -> int:
        """The average value."""

        return int(self._details_match.group("avg"))

    @property
    def var(self) -> int:
        """The variance value."""

        return int(self._details_match.group("var"))

    @property
    def unit(self) -> str:
        """The unit of ``avg`` and ``var``."""

        return self._details_match.group("unit")

197
198
199
200
201
202
    def to_raw(self) -> RawMeasurement:
        """Return a raw measurement result."""

        return RawMeasurement(
            name=self.test.name,
            abbr=self.test.abbr,
203
            result=self.result,
204
205
206
            details=self.details,
        )

207
208
209
210
211
212
213
214

TestResults = dict[str, dict[str, dict[str, ExtendedTestResult]]]
MeasurementResults = dict[str, dict[str, dict[str, ExtendedMeasurementResult]]]


class Result:
    """A pythonic version of result.json."""

215
216
217
    def __init__(
        self, file_path: Union[Path, str], raw_data: Optional[RawResult] = None
    ):
218
        self.file_path = Path(file_path)
219
        self._raw_data = raw_data
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
        self._test_results: Optional[TestResults] = None
        self._measurement_results: Optional[MeasurementResults] = None
        self._implementations_changed = False

    def __str__(self):
        return (
            f"<Result {self.file_path.name} "
            f"{len(self.tests)} test(s) "
            f"{len(self.implementations)} impl(s)>"
        )

    @property
    def raw_data(self) -> RawResult:
        """Load and return the raw json data."""

        if not self._raw_data:
            with self.file_path.open("r") as file:
                self._raw_data = cast(RawResult, json.load(file))
                assert self._raw_data

        return self._raw_data

    @raw_data.setter
    def raw_data(self, value: RawResult):
        self._raw_data = value

    @property
    def start_time(self) -> datetime:
        """The start time of the test run."""

        return datetime.fromtimestamp(self.raw_data["start_time"])

    @start_time.setter
    def start_time(self, value: datetime):
        self.raw_data["start_time"] = value.timestamp()

    @property
    def end_time(self) -> datetime:
        """The end time of the test run."""

        return datetime.fromtimestamp(self.raw_data["end_time"])

    @end_time.setter
    def end_time(self, value: datetime):
        self.raw_data["end_time"] = value.timestamp()

    @property
    def duration(self) -> timedelta:
        """The duration of the test run."""

        return self.end_time - self.start_time

    @property
    def quic_draft(self) -> int:
        """The quic draft version used in this test run."""

        return int(self.raw_data["quic_draft"])

    @quic_draft.setter
    def quic_draft(self, value: int):
        self.raw_data["quic_draft"] = value

    @property
    def quic_version(self) -> int:
        """The hexadecimal quic version used in this test run."""

        return int(self.raw_data["quic_version"], base=16)

    @quic_version.setter
    def quic_version(self, value: int):
        self.raw_data["quic_version"] = hex(value)

    @property
    def log_dir(self) -> Path:
        """The path to the detailed logs."""

        return Path(self.raw_data["log_dir"])

    @log_dir.setter
    def log_dir(self, value: Path):
        self.raw_data["log_dir"] = str(value)

    def _update_implementations(
        self, value: list[Implementation], role: ImplementationRole
    ):
        assert role != ImplementationRole.BOTH

        for impl in value:
            if impl.name not in self.raw_data["urls"]:
                self.raw_data["urls"][impl.name] = impl.url
            elif impl.url != self.raw_data["urls"][impl.name]:
                raise ValueError(
                    "There are two different urls for implementation "
                    f"{impl.url} and {self.raw_data['urls'][impl.name]}"
                )

            list_key: Union[Literal["servers"], Literal["clients"]] = (
                "servers" if role == ImplementationRole.SERVER else "clients"
            )

            if impl.name in self.raw_data[list_key]:
                return

            self._ensure_test_results_loaded()
            self._implementations_changed = True
            self.raw_data[list_key].append(impl.name)

    @property
    def servers(self) -> list[Implementation]:
        """The list of servers with metadata used in this test run."""

        return [
            Implementation(
                name=name,
                url=self.raw_data["urls"][name],
                role=(
                    ImplementationRole.BOTH
                    if name in self.raw_data["clients"]
                    else ImplementationRole.SERVER
                ),
            )
            for name in self.raw_data["servers"]
        ]

    @servers.setter
    def servers(self, value: list[Implementation]):
        self._update_implementations(value, role=ImplementationRole.SERVER)

    @property
    def clients(self) -> list[Implementation]:
        """The list of clients with metadata used in this test run."""

        return [
            Implementation(
                name=name,
                url=self.raw_data["urls"][name],
                role=(
                    ImplementationRole.BOTH
                    if name in self.raw_data["servers"]
                    else ImplementationRole.CLIENT
                ),
            )
            for name in self.raw_data["clients"]
        ]

    @clients.setter
    def clients(self, value: list[Implementation]):
        self._update_implementations(value, role=ImplementationRole.CLIENT)

    @property
    def implementations(self) -> frozenset[Implementation]:
        """Return a list of involved implementations."""

        return frozenset(self.servers) | frozenset(self.clients)

    @property
    def tests(self) -> dict[str, TestDescription]:
        """
        Return a dict of test and measurement abbr.s and description that ran during this run.
        """

        return {
            abbr: TestDescription(abbr=abbr, name=test["name"], desc=test["desc"])
            for abbr, test in self.raw_data["tests"].items()
        }

    @property
387
    def test_results(self) -> TestResults:
388
389
390
391
392
393
394
395
396
397
398
        """
        The test results of this test run in a nested dict.

        Dict keys are <server name> -> <client name> -> <test abbr>
        """

        if not self._test_results:
            self._test_results = self._load_test_results()

        return self._test_results

399
400
401
402
403
404
405
406
407
    def get_test_results_for_combination(
        self, server: Union[str, Implementation], client: Union[str, Implementation]
    ) -> dict[str, ExtendedTestResult]:
        """Return all test results for a combination of client and server."""
        server_name = server if isinstance(server, str) else server.name
        client_name = client if isinstance(client, str) else client.name

        return self.test_results[server_name][client_name]

408
409
410
411
412
413
414
415
    def get_test_result(
        self,
        server: Union[str, Implementation],
        client: Union[str, Implementation],
        test_abbr: str,
    ) -> ExtendedTestResult:
        """Get a specific test result."""

416
        return self.get_test_results_for_combination(server, client)[test_abbr]
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

    def get_all_tests_of_type(
        self,
        test_abbr: str,
        succeeding: Optional[bool] = None,
    ) -> list[ExtendedTestResult]:
        """Return a list of test results of a specific type."""

        tests = list[ExtendedTestResult]()

        for server in self.servers:
            for client in self.clients:
                test_results_for_combi = self.test_results[server.name][client.name]

                if test_abbr not in test_results_for_combi.keys():
                    continue

                test_result = test_results_for_combi[test_abbr]

                if succeeding is not None and test_result.succeeded != succeeding:
                    continue

                tests.append(test_result)

        return tests

    @property
    def measurement_results(self) -> MeasurementResults:
        """
        The measurement results of this test run in a nested dict.

        Dict keys are <server name> -> <client name> -> <measurement abbr>
        """

        if not self._measurement_results:
            self._measurement_results = self._load_measurement_results()

        return self._measurement_results

456
457
458
459
460
461
462
463
464
    def get_measurements_for_combination(
        self, server: Union[str, Implementation], client: Union[str, Implementation]
    ) -> dict[str, ExtendedMeasurementResult]:
        """Return all measurements for a combination of client and server."""
        server_name = server if isinstance(server, str) else server.name
        client_name = client if isinstance(client, str) else client.name

        return self.measurement_results[server_name][client_name]

465
466
467
468
469
470
471
472
    def get_measurement(
        self,
        server: Union[str, Implementation],
        client: Union[str, Implementation],
        measurement_abbr: str,
    ) -> ExtendedMeasurementResult:
        """Get a specific measurement result."""

473
        return self.get_measurements_for_combination(server, client)[measurement_abbr]
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

    def get_all_measuements_of_type(
        self,
        measurement_abbr: str,
        succeeding: Optional[bool] = None,
    ) -> list[ExtendedMeasurementResult]:
        """Return a list of measurement results of a specific type."""
        measurement_results = list[ExtendedMeasurementResult]()

        for server in self.servers:
            for client in self.clients:
                measurement_results_for_combi = self.measurement_results[server.name][
                    client.name
                ]

                if measurement_abbr not in measurement_results_for_combi.keys():
                    continue

                measuement_result = measurement_results_for_combi[measurement_abbr]

                if succeeding is not None and measuement_result.succeeded != succeeding:
                    continue

                measurement_results.append(measuement_result)

        return measurement_results

    def _load_test_results(self) -> TestResults:
        assert not self._implementations_changed

        results = TestResults()

        for server_index, server in enumerate(self.servers):
            results[server.name] = dict[str, dict[str, ExtendedTestResult]]()

            for client_index, client in enumerate(self.clients):
                results[server.name][client.name] = dict[str, ExtendedTestResult]()

                index = client_index * len(self.servers) + server_index

                for test in self.raw_data["results"][index]:
                    ext_result = ExtendedTestResult(
                        result=test["result"],
                        server=server,
                        client=client,
                        test=self.tests[test["abbr"]],
520
                        _base_log_dir=self.log_dir,
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
                    )
                    results[server.name][client.name][test["abbr"]] = ext_result

        return results

    def _load_measurement_results(self) -> MeasurementResults:
        assert not self._implementations_changed

        results = MeasurementResults()

        for server_index, server in enumerate(self.servers):
            results[server.name] = dict[str, dict[str, ExtendedMeasurementResult]]()

            for client_index, client in enumerate(self.clients):
                results[server.name][client.name] = dict[
                    str, ExtendedMeasurementResult
                ]()

                index = client_index * len(self.servers) + server_index

                for measurement in self.raw_data["measurements"][index]:
                    ext_result = ExtendedMeasurementResult(
                        result=measurement["result"],
                        details=measurement["details"],
                        server=server,
                        client=client,
                        test=self.tests[measurement["abbr"]],
548
                        _base_log_dir=self.log_dir,
549
550
551
552
553
554
555
556
557
                    )
                    results[server.name][client.name][measurement["abbr"]] = ext_result

        return results

    def _ensure_test_results_loaded(self):
        """Ensure that all test results are loaded."""
        self._test_results = self._load_test_results()
        self._measurement_results = self._load_measurement_results()
558
559
560
561
562
563

    def merge(
        self,
        other: "Result",
        file_path: Union[Path, str],
        log_dir: Union[Path, str],
564
        update_failed=True,
565
566
567
568
569
570
571
572
573
574
575
576
577
578
    ) -> "Result":
        """Merge this result with another result."""
        assert self.quic_draft == other.quic_draft
        assert self.quic_version == other.quic_version

        servers1 = frozenset(server.name for server in self.servers)
        servers2 = frozenset(server.name for server in other.servers)
        clients1 = frozenset(client.name for client in self.clients)
        clients2 = frozenset(client.name for client in other.clients)

        servers_merged = sorted(servers1 | servers2)
        clients_merged = sorted(clients1 | clients2)

        # check and merge test and measurements
579
580
        tests_merged = dict[str, dict[str, dict[str, ExtendedTestResult]]]()
        meass_merged = dict[str, dict[str, dict[str, ExtendedMeasurementResult]]]()
581
582

        for server in servers_merged:
583
584
            tests_merged[server] = dict[str, dict[str, ExtendedTestResult]]()
            meass_merged[server] = dict[str, dict[str, ExtendedMeasurementResult]]()
585
586

            for client in clients_merged:
587
588
589
                tests_merged[server][client] = dict[str, ExtendedTestResult]()
                meass_merged[server][client] = dict[str, ExtendedMeasurementResult]()

590
591
                # merge tests
                try:
592
                    tests_for_combi1 = self.get_test_results_for_combination(
593
594
595
                        server, client
                    )
                except KeyError:
596
                    tests_for_combi1 = dict[str, ExtendedTestResult]()
597
598

                try:
599
                    tests_for_combi2 = other.get_test_results_for_combination(
600
601
602
                        server, client
                    )
                except KeyError:
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
                    tests_for_combi2 = dict[str, ExtendedTestResult]()

                for test_abbr, test in chain(
                    tests_for_combi1.items(),
                    tests_for_combi2.items(),
                ):
                    if test_abbr in tests_merged[server][client].keys():
                        if update_failed:
                            test_included: ExtendedTestResult = tests_merged[server][
                                client
                            ][test_abbr]

                            if not test_included.succeeded and test.succeeded:
                                # overwrite failed test:
                                tests_merged[server][client][test_abbr] = test
                            elif not test.succeeded:
                                # do not overwrite with a failed test:

                                continue
                            else:
                                breakpoint()
                                raise ValueError(
                                    f"Both results have a result for the test {test_abbr} "
                                    f"for {server}_{client} and both succeeded."
                                )
                        else:
                            breakpoint()
                            raise ValueError(
                                f"Both results have a result for the test {test_abbr}."
                            )
                    else:
                        tests_merged[server][client][test_abbr] = test
635
636
637
638
639
640
641

                # merge measurements
                try:
                    meass_for_combi1 = self.get_measurements_for_combination(
                        server, client
                    )
                except KeyError:
642
                    meass_for_combi1 = dict[str, ExtendedMeasurementResult]()
643
644
645
646
647
648

                try:
                    meass_for_combi2 = other.get_measurements_for_combination(
                        server, client
                    )
                except KeyError:
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
                    meass_for_combi2 = dict[str, ExtendedMeasurementResult]()

                for meas_abbr, meas in chain(
                    meass_for_combi1.items(),
                    meass_for_combi2.items(),
                ):
                    if meas_abbr in meass_merged[server][client].keys():
                        if update_failed:
                            meas_included: ExtendedMeasurementResult = meass_merged[
                                server
                            ][client][meas_abbr]

                            if not meas_included.succeeded and meas.succeeded:
                                # overwrite failed test:
                                meass_merged[server][client][meas_abbr] = meas
                            elif not meas.succeeded:
                                # do not overwrite with a failed test:

                                continue
                            else:
                                breakpoint()
                                raise ValueError(
                                    f"Both results have a result for the test {meas_abbr} "
                                    f"for {server}_{client} and both succeeded."
                                )
                        else:
                            breakpoint()
                            raise ValueError(
                                f"Both results have a result for the test {meas_abbr}."
                            )
                    else:
                        meass_merged[server][client][meas_abbr] = meas
681
682
683
684
685
686
687

        # linearize tests and measurements
        tests_lin = list[list[RawTestResult]]()
        meass_lin = list[list[RawMeasurement]]()

        for client in clients_merged:
            for server in servers_merged:
688
689
690
691
692
693
                tests_lin.append(
                    [test.to_raw() for test in tests_merged[server][client].values()]
                )
                meass_lin.append(
                    [test.to_raw() for test in meass_merged[server][client].values()]
                )
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723

        urls = {
            **{impl.name: impl.url for impl in self.implementations},
            **{impl.name: impl.url for impl in other.implementations},
        }
        test_descriptions: dict[str, RawTest] = {
            **{abbr: test.to_raw() for abbr, test in self.tests.items()},
            **{abbr: test.to_raw() for abbr, test in other.tests.items()},
        }

        output: RawResult = {
            "start_time": min(self.start_time, other.start_time).timestamp(),
            "end_time": max(self.end_time, other.end_time).timestamp(),
            "log_dir": str(log_dir),
            "servers": servers_merged,
            "clients": clients_merged,
            "urls": urls,
            "tests": test_descriptions,
            "quic_draft": self.quic_draft,
            "quic_version": hex(other.quic_version),
            "results": tests_lin,
            "measurements": meass_lin,
        }

        return Result(file_path, raw_data=output)

    def save(self):
        """Save to file."""
        with self.file_path.open("w") as file:
            json.dump(self.raw_data, fp=file)