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

import json
import re
5
from abc import abstractmethod
6
7
8
from dataclasses import dataclass
from datetime import datetime, timedelta
from enum import Enum
9
from functools import cached_property
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
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."""

    abbr: str
    result: RawTestResultResult
    # TODO more fields


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

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

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

90
91
92
93
94
95
96

@dataclass(frozen=True)
class _ExtendedTestResultMixin:
    result: str
    server: Implementation
    client: Implementation
    test: TestDescription
97
    _base_log_dir: Path
98
99
100
101
102
103
104
105
106
107
108
109
110

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

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
    @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(
                    f"Expected the {index}. iteration directory to named {index} instead of {cur_num}"
                )

        return iterations

    @property
    def num_iterations(self) -> int:
        return len(self.iteration_log_dirs)

139
140
141
142
    @abstractmethod
    def to_raw(self):
        """Convert to a raw result."""

143
144
145
146
147
148
149

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

    # TODO more fields

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

        return RawTestResult(
            abbr=self.test.abbr,
            result=str(self.result),
        )

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

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

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

        return RawMeasurement(
            name=self.test.name,
            abbr=self.test.abbr,
            result=str(self.result),
            details=self.details,
        )

204
205
206
207
208
209
210
211

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


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

212
213
214
    def __init__(
        self, file_path: Union[Path, str], raw_data: Optional[RawResult] = None
    ):
215
        self.file_path = Path(file_path)
216
        self._raw_data = raw_data
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
        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
384
    def test_results(self) -> TestResults:
385
386
387
388
389
390
391
392
393
394
395
        """
        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

396
397
398
399
400
401
402
403
404
    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]

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

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

    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

453
454
455
456
457
458
459
460
461
    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]

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

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

    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(
                        # TODO more fields
                        result=test["result"],
                        server=server,
                        client=client,
                        test=self.tests[test["abbr"]],
518
                        _base_log_dir=self.log_dir,
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
                    )
                    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"]],
546
                        _base_log_dir=self.log_dir,
547
548
549
550
551
552
553
554
555
                    )
                    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()
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
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
635
636
637
638
639
640
641
642
643
644
645
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693

    def merge(
        self,
        other: "Result",
        file_path: Union[Path, str],
        log_dir: Union[Path, str],
    ) -> "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
        tests_merged = dict[str, dict[str, dict[str, RawTestResult]]]()
        meass_merged = dict[str, dict[str, dict[str, RawMeasurement]]]()

        for server in servers_merged:
            tests_merged[server] = dict[str, dict[str, RawTestResult]]()
            meass_merged[server] = dict[str, dict[str, RawMeasurement]]()

            for client in clients_merged:
                # merge tests
                try:
                    tests_for_combi1 = self.get_measurements_for_combination(
                        server, client
                    )
                except KeyError:
                    tests_for_combi1 = {}

                try:
                    tests_for_combi2 = other.get_measurements_for_combination(
                        server, client
                    )
                except KeyError:
                    tests_for_combi2 = {}

                test_abbrs1 = frozenset(tests_for_combi1.keys())
                test_abbrs2 = frozenset(tests_for_combi2.keys())
                common_tests = test_abbrs1 & test_abbrs2

                if common_tests:
                    breakpoint()
                    raise ValueError(
                        f"Both results have same test results for {server}_{client}: {', '.join(common_tests)}"
                    )

                tests_merged[server][client] = {
                    **{
                        test_abbr: test.to_raw()
                        for test_abbr, test in tests_for_combi1.items()
                    },
                    **{
                        test_abbr: test.to_raw()
                        for test_abbr, test in tests_for_combi2.items()
                    },
                }

                # merge measurements
                try:
                    meass_for_combi1 = self.get_measurements_for_combination(
                        server, client
                    )
                except KeyError:
                    meass_for_combi1 = {}

                try:
                    meass_for_combi2 = other.get_measurements_for_combination(
                        server, client
                    )
                except KeyError:
                    meass_for_combi2 = {}

                meas_abbrs1 = frozenset(meass_for_combi1.keys())
                meas_abbrs2 = frozenset(meass_for_combi2.keys())
                common_meass = meas_abbrs1 & meas_abbrs2

                if common_meass:
                    breakpoint()
                    raise ValueError(
                        f"Both results have same measurement results for {server}_{client}: {', '.join(common_meass)}"
                    )

                meass_merged[server][client] = {
                    **{
                        meas_abbr: meas.to_raw()
                        for meas_abbr, meas in meass_for_combi1.items()
                    },
                    **{
                        meas_abbr: meas.to_raw()
                        for meas_abbr, meas in meass_for_combi2.items()
                    },
                }

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

        for client in clients_merged:
            for server in servers_merged:
                tests_lin.append(list(tests_merged[server][client].values()))
                meass_lin.append(list(meass_merged[server][client].values()))

        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)