Skip to content

Local storage

DictStorage dataclass

DictStorage()

Bases: StorageBackend


              flowchart TD
              bloqade.core.device.local_storage.DictStorage[DictStorage]
              bloqade.core.device.local_storage.StorageBackend[StorageBackend]

                              bloqade.core.device.local_storage.StorageBackend --> bloqade.core.device.local_storage.DictStorage
                


              click bloqade.core.device.local_storage.DictStorage href "" "bloqade.core.device.local_storage.DictStorage"
              click bloqade.core.device.local_storage.StorageBackend href "" "bloqade.core.device.local_storage.StorageBackend"
            

In-memory storage backend for shot results.

This backend is useful for tests, examples, and short-lived sessions. Data is not persisted across Python processes.

add_shots

add_shots(shots: Iterable[ShotResult]) -> None

Store shot result rows in memory.

Parameters:

Name Type Description Default
shots Iterable[ShotResult]

Shot rows to store.

required
Source code in src/bloqade/core/device/local_storage.py
425
426
427
428
429
430
431
432
433
434
435
436
437
def add_shots(self, shots: Iterable[ShotResult]) -> None:
    """Store shot result rows in memory.

    Args:
        shots (Iterable[ShotResult]): Shot rows to store.
    """
    for shot in shots:
        key = (
            shot.task_id,
            shot.shot_index,
            shot.frame_type,
        )
        self._data[key] = shot

add_task_definition

add_task_definition(
    task_id: str,
    task_definition: TaskDefinition,
    creation_time: datetime,
)

Store a task definition and creation time in memory.

Parameters:

Name Type Description Default
task_id str

Backend task ID.

required
task_definition TaskDefinition

Task definition to store.

required
creation_time datetime

Backend task creation time.

required
Source code in src/bloqade/core/device/local_storage.py
500
501
502
503
504
505
506
507
508
509
510
511
512
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
def add_task_definition(
    self,
    task_id: str,
    task_definition: TaskDefinition,
    creation_time: datetime.datetime,
):
    """Store a task definition and creation time in memory.

    Args:
        task_id (str): Backend task ID.
        task_definition (TaskDefinition): Task definition to store.
        creation_time (datetime.datetime): Backend task creation time.
    """
    current_defs = self._metadata.get("task_definitions", {})
    current_defs[task_id] = {
        "task_id": task_id,
        "program_language": task_definition.program_language,
        "creation_time": creation_time,
    }
    self._metadata["task_definitions"] = current_defs

    current_programs = self._metadata.get("programs", {})
    for i, program in enumerate(task_definition.programs):
        current_programs[(task_id, i)] = {
            "task_id": task_id,
            "program_index": i,
            "content": program.content,
        }
    self._metadata["programs"] = current_programs

    current_subtasks = self._metadata.get("subtasks", {})
    for i, subtask in enumerate(task_definition.subtasks):
        if subtask.subtask_metadata is None:
            metadata = None
        else:
            metadata = subtask.subtask_metadata.model_dump()

        current_subtasks[(task_id, i)] = {
            "task_id": task_id,
            "subtask_index": i,
            "program_index": subtask.program_index,
            "num_shots": subtask.num_shots,
            "arguments": subtask.arguments,
            "metadata": metadata,
            "completed_date": None,
        }
    self._metadata["subtasks"] = current_subtasks

get_program_language

get_program_language(task_id: str) -> str

Return the program language for a stored task definition.

Parameters:

Name Type Description Default
task_id str

Backend task ID.

required

Returns:

Name Type Description
str str

Stored program language.

Raises:

Type Description
KeyError

If task_id is not present.

Source code in src/bloqade/core/device/local_storage.py
548
549
550
551
552
553
554
555
556
557
558
559
560
def get_program_language(self, task_id: str) -> str:
    """Return the program language for a stored task definition.

    Args:
        task_id (str): Backend task ID.

    Returns:
        str: Stored program language.

    Raises:
        KeyError: If `task_id` is not present.
    """
    return self._metadata["task_definitions"][task_id]["program_language"]

get_programs

get_programs(
    task_ids: tuple[str, ...] | None = None,
) -> list[dict]

Return stored program records.

Parameters:

Name Type Description Default
task_ids tuple[str, ...] | None

Optional task IDs to include. When None, programs for all stored tasks are returned. Defaults to None.

None

Returns:

Type Description
list[dict]

list[dict]: Independent program dictionaries.

Source code in src/bloqade/core/device/local_storage.py
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
def get_programs(self, task_ids: tuple[str, ...] | None = None) -> list[dict]:
    """Return stored program records.

    Args:
        task_ids (tuple[str, ...] | None): Optional task IDs to include.
            When None, programs for all stored tasks are returned. Defaults
            to None.

    Returns:
        list[dict]: Independent program dictionaries.
    """
    programs = self._metadata.get("programs")
    if programs is None:
        return []

    # NOTE: extra dict call to create a copy so we can safely mutate the return programs
    if task_ids is None:
        return list(map(dict, programs.values()))
    else:
        return [
            dict(prog) for prog in programs.values() if prog["task_id"] in task_ids
        ]

get_shots

get_shots(
    *, shot_filter: ShotFilter | None = None
) -> Iterable[ShotResult]

Return in-memory shot rows matching a filter.

Other Parameters:

Name Type Description
shot_filter ShotFilter | None

Optional shot filter. When None, all shots are returned. Defaults to None.

Returns:

Type Description
Iterable[ShotResult]

Iterable[ShotResult]: Matching shot rows.

Source code in src/bloqade/core/device/local_storage.py
439
440
441
442
443
444
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
484
485
486
def get_shots(
    self,
    *,
    shot_filter: ShotFilter | None = None,
) -> Iterable[ShotResult]:
    """Return in-memory shot rows matching a filter.

    Keyword Args:
        shot_filter (ShotFilter | None): Optional shot filter. When None,
            all shots are returned. Defaults to None.

    Returns:
        Iterable[ShotResult]: Matching shot rows.
    """
    if shot_filter is None:
        yield from self._data.values()
        return

    for val in self._data.values():
        if (
            shot_filter.task_ids is not None
            and val.task_id not in shot_filter.task_ids
        ):
            continue
        if (
            shot_filter.frame_type is not None
            and val.frame_type.upper() != shot_filter.frame_type
        ):
            continue
        if (
            shot_filter.subtask_indices is not None
            and val.subtask_index not in shot_filter.subtask_indices
        ):
            continue
        if (
            shot_filter.task_subtask_pairs is not None
            and (val.task_id, val.subtask_index)
            not in shot_filter.task_subtask_pairs
        ):
            continue

        if (
            shot_filter.task_shot_pairs is not None
            and (val.task_id, val.shot_index) not in shot_filter.task_shot_pairs
        ):
            continue

        yield val

get_subtasks

get_subtasks(
    storage_filter: StorageFilter | None = None,
) -> list[dict]

Return stored subtask records.

Parameters:

Name Type Description Default
storage_filter StorageFilter | None

Optional metadata filter. When None, all subtasks are returned. Defaults to None.

None

Returns:

Type Description
list[dict]

list[dict]: Independent subtask dictionaries.

Source code in src/bloqade/core/device/local_storage.py
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
def get_subtasks(self, storage_filter: StorageFilter | None = None) -> list[dict]:
    """Return stored subtask records.

    Args:
        storage_filter (StorageFilter | None): Optional metadata filter.
            When None, all subtasks are returned. Defaults to None.

    Returns:
        list[dict]: Independent subtask dictionaries.
    """
    subtasks = self._metadata.get("subtasks")
    if subtasks is None:
        return []

    if storage_filter is None:
        # NOTE: extra dict call so we return a copy and can safely mutate the result
        return list(map(dict, subtasks.values()))

    filtered_subtasks = []
    for subtask in subtasks.values():
        if (
            storage_filter.task_ids is not None
            and subtask["task_id"] not in storage_filter.task_ids
        ):
            continue
        if (
            storage_filter.subtask_indices is not None
            and subtask["subtask_index"] not in storage_filter.subtask_indices
        ):
            continue

        if (
            storage_filter.task_subtask_pairs is not None
            and (subtask["task_id"], subtask["subtask_index"])
            not in storage_filter.task_subtask_pairs
        ):
            continue

        # NOTE: extra dict call so we return a copy and can safely mutate the result
        filtered_subtasks.append(dict(subtask))
    return filtered_subtasks

get_task_creation_time

get_task_creation_time(task_id: str) -> datetime.datetime

Return the creation time for a stored task.

Parameters:

Name Type Description Default
task_id str

Backend task ID.

required

Returns:

Type Description
datetime

datetime.datetime: Stored task creation time.

Raises:

Type Description
KeyError

If task_id is not present.

Source code in src/bloqade/core/device/local_storage.py
562
563
564
565
566
567
568
569
570
571
572
573
574
def get_task_creation_time(self, task_id: str) -> datetime.datetime:
    """Return the creation time for a stored task.

    Args:
        task_id (str): Backend task ID.

    Returns:
        datetime.datetime: Stored task creation time.

    Raises:
        KeyError: If `task_id` is not present.
    """
    return self._metadata["task_definitions"][task_id]["creation_time"]

task_ids

task_ids() -> set[str]

Return task IDs with stored task definitions.

Returns:

Type Description
set[str]

set[str]: Stored task IDs.

Source code in src/bloqade/core/device/local_storage.py
488
489
490
491
492
493
494
495
496
497
498
def task_ids(self) -> set[str]:
    """Return task IDs with stored task definitions.

    Returns:
        set[str]: Stored task IDs.
    """
    task_defs = self._metadata.get("task_definitions")
    if task_defs is None:
        return set()

    return set(task_defs.keys())

update_subtasks_completed_date

update_subtasks_completed_date(
    task_id, subtasks: list[dict]
) -> None

Update completion times for stored subtasks.

Parameters:

Name Type Description Default
task_id str

Backend task ID.

required
subtasks list[dict]

API subtask dictionaries containing completed_date and shot_results whose entries carry the subtask_index. The subtask object itself has no index.

required
Source code in src/bloqade/core/device/local_storage.py
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
def update_subtasks_completed_date(self, task_id, subtasks: list[dict]) -> None:
    """Update completion times for stored subtasks.

    Args:
        task_id (str): Backend task ID.
        subtasks (list[dict]): API subtask dictionaries containing
            `completed_date` and `shot_results` whose entries carry the
            `subtask_index`. The subtask object itself has no index.
    """
    current_subtasks = self._metadata.get("subtasks")
    if current_subtasks is None:
        return

    for subtask in subtasks:
        completed_date = subtask.get("completed_date")
        if completed_date is None:
            continue

        shot_results = subtask.get("shot_results", [])
        if len(shot_results) == 0:
            # completed but empty? should be unreachable, but who knows
            continue

        idx = shot_results[0]["subtask_index"]
        if (task_id, idx) not in current_subtasks:
            continue

        if isinstance(completed_date, str):
            completed_date = datetime.datetime.fromisoformat(completed_date)

        current_subtasks[(task_id, idx)]["completed_date"] = completed_date

SQLiteStorage

SQLiteStorage(db_file: str)

Bases: StorageBackend


              flowchart TD
              bloqade.core.device.local_storage.SQLiteStorage[SQLiteStorage]
              bloqade.core.device.local_storage.StorageBackend[StorageBackend]

                              bloqade.core.device.local_storage.StorageBackend --> bloqade.core.device.local_storage.SQLiteStorage
                


              click bloqade.core.device.local_storage.SQLiteStorage href "" "bloqade.core.device.local_storage.SQLiteStorage"
              click bloqade.core.device.local_storage.StorageBackend href "" "bloqade.core.device.local_storage.StorageBackend"
            

SQLite-backed storage for shot results.

Use this backend to persist shots and task metadata across Python sessions. When used with a future, close the connection after fetching is complete, for example:

with SQLiteStorage("my_database.sql") as store:
    future = task.run_async(..., storage=store)

Otherwise, garbage collection closes the connection later, which may keep the file lock open longer than expected.

Parameters:

Name Type Description Default
db_file str

Path to the SQLite database file.

required

Raises:

Type Description
ValueError

If the stored schema version does not match this package's expected schema version.

Source code in src/bloqade/core/device/local_storage.py
690
691
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
724
725
726
727
728
729
730
731
732
733
734
735
736
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
def __init__(self, db_file: str):
    """Initialize a SQLite storage backend.

    Args:
        db_file (str): Path to the SQLite database file.

    Raises:
        ValueError: If the stored schema version does not match this
            package's expected schema version.
    """
    self.conn = sqlite3.connect(db_file)
    self.conn.row_factory = sqlite3.Row
    self.conn.execute("""
        CREATE TABLE IF NOT EXISTS results (
            row_number INTEGER PRIMARY KEY AUTOINCREMENT,
            task_id TEXT NOT NULL,
            shot_index INTEGER NOT NULL,
            subtask_index INTEGER NOT NULL,
            subtask_shot_index INTEGER NOT NULL,
            frame_type TEXT NOT NULL,
            bitstring TEXT NOT NULL,
            UNIQUE(task_id, shot_index, frame_type)
        )
        """)

    self.conn.execute("""
        CREATE TABLE IF NOT EXISTS bloqade_schema (
            version_number TEXT PRIMARY KEY
        )
        """)
    self.conn.execute(
        """
        INSERT OR IGNORE INTO bloqade_schema (version_number) VALUES (?)
        """,
        (_BloqadeSchemaVersion.version,),
    )

    self.conn.execute("""
        CREATE TABLE IF NOT EXISTS programs (
            task_id TEXT,
            program_index INT,
            content TEXT NOT NULL,
            PRIMARY KEY (task_id, program_index)
        )
        """)

    self.conn.execute("""
        CREATE TABLE IF NOT EXISTS subtasks (
            task_id TEXT NOT NULL,
            subtask_index INT NOT NULL,
            program_index INT NOT NULL,
            num_shots INT NOT NULL,
            arguments TEXT,
            metadata TEXT,
            completed_date TEXT,
            PRIMARY KEY (task_id, subtask_index)
        )
        """)

    self.conn.execute("""
        CREATE TABLE IF NOT EXISTS task_definitions (
            task_id TEXT PRIMARY KEY,
            program_language TEXT NOT NULL,
            creation_time TEXT NOT NULL
        )
        """)

    cur = self.conn.execute("SELECT version_number FROM bloqade_schema")
    (stored_version,) = cur.fetchone()
    if stored_version != _BloqadeSchemaVersion.version:
        raise ValueError(
            f"Schema version mismatch: expected {_BloqadeSchemaVersion.version}, found {stored_version}"
        )

    self.conn.commit()

__enter__

__enter__()

Return this storage backend for use as a context manager.

Returns:

Name Type Description
SQLiteStorage

This storage instance.

Source code in src/bloqade/core/device/local_storage.py
1112
1113
1114
1115
1116
1117
1118
def __enter__(self):
    """Return this storage backend for use as a context manager.

    Returns:
        SQLiteStorage: This storage instance.
    """
    return self

__exit__

__exit__(type, value, traceback)

Close the SQLite connection when leaving a context manager.

Source code in src/bloqade/core/device/local_storage.py
1120
1121
1122
def __exit__(self, type, value, traceback):
    """Close the SQLite connection when leaving a context manager."""
    self.close()

add_shots

add_shots(shots: Iterable[ShotResult]) -> None

Store shot result rows in SQLite.

Parameters:

Name Type Description Default
shots Iterable[ShotResult]

Shot rows to store.

required
Source code in src/bloqade/core/device/local_storage.py
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
def add_shots(self, shots: Iterable[ShotResult]) -> None:
    """Store shot result rows in SQLite.

    Args:
        shots (Iterable[ShotResult]): Shot rows to store.
    """
    # TODO: optionally compress bit string data
    self.conn.executemany(
        """
        INSERT OR IGNORE INTO results (task_id, shot_index, subtask_index, subtask_shot_index, frame_type, bitstring)
        VALUES (?, ?, ?, ?, ?, ?)
        """,
        (
            (
                shot.task_id,
                shot.shot_index,
                shot.subtask_index,
                shot.subtask_shot_index,
                shot.frame_type,
                "".join(str(int(b)) for b in shot.bitstring),
            )
            for shot in shots
        ),
    )
    self.conn.commit()

add_task_definition

add_task_definition(
    task_id: str,
    task_definition: TaskDefinition,
    creation_time: datetime,
)

Store a task definition and creation time in SQLite.

Parameters:

Name Type Description Default
task_id str

Backend task ID.

required
task_definition TaskDefinition

Task definition to store.

required
creation_time datetime

Backend task creation time.

required
Source code in src/bloqade/core/device/local_storage.py
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def add_task_definition(
    self,
    task_id: str,
    task_definition: TaskDefinition,
    creation_time: datetime.datetime,
):
    """Store a task definition and creation time in SQLite.

    Args:
        task_id (str): Backend task ID.
        task_definition (TaskDefinition): Task definition to store.
        creation_time (datetime.datetime): Backend task creation time.
    """
    programs = task_definition.programs
    subtasks = task_definition.subtasks

    # task_id, program_index, content
    program_rows = [(task_id, i, programs[i].content) for i in range(len(programs))]

    subtask_rows = []
    for i in range(len(subtasks)):
        # task_id, subtask_index, program_index, num_shots, arguments, metadata
        subtask_row = [task_id, i, subtasks[i].program_index, subtasks[i].num_shots]

        if subtasks[i].arguments is not None:
            subtask_row.append(json.dumps(subtasks[i].arguments))
        else:
            subtask_row.append(None)

        subtask_metadata = subtasks[i].subtask_metadata
        if subtask_metadata is not None:
            subtask_row.append(subtask_metadata.model_dump_json())
        else:
            subtask_row.append(None)

        subtask_rows.append(tuple(subtask_row))

    self.conn.executemany(
        "INSERT OR IGNORE INTO programs (task_id, program_index, content) VALUES (?, ?, ?)",
        program_rows,
    )

    self.conn.executemany(
        "INSERT OR IGNORE INTO subtasks (task_id, subtask_index, program_index, num_shots, arguments, metadata) VALUES (?, ?, ?, ?, ?, ?)",
        subtask_rows,
    )

    creation_time_str = self._datetime_to_sql_txt(creation_time)
    self.conn.execute(
        "INSERT OR IGNORE INTO task_definitions (task_id, program_language, creation_time) VALUES (?, ?, ?)",
        (task_id, task_definition.program_language, creation_time_str),
    )

    self.conn.commit()

close

close()

Close the SQLite connection.

Source code in src/bloqade/core/device/local_storage.py
898
899
900
def close(self):
    """Close the SQLite connection."""
    self.conn.close()

get_program_language

get_program_language(task_id: str) -> str

Return the program language for a stored task definition.

Parameters:

Name Type Description Default
task_id str

Backend task ID.

required

Returns:

Name Type Description
str str

Stored program language.

Raises:

Type Description
KeyError

If task_id is not present.

Source code in src/bloqade/core/device/local_storage.py
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
def get_program_language(self, task_id: str) -> str:
    """Return the program language for a stored task definition.

    Args:
        task_id (str): Backend task ID.

    Returns:
        str: Stored program language.

    Raises:
        KeyError: If `task_id` is not present.
    """
    cursor = self.conn.execute(
        "SELECT program_language FROM task_definitions WHERE task_id = (?)",
        (task_id,),
    )
    row = cursor.fetchone()
    if row is None:
        raise KeyError(task_id)
    else:
        return row[0]

get_programs

get_programs(
    task_ids: tuple[str, ...] | None = None,
) -> list[dict]

Return stored program records.

Parameters:

Name Type Description Default
task_ids tuple[str, ...] | None

Optional task IDs to include. When None, programs for all stored tasks are returned. Defaults to None.

None

Returns:

Type Description
list[dict]

list[dict]: Program dictionaries ordered by task ID and program index.

Source code in src/bloqade/core/device/local_storage.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
def get_programs(self, task_ids: tuple[str, ...] | None = None) -> list[dict]:
    """Return stored program records.

    Args:
        task_ids (tuple[str, ...] | None): Optional task IDs to include.
            When None, programs for all stored tasks are returned. Defaults
            to None.

    Returns:
        list[dict]: Program dictionaries ordered by task ID and program
            index.
    """
    query = "SELECT * FROM programs"
    if task_ids is not None:
        placeholders = ", ".join("?" for _ in task_ids)
        query += f" WHERE task_id IN ({placeholders})"
    else:
        task_ids = ()
    query += " ORDER BY task_id, program_index"
    cursor = self.conn.execute(
        query,
        task_ids,
    )
    return list(map(dict, cursor))

get_shots

get_shots(
    *, shot_filter: ShotFilter | None = None
) -> Iterable[ShotResult]

Return SQLite shot rows matching a filter.

Other Parameters:

Name Type Description
shot_filter ShotFilter | None

Optional shot filter. When None, all shots are returned. Defaults to None.

Returns:

Type Description
Iterable[ShotResult]

Iterable[ShotResult]: Matching shot rows.

Source code in src/bloqade/core/device/local_storage.py
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
def get_shots(
    self,
    *,
    shot_filter: ShotFilter | None = None,
) -> Iterable[ShotResult]:
    """Return SQLite shot rows matching a filter.

    Keyword Args:
        shot_filter (ShotFilter | None): Optional shot filter. When None,
            all shots are returned. Defaults to None.

    Returns:
        Iterable[ShotResult]: Matching shot rows.
    """
    query = "SELECT * FROM results"

    where_clauses, filter_values = self._shot_filter_to_where_clause(shot_filter)
    if where_clauses:
        query += " WHERE " + " AND ".join(where_clauses)

    cur = self.conn.execute(query, filter_values)

    for row in cur:
        shot = ShotResult(
            task_id=row["task_id"],
            shot_index=row["shot_index"],
            subtask_index=row["subtask_index"],
            subtask_shot_index=row["subtask_shot_index"],
            frame_type=row["frame_type"],
            bitstring=np.array(list(row["bitstring"]), dtype=np.uint8).view(bool),
        )
        yield shot

get_subtasks

get_subtasks(
    storage_filter: StorageFilter | None = None,
) -> list[dict]

Return stored subtask records.

Parameters:

Name Type Description Default
storage_filter StorageFilter | None

Optional metadata filter. When None, all subtasks are returned. Defaults to None.

None

Returns:

Type Description
list[dict]

list[dict]: Subtask dictionaries ordered by task ID and subtask index.

Source code in src/bloqade/core/device/local_storage.py
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
def get_subtasks(self, storage_filter: StorageFilter | None = None) -> list[dict]:
    """Return stored subtask records.

    Args:
        storage_filter (StorageFilter | None): Optional metadata filter.
            When None, all subtasks are returned. Defaults to None.

    Returns:
        list[dict]: Subtask dictionaries ordered by task ID and subtask
            index.
    """
    query = "SELECT * FROM subtasks"
    where_clauses, filter_values = self._storage_filter_to_where_clause(
        storage_filter
    )
    if where_clauses:
        query += " WHERE " + " AND ".join(where_clauses)

    query += " ORDER BY task_id, subtask_index"

    cursor = self.conn.execute(query, filter_values)
    subtasks = []
    for row in cursor:
        subtask = dict(row)
        arguments = row["arguments"]
        if arguments is not None:
            subtask["arguments"] = json.loads(arguments)
        metadata = row["metadata"]
        if metadata is not None:
            subtask["metadata"] = json.loads(metadata)
        completed_date = subtask["completed_date"]
        if completed_date is not None:
            subtask["completed_date"] = self._sql_txt_to_datetime(completed_date)
        subtasks.append(subtask)
    return subtasks

get_task_creation_time

get_task_creation_time(task_id: str) -> datetime.datetime

Return the creation time for a stored task.

Parameters:

Name Type Description Default
task_id str

Backend task ID.

required

Returns:

Type Description
datetime

datetime.datetime: Stored task creation time.

Raises:

Type Description
KeyError

If task_id is not present.

Source code in src/bloqade/core/device/local_storage.py
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
def get_task_creation_time(self, task_id: str) -> datetime.datetime:
    """Return the creation time for a stored task.

    Args:
        task_id (str): Backend task ID.

    Returns:
        datetime.datetime: Stored task creation time.

    Raises:
        KeyError: If `task_id` is not present.
    """
    cursor = self.conn.execute(
        "SELECT creation_time FROM task_definitions WHERE task_id = (?)",
        (task_id,),
    )
    row = cursor.fetchone()
    if row is None:
        raise KeyError(task_id)
    else:
        return self._sql_txt_to_datetime(row[0])

task_ids

task_ids() -> set[str]

Return task IDs with stored task definitions.

Returns:

Type Description
set[str]

set[str]: Stored task IDs.

Source code in src/bloqade/core/device/local_storage.py
902
903
904
905
906
907
908
909
def task_ids(self) -> set[str]:
    """Return task IDs with stored task definitions.

    Returns:
        set[str]: Stored task IDs.
    """
    cur = self.conn.execute("SELECT task_id FROM task_definitions")
    return {row["task_id"] for row in cur}

update_subtasks_completed_date

update_subtasks_completed_date(
    task_id, subtasks: list[dict]
) -> None

Update completion times for stored subtasks.

Parameters:

Name Type Description Default
task_id str

Backend task ID.

required
subtasks list[dict]

API subtask dictionaries containing completed_date and shot_results whose entries carry the subtask_index. The subtask object itself has no index.

required
Source code in src/bloqade/core/device/local_storage.py
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
def update_subtasks_completed_date(self, task_id, subtasks: list[dict]) -> None:
    """Update completion times for stored subtasks.

    Args:
        task_id (str): Backend task ID.
        subtasks (list[dict]): API subtask dictionaries containing
            `completed_date` and `shot_results` whose entries carry the
            `subtask_index`. The subtask object itself has no index.
    """
    values = []
    for subtask in subtasks:
        completed_date = subtask.get("completed_date")
        if completed_date is None:
            continue

        shot_results = subtask.get("shot_results", [])
        if len(shot_results) == 0:
            # completed but empty? should be unreachable, but who knows
            continue

        idx = shot_results[0]["subtask_index"]

        if isinstance(completed_date, datetime.datetime):
            completed_date_str = completed_date.isoformat()
        else:
            completed_date_str = completed_date
        values.append((completed_date_str, task_id, idx))
    self.conn.executemany(
        "UPDATE subtasks SET completed_date = (?) WHERE task_id = (?) AND subtask_index = (?)",
        values,
    )
    self.conn.commit()

ShotFilter dataclass

ShotFilter(
    task_ids: tuple[str, ...] | None = None,
    subtask_indices: tuple[int, ...] | None = None,
    task_subtask_pairs: (
        tuple[tuple[str, int], ...] | None
    ) = None,
    frame_type: str | None = None,
    task_shot_pairs: (
        tuple[tuple[str, int], ...] | None
    ) = None,
)

Bases: StorageFilter


              flowchart TD
              bloqade.core.device.local_storage.ShotFilter[ShotFilter]
              bloqade.core.device.local_storage.StorageFilter[StorageFilter]

                              bloqade.core.device.local_storage.StorageFilter --> bloqade.core.device.local_storage.ShotFilter
                


              click bloqade.core.device.local_storage.ShotFilter href "" "bloqade.core.device.local_storage.ShotFilter"
              click bloqade.core.device.local_storage.StorageFilter href "" "bloqade.core.device.local_storage.StorageFilter"
            

Filter for shot result rows.

Extends StorageFilter with frame-type and shot-pair criteria. frame_type is normalized to uppercase during initialization.

Attributes:

Name Type Description
frame_type str | None

Frame type to include. Defaults to None.

task_shot_pairs tuple[tuple[str, int], ...] | None

Exact (task_id, shot_index) pairs to include. Defaults to None.

ShotResult dataclass

ShotResult(
    task_id: str,
    shot_index: int,
    subtask_index: int,
    subtask_shot_index: int,
    frame_type: str,
    bitstring: ndarray,
)

Stored result for one shot and frame type.

Attributes:

Name Type Description
task_id str

Backend task ID that produced the shot.

shot_index int

Shot index within the task.

subtask_index int

Subtask index within the task definition.

subtask_shot_index int

Shot index local to the subtask.

frame_type str

Result frame type, such as "DETECTED".

bitstring ndarray

Boolean measurement bitstring.

StorageBackend

Bases: ABC


              flowchart TD
              bloqade.core.device.local_storage.StorageBackend[StorageBackend]

              

              click bloqade.core.device.local_storage.StorageBackend href "" "bloqade.core.device.local_storage.StorageBackend"
            

Abstract storage backend for shot results.

Implementations store shot rows together with enough task metadata to reconstruct TaskDefinition objects and create Result views.

NOTE: methods that return mutable dictionaries should return independent copies. Result helpers may mutate returned metadata records while building merged views.

add_shots abstractmethod

add_shots(shots: Iterable[ShotResult]) -> None

Store shot result rows.

Parameters:

Name Type Description Default
shots Iterable[ShotResult]

Shot rows to store.

required
Source code in src/bloqade/core/device/local_storage.py
 98
 99
100
101
102
103
104
105
@abstractmethod
def add_shots(self, shots: Iterable[ShotResult]) -> None:
    """Store shot result rows.

    Args:
        shots (Iterable[ShotResult]): Shot rows to store.
    """
    ...

add_task_definition abstractmethod

add_task_definition(
    task_id: str,
    task_definition: TaskDefinition,
    creation_time: datetime,
)

Store a task definition and its creation time.

Parameters:

Name Type Description Default
task_id str

Backend task ID.

required
task_definition TaskDefinition

Task definition to store.

required
creation_time datetime

Backend task creation time.

required
Source code in src/bloqade/core/device/local_storage.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
@abstractmethod
def add_task_definition(
    self,
    task_id: str,
    task_definition: TaskDefinition,
    creation_time: datetime.datetime,
):
    """Store a task definition and its creation time.

    Args:
        task_id (str): Backend task ID.
        task_definition (TaskDefinition): Task definition to store.
        creation_time (datetime.datetime): Backend task creation time.
    """
    ...

filter_by_arguments

filter_by_arguments(
    predicate: Callable[[dict | None], bool],
    storage_filter: StorageFilter | None = None,
) -> StorageFilter

Build a filter from subtask arguments matching a predicate.

Parameters:

Name Type Description Default
predicate Callable[[dict | None], bool]

Predicate applied to each selected subtask's arguments.

required
storage_filter StorageFilter | None

Optional filter used before evaluating the predicate. Defaults to None.

None

Returns:

Name Type Description
StorageFilter StorageFilter

Filter containing matching (task_id, subtask_index) pairs.

Source code in src/bloqade/core/device/local_storage.py
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
def filter_by_arguments(
    self,
    predicate: Callable[[dict | None], bool],
    storage_filter: StorageFilter | None = None,
) -> StorageFilter:
    """Build a filter from subtask arguments matching a predicate.

    Args:
        predicate (Callable[[dict | None], bool]): Predicate applied to each
            selected subtask's arguments.
        storage_filter (StorageFilter | None): Optional filter used before
            evaluating the predicate. Defaults to None.

    Returns:
        StorageFilter: Filter containing matching `(task_id, subtask_index)`
            pairs.
    """
    subtasks = self.get_subtasks(storage_filter=storage_filter)

    task_subtask_pairs = []
    for subtask in subtasks:
        arguments = subtask.get("arguments")
        if not predicate(arguments):
            continue
        task_subtask_pairs.append((subtask["task_id"], subtask["subtask_index"]))

    return StorageFilter(task_subtask_pairs=tuple(task_subtask_pairs))

filter_by_metadata

filter_by_metadata(
    predicate: Callable[[dict | None], bool],
    storage_filter: StorageFilter | None = None,
) -> StorageFilter

Build a filter from JSON-decoded user metadata.

This expects metadata to have been set as a dictionary and serialized as JSON. If metadata cannot be deserialized by JSON, fetch and filter the subtasks manually.

Parameters:

Name Type Description Default
predicate Callable[[dict | None], bool]

Predicate applied to each selected subtask's decoded user_metadata.

required
storage_filter StorageFilter | None

Optional filter used before evaluating the predicate. Defaults to None.

None

Returns:

Name Type Description
StorageFilter StorageFilter

Filter containing matching (task_id, subtask_index) pairs.

Source code in src/bloqade/core/device/local_storage.py
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
def filter_by_metadata(
    self,
    predicate: Callable[[dict | None], bool],
    storage_filter: StorageFilter | None = None,
) -> StorageFilter:
    """Build a filter from JSON-decoded user metadata.

    This expects metadata to have been set as a dictionary and serialized as
    JSON. If metadata cannot be deserialized by JSON, fetch and filter the
    subtasks manually.

    Args:
        predicate (Callable[[dict | None], bool]): Predicate applied to each
            selected subtask's decoded `user_metadata`.
        storage_filter (StorageFilter | None): Optional filter used before
            evaluating the predicate. Defaults to None.

    Returns:
        StorageFilter: Filter containing matching `(task_id, subtask_index)`
            pairs.
    """
    subtasks = self.get_subtasks(storage_filter=storage_filter)

    task_subtask_pairs = []
    for subtask in subtasks:
        metadata = subtask["metadata"]
        if metadata is None:
            user_metadata = None
        else:
            user_metadata_str = metadata["user_metadata"]
            user_metadata = (
                json.loads(user_metadata_str)
                if user_metadata_str is not None
                else None
            )

        if not predicate(user_metadata):
            continue

        task_subtask_pairs.append((subtask["task_id"], subtask["subtask_index"]))

    return StorageFilter(task_subtask_pairs=tuple(task_subtask_pairs))

filter_by_shots

filter_by_shots(
    predicate: Callable[[ShotResult], bool],
    shot_filter: ShotFilter | None = None,
) -> ShotFilter

Build a filter from shots matching a predicate.

Parameters:

Name Type Description Default
predicate Callable[[ShotResult], bool]

Predicate applied to each selected shot.

required
shot_filter ShotFilter | None

Optional filter used before evaluating the predicate. Defaults to None.

None

Returns:

Name Type Description
ShotFilter ShotFilter

Filter containing matching (task_id, shot_index) pairs.

Source code in src/bloqade/core/device/local_storage.py
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
def filter_by_shots(
    self,
    predicate: Callable[[ShotResult], bool],
    shot_filter: ShotFilter | None = None,
) -> ShotFilter:
    """Build a filter from shots matching a predicate.

    Args:
        predicate (Callable[[ShotResult], bool]): Predicate applied to each
            selected shot.
        shot_filter (ShotFilter | None): Optional filter used before
            evaluating the predicate. Defaults to None.

    Returns:
        ShotFilter: Filter containing matching `(task_id, shot_index)`
            pairs.
    """
    shots = self.get_shots(shot_filter=shot_filter)

    task_shot_pairs = []
    for shot in shots:
        if not predicate(shot):
            continue

        task_shot_pairs.append((shot.task_id, shot.shot_index))

    return ShotFilter(
        task_shot_pairs=tuple(task_shot_pairs),
    )

filter_by_subtasks

filter_by_subtasks(
    predicate: Callable[[dict], bool],
    storage_filter: StorageFilter | None = None,
) -> StorageFilter

Build a filter from subtasks matching a predicate.

Parameters:

Name Type Description Default
predicate Callable[[dict], bool]

Predicate applied to each selected subtask dictionary.

required
storage_filter StorageFilter | None

Optional filter used before evaluating the predicate. Defaults to None.

None

Returns:

Name Type Description
StorageFilter StorageFilter

Filter containing matching (task_id, subtask_index) pairs.

Source code in src/bloqade/core/device/local_storage.py
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
def filter_by_subtasks(
    self,
    predicate: Callable[[dict], bool],
    storage_filter: StorageFilter | None = None,
) -> StorageFilter:
    """Build a filter from subtasks matching a predicate.

    Args:
        predicate (Callable[[dict], bool]): Predicate applied to each
            selected subtask dictionary.
        storage_filter (StorageFilter | None): Optional filter used before
            evaluating the predicate. Defaults to None.

    Returns:
        StorageFilter: Filter containing matching `(task_id, subtask_index)`
            pairs.
    """

    subtasks = self.get_subtasks(storage_filter=storage_filter)
    task_subtask_pairs = []
    for subtask in subtasks:
        if not predicate(subtask):
            continue

        task_subtask_pairs.append((subtask["task_id"], subtask["subtask_index"]))

    return StorageFilter(
        task_subtask_pairs=tuple(task_subtask_pairs),
    )

get_arguments

get_arguments(
    storage_filter: StorageFilter | None = None,
) -> list[dict | None]

Return arguments from stored subtasks.

Parameters:

Name Type Description Default
storage_filter StorageFilter | None

Optional subtask metadata filter. Defaults to None.

None

Returns:

Type Description
list[dict | None]

list[dict | None]: Arguments from matching subtasks.

Source code in src/bloqade/core/device/local_storage.py
263
264
265
266
267
268
269
270
271
272
273
274
275
276
def get_arguments(
    self, storage_filter: StorageFilter | None = None
) -> list[dict | None]:
    """Return arguments from stored subtasks.

    Args:
        storage_filter (StorageFilter | None): Optional subtask metadata
            filter. Defaults to None.

    Returns:
        list[dict | None]: Arguments from matching subtasks.
    """
    subtasks = self.get_subtasks(storage_filter=storage_filter)
    return [subtask["arguments"] for subtask in subtasks]

get_program_language abstractmethod

get_program_language(task_id: str) -> str

Return the program language for a stored task definition.

Parameters:

Name Type Description Default
task_id str

Backend task ID.

required

Returns:

Name Type Description
str str

Program language stored for the task.

Raises:

Type Description
KeyError

If task_id is not present.

Source code in src/bloqade/core/device/local_storage.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
@abstractmethod
def get_program_language(self, task_id: str) -> str:
    """Return the program language for a stored task definition.

    Args:
        task_id (str): Backend task ID.

    Returns:
        str: Program language stored for the task.

    Raises:
        KeyError: If `task_id` is not present.
    """
    ...

get_programs abstractmethod

get_programs(
    task_ids: tuple[str, ...] | None = None,
) -> list[dict]

Return stored program records.

Parameters:

Name Type Description Default
task_ids tuple[str, ...] | None

Optional task IDs to include. When None, programs for all stored task IDs are returned. Defaults to None.

None

Returns:

Type Description
list[dict]

list[dict]: Program dictionaries with task_id, program_index, and content.

Source code in src/bloqade/core/device/local_storage.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
@abstractmethod
def get_programs(self, task_ids: tuple[str, ...] | None = None) -> list[dict]:
    """Return stored program records.

    Args:
        task_ids (tuple[str, ...] | None): Optional task IDs to include.
            When None, programs for all stored task IDs are returned.
            Defaults to None.

    Returns:
        list[dict]: Program dictionaries with `task_id`, `program_index`,
            and `content`.
    """
    ...

get_shots abstractmethod

get_shots(
    *, shot_filter: ShotFilter | None = None
) -> Iterable[ShotResult]

Return stored shot rows matching a filter.

Other Parameters:

Name Type Description
shot_filter ShotFilter | None

Optional shot filter. When None, all shots are returned. Defaults to None.

Returns:

Type Description
Iterable[ShotResult]

Iterable[ShotResult]: Matching shot rows.

Source code in src/bloqade/core/device/local_storage.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
@abstractmethod
def get_shots(
    self,
    *,
    shot_filter: ShotFilter | None = None,
) -> Iterable[ShotResult]:
    """Return stored shot rows matching a filter.

    Keyword Args:
        shot_filter (ShotFilter | None): Optional shot filter. When None,
            all shots are returned. Defaults to None.

    Returns:
        Iterable[ShotResult]: Matching shot rows.
    """
    ...

get_subtasks abstractmethod

get_subtasks(
    storage_filter: StorageFilter | None = None,
) -> list[dict]

Return stored subtask records.

Parameters:

Name Type Description Default
storage_filter StorageFilter | None

Optional subtask metadata filter. When None, all subtasks are returned. Defaults to None.

None

Returns:

Type Description
list[dict]

list[dict]: Subtask dictionaries, including task ID, subtask index, program index, shot count, arguments, metadata, and completion date.

Source code in src/bloqade/core/device/local_storage.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
@abstractmethod
def get_subtasks(self, storage_filter: StorageFilter | None = None) -> list[dict]:
    """Return stored subtask records.

    Args:
        storage_filter (StorageFilter | None): Optional subtask metadata
            filter. When None, all subtasks are returned. Defaults to None.

    Returns:
        list[dict]: Subtask dictionaries, including task ID, subtask index,
            program index, shot count, arguments, metadata, and completion
            date.
    """
    ...

get_task_creation_time abstractmethod

get_task_creation_time(task_id: str) -> datetime.datetime

Return the creation time for a stored task.

Parameters:

Name Type Description Default
task_id str

Backend task ID.

required

Returns:

Type Description
datetime

datetime.datetime: Stored task creation time.

Raises:

Type Description
KeyError

If task_id is not present.

Source code in src/bloqade/core/device/local_storage.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
@abstractmethod
def get_task_creation_time(self, task_id: str) -> datetime.datetime:
    """Return the creation time for a stored task.

    Args:
        task_id (str): Backend task ID.

    Returns:
        datetime.datetime: Stored task creation time.

    Raises:
        KeyError: If `task_id` is not present.
    """
    ...

get_task_definition

get_task_definition(task_id: str) -> TaskDefinition

Reconstruct a task definition from stored metadata.

Parameters:

Name Type Description Default
task_id str

Backend task ID.

required

Returns:

Name Type Description
TaskDefinition TaskDefinition

Reconstructed task definition.

Source code in src/bloqade/core/device/local_storage.py
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
def get_task_definition(self, task_id: str) -> TaskDefinition:
    """Reconstruct a task definition from stored metadata.

    Args:
        task_id (str): Backend task ID.

    Returns:
        TaskDefinition: Reconstructed task definition.
    """
    program_language = self.get_program_language(task_id=task_id)

    program_dicts = self.get_programs(task_ids=(task_id,))
    program_dicts.sort(key=lambda prog: prog["program_index"])

    subtask_dicts = self.get_subtasks(
        storage_filter=StorageFilter(task_ids=(task_id,))
    )
    subtask_dicts.sort(key=lambda subtask: subtask["subtask_index"])

    programs = [Program(content=prog["content"]) for prog in program_dicts]
    subtasks = []
    for subtask_dict in subtask_dicts:
        metadata = subtask_dict["metadata"]
        if metadata is None:
            subtask_metadata = None
        else:
            subtask_metadata = TaskMetadata(**metadata)
        subtasks.append(
            Subtask(
                program_index=subtask_dict["program_index"],
                num_shots=subtask_dict["num_shots"],
                arguments=subtask_dict["arguments"],
                subtask_metadata=subtask_metadata,
            )
        )

    return TaskDefinition(
        program_language=program_language,
        programs=programs,
        subtasks=subtasks,
    )

task_ids abstractmethod

task_ids() -> set[str]

Return task IDs with stored task definitions.

Returns:

Type Description
set[str]

set[str]: Stored task IDs.

Source code in src/bloqade/core/device/local_storage.py
124
125
126
127
128
129
130
131
@abstractmethod
def task_ids(self) -> set[str]:
    """Return task IDs with stored task definitions.

    Returns:
        set[str]: Stored task IDs.
    """
    ...

update_subtasks_completed_date abstractmethod

update_subtasks_completed_date(
    task_id, subtasks: list[dict]
) -> None

Update completion times for stored subtasks.

Parameters:

Name Type Description Default
task_id str

Backend task ID.

required
subtasks list[dict]

API subtask dictionaries containing completed_date and shot_results whose entries carry the subtask_index. The subtask object itself has no index.

required
Source code in src/bloqade/core/device/local_storage.py
209
210
211
212
213
214
215
216
217
218
219
@abstractmethod
def update_subtasks_completed_date(self, task_id, subtasks: list[dict]) -> None:
    """Update completion times for stored subtasks.

    Args:
        task_id (str): Backend task ID.
        subtasks (list[dict]): API subtask dictionaries containing
            `completed_date` and `shot_results` whose entries carry the
            `subtask_index`. The subtask object itself has no index.
    """
    ...

StorageFilter dataclass

StorageFilter(
    task_ids: tuple[str, ...] | None = None,
    subtask_indices: tuple[int, ...] | None = None,
    task_subtask_pairs: (
        tuple[tuple[str, int], ...] | None
    ) = None,
)

Filter for task and subtask metadata rows.

All separate filters are AND-ed. Use task_subtask_pairs to specify exact pairs rather than combining task_ids and subtask_indices independently.

Attributes:

Name Type Description
task_ids tuple[str, ...] | None

Task IDs to include. Defaults to None.

subtask_indices tuple[int, ...] | None

Subtask indices to include. Defaults to None.

task_subtask_pairs tuple[tuple[str, int], ...] | None

Exact (task_id, subtask_index) pairs to include. Defaults to None.

task_subtask_pairs class-attribute instance-attribute

task_subtask_pairs: tuple[tuple[str, int], ...] | None = (
    None
)

Exact pairs to use instead of separate task and subtask filters.