Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Reject iterator inputs for multi-action tasks without buffering (#1272)

LimbC-Cef28da8735d6
diff --git a/docs/workflow/task/index.md b/docs/workflow/task/index.md
index ba56d503..bdaeb062 100644
--- a/docs/workflow/task/index.md
+++ b/docs/workflow/task/index.md
@@ -42,6 +42,19 @@ workflow:
::: txtai.workflow.Task.__init__
+## Multi-action task inputs
+
+A multi-action `Task` requires reusable inputs. Passing a single-pass iterator, such as a generator or the output of a `StreamTask`, raises a `ValueError` before consuming inputs or running any actions. Automatically buffering an iterator could exhaust memory, so tasks do not convert these inputs to a list.
+
+Iterators passed to a `Workflow` remain supported: the workflow collects bounded batches before passing them to its tasks. For example:
+
+```python
+workflow = Workflow([Task([list, list])], batch=2)
+list(workflow(iter([1, 2, 3]))) # [(1, 1), (2, 2), (3, 3)]
+```
+
+This batching occurs at the workflow input; it does not batch iterator outputs produced by tasks inside that workflow. Single-action tasks continue to accept iterator inputs.
+
## Multi-action task concurrency
The default processing mode is to run actions sequentially. Multiprocessing support is already built in at a number of levels. Any of the GPU models will maximize GPU utilization for example and even in CPU mode, concurrency is utilized. But there are still use cases for task action concurrency. For example, if the system has multiple GPUs, the task runs external sequential code, or the task has a large number of I/O tasks.
diff --git a/src/python/txtai/workflow/task/base.py b/src/python/txtai/workflow/task/base.py
index aadc85de..b00d226b 100644
--- a/src/python/txtai/workflow/task/base.py
+++ b/src/python/txtai/workflow/task/base.py
@@ -6,6 +6,8 @@ import logging
import re
import types
+from collections.abc import Iterator
+
# Core library imports
from ...util import Library
@@ -265,14 +267,21 @@ class Task:
Executes action(s) on elements.
Args:
- elements: list of data elements
+ elements: iterable data elements
executor: execute instance, enables concurrent task actions
Returns:
transformed data elements
+
+ Raises:
+ ValueError: if iterator inputs are passed to a multi-action task
"""
if self.action:
+ # Reject single-pass inputs without consuming or buffering them.
+ if len(self.action) > 1 and isinstance(elements, Iterator):
+ raise ValueError("Iterator inputs are not supported for multi-action tasks")
+
# Run actions
outputs = []
for x, action in enumerate(self.action):
diff --git a/test/python/testworkflow.py b/test/python/testworkflow.py
index c8221dec..10bf1a94 100644
--- a/test/python/testworkflow.py
+++ b/test/python/testworkflow.py
@@ -28,6 +28,7 @@ from txtai.workflow import (
RagTask,
RetrieveTask,
StorageTask,
+ StreamTask,
TemplateTask,
UrlTask,
WorkflowTask,
@@ -161,6 +162,63 @@ class TestWorkflow(unittest.TestCase):
results = list(workflow([2, 4]))
self.assertEqual(results, [(2, 2), (4, 4)])
+ def testIteratorActions(self):
+ """
+ Test multi-action tasks reject iterators without consuming inputs or running actions
+ """
+
+ for merge, generator in product(["hstack", "vstack", "concat", None], [False, True]):
+ with self.subTest(merge=merge, generator=generator):
+ elements = (x for x in [1, 2]) if generator else iter([1, 2])
+ calls = []
+ task = Task([lambda values, calls=calls: calls.append(True) or list(values)] * 2, merge=merge)
+ with self.assertRaisesRegex(ValueError, "Iterator inputs are not supported for multi-action tasks"):
+ task(elements)
+ self.assertEqual(calls, [])
+ self.assertEqual(list(elements), [1, 2])
+
+ def testIteratorColumns(self):
+ """
+ Test iterators are rejected before extracting per-action columns
+ """
+
+ elements = iter([(1, 10), (2, 20)])
+ task = Task([list, list], column={0: 0, 1: 1}, unpack=False)
+ with self.assertRaisesRegex(ValueError, "Iterator inputs are not supported for multi-action tasks"):
+ task(elements)
+ self.assertEqual(list(elements), [(1, 10), (2, 20)])
+
+ def testIteratorSingleAction(self):
+ """
+ Test single-action and no-action tasks retain lazy iterator inputs
+ """
+
+ elements = iter([1, 2, 3])
+ self.assertIs(Task()(elements), elements)
+ self.assertEqual(Task(lambda values: [next(values)])(elements), [1])
+ self.assertEqual(list(elements), [2, 3])
+
+ def testStreamMultiActionWorkflow(self):
+ """
+ Test streamed inputs fail before downstream sequential or concurrent actions run
+ """
+
+ for concurrency in [None, "thread", "process"]:
+ with self.subTest(concurrency=concurrency):
+ workflow = Workflow([StreamTask(lambda value: iter([value])), Task([Nop(), Nop()], concurrency=concurrency)], batch=2)
+ with self.assertRaisesRegex(ValueError, "Iterator inputs are not supported for multi-action tasks"):
+ list(workflow([1, 2, 3]))
+
+ def testIteratorWorkflowBatches(self):
+ """
+ Test workflow-level iterators remain supported through bounded batches
+ """
+
+ for concurrency in [None, "thread", "process"]:
+ with self.subTest(concurrency=concurrency):
+ workflow = Workflow([Task([Nop(), Nop()], concurrency=concurrency)], batch=2)
+ self.assertEqual(list(workflow(iter([1, 2, 3]))), [(1, 1), (2, 2), (3, 3)])
+
def testConsoleWorkflow(self):
"""
Test a console task