Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions ipyparallel/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 5 additions & 2 deletions ipyparallel/controller/dictdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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)
Expand Down
49 changes: 32 additions & 17 deletions ipyparallel/controller/hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand All @@ -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()
Expand Down
19 changes: 17 additions & 2 deletions ipyparallel/tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"""
Expand Down
48 changes: 47 additions & 1 deletion ipyparallel/tests/test_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down