def iterate_with_bound( *, initial_state: TState, run_pass: Callable[[TState], TResult], is_satisfactory: Callable[[TResult], bool], adjust: Callable[[TState, TResult], TState], record: Callable[[int, TResult, TState, TResult | None], IterationRecord], max_iterations: int = 3, ) -> IterationOutcome[TState, TResult]: """Run a bounded pipeline-with-feedback loop.""" state = initial_state history: list[IterationRecord] = [] result = run_pass(state) previous_result: TResult | None = None if is_satisfactory(result): history.append(record(0, result, state, previous_result)) return IterationOutcome(result=result, history=history, exhausted=False) for i in range(1, max_iterations): next_state = adjust(state, result) history.append(record(i, result, next_state, previous_result)) previous_result = result state = next_state result = run_pass(state) if is_satisfactory(result): return IterationOutcome(result=result, history=history, exhausted=False) return IterationOutcome(result=result, history=history, exhausted=True)