| 
 | 1 | +import logging  | 
 | 2 | +import pickle  | 
 | 3 | +import sqlite3  | 
 | 4 | +from concurrent.futures import Future  | 
 | 5 | +from pathlib import Path  | 
 | 6 | +from typing import Any, Optional  | 
 | 7 | + | 
 | 8 | +from parsl.dataflow.memoization import Memoizer, make_hash  | 
 | 9 | +from parsl.dataflow.taskrecord import TaskRecord  | 
 | 10 | + | 
 | 11 | +logger = logging.getLogger(__name__)  | 
 | 12 | + | 
 | 13 | + | 
 | 14 | +class SQLiteMemoizer(Memoizer):  | 
 | 15 | +    """Memoize out of memory into an sqlite3 database.  | 
 | 16 | +    """  | 
 | 17 | + | 
 | 18 | +    def __init__(self, *, checkpoint_dir: str | None = None):  | 
 | 19 | +        self.checkpoint_dir = checkpoint_dir  | 
 | 20 | + | 
 | 21 | +    def start(self, *, run_dir: str) -> None:  | 
 | 22 | +        """TODO: run_dir is the per-workflow run dir, but we need a broader checkpoint context... one level up  | 
 | 23 | +        by default... get_all_checkpoints uses "runinfo/" as a relative path for that by default so replicating  | 
 | 24 | +        that choice would do here. likewise I think for monitoring."""  | 
 | 25 | + | 
 | 26 | +        self.run_dir = run_dir  | 
 | 27 | + | 
 | 28 | +        dir = self.checkpoint_dir if self.checkpoint_dir is not None else self.run_dir  | 
 | 29 | + | 
 | 30 | +        self.db_path = Path(dir) / "checkpoint.sqlite3"  | 
 | 31 | +        logger.debug("starting with db_path %r", self.db_path)  | 
 | 32 | + | 
 | 33 | +        connection = sqlite3.connect(self.db_path)  | 
 | 34 | +        cursor = connection.cursor()  | 
 | 35 | + | 
 | 36 | +        cursor.execute("CREATE TABLE IF NOT EXISTS checkpoints(key, result)")  | 
 | 37 | +        # probably want some index on key because that's what we're doing all the access via.  | 
 | 38 | + | 
 | 39 | +        connection.commit()  | 
 | 40 | +        connection.close()  | 
 | 41 | +        logger.debug("checkpoint table created")  | 
 | 42 | + | 
 | 43 | +    def close(self):  | 
 | 44 | +        """TODO: probably going to need some kind of shutdown now, to close the sqlite3 connection."""  | 
 | 45 | +        pass  | 
 | 46 | + | 
 | 47 | +    def checkpoint(self, *, task: TaskRecord | None = None) -> None:  | 
 | 48 | +        """All the behaviour for this memoizer is in check_memo and update_memo.  | 
 | 49 | +        """  | 
 | 50 | +        logger.debug("Explicit checkpoint call is a no-op with this memoizer")  | 
 | 51 | + | 
 | 52 | +    def check_memo(self, task: TaskRecord) -> Optional[Future]:  | 
 | 53 | +        """TODO: document this: check_memo is required to set the task hashsum,  | 
 | 54 | +        if that's how we're going to key checkpoints in update_memo. (that's not  | 
 | 55 | +        a requirement though: other equalities are available."""  | 
 | 56 | +        task_id = task['id']  | 
 | 57 | + | 
 | 58 | +        if not task['memoize']:  | 
 | 59 | +            task['hashsum'] = None  | 
 | 60 | +            logger.debug("Task %s will not be memoized", task_id)  | 
 | 61 | +            return None  | 
 | 62 | + | 
 | 63 | +        hashsum = make_hash(task)  | 
 | 64 | +        logger.debug("Task {} has memoization hash {}".format(task_id, hashsum))  | 
 | 65 | +        task['hashsum'] = hashsum  | 
 | 66 | + | 
 | 67 | +        connection = sqlite3.connect(self.db_path)  | 
 | 68 | +        cursor = connection.cursor()  | 
 | 69 | +        cursor.execute("SELECT result FROM checkpoints WHERE key = ?", (hashsum, ))  | 
 | 70 | +        r = cursor.fetchone()  | 
 | 71 | + | 
 | 72 | +        if r is None:  | 
 | 73 | +            connection.close()  | 
 | 74 | +            return None  | 
 | 75 | +        else:  | 
 | 76 | +            data = pickle.loads(r[0])  | 
 | 77 | +            connection.close()  | 
 | 78 | + | 
 | 79 | +            memo_fu: Future = Future()  | 
 | 80 | + | 
 | 81 | +            if data['exception'] is None:  | 
 | 82 | +                memo_fu.set_result(data['result'])  | 
 | 83 | +            else:  | 
 | 84 | +                assert data['result'] is None  | 
 | 85 | +                memo_fu.set_exception(data['exception'])  | 
 | 86 | + | 
 | 87 | +            return memo_fu  | 
 | 88 | + | 
 | 89 | +    def update_memo_result(self, task: TaskRecord, result: Any) -> None:  | 
 | 90 | +        logger.debug("updating memo")  | 
 | 91 | + | 
 | 92 | +        if not task['memoize'] or 'hashsum' not in task:  | 
 | 93 | +            logger.debug("preconditions for memo not satisfied")  | 
 | 94 | +            return  | 
 | 95 | + | 
 | 96 | +        if not isinstance(task['hashsum'], str):  | 
 | 97 | +            logger.error(f"Attempting to update app cache entry but hashsum is not a string key: {task['hashsum']}")  | 
 | 98 | +            return  | 
 | 99 | + | 
 | 100 | +        hashsum = task['hashsum']  | 
 | 101 | + | 
 | 102 | +        # this comes from the original concatenation-based checkpoint code:  | 
 | 103 | +        # assert app_fu.done(), "assumption: update_memo is called after future has a result"  | 
 | 104 | +        t = {'hash': hashsum, 'exception': None, 'result': result}  | 
 | 105 | +        # else:  | 
 | 106 | +        #    t = {'hash': hashsum, 'exception': app_fu.exception(), 'result': None}  | 
 | 107 | + | 
 | 108 | +        value = pickle.dumps(t)  | 
 | 109 | + | 
 | 110 | +        connection = sqlite3.connect(self.db_path)  | 
 | 111 | +        cursor = connection.cursor()  | 
 | 112 | + | 
 | 113 | +        cursor.execute("INSERT INTO checkpoints VALUES(?, ?)", (hashsum, value))  | 
 | 114 | + | 
 | 115 | +        connection.commit()  | 
 | 116 | +        connection.close()  | 
 | 117 | + | 
 | 118 | +    def update_memo_exception(self, task: TaskRecord, exception: BaseException) -> None:  | 
 | 119 | +        logger.debug("updating memo")  | 
 | 120 | + | 
 | 121 | +        if not task['memoize'] or 'hashsum' not in task:  | 
 | 122 | +            logger.debug("preconditions for memo not satisfied")  | 
 | 123 | +            return  | 
 | 124 | + | 
 | 125 | +        if not isinstance(task['hashsum'], str):  | 
 | 126 | +            logger.error(f"Attempting to update app cache entry but hashsum is not a string key: {task['hashsum']}")  | 
 | 127 | +            return  | 
 | 128 | + | 
 | 129 | +        hashsum = task['hashsum']  | 
 | 130 | + | 
 | 131 | +        # this comes from the original concatenation-based checkpoint code:  | 
 | 132 | +        # assert app_fu.done(), "assumption: update_memo is called after future has a result"  | 
 | 133 | +        # t = {'hash': hashsum, 'exception': None, 'result': app_fu.result()}  | 
 | 134 | +        # else:  | 
 | 135 | +        t = {'hash': hashsum, 'exception': exception, 'result': None}  | 
 | 136 | + | 
 | 137 | +        value = pickle.dumps(t)  | 
 | 138 | + | 
 | 139 | +        connection = sqlite3.connect(self.db_path)  | 
 | 140 | +        cursor = connection.cursor()  | 
 | 141 | + | 
 | 142 | +        cursor.execute("INSERT INTO checkpoints VALUES(?, ?)", (hashsum, value))  | 
 | 143 | + | 
 | 144 | +        connection.commit()  | 
 | 145 | +        connection.close()  | 
0 commit comments