3333from devqubit_braket .utils import braket_version , get_adapter_version , get_backend_name
3434from devqubit_engine .circuit .models import CircuitFormat
3535from devqubit_engine .storage .types import ArtifactRef
36+ from devqubit_engine .uec .errors import EnvelopeValidationError
3637from devqubit_engine .uec .models .device import DeviceSnapshot
3738from devqubit_engine .uec .models .envelope import ExecutionEnvelope
3839from devqubit_engine .uec .models .execution import ExecutionSnapshot , ProducerInfo
6061
6162_serializer = BraketCircuitSerializer ()
6263
64+ # Pre-computed base CountsFormat dict for Braket (source=braket, cbit0_left).
65+ # Dynamic fields (measured_qubits) are overlaid per-call.
66+ _BRAKET_COUNTS_FORMAT : dict [str , Any ] = CountsFormat (
67+ source_sdk = "braket" ,
68+ source_key_format = "bitstring" ,
69+ bit_order = "cbit0_left" ,
70+ transformed = False ,
71+ ).to_dict ()
72+
6373
6474# =============================================================================
6575# Counts Format
@@ -95,7 +105,7 @@ def _get_braket_counts_format(
95105 bit_order = "cbit0_left" ,
96106 transformed = transformed ,
97107 )
98- result = fmt .to_dict ()
108+ result = fmt .to_dict () if transformed else dict ( _BRAKET_COUNTS_FORMAT )
99109
100110 if measured_qubits is not None :
101111 result ["measured_qubits" ] = measured_qubits
@@ -344,6 +354,7 @@ def _create_result_snapshot(
344354 raw_result_ref : ArtifactRef | None ,
345355 shots : int | None ,
346356 error : Exception | None = None ,
357+ counts_payload : dict [str , Any ] | None = None ,
347358) -> ResultSnapshot :
348359 """
349360 Create a ResultSnapshot from Braket result.
@@ -358,6 +369,9 @@ def _create_result_snapshot(
358369 Number of shots used.
359370 error : Exception or None
360371 Exception if execution failed.
372+ counts_payload : dict or None
373+ Pre-extracted counts payload. When provided, skips redundant
374+ extraction. Callers should extract once and pass through.
361375
362376 Returns
363377 -------
@@ -379,11 +393,12 @@ def _create_result_snapshot(
379393 # Extract measured qubits if available (for accurate bit-order semantics)
380394 measured_qubits = _extract_measured_qubits (result )
381395
382- # Check if result is already a combined payload dict (from batch)
383- if isinstance (result , dict ) and "experiments" in result :
384- counts_payload = result
385- else :
386- counts_payload = extract_counts_payload (result )
396+ # Use pre-computed counts_payload if provided
397+ if counts_payload is None :
398+ if isinstance (result , dict ) and "experiments" in result :
399+ counts_payload = result
400+ else :
401+ counts_payload = extract_counts_payload (result )
387402
388403 if counts_payload and counts_payload .get ("experiments" ):
389404 format_dict = _get_braket_counts_format (measured_qubits = measured_qubits )
@@ -632,27 +647,31 @@ def finalize_envelope(
632647 except Exception as e :
633648 logger .warning ("Failed to log error: %s" , e )
634649
650+ # Extract counts once (used for both result snapshot and separate logging)
651+ counts_payload : dict [str , Any ] | None = None
652+ if result is not None and error is None :
653+ try :
654+ if isinstance (result , dict ) and "experiments" in result :
655+ counts_payload = result # Batch: already structured
656+ else :
657+ counts_payload = extract_counts_payload (result )
658+ except Exception as e :
659+ logger .debug ("Failed to extract counts payload: %s" , e )
660+
635661 # Create result snapshot
636- result_snapshot = _create_result_snapshot (result , raw_result_ref , shots , error )
662+ result_snapshot = _create_result_snapshot (
663+ result , raw_result_ref , shots , error , counts_payload = counts_payload
664+ )
637665
638666 # Update execution snapshot with completion time
639667 if envelope .execution :
640668 envelope .execution .completed_at = utc_now_iso ()
641669
642670 envelope .result = result_snapshot
643671
644- # Extract counts for separate logging
645- counts_payload = None
646- if result is not None :
647- try :
648- counts_payload = extract_counts_payload (result )
649- except Exception as e :
650- logger .debug ("Failed to extract counts payload: %s" , e )
651-
652672 # Validate and log envelope
653673 # EnvelopeValidationError is raised by log_envelope for adapter runs with
654674 # invalid envelopes - this MUST propagate to enforce UEC contract
655- from devqubit_engine .uec .errors import EnvelopeValidationError
656675
657676 try :
658677 tracker .log_envelope (envelope = envelope )
0 commit comments