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

import json
4
import logging
5
import re
6
from abc import ABC, abstractmethod
7
8
9
from dataclasses import dataclass
from datetime import datetime, timedelta
from enum import Enum
10
from functools import cached_property
11
from itertools import chain
12
13
14
15
16
17
18
19
20
21
22
23
24
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


25
26
27
RawTestResultResult = Union[
    None, Literal["succeeded"], Literal["failed"], Literal["unsupported"]
]
28
29
30
31
32


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

33
34
    #: deprecated
    name: str
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
    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

90
91
92
93
94
    def to_raw(self) -> RawTest:
        """Convert to a raw test description."""

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

95

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

    @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}"

116
117
118
119
120
121
    @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

122
123
124
125
    @abstractmethod
    def to_raw(self):
        """Convert to a raw result."""

126
127
128
129
130

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

131
132
133
134
    def to_raw(self) -> RawTestResult:
        """Return a raw measurement result."""

        return RawTestResult(
135
            name=self.test.name,
136
            abbr=self.test.abbr,
137
            result=self.result,
138
139
        )

140
141
142
143
144
145
146

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

    details: str

147
148
149
    @cached_property
    def repetition_log_dirs(self) -> list[Path]:
        """Return a list of log dirs for each test repetition."""
150
151
152
153
154
155
156
157
158
159
        try:
            repetitions = sorted(
                iterdir
                for iterdir in self.log_dir_for_test.iterdir()
                if iterdir.is_dir() and iterdir.name.isnumeric()
            )
            repetition_nums = [int(iterdir.name) for iterdir in repetitions]
        except FileNotFoundError as err:
            breakpoint()
            raise err
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175

        for index, cur_num in enumerate(repetition_nums):
            if index + 1 != cur_num:
                raise AssertionError(
                    f"Expected the {index}th repetition directory "
                    f"to be named {index} instead of {cur_num}."
                )

        return repetitions

    @property
    def num_repetitions(self) -> int:
        """Return the number of test repetitions found for this test case."""

        return len(self.repetition_log_dirs)

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
    @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")

205
206
207
208
209
210
    def to_raw(self) -> RawMeasurement:
        """Return a raw measurement result."""

        return RawMeasurement(
            name=self.test.name,
            abbr=self.test.abbr,
211
            result=self.result,
212
213
214
            details=self.details,
        )

215
216
217
218
219
220
221
222

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


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

223
224
225
    def __init__(
        self, file_path: Union[Path, str], raw_data: Optional[RawResult] = None
    ):
226
        self.file_path = Path(file_path)
227
        self._raw_data = raw_data
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
        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."""
303
        log_dir = Path(self.raw_data["log_dir"])
304
305
306
307
308
309
310
311
312
313

        if not log_dir.is_absolute():
            log_dir = self.file_path.parent / log_dir

        if not log_dir.is_dir():
            logging.warning(
                f"The log dir {log_dir} given in {self.file_path} does not exist"
            )

        return log_dir
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

    @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
404
    def test_results(self) -> TestResults:
405
406
407
408
409
410
411
412
413
414
415
        """
        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

416
417
418
419
420
421
422
423
424
425
426
    @property
    def all_test_results(self) -> list[ExtendedTestResult]:
        """Return all test results."""

        return [
            test_result
            for results_by_server in self.test_results.values()
            for results_by_client in results_by_server.values()
            for test_result in results_by_client.values()
        ]

427
428
429
430
431
432
433
434
435
    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]

436
437
438
439
440
441
442
443
    def get_test_result(
        self,
        server: Union[str, Implementation],
        client: Union[str, Implementation],
        test_abbr: str,
    ) -> ExtendedTestResult:
        """Get a specific test result."""

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

    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

484
485
486
487
488
489
490
491
492
493
494
    @property
    def all_measurement_results(self) -> list[ExtendedMeasurementResult]:
        """Return all measurement results."""

        return [
            measurement_result
            for results_by_server in self.measurement_results.values()
            for results_by_client in results_by_server.values()
            for measurement_result in results_by_client.values()
        ]

495
496
497
498
499
500
501
502
503
    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]

504
505
506
507
508
509
510
511
    def get_measurement(
        self,
        server: Union[str, Implementation],
        client: Union[str, Implementation],
        measurement_abbr: str,
    ) -> ExtendedMeasurementResult:
        """Get a specific measurement result."""

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

    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]:
554
555
                    if not test["result"]:
                        continue
556
557
558
559
560
                    ext_result = ExtendedTestResult(
                        result=test["result"],
                        server=server,
                        client=client,
                        test=self.tests[test["abbr"]],
561
                        _base_log_dir=self.log_dir,
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
                    )
                    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]:
583
584
                    if not measurement["result"]:
                        continue
585
586
587
588
589
590
                    ext_result = ExtendedMeasurementResult(
                        result=measurement["result"],
                        details=measurement["details"],
                        server=server,
                        client=client,
                        test=self.tests[measurement["abbr"]],
591
                        _base_log_dir=self.log_dir,
592
593
594
595
596
597
598
599
600
                    )
                    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()
601
602
603
604
605
606

    def merge(
        self,
        other: "Result",
        file_path: Union[Path, str],
        log_dir: Union[Path, str],
607
        update_failed=True,
608
609
610
611
612
613
614
615
616
617
618
619
620
621
    ) -> "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
622
623
        tests_merged = dict[str, dict[str, dict[str, ExtendedTestResult]]]()
        meass_merged = dict[str, dict[str, dict[str, ExtendedMeasurementResult]]]()
624
625

        for server in servers_merged:
626
627
            tests_merged[server] = dict[str, dict[str, ExtendedTestResult]]()
            meass_merged[server] = dict[str, dict[str, ExtendedMeasurementResult]]()
628
629

            for client in clients_merged:
630
631
632
                tests_merged[server][client] = dict[str, ExtendedTestResult]()
                meass_merged[server][client] = dict[str, ExtendedMeasurementResult]()

633
634
                # merge tests
                try:
635
                    tests_for_combi1 = self.get_test_results_for_combination(
636
637
638
                        server, client
                    )
                except KeyError:
639
                    tests_for_combi1 = dict[str, ExtendedTestResult]()
640
641

                try:
642
                    tests_for_combi2 = other.get_test_results_for_combination(
643
644
645
                        server, client
                    )
                except KeyError:
646
647
648
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
                    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
678
679
680
681
682
683
684

                # merge measurements
                try:
                    meass_for_combi1 = self.get_measurements_for_combination(
                        server, client
                    )
                except KeyError:
685
                    meass_for_combi1 = dict[str, ExtendedMeasurementResult]()
686
687
688
689
690
691

                try:
                    meass_for_combi2 = other.get_measurements_for_combination(
                        server, client
                    )
                except KeyError:
692
693
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
                    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
724
725
726
727
728
729
730

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

        for client in clients_merged:
            for server in servers_merged:
731
732
733
734
735
736
                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()]
                )
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766

        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)