diff --git a/ipyparallel/client/client.py b/ipyparallel/client/client.py index 0e7fd64cd..56e47fb34 100644 --- a/ipyparallel/client/client.py +++ b/ipyparallel/client/client.py @@ -2208,6 +2208,9 @@ def result_status(self, msg_ids, status_only=True): If status_only is False, then the actual results will be retrieved, else only the status of the results will be checked. + The Hub can report a task as completed after discarding its result. + Requesting the discarded result from the Hub raises a remote ``KeyError``. + Parameters ---------- msg_ids : list of msg_ids diff --git a/ipyparallel/controller/dictdb.py b/ipyparallel/controller/dictdb.py index e9e67e775..9f0bb5932 100644 --- a/ipyparallel/controller/dictdb.py +++ b/ipyparallel/controller/dictdb.py @@ -40,7 +40,7 @@ from copy import deepcopy from datetime import datetime -from traitlets import Dict, Float, Integer, Unicode +from traitlets import Dict, Float, Integer, Set, Unicode from traitlets.config.configurable import LoggingConfigurable from ..util import ensure_timezone @@ -108,7 +108,7 @@ class DictDB(BaseDB): """ _records = Dict() - _culled_ids = set() # set of ids which have been culled + _culled_ids = Set() # set of ids which have been culled _buffer_bytes = Integer(0) # running total of the bytes in the DB size_limit = Integer( @@ -240,6 +240,9 @@ def _check_dates(self, rec): def add_record(self, msg_id, rec): """Add a new Task Record, by msg_id.""" + if msg_id in self._culled_ids: + # A running task can be culled before its output arrives. + return if msg_id in self._records: raise KeyError(f"Already have msg_id {msg_id!r}") self._check_dates(rec) diff --git a/ipyparallel/controller/hub.py b/ipyparallel/controller/hub.py index 282ffa10f..ab2c5705d 100644 --- a/ipyparallel/controller/hub.py +++ b/ipyparallel/controller/hub.py @@ -824,6 +824,9 @@ def save_iopub_message(self, topics, msg): try: rec = self.db.get_record(msg_id) except KeyError: + if msg_id in self.all_completed: + # The result was removed before this output arrived. + return rec = None # stream @@ -1395,9 +1398,7 @@ def get_results(self, client_id, msg): try: matches = self.db.find_records(dict(msg_id={'$in': msg_ids})) # turn match list into dict, for faster lookup - records = {} - for rec in matches: - records[rec['msg_id']] = rec + records = {rec['msg_id']: rec for rec in matches} except Exception: content = error.wrap_exception() self.log.exception("Failed to get results") @@ -1412,24 +1413,38 @@ def get_results(self, client_id, msg): else: records = {} for msg_id in msg_ids: - if msg_id in self.pending: + rec = records.get(msg_id) + is_completed = msg_id in self.all_completed or ( + rec is not None and rec.get('completed') is not None + ) + if msg_id in self.pending or (rec is not None and not is_completed): pending.append(msg_id) - elif msg_id in self.all_completed: + elif is_completed and statusonly: + completed.append(msg_id) + elif ( + is_completed + and rec is not None + and all( + rec.get(key) is not None + for key in ( + 'header', + 'result_header', + 'result_metadata', + 'result_content', + ) + ) + ): completed.append(msg_id) - if not statusonly: - c, bufs = self._extract_record(records[msg_id]) - content[msg_id] = c - buffers.extend(bufs) - elif msg_id in records: - if rec['completed']: - completed.append(msg_id) - c, bufs = self._extract_record(records[msg_id]) - content[msg_id] = c - buffers.extend(bufs) - else: - pending.append(msg_id) + c, bufs = self._extract_record(rec) + content[msg_id] = c + buffers.extend(bufs) else: try: + if is_completed: + raise KeyError( + f"Result for completed task {msg_id} is no longer available " + "from the Hub. It may have been culled or purged." + ) raise KeyError('No such message: ' + msg_id) except Exception: content = error.wrap_exception() diff --git a/ipyparallel/tests/test_client.py b/ipyparallel/tests/test_client.py index a26fa231e..823ed83f4 100644 --- a/ipyparallel/tests/test_client.py +++ b/ipyparallel/tests/test_client.py @@ -248,8 +248,23 @@ def test_shutdown(self): self.client[id0] def test_result_status(self): - pass - # to be written + result = self.client.load_balanced_view().apply_async(lambda: 42) + assert result.get() == 42 + self._wait_for_idle() + msg_id = result.msg_ids[0] + with self.connect_client() as observer: + assert observer.result_status([msg_id])["completed"] == [msg_id] + self.client.purge_hub_results(jobs=[msg_id]) + assert observer.result_status([msg_id])["completed"] == [msg_id] + with pytest.raises(error.RemoteError) as exc: + observer.result_status([msg_id], status_only=False) + with pytest.raises(error.RemoteError, match="No such message"): + observer.result_status(["unknown-task"], status_only=False) + assert exc.value.ename == "KeyError" + assert ( + f"Result for completed task {msg_id} is no longer available" + in exc.value.evalue + ) def test_db_query_dt(self): """test db query by date""" diff --git a/ipyparallel/tests/test_db.py b/ipyparallel/tests/test_db.py index 69617ef0d..5d1c402a1 100644 --- a/ipyparallel/tests/test_db.py +++ b/ipyparallel/tests/test_db.py @@ -10,13 +10,15 @@ import time from datetime import datetime, timedelta from unittest import TestCase +from unittest.mock import Mock import pytest from jupyter_client.session import Session +from zmq.eventloop.zmqstream import ZMQStream from ipyparallel import util from ipyparallel.controller.dictdb import DictDB -from ipyparallel.controller.hub import init_record +from ipyparallel.controller.hub import Hub, empty_record, init_record from ipyparallel.controller.sqlitedb import SQLiteDB from ipyparallel.util import utc @@ -45,6 +47,34 @@ def load_records(self, n=1, buffer_size=100): self.db.add_record(msg_id, rec) return msg_ids + def test_iopub_without_a_result(self): + stream = Mock(spec=ZMQStream) + session = Mock(spec=Session) + hub = Hub( + db=self.db, session=session, query=stream, monitor=stream, resubmit=stream + ) + request = self.session.msg("apply_request") + msg_id = request["msg_id"] + message = self.session.msg( + "stream", {"name": "stdout", "text": "hello"}, parent=request + ) + hub.save_iopub_message([], message) + assert self.db.get_record(msg_id)["stdout"] == "hello" + + hub.all_completed.add(msg_id) + query = self.session.msg( + "result_request", {"msg_ids": [msg_id], "status_only": False} + ) + hub.get_results(b"client", query) + reply = session.send.call_args.kwargs["content"] + assert reply["status"] == "error" + assert reply["ename"] == "KeyError" + assert msg_id in reply["evalue"] + + self.db.drop_record(msg_id) + hub.save_iopub_message([], message) + assert self.db.find_records({"msg_id": msg_id}) == [] + def test_add_record(self): before = self.db.get_history() self.load_records(5) @@ -253,6 +283,22 @@ class TestDictBackend(TaskDBTest, TestCase): def create_db(self): return DictDB() + def test_culled_record_stays_culled_after_late_output(self): + self.db = self.create_db() + self.db.record_limit = 2 + self.db.cull_fraction = 0.5 + culled = self.load_records(3)[0] + + record = dict(empty_record(), msg_id=culled, stdout="hello") + self.db.add_record(culled, record) + assert self.db.find_records({"msg_id": culled}) == [] + with self.assertRaises(KeyError): + self.db.get_record(culled) + + other_db = self.create_db() + other_db.add_record(culled, record) + assert other_db.get_record(culled)["stdout"] == "hello" + def test_cull_count(self): self.db = self.create_db() # skip the load-records init from setUp self.db.record_limit = 20