Skip to content
Merged
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
21 changes: 17 additions & 4 deletions src/vfbquery/circuit_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@
Searches run in ``VFBQUERY_CIRCUIT_WORKERS`` processes (default 2), forked
after the graphs are loaded so they share the parent's memory. ``0`` runs
searches in threads in the server process (for tests and local use).

``VFBQUERY_CIRCUIT_TIME_LIMIT`` (seconds, default 30; 0 for none) bounds the
time one search spends on example neuron chains (``instance_graph``), the
only slow part: paths are always returned, and those not reached in time have
no chains (see :func:`vfbquery.vfb_circuit.find_paths`). A worker cannot be
stopped partway, so this is what keeps a slow request, even one whose client
has gone, from holding a worker for minutes.
"""
import asyncio
import gc
Expand Down Expand Up @@ -78,11 +85,13 @@ def _keep_only(run):
class CircuitState:
"""The run being served, its worker pool, and what is happening to them."""

def __init__(self, fixed_dir=None, root=None, workers=2, poll=60):
def __init__(self, fixed_dir=None, root=None, workers=2, poll=60,
time_limit=vc.DEFAULT_TIME_LIMIT):
if bool(fixed_dir) == bool(root):
raise ValueError("give exactly one of VFBQUERY_CIRCUIT_DIR or VFBQUERY_CIRCUIT_ROOT")
self.fixed_dir, self.root = fixed_dir, root
self.workers, self.poll = workers, poll
self.time_limit = time_limit or None # 0 -> no limit
self.store = None
self.pool = None
self.loaded_at = None
Expand Down Expand Up @@ -230,7 +239,7 @@ async def handle_circuit_paths(request):
result = cache.get(key)
if result is None:
result = await state.search(dict(kwargs, sources=sources, targets=targets,
exclude=exclude))
exclude=exclude, time_limit=state.time_limit))
cache.put(key, result)
if warnings:
result = dict(result, warnings=list(result.get("warnings") or []) + warnings)
Expand All @@ -254,6 +263,7 @@ async def handle_status(request):
"loading": state.loading,
"last_error": state.last_error,
"workers": state.workers,
"time_limit": state.time_limit,
"cache_entries": request.app["result_cache"].size,
})

Expand All @@ -263,14 +273,17 @@ async def handle_index(request):
"endpoints": ["/circuit_paths", "/health", "/status"]})


def create_circuit_app(fixed_dir=None, root=None, workers=None, poll=None, cache_ttl=None):
def create_circuit_app(fixed_dir=None, root=None, workers=None, poll=None, cache_ttl=None,
time_limit=None):
"""Build the circuit-mode aiohttp app (settings default to the env vars)."""
fixed_dir = fixed_dir or os.getenv("VFBQUERY_CIRCUIT_DIR") or None
root = root or os.getenv("VFBQUERY_CIRCUIT_ROOT") or None
workers = int(os.getenv("VFBQUERY_CIRCUIT_WORKERS", "2")) if workers is None else workers
poll = float(os.getenv("VFBQUERY_CIRCUIT_POLL", "60")) if poll is None else poll
cache_ttl = int(os.getenv("VFBQUERY_CACHE_TTL", "300")) if cache_ttl is None else cache_ttl
state = CircuitState(fixed_dir, root, workers, poll)
time_limit = (float(os.getenv("VFBQUERY_CIRCUIT_TIME_LIMIT", str(vc.DEFAULT_TIME_LIMIT)))
if time_limit is None else time_limit)
state = CircuitState(fixed_dir, root, workers, poll, time_limit)

app = web.Application(middlewares=[security_middleware])
app.router.add_get("/", handle_index)
Expand Down
51 changes: 47 additions & 4 deletions src/vfbquery/vfb_circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@
MAX_INSTANCE_K = 10
DEFAULT_K = 5
DEFAULT_INSTANCE_K = 3
#: Seconds a search may spend on example neuron chains (instance_graph). Each
#: chain search is one uninterruptible igraph call, 0.3-3 s on the large
#: connectomes, so a search can run over by about that much.
DEFAULT_TIME_LIMIT = 30.0
#: Same default threshold as /query_connectivity's ``weight``.
DEFAULT_MIN_SYNAPSES = 5
NORMALISE = ("input", "output")
Expand Down Expand Up @@ -459,9 +463,19 @@ def ends(expanded):

def find_paths(store, sources, targets, k=DEFAULT_K, min_synapses=DEFAULT_MIN_SYNAPSES,
min_inprop=0.0, normalise="input", exclude=(), instance_graph=False,
instance_k=DEFAULT_INSTANCE_K):
"""Search every dataset in ``store`` except the ``exclude`` keys."""
instance_k=DEFAULT_INSTANCE_K, time_limit=None):
"""Search every dataset in ``store`` except the ``exclude`` keys.

``time_limit`` (seconds, None for none) bounds the time spent on example
neuron chains, the slow part of ``instance_graph``. The paths themselves
are always returned; chains are found best path first, taking each
dataset's first path, then each one's second, and so on, and stop when the
time is up. Paths left without chains have no ``instances`` key, and the
response says how many.
"""
validate(k, min_synapses, min_inprop, normalise, instance_k)
if time_limit is not None and not time_limit > 0:
raise ValueError("time_limit must be a positive number of seconds")
t0 = time.time()
blocks, found_in = [], {t: [] for t in list(sources) + list(targets)}
for key, con in store.datasets.items():
Expand All @@ -471,9 +485,11 @@ def find_paths(store, sources, targets, k=DEFAULT_K, min_synapses=DEFAULT_MIN_SY
if con.expand(t):
found_in[t].append(key)
block = search_dataset(con, sources, targets, k, min_synapses, min_inprop,
normalise, instance_graph, instance_k)
normalise, False, instance_k)
if block is not None:
blocks.append(block)
blocks.append((con, block))
timed_out = _add_instances(blocks, instance_k, normalise, time_limit, t0) if instance_graph else 0
blocks = [b for _, b in blocks]

shared = collections.defaultdict(list)
for b in blocks:
Expand All @@ -495,6 +511,33 @@ def find_paths(store, sources, targets, k=DEFAULT_K, min_synapses=DEFAULT_MIN_SY
for c, ds in shared.items() if len(ds) > 1],
"seconds": round(time.time() - t0, 3),
}
if timed_out:
result["time_limit_reached"] = True
warnings_.append(
f"Time limit ({time_limit:g} s) reached: {timed_out} of the class paths have no "
"example neuron chains (no 'instances'). Ask for fewer paths (k) or chains "
"(instance_k), or fewer datasets, to get them all.")
if warnings_:
result["warnings"] = warnings_
return result


def _add_instances(blocks, instance_k, normalise, time_limit, t0):
"""Add example neuron chains to class paths until ``time_limit`` is used.

Best paths first across datasets, so that every dataset gets chains for
its top path before any gets them for its second. Returns how many paths
were left without chains.
"""
pending = [(rank, i, con, path)
for i, (con, block) in enumerate(blocks) if block["level"] == "class"
for rank, path in enumerate(block["paths"])]
pending.sort(key=lambda x: (x[0], x[1]))
skipped = 0
for _, _, con, path in pending:
if time_limit is not None and time.time() - t0 >= time_limit:
skipped += 1
continue
vertices = [con.class_graph.index[n["id"]] for n in path["nodes"]]
path["instances"] = _instance_chains(con, vertices, instance_k, normalise)
return skipped
40 changes: 39 additions & 1 deletion tests/test_circuit_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,43 @@ def test_a_run_without_a_report_still_loads(tmp_path):
assert x1["class"] is None and "status" not in x1


class _Clock:
"""Stands in for the time module: each neuron chain search takes 10 s."""
def __init__(self):
self.now = 1000.0

def time(self):
return self.now


def test_neuron_chains_stop_at_the_time_limit_best_paths_first(tmp_path, monkeypatch):
store = vc.load_run(write_run(tmp_path, datasets={"one": ("o1", DOWN), "two": ("t2", DOWN)}),
log=lambda *_: None)
clock = _Clock()
chains = vc._instance_chains

def slow_chains(*args):
clock.now += 10
return chains(*args)
monkeypatch.setattr(vc, "time", clock)
monkeypatch.setattr(vc, "_instance_chains", slow_chains)

result = vc.find_paths(store, ["A"], ["D"], instance_graph=True, time_limit=25)
one, two = (next(b for b in result["datasets"] if b["dataset"] == d) for d in ("one", "two"))
# Each dataset's best path first, then each one's second: started at 0, 10
# and 20 s, so the fourth (two's second path) is left out.
assert [("instances" in p) for p in one["paths"]] == [True, True]
assert [("instances" in p) for p in two["paths"]] == [True, False]
assert result["time_limit_reached"] is True
assert any("1 of the class paths have no example neuron chains" in w for w in result["warnings"])

full = vc.find_paths(store, ["A"], ["D"], instance_graph=True, time_limit=None)
assert all("instances" in p for b in full["datasets"] for p in b["paths"])
assert "time_limit_reached" not in full
with pytest.raises(ValueError, match="time_limit"):
vc.find_paths(store, ["A"], ["D"], time_limit=0)


def test_instance_graph_gives_neuron_chains_along_each_class_path(store):
_, block = paths(vc.find_paths(store, ["A"], ["D"], instance_graph=True))
chains = block["paths"][0]["instances"]
Expand Down Expand Up @@ -244,8 +281,9 @@ async def calls(client):
status = await (await client.get("/status")).json()
return r.status, body, bad.status, await all_dbs.json(), status

app = create_circuit_app(root=str(tmp_path), workers=0, poll=3600)
app = create_circuit_app(root=str(tmp_path), workers=0, poll=3600, time_limit=12)
status, body, bad, all_dbs, st = _serve(app, calls)
assert st["time_limit"] == 12
assert status == 200
assert body["run"] == "run-1"
# hb is excluded by default, as on /query_connectivity.
Expand Down
Loading