feat(ops): open(), close(ok) and opened(op), setup and teardown around a run

Open
#384 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
35/100
Issue type
Feature
Clarity
Clearly specified
Activity status
Active
Tech stack
python
Domain
backend

Research direction

Start with src/pipekit_ops/core/_operator.py and the container implementations, then read the P9 roadmap entry in packages/pipekit-ops/docs/design/roadmap.md and inspect Graph traversal order. Implement and export opened from src/pipekit_ops/core/_lifecycle.py; use the listed G9 tests and public operator sweep to check ordering, cleanup, and deduplication. Done means the API, tests, docs, and roadmap update meet the issue’s definition of done.

Written by the indexing model from the issue text.

Description

area:code priority:p2 type:feature

Problem / Request

An operator that holds a resource (a signal handler, an open file, a thread, a clock) has no hook to acquire it before a run and release it after.
This issue adds Operator.open() and Operator.close(ok), which do nothing by default, a children() method that lists an operator's direct children, and a context manager opened(op) that opens a whole pipeline in order and closes what opened in reverse.
It is phase P9 of packages/pipekit-ops/docs/design/roadmap.md.

User Story

As the author of an operator that installs a signal handler, I want the pipeline to set it up before the run and always put it back afterwards, so that I don't write a try/finally around every loop that uses it.

Motivation

sesmax-experiment's monitors have on_run_start and on_run_end(ok=...) hooks, and its chunked run loop calls them by hand (run/chunks.py and RunMonitors.start / RunMonitors.end in run/stages.py @ 12f169f6bf):

ok = False
try:
    watch.start(state0, spec=spec)            # records each monitor whose start returned
    frame, _ = Cycle(step_op=chunk, n_steps=timeline.n_chunks)(first, 0)
    ok = True
finally:
    watch.end(last[0].state, ok=ok)          # ends only those that started, newest first

The "only those that started" rule matters: its SignalMonitor replaces the process's SIGTERM handler in on_run_start, and a later monitor whose start raises must not leave that handler installed.
pipekit-train's Callback protocol (on_train_begin, … in pipekit_train/loop/_callbacks.py @ be1b64a900) is a second copy of the same idea.
Operator has no such hook today, and no generic way to list an operator's children: each container keeps them in its own attributes (Branch.if_true, Try.primary, Retry.op, a Sequential's list, …).

Proposed API

# pipekit_ops/core/_operator.py  (proposed, this issue)
class Operator(ConfigMixin):
    def open(self) -> None:
        """Acquire what this operator holds for a run. Default: nothing."""

    def close(self, ok: bool) -> None:
        """Release it; ok is False when the run raised. Default: nothing."""

    def children(self) -> tuple[Operator, ...]:
        """The direct child operators, in the order they run.

        Default: every attribute that is an Operator, or a list, tuple or dict
        whose values are Operators, in attribute order.
        """

# pipekit_ops/core/_lifecycle.py  (proposed, this issue)
@contextlib.contextmanager
def opened(op: Operator) -> Iterator[Operator]:
    """Open op and its descendants depth-first in run order; on exit close those
    that opened, in reverse, with ok=False if the block raised."""

Design Snapshot

from pipekit_ops import Sequential, opened

pipeline = Sequential([read, StopOnSignal(), advance, write])   # StopOnSignal from #385
with opened(pipeline):
    carrier, state = Cycle(step_op=pipeline, n_steps=100)(x0, 0)
# every handler StopOnSignal installed is back as it was, even if the run raised

opened walks the tree once with children(), skips an operator it has already opened (the same instance can sit in two places of a Graph), and calls open() on each in that order.
If an open() raises, it closes the ones already opened with ok=False and re-raises.
A Stop (#382) leaving the block counts as ok=True when its resumable or complete flag is set, and as ok=False otherwise.
Under Map with a thread or process executor, opened opens the operator in the calling process only; opening per worker is out of scope.
Calling an operator outside opened behaves exactly as today.

References & Existing Code

  • Roadmap: packages/pipekit-ops/docs/design/roadmap.md, phase P9 (merged in #374).
  • sesmax-experiment's lifecycle, linked above, and SignalMonitor in monitor/builtins.py @ 12f169f6bf.
  • Operator in pipekit_ops/core/_operator.py @ be1b64a900.
  • public_operators(module) in pipekit_ops/testing/__init__.py lists every exported operator class, for the sweep below.

Implementation Steps

  • Add open, close and children to Operator in src/pipekit_ops/core/_operator.py; none goes into get_config.
  • Override children where the attribute order is not the run order; check Graph first, whose nodes may be stored in a different order from the one they run in (unverified).
  • Add opened in src/pipekit_ops/core/_lifecycle.py and export it from pipekit_ops.core and pipekit_ops.
  • Add the sweep test below, so a container that hides a child fails CI.
  • Mark P9 as built in the roadmap.

Definition of Done

  • Code lands at the paths above
  • Public API exported via pipekit_ops/__init__.py
  • Tests pass: make test
  • Lint and typecheck pass: make lint && make typecheck
  • Google-style docstrings with a doctested example of opened

Testing

  • G9-1: for Sequential([a, b, c]) under opened, the opens run as a, b, c and the closes as c, b, a.
  • G9-2: when b.open() raises, a.close(ok=False) runs, c is never opened, and the error propagates.
  • G9-3: an exception inside the block closes every operator with ok=False and propagates; a clean exit closes with ok=True.
  • G9-4: an operator inside When(EveryN(2), Retry(Sequential([op]), attempts=2, base_delay=0, on=(OSError,))) is opened and closed exactly once (or Branch(...) if #381 has not landed).
  • G9-5: get_config and pipeline_hash of every public operator are unchanged.
  • Sweep: for each container in public_operators(pipekit_ops), a recording child placed in it is opened and closed by opened.
  • The same instance placed twice in a Graph is opened once.

Documentation

  • The core API page describes open, close, children and opened, with the ordering rules.

Relationships

  • Parent (theme epic): #379
  • Blocked by: #382 (the ok rule for a Stop leaving the block)
  • Blocks: #385
  • Related: #326 (typing.get_type_hints fails on every operator; new methods on Operator should not make it worse)
Dominant language
Python
Stars
0
Forks
0
Avg merge
3h 50m
Merged PRs (30d)
143

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from jejjohnson/pipekit

All issues in jejjohnson/pipekit

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.