2222from collections .abc import Iterator , Mapping
2323from contextlib import contextmanager
2424from contextvars import ContextVar
25- from dataclasses import asdict , dataclass , field
25+ from dataclasses import asdict , dataclass , field , fields
2626from types import NotImplementedType
2727from typing import TYPE_CHECKING , ClassVar , TypeGuard , TypeVar
2828
@@ -454,7 +454,17 @@ def record(self, record: ConversionRecord) -> None:
454454 "arraybridge conversion observer" , default = IgnoreConversions ()
455455)
456456
457- ConversionKey = tuple [str , str , str , str , str ]
457+ # A conversion kind is identified by every field of the record except its measurements.
458+ _MEASUREMENTS = frozenset ({"nbytes" , "seconds" })
459+ _IDENTITY_FIELDS = tuple (
460+ each .name for each in fields (ConversionRecord ) if each .name not in _MEASUREMENTS
461+ )
462+ ConversionKey = tuple [str | tuple [str , ...], ...]
463+ JsonRow = dict [str , str | int | float | list [str ]]
464+
465+
466+ def _key_of (record : ConversionRecord ) -> ConversionKey :
467+ return tuple (getattr (record , name ) for name in _IDENTITY_FIELDS )
458468
459469
460470@dataclass (slots = True )
@@ -468,27 +478,18 @@ class ConversionTotal:
468478
469479@dataclass (slots = True )
470480class ConversionCounters (ConversionObserver ):
471- """Per-process totals keyed by source, target and mechanism .
481+ """Per-process totals keyed by what identifies a conversion .
472482
473- Counters from worker processes are plain data: pickle them or send
474- ``to_json()`` back, then ``merge`` them into the parent's.
483+ The key is every field of ``ConversionRecord`` but ``nbytes`` and
484+ ``seconds``: the libraries and devices, the mechanism and the declined
485+ mechanisms. Counters from worker processes are plain data: pickle them or
486+ send ``to_json()`` back, then ``merge`` them into the parent's.
475487 """
476488
477489 totals : dict [ConversionKey , ConversionTotal ] = field (default_factory = dict )
478490
479491 def record (self , record : ConversionRecord ) -> None :
480- self ._add (
481- (
482- record .source_library ,
483- record .source_device ,
484- record .target_library ,
485- record .target_device ,
486- record .mechanism ,
487- ),
488- 1 ,
489- record .nbytes ,
490- record .seconds ,
491- )
492+ self ._add (_key_of (record ), 1 , record .nbytes , record .seconds )
492493
493494 def _add (self , key : ConversionKey , count : int , nbytes : int , seconds : float ) -> None :
494495 total = self .totals .setdefault (key , ConversionTotal ())
@@ -503,55 +504,56 @@ def merge(self, other: ConversionCounters) -> ConversionCounters:
503504 self ._add (key , total .count , total .nbytes , total .seconds )
504505 return self
505506
506- def rows (self ) -> list [dict [str , str | int | float ]]:
507+ def _largest_first (self ) -> list [tuple [ConversionKey , ConversionTotal ]]:
508+ return sorted (self .totals .items (), key = lambda item : (- item [1 ].nbytes , item [0 ]))
509+
510+ def rows (self ) -> list [JsonRow ]:
507511 """One JSON-ready row per kind of conversion, largest byte total first."""
508512
509513 return [
510514 {
511- "source_library" : key [0 ],
512- "source_device" : key [1 ],
513- "target_library" : key [2 ],
514- "target_device" : key [3 ],
515- "mechanism" : key [4 ],
515+ ** {
516+ name : list (part ) if isinstance (part , tuple ) else part
517+ for name , part in zip (_IDENTITY_FIELDS , key , strict = True )
518+ },
516519 "count" : total .count ,
517520 "nbytes" : total .nbytes ,
518521 "seconds" : total .seconds ,
519522 }
520- for key , total in sorted (
521- self .totals .items (), key = lambda item : (- item [1 ].nbytes , item [0 ])
522- )
523+ for key , total in self ._largest_first ()
523524 ]
524525
525526 to_json = rows
526527
527528 @classmethod
528- def from_json (cls , rows : list [dict [ str , str | int | float ] ]) -> ConversionCounters :
529+ def from_json (cls , rows : list [JsonRow ]) -> ConversionCounters :
529530 counters = cls ()
530531 for row in rows :
532+ key = tuple (
533+ tuple (map (str , part )) if isinstance (part , list ) else str (part )
534+ for part in (row [name ] for name in _IDENTITY_FIELDS )
535+ )
531536 counters ._add (
532- (
533- str (row ["source_library" ]),
534- str (row ["source_device" ]),
535- str (row ["target_library" ]),
536- str (row ["target_device" ]),
537- str (row ["mechanism" ]),
538- ),
539- int (row ["count" ]),
540- int (row ["nbytes" ]),
541- float (row ["seconds" ]),
537+ key , int (str (row ["count" ])), int (str (row ["nbytes" ])), float (str (row ["seconds" ]))
542538 )
543539 return counters
544540
545541 def format_table (self ) -> str :
546542 """The totals as aligned text, one line per kind of conversion."""
547543
548544 lines = [
549- f"{ 'source' :<28} { 'target' :<28} { 'mechanism' :<12 } "
550- f"{ 'count' :>7} { 'MB' :>10} { 'seconds' :>9} "
545+ f"{ 'source' :<28} { 'target' :<28} { 'mechanism' :<20 } "
546+ f"{ 'count' :>7} { 'MB' :>10} { 'seconds' :>9} declined "
551547 ]
552- for key , total in sorted (self .totals .items (), key = lambda item : (- item [1 ].nbytes , item [0 ])):
548+ for key , total in self ._largest_first ():
549+ row = dict (zip (_IDENTITY_FIELDS , key , strict = True ))
550+ declined = row ["declined_mechanisms" ]
551+ assert isinstance (declined , tuple )
553552 lines .append (
554- f"{ key [0 ] + ' ' + key [1 ]:<28} { key [2 ] + ' ' + key [3 ]:<28} { key [4 ]:<12} "
555- f"{ total .count :>7} { total .nbytes / 1e6 :>10.1f} { total .seconds :>9.3f} "
553+ f"{ row ['source_library' ]} { row ['source_device' ]} " .ljust (29 )
554+ + f"{ row ['target_library' ]} { row ['target_device' ]} " .ljust (29 )
555+ + f"{ row ['mechanism' ]!s:<20} "
556+ + f"{ total .count :>7} { total .nbytes / 1e6 :>10.1f} { total .seconds :>9.3f} "
557+ + ", " .join (declined )
556558 )
557559 return "\n " .join (lines )
0 commit comments