From 642fe1a283d9d720399260e15191c4b4b30922ea Mon Sep 17 00:00:00 2001 From: WH-2099 Date: Mon, 2 Nov 2026 18:26:14 +0000 Subject: [PATCH 1/6] fix(runtime)!: resolve Dify 0.9 integration regressions Serialize files nested in mixed arrays, replace named tool argument snapshots, avoid callback-free result accumulation, and allow hosts to disable frame observations before copying values. BREAKING CHANGE: Named tool calls carry the current argument snapshot. Runtime adapters emitting argument fragments must omit the function name after the initial call. --- ARCHITECTURE.md | 14 +-- src/graphon/engine/engine.py | 8 +- src/graphon/engine/frame.py | 3 +- src/graphon/model_runtime/README.md | 5 + .../model_runtime/entities/llm_entities.py | 7 +- .../base/large_language_model.py | 47 ++++---- src/graphon/variables/utils.py | 6 +- tests/engine/test_frame_observations.py | 89 +++++++++++++++- tests/model_runtime/test_model_dispatch.py | 100 ++++++++++++++++++ tests/utils/test_variable_utils.py | 29 ++++- 10 files changed, 276 insertions(+), 32 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 728fc535..19b76693 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -97,8 +97,7 @@ See [raw-event tests](tests/engine/test_raw_engine_events.py) and ## Raw frame observations -[Frame events](src/graphon/engine_events/frame.py) expose execution state for -consumers that may read events after a child frame has been removed: +By default, [Engine](src/graphon/engine/engine.py) emits [frame events](src/graphon/engine_events/frame.py) that expose execution state for consumers that may read events after a child frame has been removed: | Event | Meaning | | --- | --- | @@ -106,6 +105,9 @@ consumers that may read events after a child frame has been removed: | `FrameVariablesUpdatedEvent` | Detached replacements at the written selectors, published after successful commits. Empty and `None` values are retained; partial failures report only writes that succeeded. | | `FrameFinishedEvent` | The frame has emitted its last node, traversal, and variable observations, with a succeeded, failed, or aborted outcome. Child completion is published before registry removal. | +Set `Engine(..., emit_frame_events=False)` to skip these events and their detached value copies for both event consumers and layers while execution and variable commits continue. +This engine option is not persisted; supply it again when rebuilding from a snapshot. + [FrameRegistry](src/graphon/engine/frame.py) publishes commits for node outputs and handled-failure defaults, variable requests, Loop initialization, Loop and Iteration ancestor write-back, and external commands. Every frame sharing an @@ -136,10 +138,9 @@ commits, detached values, and raw chunk delivery, and the [frame failure tests](tests/engine/test_frame_failures.py) for pause/restore and consumer exceptions. -Baselines and commits contain full variable values. `ResponseStreamFilter` -suppresses those events from its output; this compatibility guard does not add -child response assembly. Response buffers and presentation state remain in the -filter, separate from runtime snapshots. +Baselines and commits contain full variable values. +`ResponseStreamFilter` suppresses those events from its output after the engine has constructed and copied them; this compatibility guard does not add child response assembly. +Response buffers and presentation state remain in the filter, separate from runtime snapshots. ## State and execution invariants @@ -169,6 +170,7 @@ compatibility details: [Factories](src/graphon/variables/factory.py) infer types for raw values or validate explicit declarations, preserving declared empty arrays and `array[any]` values. See [factory tests](tests/variables/test_factory.py) for declared types and serialized tag selection. `array[any]` restores serialized [marked file values](src/graphon/file/constants.py) recursively inside arrays and objects using [File validation](src/graphon/file/models.py), preserving file values in container task and variable pool snapshots. +The [segment serializer](src/graphon/variables/utils.py) preserves nested `File` model fields and their identity marker without log redaction; see the [serialization tests](tests/utils/test_variable_utils.py). Unmarked objects retain their data, and invalid marked files fail validation; see [container tests](tests/nodes/test_container_effects.py) and [workflow tests](tests/workflows/test_full_engine_events.py). [VariableBase.copy_with_value](src/graphon/variables/variables.py) validates replacements for assignment nodes, retaining identity and metadata and promoting integer variables when the new value is a float. The [v1 assignment tests](tests/nodes/variable_assigner/test_v1_node.py) and [v2 assignment tests](tests/nodes/variable_assigner/test_v2_node.py) cover invalid updates, fractional results, and clearing arrays while preserving their declared type, including `array[file]`. diff --git a/src/graphon/engine/engine.py b/src/graphon/engine/engine.py index 4507424d..fb5079b3 100644 --- a/src/graphon/engine/engine.py +++ b/src/graphon/engine/engine.py @@ -68,6 +68,7 @@ def __init__( container_handler_factories: Sequence[ContainerHandlerFactory] = (), *, file_runtime: WorkflowFileRuntimeProtocol | None = None, + emit_frame_events: bool = True, ) -> None: """Build an engine for one graph execution. @@ -86,6 +87,9 @@ def __init__( file_runtime: File adapter for this execution. None captures the current scoped adapter, even if it is unconfigured. Supply it again when rebuilding an engine from a snapshot. + emit_frame_events: Publish frame lifecycle and variable observations. + False skips their construction and value copies without changing + execution. Supply it again when rebuilding from a snapshot. Raises: ValueError: If ``workers`` is not a positive integer. @@ -114,7 +118,9 @@ def __init__( # === State Management === self._event_stream = EventStream(self._layers) - self._frame_registry = FrameRegistry(self._event_stream) + self._frame_registry = FrameRegistry( + self._event_stream if emit_frame_events else None + ) root_frame = self._frame_registry.create( frame_id=ROOT_FRAME_ID, container_id="", diff --git a/src/graphon/engine/frame.py b/src/graphon/engine/frame.py index 023fbc26..8b246f3a 100644 --- a/src/graphon/engine/frame.py +++ b/src/graphon/engine/frame.py @@ -114,7 +114,8 @@ def reset_observations(self) -> None: self._open_frame_ids.clear() def record_failure(self, frame_id: str, error: str) -> None: - self._frame_errors.setdefault(frame_id, error) + if self._event_stream is not None: + self._frame_errors.setdefault(frame_id, error) if frame_id == ROOT_FRAME_ID: return root_state = self[ROOT_FRAME_ID].state diff --git a/src/graphon/model_runtime/README.md b/src/graphon/model_runtime/README.md index 2bcf9756..fbd9afb3 100644 --- a/src/graphon/model_runtime/README.md +++ b/src/graphon/model_runtime/README.md @@ -39,9 +39,14 @@ blocks retain their order and block state; see the [SlimLLM](../dsl/slim/llm.py) shares this aggregation for blocking ordinary and structured output calls, covered by the [Slim tests](../../../tests/dsl/test_slim_llm.py). +[LLMResultChunkDelta](entities/llm_entities.py) tool calls with a nonempty function name carry the current argument snapshot, replacing earlier arguments for that ID, including with an empty string. +Updates with an empty name append arguments to their ID, or to the most recently created call when the ID is empty; the latter requires a preceding call. +Calls keep their first-seen order, and a named call without an ID starts a new call with a generated ID; see the [tool call tests](../../../tests/model_runtime/test_large_language_model_tool_calls.py) and [dispatch tests](../../../tests/model_runtime/test_model_dispatch.py). + After a `LargeLanguageModel.invoke` stream is fully consumed without errors, `on_after_invoke` receives a result containing all tool calls, assembled with the same merging rules as blocking results. Iteration failures, including before the first chunk, notify `on_invoke_error` once with the original exception before normal exception conversion and propagation, and skip `on_after_invoke`. See the [callback regression tests](../../../tests/model_runtime/test_model_dispatch.py). +With no active callbacks, streaming invocation yields chunks without accumulating a complete result; enabling DEBUG on the wrapper's logger adds a `LoggingCallback` and enables accumulation. Hosts can display chunks while calling `consume(chunk)` on one [LLMResultAccumulator](model_providers/base/large_language_model.py) per invocation. After consuming the stream, call its `to_result(model=..., prompt_messages=...)` and use the returned `message` for replay or [JSON persistence](../../../tests/model_runtime/test_llm_result_accumulator.py). diff --git a/src/graphon/model_runtime/entities/llm_entities.py b/src/graphon/model_runtime/entities/llm_entities.py index 16a23764..08e789f2 100644 --- a/src/graphon/model_runtime/entities/llm_entities.py +++ b/src/graphon/model_runtime/entities/llm_entities.py @@ -264,7 +264,12 @@ def _validate_intervals(self) -> LLMPollingConfig: class LLMResultChunkDelta(BaseModel): - """Model class for llm result chunk delta.""" + """Stream content with tool-call updates and cumulative usage snapshots. + + A tool call with a function name carries its current argument snapshot. + Repeating its ID replaces that snapshot. Argument fragments omit the + function name and append to their ID, or to the latest call without an ID. + """ index: int message: AssistantPromptMessage diff --git a/src/graphon/model_runtime/model_providers/base/large_language_model.py b/src/graphon/model_runtime/model_providers/base/large_language_model.py index 835a996a..6a6ee7bf 100644 --- a/src/graphon/model_runtime/model_providers/base/large_language_model.py +++ b/src/graphon/model_runtime/model_providers/base/large_language_model.py @@ -113,7 +113,8 @@ def _merge_tool_call_delta( tool_call.type = delta.type if delta.function.name: tool_call.function.name = delta.function.name - if delta.function.arguments: + tool_call.function.arguments = delta.function.arguments + elif delta.function.arguments: tool_call.function.arguments += delta.function.arguments @@ -283,9 +284,13 @@ def merge_tool_call_deltas( *, id_generator: Callable[[], str] | None = None, ) -> None: - """Merge incremental tool call deltas into existing tool calls. + """Merge tool-call snapshots and argument fragments in first-seen order. - :param new_tool_calls: List of new tool call deltas to be merged. + Named calls carry the current argument snapshot and replace the previous + snapshot for their ID. Unnamed calls append an argument fragment to their + ID, or to the latest call when the ID is empty. Inputs are not retained. + + :param new_tool_calls: Named snapshots or unnamed argument fragments. :param existing_tools_calls: List of existing tool calls modified in place. :param id_generator: Optional callable for generating IDs in tests/callers. """ @@ -455,7 +460,9 @@ def _invoke_result_generator( ) -> Generator[LLMResultChunk, None, None]: """Stream runtime result chunks through callbacks and bookkeeping hooks.""" callbacks = callbacks or [] - accumulator = _StreamingInvokeAccumulator(real_model=model) + accumulator = ( + _StreamingInvokeAccumulator(real_model=model) if callbacks else None + ) try: yield from self._stream_invoke_result_chunks( @@ -486,26 +493,27 @@ def _invoke_result_generator( ) raise self._transform_invoke_error(e) from e - self._trigger_after_invoke_callbacks( - model=model, - result=accumulator.to_result( + if accumulator is not None: + self._trigger_after_invoke_callbacks( + model=model, + result=accumulator.to_result( + prompt_messages=prompt_messages, + ), + credentials=credentials, prompt_messages=prompt_messages, - ), - credentials=credentials, - prompt_messages=prompt_messages, - model_parameters=model_parameters, - tools=tools, - stop=stop, - stream=stream, - request_metadata=request_metadata, - callbacks=callbacks, - ) + model_parameters=model_parameters, + tools=tools, + stop=stop, + stream=stream, + request_metadata=request_metadata, + callbacks=callbacks, + ) def _stream_invoke_result_chunks( self, *, result: Generator[LLMResultChunk, None, None], - accumulator: _StreamingInvokeAccumulator, + accumulator: _StreamingInvokeAccumulator | None, model: str, credentials: dict, prompt_messages: Sequence[PromptMessage], @@ -536,7 +544,8 @@ def _stream_invoke_result_chunks( request_metadata=request_metadata, callbacks=callbacks, ) - accumulator.consume(chunk) + if accumulator is not None: + accumulator.consume(chunk) def get_num_tokens( self, diff --git a/src/graphon/variables/utils.py b/src/graphon/variables/utils.py index da09a29e..9e882fc8 100644 --- a/src/graphon/variables/utils.py +++ b/src/graphon/variables/utils.py @@ -3,6 +3,8 @@ import orjson +from graphon.file.models import File + from .segment_group import SegmentGroup from .segments import ArrayFileSegment, FileSegment, Segment @@ -14,7 +16,7 @@ def to_selector(node_id: str, name: str, paths: Iterable[str] = ()) -> Sequence[ def segment_orjson_default(o: Any) -> object: - """Default function for orjson serialization of Segment types""" + """Unwrap segments and files without redacting values used for persistence.""" result: object match o: case ArrayFileSegment(): @@ -25,6 +27,8 @@ def segment_orjson_default(o: Any) -> object: result = [segment_orjson_default(seg) for seg in o.value] case Segment(): result = o.value + case File(): + result = o.model_dump(mode="json") case _: msg = f"Object of type {type(o).__name__} is not JSON serializable" raise TypeError(msg) diff --git a/tests/engine/test_frame_observations.py b/tests/engine/test_frame_observations.py index 9d16748a..ce94d3a5 100644 --- a/tests/engine/test_frame_observations.py +++ b/tests/engine/test_frame_observations.py @@ -3,15 +3,17 @@ from __future__ import annotations import json +from collections import UserDict from collections.abc import Generator, Sequence from datetime import UTC, datetime from threading import Event, Thread -from typing import Any +from typing import Any, override import pytest from graphon import engine_events from graphon.dsl import loads +from graphon.engine import Engine from graphon.engine.command import ( CommandProcessor, UpdateVariablesCommand, @@ -29,6 +31,7 @@ ) from graphon.entities.workflow_start_reason import WorkflowStartReason from graphon.enums import BuiltinNodeTypes, WorkflowNodeExecutionStatus +from graphon.graph import Graph from graphon.node_events.base import NodeEventPayload, NodeRunResult from graphon.node_events.node import StreamChunkEvent, StreamCompletedEvent from graphon.nodes.container_effects import ( @@ -38,6 +41,8 @@ LoopFrameRequest, ) from graphon.nodes.human_input.entities import Completed, HITLContext, PauseRequested +from graphon.nodes.start.entities import StartNodeData +from graphon.nodes.start.start_node import StartNode from graphon.nodes.template_transform.template_transform_node import ( TemplateTransformNode, ) @@ -56,6 +61,7 @@ _iteration_dsl, _new_runtime_state, ) +from tests.helpers import build_init_params def _node(node_id: str, node_type: str, **data: Any) -> dict[str, Any]: @@ -165,6 +171,87 @@ def test_root_baseline_commits_identity_and_detached_values() -> None: assert type(event).model_validate_json(event.model_dump_json()) == event +@pytest.mark.parametrize("emit_frame_events", [True, False]) +def test_frame_observations_can_be_disabled_without_changing_iteration_results( + emit_frame_events: bool, +) -> None: + loaded = loads( + _dsl( + [ + _node( + "iteration", + "iteration", + start_node_id="body", + iterator_selector=["start", "items"], + output_selector=["iteration", "item"], + ), + _node("body", "iteration-start", container_id="iteration"), + _node( + "end", + "end", + outputs=[ + { + "variable": "result", + "value_selector": ["iteration", "output"], + } + ], + ), + ], + [("start", "iteration"), ("iteration", "end")], + ), + start_inputs={"items": ["first", "second"]}, + ) + engine = Engine( + graph=loaded.graph, + runtime_state=loaded.runtime_state, + emit_frame_events=emit_frame_events, + ) + + events = list(engine.run()) + + assert isinstance(events[-1], engine_events.GraphRunSucceededEvent) + assert events[-1].outputs == {"result": ["first", "second"]} + for event_type in ( + engine_events.FrameStartedEvent, + engine_events.FrameVariablesUpdatedEvent, + engine_events.FrameFinishedEvent, + ): + assert ( + any(isinstance(event, event_type) for event in events) is emit_frame_events + ) + + +def test_disabled_frame_observations_do_not_copy_unused_context() -> None: + class UncopyablePayload(UserDict[str, str]): + def __deepcopy__(self, _memo: dict[int, Any]) -> UncopyablePayload: + msg = "unused context must not be copied for frame observations" + raise AssertionError(msg) + + class EmptyStartNode(StartNode): + node_type = "empty-root" + + @override + def _run(self) -> NodeRunResult: + return NodeRunResult(status=WorkflowNodeExecutionStatus.SUCCEEDED) + + state = _new_runtime_state({}) + state.variable_pool.add( + ("context", "payload"), {"unused": UncopyablePayload(value="unchanged")} + ) + root = EmptyStartNode( + "root", StartNodeData(), init_params=build_init_params(), runtime_state=state + ) + engine = Engine( + graph=Graph.new().add_root(root).build(), + runtime_state=state, + emit_frame_events=False, + ) + + events = list(engine.run()) + + assert isinstance(events[-1], engine_events.GraphRunSucceededEvent) + + @pytest.mark.parametrize("items", [[], ["a", "b"]]) def test_nested_parallel_frames_include_empty_bodies_and_invocation_identity( items: list[str], diff --git a/tests/model_runtime/test_model_dispatch.py b/tests/model_runtime/test_model_dispatch.py index f188e422..53266611 100644 --- a/tests/model_runtime/test_model_dispatch.py +++ b/tests/model_runtime/test_model_dispatch.py @@ -1,4 +1,6 @@ import inspect +import logging +import weakref from collections.abc import Generator, Mapping, Sequence from decimal import Decimal from io import BytesIO @@ -775,6 +777,104 @@ def test_large_language_model_stream_after_invoke_preserves_chunk_state( assert after_result.message.tool_calls == tool_calls +@pytest.mark.parametrize("stream", [True, False]) +def test_large_language_model_replaces_named_tool_call_snapshots(stream: bool) -> None: + provider = ProviderEntity( + provider="test-provider", + label=I18nObject(en_US="Test Provider"), + supported_model_types=[ModelType.LLM], + configurate_methods=[], + ) + calls = [ + AssistantPromptMessage.ToolCall( + id=call_id, + type="function", + function=AssistantPromptMessage.ToolCall.ToolCallFunction( + name=name, arguments=arguments + ), + ) + for call_id, name, arguments in ( + ("first", "lookup", '{"text":"a'), + ("second", "lookup", '{"city":"Rome"}'), + ("first", "lookup", '{"text":"aa"}'), + ("first", "lookup", '{"text":"aa"}'), + ("third", "lookup", '{"text":"'), + ("third", "", "aa"), + ("third", "", "aa"), + ("third", "", '"}'), + ) + ] + runtime = _StreamingLLMRuntimeStub([ + _make_chunk(model="test-model", content="", tool_calls=[call]) for call in calls + ]) + model = LargeLanguageModel( + provider_schema=provider, model_runtime=cast("LLMModelRuntime", runtime) + ) + callback = _RecordingCallback() + + result = model.invoke( + model="test-model", + credentials={}, + prompt_messages=[], + stream=stream, + callbacks=[callback], + ) + if stream: + list(cast("Generator[LLMResultChunk, None, None]", result)) + + assert len(callback.after_results) == 1 + assert [ + (call.id, call.function.name, call.function.arguments) + for call in callback.after_results[0].message.tool_calls + ] == [ + ("first", "lookup", '{"text":"aa"}'), + ("second", "lookup", '{"city":"Rome"}'), + ("third", "lookup", '{"text":"aaaa"}'), + ] + assert calls[0].function.arguments == '{"text":"a' + + +def test_large_language_model_without_callbacks_releases_consumed_content( + caplog: pytest.LogCaptureFixture, +) -> None: + caplog.set_level( + logging.INFO, + logger="graphon.model_runtime.model_providers.base.large_language_model", + ) + references: list[weakref.ReferenceType[TextPromptMessageContent]] = [] + + class TextChunkRuntime(_LLMRuntimeStub): + def invoke_llm(self, **_: Any) -> Generator[LLMResultChunk, None, None]: + for index in range(8): + content = TextPromptMessageContent(data=str(index)) + references.append(weakref.ref(content)) + yield _make_chunk(model="test-model", content=[content]) + + provider = ProviderEntity( + provider="test-provider", + label=I18nObject(en_US="Test Provider"), + supported_model_types=[ModelType.LLM], + configurate_methods=[], + ) + model = LargeLanguageModel( + provider_schema=provider, + model_runtime=cast("LLMModelRuntime", TextChunkRuntime()), + ) + result = model.invoke( + model="test-model", credentials={}, prompt_messages=[], callbacks=[] + ) + + chunk_count = 0 + for chunk_count, chunk in enumerate( + cast("Generator[LLMResultChunk, None, None]", result), start=1 + ): + assert chunk.delta.message.content == [ + TextPromptMessageContent(data=str(chunk_count - 1)) + ] + assert sum(reference() is not None for reference in references) <= 2 + assert chunk_count == 8 + + @pytest.mark.parametrize("stream", [True, False]) @pytest.mark.parametrize("mixed_content", [True, False]) @pytest.mark.parametrize("opaque_body", [{"signature": "s"}, {}, [], "", 0, False]) diff --git a/tests/utils/test_variable_utils.py b/tests/utils/test_variable_utils.py index 99e4b5f9..52535dec 100644 --- a/tests/utils/test_variable_utils.py +++ b/tests/utils/test_variable_utils.py @@ -1,6 +1,9 @@ +import json + +from graphon.file import File, FileTransferMethod, FileType from graphon.variables.segment_group import SegmentGroup -from graphon.variables.segments import StringSegment -from graphon.variables.utils import segment_orjson_default +from graphon.variables.segments import ArrayAnySegment, StringSegment +from graphon.variables.utils import dumps_with_segments, segment_orjson_default def test_segment_orjson_default_uses_match_dispatch() -> None: @@ -9,3 +12,25 @@ def test_segment_orjson_default_uses_match_dispatch() -> None: assert segment_orjson_default(segment) == "value" assert segment_orjson_default(group) == ["value"] + + +def test_mixed_array_file_values_survive_json_round_trip() -> None: + file = File( + file_type=FileType.IMAGE, + transfer_method=FileTransferMethod.REMOTE_URL, + remote_url="https://example.com/image.png", + related_id="upload-id", + filename="image.png", + mime_type="image/png", + size=42, + ) + file_data = file.model_dump(mode="json") + value = ["metadata", file_data, {"files": [file_data]}] + segment = ArrayAnySegment(value=value) + + serialized = dumps_with_segments(segment) + + assert json.loads(serialized) == value + restored = ArrayAnySegment(value=json.loads(serialized)) + assert restored.value[1] == file + assert restored.value[2]["files"][0] == file From 7db2f7b5fb919f3a8959871163b587b52a319205 Mon Sep 17 00:00:00 2001 From: WH-2099 Date: Mon, 2 Nov 2026 19:02:56 +0000 Subject: [PATCH 2/6] fix(variables): serialize nested models in object array templates --- ARCHITECTURE.md | 8 +++--- src/graphon/variables/segments.py | 2 +- tests/engine/test_frame_failures.py | 18 +++++++++---- tests/variables/test_template_resolution.py | 28 ++++++++++++++++++++- 4 files changed, 46 insertions(+), 10 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 19b76693..c5b5ea59 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -125,9 +125,8 @@ pause/restore and distinguishes separate runs with the same `workflow_id`. Pause leaves unfinished frames open. Resume publishes new baselines with the resumption reason and existing execution IDs before resumed body events. -[Persisted container state](src/graphon/runtime/container_state.py) preserves -pending frame failures across pause and snapshot restore. Terminal failure or -abort closes each remaining frame once, before the graph's terminal event. +[Persisted container state](src/graphon/runtime/container_state.py) preserves pending frame failures across pause and snapshot restore even when frame events are disabled. +Terminal failure or abort closes each remaining frame once, before the graph's terminal event. An `Exception` thrown into `Engine.run()` during execution or at the paused event follows the same failure ordering; continued consumption re-raises the exception. @@ -175,6 +174,9 @@ Unmarked objects retain their data, and invalid marked files fail validation; se [VariableBase.copy_with_value](src/graphon/variables/variables.py) validates replacements for assignment nodes, retaining identity and metadata and promoting integer variables when the new value is a float. The [v1 assignment tests](tests/nodes/variable_assigner/test_v1_node.py) and [v2 assignment tests](tests/nodes/variable_assigner/test_v2_node.py) cover invalid updates, fractional results, and clearing arrays while preserving their declared type, including `array[file]`. +In [template interpolation](src/graphon/variables/template_resolution.py), nonempty object arrays render as JSON, including nested `File` and segment model data. +Empty object arrays render as an empty string; see [template resolution tests](tests/variables/test_template_resolution.py). + [Container values](src/graphon/nodes/container_effects.py) preserve declared segment types through construction, snapshots, and completion, including secret tags. Explicit `to_segment()` conversion removes source variable identity so the parent pool binds completed outputs to the container's selectors. Snapshot restoration uses the `SerializableSegment` discriminated union directly. diff --git a/src/graphon/variables/segments.py b/src/graphon/variables/segments.py index 1ef9c443..56720a4d 100644 --- a/src/graphon/variables/segments.py +++ b/src/graphon/variables/segments.py @@ -242,7 +242,7 @@ def text(self) -> str: # Return empty string for empty arrays instead of "[]" if not self.value: return "" - return json.dumps(self.value, ensure_ascii=False) + return json.dumps(self.model_dump()["value"], ensure_ascii=False) def to_segment(self) -> ArrayObjectSegment: return ArrayObjectSegment(value=self.value) diff --git a/tests/engine/test_frame_failures.py b/tests/engine/test_frame_failures.py index c12623bd..37e7ee51 100644 --- a/tests/engine/test_frame_failures.py +++ b/tests/engine/test_frame_failures.py @@ -124,7 +124,10 @@ def complete_frame_if_ready(self, frame: ExecutionFrame) -> None: @pytest.mark.parametrize("restore_snapshot", [False, True]) -def test_custom_frame_failure_survives_pause(restore_snapshot: bool) -> None: +@pytest.mark.parametrize("emit_frame_events", [False, True]) +def test_custom_frame_failure_survives_pause( + restore_snapshot: bool, emit_frame_events: bool +) -> None: document = _dsl( [ _node( @@ -175,6 +178,7 @@ def complete_or_pause_human_input( human_input_engine.runtime_state, workers=2, container_handler_factories=[_CustomLoopHandler], + emit_frame_events=emit_frame_events, ) pause_events = list(engine.run()) assert isinstance(pause_events[-1], GraphRunPausedEvent) @@ -195,18 +199,22 @@ def complete_or_pause_human_input( human_input_engine.runtime_state, workers=2, container_handler_factories=[_CustomLoopHandler], + emit_frame_events=emit_frame_events, ) human_input_ready.set() events: list[EngineEvent] = [] with pytest.raises(RuntimeError, match="missing"): events.extend(engine.run()) + graph_failed = next( + event for event in events if isinstance(event, GraphRunFailedEvent) + ) + assert graph_failed.error == failure.error frame_finished_events = [ event for event in events if isinstance(event, FrameFinishedEvent) ] - assert {event.frame_id for event in frame_finished_events} == { - "root", - failure.frame_id, - } + assert {event.frame_id for event in frame_finished_events} == ( + {"root", failure.frame_id} if emit_frame_events else set() + ) assert all( event.outcome == "failed" and event.error == failure.error for event in frame_finished_events diff --git a/tests/variables/test_template_resolution.py b/tests/variables/test_template_resolution.py index cb7dca41..6877cec3 100644 --- a/tests/variables/test_template_resolution.py +++ b/tests/variables/test_template_resolution.py @@ -1,8 +1,11 @@ +import json + import pytest +from graphon.file import File, FileTransferMethod, FileType from graphon.runtime.read_only_wrappers import ReadOnlyVariablePoolWrapper from graphon.runtime.variable_pool import VariablePool -from graphon.variables.segments import ArrayObjectSegment +from graphon.variables.segments import ArrayObjectSegment, StringSegment from graphon.variables.template_resolution import convert_template @@ -85,3 +88,26 @@ def test_inserts_array_object_as_json(self) -> None: ) assert nullable.text == '[{"a": null}]' assert ArrayObjectSegment(value=[]).text == "" + + def test_inserts_object_arrays_with_files_and_segments_as_json(self) -> None: + file = File( + file_type=FileType.IMAGE, + transfer_method=FileTransferMethod.REMOTE_URL, + remote_url="https://example.com/image.png", + filename="image.png", + ) + pool = VariablePool.empty() + pool.add( + ("iteration", "output"), + [{"file": file, "group": {"output": StringSegment(value="hello")}}], + ) + + rendered = convert_template( + ReadOnlyVariablePoolWrapper(pool), + '{"items": {{#iteration.output#}}}', + ) + item = json.loads(rendered.text)["items"][0] + + assert item["file"]["remote_url"] == "https://example.com/image.png" + assert item["file"]["filename"] == "image.png" + assert item["group"]["output"] == {"value_type": "string", "value": "hello"} From b5407fa89452fe7135b30a4cb3e41830b775d86f Mon Sep 17 00:00:00 2001 From: WH-2099 Date: Tue, 3 Nov 2026 08:08:04 +0000 Subject: [PATCH 3/6] fix(variables): distinguish file snapshots from JSON data --- ARCHITECTURE.md | 9 +- src/graphon/variables/segments.py | 90 +++++++++++++++-- tests/nodes/test_container_effects.py | 65 +++++++++--- tests/utils/test_variable_utils.py | 138 +++++++++++++++++++++++++- 4 files changed, 273 insertions(+), 29 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index c5b5ea59..dead58c4 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -168,9 +168,12 @@ compatibility details: [Concrete segment models](src/graphon/variables/segments.py) own fixed `value_type` tags and value validation; serialized values select their model by that tag. [Factories](src/graphon/variables/factory.py) infer types for raw values or validate explicit declarations, preserving declared empty arrays and `array[any]` values. See [factory tests](tests/variables/test_factory.py) for declared types and serialized tag selection. -`array[any]` restores serialized [marked file values](src/graphon/file/constants.py) recursively inside arrays and objects using [File validation](src/graphon/file/models.py), preserving file values in container task and variable pool snapshots. -The [segment serializer](src/graphon/variables/utils.py) preserves nested `File` model fields and their identity marker without log redaction; see the [serialization tests](tests/utils/test_variable_utils.py). -Unmarked objects retain their data, and invalid marked files fail validation; see [container tests](tests/nodes/test_container_effects.py) and [workflow tests](tests/workflows/test_full_engine_events.py). +`array[any]` keeps ordinary JSON dictionaries as data, including dictionaries with a file identity marker or the full set of file fields. +Complete snapshots produced without `include` or `exclude` record the locations of actual [File](src/graphon/file/models.py) values in the segment's `file_paths`, preserving their types through variable pool and container task restoration. +These snapshots require string keys on dictionaries containing files; dictionaries without files follow ordinary JSON serialization. +Exports using `include` or `exclude` omit file restoration metadata, as does [dumps_with_segments](src/graphon/variables/utils.py), which exports plain values without log redaction. +Historical `array[any]` snapshots without `file_paths` retain dictionaries as data. +Invalid declared paths or file payloads fail validation; see [serialization tests](tests/utils/test_variable_utils.py) and [container tests](tests/nodes/test_container_effects.py). [VariableBase.copy_with_value](src/graphon/variables/variables.py) validates replacements for assignment nodes, retaining identity and metadata and promoting integer variables when the new value is a float. The [v1 assignment tests](tests/nodes/variable_assigner/test_v1_node.py) and [v2 assignment tests](tests/nodes/variable_assigner/test_v2_node.py) cover invalid updates, fractional results, and clearing arrays while preserving their declared type, including `array[file]`. diff --git a/src/graphon/variables/segments.py b/src/graphon/variables/segments.py index 56720a4d..681e9ea6 100644 --- a/src/graphon/variables/segments.py +++ b/src/graphon/variables/segments.py @@ -2,12 +2,22 @@ import json import sys -from collections.abc import Mapping, Sequence +from collections.abc import Iterator, Mapping, Sequence from typing import Annotated, Any, Literal -from pydantic import AfterValidator, BaseModel, ConfigDict, Field +from pydantic import ( + BaseModel, + ConfigDict, + Field, + SerializationInfo, + SerializerFunctionWrapHandler, + StrictInt, + StrictStr, + TypeAdapter, + model_serializer, + model_validator, +) -from graphon.file.constants import maybe_file_object from graphon.file.models import File from .types import SegmentType @@ -23,13 +33,45 @@ def _mask_token(token: str) -> str: return token[:6] + "*" * 12 + token[-2:] -def _restore_files(value: Any) -> Any: - if maybe_file_object(value): +type FilePath = tuple[StrictStr | StrictInt, ...] + +_FILE_PATHS_ADAPTER = TypeAdapter(list[FilePath]) + + +def _iter_file_paths(value: Any, path: FilePath = ()) -> Iterator[FilePath]: + """Record actual files without interpreting fields inside ordinary JSON.""" + if isinstance(value, File): + yield path + if isinstance(value, (list, tuple)): + for index, item in enumerate(value): + yield from _iter_file_paths(item, (*path, index)) + if isinstance(value, dict): + paths = [ + file_path + for key, item in value.items() + for file_path in _iter_file_paths(item, (*path, key)) + ] + if paths and any(not isinstance(key, str) for key in value): + msg = "File snapshots require string object keys" + raise ValueError(msg) + yield from paths + + +def _restore_files(value: Any, paths: set[FilePath], path: FilePath = ()) -> Any: + """Restore declared files once, leaving unmatched paths for validation.""" + if path in paths: + paths.remove(path) return File.model_validate(value) if isinstance(value, (list, tuple)): - return type(value)(_restore_files(item) for item in value) + return type(value)( + _restore_files(item, paths, (*path, index)) + for index, item in enumerate(value) + ) if isinstance(value, dict): - return {key: _restore_files(item) for key, item in value.items()} + return { + key: _restore_files(item, paths, (*path, key)) + for key, item in value.items() + } return value @@ -203,8 +245,40 @@ def to_segment(self) -> BooleanSegment: class ArrayAnySegment(ArraySegment): + """Keep ordinary JSON distinct from files in complete, unfiltered snapshots. + + Objects containing files require string keys. Exports using include or exclude + are plain JSON and do not carry file types for restoration. + """ + value_type: Literal[SegmentType.ARRAY_ANY] = SegmentType.ARRAY_ANY - value: Annotated[Sequence[Any], AfterValidator(_restore_files)] + value: Sequence[Any] + + @model_serializer(mode="wrap") + def _serialize_with_file_paths( # ruff: ignore[missing-return-type-private-function] - A return type would replace the declared segment JSON Schema. + self, handler: SerializerFunctionWrapHandler, info: SerializationInfo + ): + data = handler(self) + if ( + "value" in data + and info.include is None + and info.exclude is None + and (paths := list(_iter_file_paths(self.value))) + ): + data["file_paths"] = paths + return data + + @model_validator(mode="before") + @classmethod + def _restore_snapshot_files(cls, data: Any) -> Any: + if not isinstance(data, dict) or "file_paths" not in data: + return data + paths = set(_FILE_PATHS_ADAPTER.validate_python(data["file_paths"])) + value = _restore_files(data.get("value"), paths) + if paths: + msg = "Invalid file path in array snapshot" + raise ValueError(msg) + return {**data, "value": value} def to_segment(self) -> ArrayAnySegment: return ArrayAnySegment(value=self.value) diff --git a/tests/nodes/test_container_effects.py b/tests/nodes/test_container_effects.py index 63547cff..7f45dc9e 100644 --- a/tests/nodes/test_container_effects.py +++ b/tests/nodes/test_container_effects.py @@ -101,6 +101,42 @@ def test_container_outputs_keep_their_type_after_snapshot_and_resume( assert result.inputs == {"input": segment.to_object()} +def test_snapshot_distinguishes_files_from_json_in_pool_and_resume_task() -> None: + file = File( + file_type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.LOCAL_FILE, + reference="example-record", + ) + file_data = file.model_dump(mode="json") + value = [file, file_data, {"files": [file, file_data], "file_paths": [[0]]}] + segment = ArrayAnySegment(value=value) + state = RuntimeState( + workflow_id="workflow", variable_pool=VariablePool(), start_at=1 + ) + state.variable_pool.add(("source", "value"), segment) + state.enqueue_ready_task( + ResumeTask( + invocation_id="container-run", + result=ContainerExecutionResult( + metadata={}, + steps=1, + node_run_result=ContainerNodeRunResult(outputs={"output": segment}), + ), + ) + ) + + for _ in range(2): + state = RuntimeState.from_snapshot(state.dumps()) + + stored = state.variable_pool.get_variable(("source", "value")) + assert stored is not None + assert stored.to_object() == value + task = state.ready_queue.get(timeout=0.01) + assert isinstance(task, ResumeTask) + assert isinstance(task.result, ContainerExecutionResult) + assert task.result.node_run_result.outputs["output"].to_object() == value + + @pytest.mark.parametrize("use_builder", [False, True], ids=["direct", "builder"]) def test_live_container_outputs_rebind_variable_selectors(use_builder: bool) -> None: variable = ArrayFileVariable(name="files", selector=["child", "files"], value=[]) @@ -138,21 +174,22 @@ def test_container_values_preserve_secret_types_and_masking() -> None: def test_container_any_array_rejects_invalid_serialized_file() -> None: + snapshot = ContainerNodeRunResult( + outputs={ + "files": ArrayAnySegment( + value=[ + File( + file_type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.LOCAL_FILE, + reference="example-record", + ) + ] + ) + } + ).model_dump(mode="json") + del snapshot["outputs"]["files"]["value"][0]["reference"] with pytest.raises(ValidationError, match="Missing file reference"): - ContainerNodeRunResult.model_validate({ - "outputs": { - "files": { - "value_type": "array[any]", - "value": [ - { - "dify_model_identity": "__dify__file__", - "type": "document", - "transfer_method": "local_file", - }, - ], - }, - }, - }) + ContainerNodeRunResult.model_validate(snapshot) @pytest.mark.parametrize( diff --git a/tests/utils/test_variable_utils.py b/tests/utils/test_variable_utils.py index 52535dec..a3731a41 100644 --- a/tests/utils/test_variable_utils.py +++ b/tests/utils/test_variable_utils.py @@ -1,9 +1,21 @@ import json +from unittest.mock import patch + +import pytest +from jsonschema import Draft202012Validator +from pydantic import TypeAdapter +from pydantic_core import PydanticSerializationError from graphon.file import File, FileTransferMethod, FileType +from graphon.variables.factory import build_segment from graphon.variables.segment_group import SegmentGroup -from graphon.variables.segments import ArrayAnySegment, StringSegment +from graphon.variables.segments import ( + ArrayAnySegment, + SerializableSegment, + StringSegment, +) from graphon.variables.utils import dumps_with_segments, segment_orjson_default +from graphon.variables.variables import StringVariable, Variable def test_segment_orjson_default_uses_match_dispatch() -> None: @@ -14,7 +26,7 @@ def test_segment_orjson_default_uses_match_dispatch() -> None: assert segment_orjson_default(group) == ["value"] -def test_mixed_array_file_values_survive_json_round_trip() -> None: +def test_mixed_array_preserves_plain_file_json() -> None: file = File( file_type=FileType.IMAGE, transfer_method=FileTransferMethod.REMOTE_URL, @@ -32,5 +44,123 @@ def test_mixed_array_file_values_survive_json_round_trip() -> None: assert json.loads(serialized) == value restored = ArrayAnySegment(value=json.loads(serialized)) - assert restored.value[1] == file - assert restored.value[2]["files"][0] == file + assert segment.to_object() == value + assert restored.to_object() == value + + +@pytest.mark.parametrize("json_mode", [False, True], ids=["python", "json"]) +def test_mixed_array_snapshots_distinguish_files_from_plain_json( + json_mode: bool, +) -> None: + file = File( + file_type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.LOCAL_FILE, + reference="upload-id", + ) + file_data = file.model_dump(mode="json") + value = [ + file, + file_data, + {"files": [file, file_data], "file_paths": [[0]]}, + {"dify_model_identity": "__dify__file__"}, + ] + segment = ArrayAnySegment(value=value) + + for _ in range(2): + segment = ( + ArrayAnySegment.model_validate_json(segment.model_dump_json()) + if json_mode + else ArrayAnySegment.model_validate(segment.model_dump()) + ) + + assert segment.to_object() == value + + +@pytest.mark.parametrize("use_plugin_parameter", [False, True]) +def test_mixed_array_preserves_public_file_json(use_plugin_parameter: bool) -> None: + file = File( + file_type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.REMOTE_URL, + remote_url="https://example.com/report.pdf", + related_id="upload-id", + filename="report.pdf", + ) + with patch.object(File, "generate_url", return_value=file.remote_url): + file_data = ( + file.to_plugin_parameter() if use_plugin_parameter else file.to_dict() + ) + value = [None, file_data, {"files": [file_data]}] + + with patch.object( + File, + "generate_url", + side_effect=AssertionError("Must not resolve public file JSON"), + ): + segment = build_segment(value) + serialized = dumps_with_segments(segment) + restored = ArrayAnySegment(value=json.loads(serialized)) + + assert segment.to_object() == value + assert json.loads(serialized) == value + assert restored.to_object() == value + + +@pytest.mark.parametrize("json_mode", [False, True], ids=["python", "json"]) +@pytest.mark.parametrize("include", [False, True], ids=["exclude", "include"]) +@pytest.mark.parametrize("keep_index", [0, 1], ids=["file", "json"]) +@pytest.mark.parametrize("selector", ["value", "__all__"]) +def test_partial_array_dumps_do_not_turn_remaining_json_into_files( + json_mode: bool, include: bool, keep_index: int, selector: str +) -> None: + file = File( + file_type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.LOCAL_FILE, + reference="upload-id", + ) + file_data = file.model_dump(mode="json") + segment = ArrayAnySegment(value=[file, file_data]) + mode = "json" if json_mode else "python" + data = ( + segment.model_dump(mode=mode, include={selector: {keep_index}}) + if include + else segment.model_dump(mode=mode, exclude={selector: {1 - keep_index}}) + ) + + restored = ArrayAnySegment.model_validate(data) + + assert restored.to_object() == [file_data] + + +@pytest.mark.parametrize(("file_key", "plain_key"), [(1, "1"), ("1", 1), ("file", 2)]) +def test_file_snapshots_require_string_keys( + file_key: str | int, plain_key: str | int +) -> None: + file = File( + file_type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.LOCAL_FILE, + reference="upload-id", + ) + value = [{file_key: file, plain_key: file.model_dump(mode="json")}] + + with pytest.raises(PydanticSerializationError, match="string"): + ArrayAnySegment(value=value).model_dump_json() + + +def test_plain_mapping_with_integer_keys_remains_json() -> None: + segment = ArrayAnySegment(value=[{1: "plain"}]) + + assert json.loads(segment.model_dump_json())["value"] == [{"1": "plain"}] + + +@pytest.mark.parametrize("use_variable", [False, True], ids=["segment", "variable"]) +def test_serialized_union_values_match_their_json_schema(use_variable: bool) -> None: + adapter = TypeAdapter(Variable if use_variable else SerializableSegment) + value = ( + StringVariable(name="text", value="hello") + if use_variable + else StringSegment(value="hello") + ) + + Draft202012Validator(adapter.json_schema(mode="serialization")).validate( + adapter.dump_python(value, mode="json") + ) From dc1fa4d913d71dbc458b0d0f76f13c02d41b181e Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 05:46:52 +0000 Subject: [PATCH 4/6] docs: update document review timestamps --- ARCHITECTURE.md | 2 +- src/graphon/model_runtime/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index dead58c4..f226dd34 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -1,5 +1,5 @@ # Architecture diff --git a/src/graphon/model_runtime/README.md b/src/graphon/model_runtime/README.md index fbd9afb3..faa7a07b 100644 --- a/src/graphon/model_runtime/README.md +++ b/src/graphon/model_runtime/README.md @@ -1,5 +1,5 @@ # Model Runtime From 7e8007a1b12f33a04d3c48f460fce9f51c42abbc Mon Sep 17 00:00:00 2001 From: WH-2099 Date: Wed, 11 Nov 2026 07:10:53 +0000 Subject: [PATCH 5/6] fix(variables): preserve files through nested model snapshots --- ARCHITECTURE.md | 7 +- docs/development.md | 2 +- src/graphon/file/models.py | 18 +- src/graphon/file/serialization.py | 31 +++ src/graphon/variables/file_snapshot.py | 112 ++++++++++ src/graphon/variables/segments.py | 71 +------ tests/nodes/test_container_effects.py | 42 ++++ tests/utils/test_variable_utils.py | 94 --------- tests/variables/test_file_snapshots.py | 281 +++++++++++++++++++++++++ 9 files changed, 499 insertions(+), 159 deletions(-) create mode 100644 src/graphon/file/serialization.py create mode 100644 src/graphon/variables/file_snapshot.py create mode 100644 tests/variables/test_file_snapshots.py diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index f226dd34..385f92c6 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -169,11 +169,14 @@ compatibility details: [Factories](src/graphon/variables/factory.py) infer types for raw values or validate explicit declarations, preserving declared empty arrays and `array[any]` values. See [factory tests](tests/variables/test_factory.py) for declared types and serialized tag selection. `array[any]` keeps ordinary JSON dictionaries as data, including dictionaries with a file identity marker or the full set of file fields. -Complete snapshots produced without `include` or `exclude` record the locations of actual [File](src/graphon/file/models.py) values in the segment's `file_paths`, preserving their types through variable pool and container task restoration. +Complete snapshots produced without `include` or `exclude` use [file snapshot serialization](src/graphon/variables/file_snapshot.py) to record actual [File](src/graphon/file/models.py) locations in `file_paths`. +Paths follow Pydantic's Python serialization of nested values, honoring declared model fields, aliases, field exclusions, and caller context. +Nested models become plain data; sequences, sets, and iterators become arrays, while recorded files restore as `File` objects through variable pool and container task restoration. +[File serialization markers](src/graphon/file/serialization.py) are scoped to this projection and reset on exit, including serialization errors. These snapshots require string keys on dictionaries containing files; dictionaries without files follow ordinary JSON serialization. Exports using `include` or `exclude` omit file restoration metadata, as does [dumps_with_segments](src/graphon/variables/utils.py), which exports plain values without log redaction. Historical `array[any]` snapshots without `file_paths` retain dictionaries as data. -Invalid declared paths or file payloads fail validation; see [serialization tests](tests/utils/test_variable_utils.py) and [container tests](tests/nodes/test_container_effects.py). +Invalid declared paths or file payloads fail validation; see [snapshot tests](tests/variables/test_file_snapshots.py), [plain value export tests](tests/utils/test_variable_utils.py), and [container tests](tests/nodes/test_container_effects.py). [VariableBase.copy_with_value](src/graphon/variables/variables.py) validates replacements for assignment nodes, retaining identity and metadata and promoting integer variables when the new value is a float. The [v1 assignment tests](tests/nodes/variable_assigner/test_v1_node.py) and [v2 assignment tests](tests/nodes/variable_assigner/test_v2_node.py) cover invalid updates, fractional results, and clearing arrays while preserving their declared type, including `array[file]`. diff --git a/docs/development.md b/docs/development.md index e7a94952..49b45c32 100644 --- a/docs/development.md +++ b/docs/development.md @@ -30,7 +30,7 @@ Follow the [variable and container contracts](../ARCHITECTURE.md#state-and-execu | Change dispatch, scheduling, or containers | [engine](../src/graphon/engine/), [container effects](../src/graphon/nodes/container_effects.py) | [engine tests](../tests/engine/), [container values](../tests/nodes/test_container_effects.py), [container dispatch](../tests/nodes/test_container_dispatch.py), [workflow events](../tests/workflows/test_full_engine_events.py) | | Change event payloads or response streaming | [raw frame observations](../ARCHITECTURE.md#raw-frame-observations), [node events](../src/graphon/node_events/), [engine events](../src/graphon/engine_events/), [filters](../src/graphon/engine/filter/) | [frame observation tests](../tests/engine/test_frame_observations.py), [frame failure tests](../tests/engine/test_frame_failures.py), [node event tests](../tests/node_events/), [engine event tests](../tests/engine_events/), [response filter tests](../tests/engine/test_response_stream_filter.py) | | Change variables or secrets | [variable pool](../src/graphon/runtime/variable_pool.py), [segment models](../src/graphon/variables/segments.py), [variable models](../src/graphon/variables/variables.py), [conversion](../src/graphon/variables/factory.py), [variable assignment](../src/graphon/nodes/variable_assigner/) | [variable pool tests](../tests/runtime/test_variable_pool.py), [Iteration variable ownership](../tests/engine/test_iteration_variable_scopes.py), [variable tests](../tests/variables/), [assignment tests](../tests/nodes/variable_assigner/), [HTTP secret masking](../tests/http/test_executor_secret_masking.py) | -| Change persistence or resume | [runtime state](../src/graphon/runtime/runtime_state/), [container state](../src/graphon/runtime/container_state.py) | [runtime tests](../tests/runtime/), [engine serialization](../tests/engine/test_runtime_state_serialization.py), [frame failure restoration](../tests/engine/test_frame_failures.py), [version isolation](../tests/test_snapshot_version_isolation.py) | +| Change persistence or resume | [runtime state](../src/graphon/runtime/runtime_state/), [container state](../src/graphon/runtime/container_state.py), [nested file snapshots](../src/graphon/variables/file_snapshot.py) | [runtime tests](../tests/runtime/), [file snapshots](../tests/variables/test_file_snapshots.py), [engine serialization](../tests/engine/test_runtime_state_serialization.py), [frame failure restoration](../tests/engine/test_frame_failures.py), [version isolation](../tests/test_snapshot_version_isolation.py) | | Change model invocation | [graph-facing LLM protocol](../src/graphon/nodes/llm/runtime_protocols.py), [Slim adapter](../src/graphon/dsl/slim/llm.py), [model runtime](../src/graphon/model_runtime/) | [LLM node tests](../tests/nodes/llm/), [Slim tests](../tests/dsl/test_slim_llm.py), [model dispatch](../tests/model_runtime/test_model_dispatch.py) | | Change file or HTTP integration | [file](../src/graphon/file/), [engine adapter binding](../src/graphon/engine/engine.py), [HTTP](../src/graphon/http/), [node ports](../src/graphon/nodes/protocols.py) | [file tests](../tests/file/), [execution file isolation](../tests/engine/test_file_runtime.py), [HTTP tests](../tests/http/), [HTTP node tests](../tests/nodes/http_request/), [extractor tests](../tests/nodes/document_extractor/) | diff --git a/src/graphon/file/models.py b/src/graphon/file/models.py index d8294f2d..6d0637ed 100644 --- a/src/graphon/file/models.py +++ b/src/graphon/file/models.py @@ -5,13 +5,21 @@ from collections.abc import Mapping, Sequence from typing import Any, assert_never -from pydantic import BaseModel, Field, model_validator +from pydantic import ( + BaseModel, + Field, + SerializationInfo, + SerializerFunctionWrapHandler, + model_serializer, + model_validator, +) from graphon.model_runtime.entities.message_entities import ImagePromptMessageContent from . import helpers from .constants import FILE_MODEL_IDENTITY from .enums import FileTransferMethod, FileType +from .serialization import SerializedFile, file_markers_enabled _FILE_REFERENCE_PREFIX = "dify-file-ref:" @@ -112,6 +120,14 @@ class File(BaseModel): size: int = -1 _storage_key: str + @model_serializer(mode="wrap") + def _serialize_file( # ruff: ignore[missing-return-type-private-function] - Keep the declared File JSON Schema. + self, handler: SerializerFunctionWrapHandler, info: SerializationInfo + ): + if info.mode == "python" and file_markers_enabled(): + return SerializedFile(handler(self)) + return handler(self) + def __init__( self, *, diff --git a/src/graphon/file/serialization.py b/src/graphon/file/serialization.py new file mode 100644 index 00000000..e3057a4e --- /dev/null +++ b/src/graphon/file/serialization.py @@ -0,0 +1,31 @@ +"""Scoped file markers that retain Pydantic's selected fields during projection.""" + +from collections.abc import Generator +from contextlib import contextmanager +from contextvars import ContextVar +from typing import Any, Final + +_FILE_MARKERS_ENABLED: Final[ContextVar[bool]] = ContextVar( + "file_markers_enabled", default=False +) + + +class SerializedFile: # ruff: ignore[class-as-data-structure] - Pydantic would serialize a dataclass and lose the file marker. + __slots__ = ("data",) + + def __init__(self, data: dict[str, Any]) -> None: + self.data = data + + +def file_markers_enabled() -> bool: + return _FILE_MARKERS_ENABLED.get() + + +@contextmanager +def mark_serialized_files() -> Generator[None]: + """Mark files while Pydantic projects their enclosing models.""" + token = _FILE_MARKERS_ENABLED.set(True) + try: + yield + finally: + _FILE_MARKERS_ENABLED.reset(token) diff --git a/src/graphon/variables/file_snapshot.py b/src/graphon/variables/file_snapshot.py new file mode 100644 index 00000000..d16e005c --- /dev/null +++ b/src/graphon/variables/file_snapshot.py @@ -0,0 +1,112 @@ +"""Snapshot untyped values without interpreting ordinary JSON as files.""" + +from __future__ import annotations + +from collections.abc import Iterator, Mapping, Sequence +from collections.abc import Set as AbstractSet +from typing import TYPE_CHECKING, Any + +from pydantic import ( + SerializationInfo, + SerializerFunctionWrapHandler, + StrictInt, + StrictStr, + TypeAdapter, +) + +from graphon.file.models import File +from graphon.file.serialization import SerializedFile, mark_serialized_files + +if TYPE_CHECKING: + from .segments import Segment + +type FilePath = tuple[StrictStr | StrictInt, ...] + +_VALUE_ADAPTER = TypeAdapter(Any) +_FILE_PATHS_ADAPTER = TypeAdapter(list[FilePath]) + + +def serialize_file_snapshot( + model: Segment, handler: SerializerFunctionWrapHandler, info: SerializationInfo +) -> dict[str, Any]: + """Project models once, then record files in the resulting snapshot tree.""" + if info.include is not None or info.exclude is not None: + with mark_serialized_files(): + data = handler(model) + if "value" in data: + data["value"] = _collect_file_paths(data["value"], None) + return data + with mark_serialized_files(): + serialized_value = _VALUE_ADAPTER.dump_python( + model.value, + context=info.context, + by_alias=info.by_alias, + exclude_unset=info.exclude_unset, + exclude_defaults=info.exclude_defaults, + exclude_none=info.exclude_none, + round_trip=info.round_trip, + serialize_as_any=info.serialize_as_any, + ) + paths: list[FilePath] = [] + value = _collect_file_paths(serialized_value, paths) + data = handler(model.model_copy(update={"value": value})) + if paths and "value" in data: + data["file_paths"] = paths + return data + + +def _collect_file_paths( + value: Any, paths: list[FilePath] | None, path: FilePath = () +) -> Any: + if isinstance(value, SerializedFile): + if paths is not None: + paths.append(path) + return value.data + if isinstance(value, Mapping): + path_count = len(paths or ()) + result = { + key: _collect_file_paths(item, paths, (*path, key)) + for key, item in value.items() + } + if ( + paths is not None + and len(paths) > path_count + and any(not isinstance(key, str) for key in value) + ): + msg = "File snapshots require string object keys" + raise ValueError(msg) + return result + if isinstance(value, (Sequence, AbstractSet, Iterator)) and not isinstance( + value, (str, bytes, bytearray) + ): + return [ + _collect_file_paths(item, paths, (*path, index)) + for index, item in enumerate(value) + ] + return value + + +def restore_file_snapshot(value: Any, file_paths: Any) -> Any: + paths = set(_FILE_PATHS_ADAPTER.validate_python(file_paths)) + restored = _restore_files(value, paths) + if paths: + msg = "Invalid file path in array snapshot" + raise ValueError(msg) + return restored + + +def _restore_files(value: Any, paths: set[FilePath], path: FilePath = ()) -> Any: + if path in paths: + paths.remove(path) + return File.model_validate(value) + if isinstance(value, (list, tuple)): + return type(value)( + _restore_files(item, paths, (*path, index)) + for index, item in enumerate(value) + ) + if isinstance(value, dict): + return { + key: _restore_files(item, paths, (*path, key)) + for key, item in value.items() + } + return value diff --git a/src/graphon/variables/segments.py b/src/graphon/variables/segments.py index 681e9ea6..885378c7 100644 --- a/src/graphon/variables/segments.py +++ b/src/graphon/variables/segments.py @@ -2,7 +2,7 @@ import json import sys -from collections.abc import Iterator, Mapping, Sequence +from collections.abc import Mapping, Sequence from typing import Annotated, Any, Literal from pydantic import ( @@ -11,15 +11,14 @@ Field, SerializationInfo, SerializerFunctionWrapHandler, - StrictInt, - StrictStr, - TypeAdapter, model_serializer, model_validator, ) from graphon.file.models import File +from graphon.file.serialization import file_markers_enabled +from .file_snapshot import restore_file_snapshot, serialize_file_snapshot from .types import SegmentType SHORT_TOKEN_MAX_LENGTH = 8 @@ -33,48 +32,6 @@ def _mask_token(token: str) -> str: return token[:6] + "*" * 12 + token[-2:] -type FilePath = tuple[StrictStr | StrictInt, ...] - -_FILE_PATHS_ADAPTER = TypeAdapter(list[FilePath]) - - -def _iter_file_paths(value: Any, path: FilePath = ()) -> Iterator[FilePath]: - """Record actual files without interpreting fields inside ordinary JSON.""" - if isinstance(value, File): - yield path - if isinstance(value, (list, tuple)): - for index, item in enumerate(value): - yield from _iter_file_paths(item, (*path, index)) - if isinstance(value, dict): - paths = [ - file_path - for key, item in value.items() - for file_path in _iter_file_paths(item, (*path, key)) - ] - if paths and any(not isinstance(key, str) for key in value): - msg = "File snapshots require string object keys" - raise ValueError(msg) - yield from paths - - -def _restore_files(value: Any, paths: set[FilePath], path: FilePath = ()) -> Any: - """Restore declared files once, leaving unmatched paths for validation.""" - if path in paths: - paths.remove(path) - return File.model_validate(value) - if isinstance(value, (list, tuple)): - return type(value)( - _restore_files(item, paths, (*path, index)) - for index, item in enumerate(value) - ) - if isinstance(value, dict): - return { - key: _restore_files(item, paths, (*path, key)) - for key, item in value.items() - } - return value - - class Segment(BaseModel): """Segment is runtime type used during the execution of workflow. @@ -258,27 +215,19 @@ class ArrayAnySegment(ArraySegment): def _serialize_with_file_paths( # ruff: ignore[missing-return-type-private-function] - A return type would replace the declared segment JSON Schema. self, handler: SerializerFunctionWrapHandler, info: SerializationInfo ): - data = handler(self) - if ( - "value" in data - and info.include is None - and info.exclude is None - and (paths := list(_iter_file_paths(self.value))) - ): - data["file_paths"] = paths - return data + if file_markers_enabled(): + return handler(self) + return serialize_file_snapshot(self, handler, info) @model_validator(mode="before") @classmethod def _restore_snapshot_files(cls, data: Any) -> Any: if not isinstance(data, dict) or "file_paths" not in data: return data - paths = set(_FILE_PATHS_ADAPTER.validate_python(data["file_paths"])) - value = _restore_files(data.get("value"), paths) - if paths: - msg = "Invalid file path in array snapshot" - raise ValueError(msg) - return {**data, "value": value} + return { + **data, + "value": restore_file_snapshot(data.get("value"), data["file_paths"]), + } def to_segment(self) -> ArrayAnySegment: return ArrayAnySegment(value=self.value) diff --git a/tests/nodes/test_container_effects.py b/tests/nodes/test_container_effects.py index 7f45dc9e..4725b5df 100644 --- a/tests/nodes/test_container_effects.py +++ b/tests/nodes/test_container_effects.py @@ -19,6 +19,7 @@ ArrayNumberSegment, ArrayObjectSegment, ArrayStringSegment, + FileSegment, IntegerSegment, SerializableSegment, ) @@ -137,6 +138,47 @@ def test_snapshot_distinguishes_files_from_json_in_pool_and_resume_task() -> Non assert task.result.node_run_result.outputs["output"].to_object() == value +def test_nested_file_remains_downloadable_after_snapshot( + monkeypatch: pytest.MonkeyPatch, +) -> None: + file = File( + file_type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.LOCAL_FILE, + reference="upload-id", + ) + segment = ArrayAnySegment(value=[FileSegment(value=file)]) + state = RuntimeState( + workflow_id="workflow", variable_pool=VariablePool(), start_at=1 + ) + state.variable_pool.add(("source", "value"), segment) + state.enqueue_ready_task( + ResumeTask( + invocation_id="container-run", + result=ContainerExecutionResult( + metadata={}, + steps=1, + node_run_result=ContainerNodeRunResult(outputs={"output": segment}), + ), + ) + ) + for _ in range(2): + state = RuntimeState.from_snapshot(state.dumps()) + + task = state.ready_queue.get(timeout=0.01) + assert isinstance(task, ResumeTask) + assert isinstance(task.result, ContainerExecutionResult) + monkeypatch.setattr( + File, "generate_url", lambda *_args, **_kwargs: "https://example.com/download" + ) + result = WorkflowRuntimeTypeConverter().to_json_encodable({ + "pool": state.variable_pool.get_variable(("source", "value")), + "task": task.result.node_run_result.outputs["output"], + }) + + assert result["pool"][0]["value"]["url"] == "https://example.com/download" + assert result["task"][0]["value"]["url"] == "https://example.com/download" + + @pytest.mark.parametrize("use_builder", [False, True], ids=["direct", "builder"]) def test_live_container_outputs_rebind_variable_selectors(use_builder: bool) -> None: variable = ArrayFileVariable(name="files", selector=["child", "files"], value=[]) diff --git a/tests/utils/test_variable_utils.py b/tests/utils/test_variable_utils.py index a3731a41..00b283fc 100644 --- a/tests/utils/test_variable_utils.py +++ b/tests/utils/test_variable_utils.py @@ -2,20 +2,15 @@ from unittest.mock import patch import pytest -from jsonschema import Draft202012Validator -from pydantic import TypeAdapter -from pydantic_core import PydanticSerializationError from graphon.file import File, FileTransferMethod, FileType from graphon.variables.factory import build_segment from graphon.variables.segment_group import SegmentGroup from graphon.variables.segments import ( ArrayAnySegment, - SerializableSegment, StringSegment, ) from graphon.variables.utils import dumps_with_segments, segment_orjson_default -from graphon.variables.variables import StringVariable, Variable def test_segment_orjson_default_uses_match_dispatch() -> None: @@ -48,34 +43,6 @@ def test_mixed_array_preserves_plain_file_json() -> None: assert restored.to_object() == value -@pytest.mark.parametrize("json_mode", [False, True], ids=["python", "json"]) -def test_mixed_array_snapshots_distinguish_files_from_plain_json( - json_mode: bool, -) -> None: - file = File( - file_type=FileType.DOCUMENT, - transfer_method=FileTransferMethod.LOCAL_FILE, - reference="upload-id", - ) - file_data = file.model_dump(mode="json") - value = [ - file, - file_data, - {"files": [file, file_data], "file_paths": [[0]]}, - {"dify_model_identity": "__dify__file__"}, - ] - segment = ArrayAnySegment(value=value) - - for _ in range(2): - segment = ( - ArrayAnySegment.model_validate_json(segment.model_dump_json()) - if json_mode - else ArrayAnySegment.model_validate(segment.model_dump()) - ) - - assert segment.to_object() == value - - @pytest.mark.parametrize("use_plugin_parameter", [False, True]) def test_mixed_array_preserves_public_file_json(use_plugin_parameter: bool) -> None: file = File( @@ -103,64 +70,3 @@ def test_mixed_array_preserves_public_file_json(use_plugin_parameter: bool) -> N assert segment.to_object() == value assert json.loads(serialized) == value assert restored.to_object() == value - - -@pytest.mark.parametrize("json_mode", [False, True], ids=["python", "json"]) -@pytest.mark.parametrize("include", [False, True], ids=["exclude", "include"]) -@pytest.mark.parametrize("keep_index", [0, 1], ids=["file", "json"]) -@pytest.mark.parametrize("selector", ["value", "__all__"]) -def test_partial_array_dumps_do_not_turn_remaining_json_into_files( - json_mode: bool, include: bool, keep_index: int, selector: str -) -> None: - file = File( - file_type=FileType.DOCUMENT, - transfer_method=FileTransferMethod.LOCAL_FILE, - reference="upload-id", - ) - file_data = file.model_dump(mode="json") - segment = ArrayAnySegment(value=[file, file_data]) - mode = "json" if json_mode else "python" - data = ( - segment.model_dump(mode=mode, include={selector: {keep_index}}) - if include - else segment.model_dump(mode=mode, exclude={selector: {1 - keep_index}}) - ) - - restored = ArrayAnySegment.model_validate(data) - - assert restored.to_object() == [file_data] - - -@pytest.mark.parametrize(("file_key", "plain_key"), [(1, "1"), ("1", 1), ("file", 2)]) -def test_file_snapshots_require_string_keys( - file_key: str | int, plain_key: str | int -) -> None: - file = File( - file_type=FileType.DOCUMENT, - transfer_method=FileTransferMethod.LOCAL_FILE, - reference="upload-id", - ) - value = [{file_key: file, plain_key: file.model_dump(mode="json")}] - - with pytest.raises(PydanticSerializationError, match="string"): - ArrayAnySegment(value=value).model_dump_json() - - -def test_plain_mapping_with_integer_keys_remains_json() -> None: - segment = ArrayAnySegment(value=[{1: "plain"}]) - - assert json.loads(segment.model_dump_json())["value"] == [{"1": "plain"}] - - -@pytest.mark.parametrize("use_variable", [False, True], ids=["segment", "variable"]) -def test_serialized_union_values_match_their_json_schema(use_variable: bool) -> None: - adapter = TypeAdapter(Variable if use_variable else SerializableSegment) - value = ( - StringVariable(name="text", value="hello") - if use_variable - else StringSegment(value="hello") - ) - - Draft202012Validator(adapter.json_schema(mode="serialization")).validate( - adapter.dump_python(value, mode="json") - ) diff --git a/tests/variables/test_file_snapshots.py b/tests/variables/test_file_snapshots.py new file mode 100644 index 00000000..7144d606 --- /dev/null +++ b/tests/variables/test_file_snapshots.py @@ -0,0 +1,281 @@ +import json +from collections import deque +from dataclasses import dataclass +from typing import Literal, cast + +import pytest +from jsonschema import Draft202012Validator +from pydantic import ( + BaseModel, + ConfigDict, + Field, + RootModel, + SerializationInfo, + TypeAdapter, + model_serializer, +) +from pydantic_core import PydanticSerializationError + +from graphon.file import File, FileTransferMethod, FileType +from graphon.variables.segments import ( + ArrayAnySegment, + FileSegment, + ObjectSegment, + SerializableSegment, + StringSegment, +) +from graphon.variables.variables import StringVariable, Variable + + +@pytest.mark.parametrize("mode", ["python", "json"]) +def test_snapshots_preserve_files_inside_serializable_models( + mode: Literal["python", "json"], +) -> None: + class Attachment(BaseModel): + visible: File = Field(serialization_alias="file") + hidden: File = Field(exclude=True) + + @dataclass + class Document: + file: File + + class CustomAttachment(BaseModel): + file: File + + @model_serializer + def serialize_attachment(self, info: SerializationInfo) -> dict[str, File]: + return {cast("dict[str, str]", info.context)["file_field"]: self.file} + + file = File( + file_type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.LOCAL_FILE, + reference="upload-id", + ) + file_data = file.model_dump(mode="json") + segment = ArrayAnySegment( + value=[ + FileSegment(value=file), + ObjectSegment(value={"file": file, "json": file_data}), + ArrayAnySegment(value=[file, file_data]), + Attachment(visible=file, hidden=file), + Document(file), + RootModel[File](file), + CustomAttachment(file=file), + deque([file, file_data]), + ] + ) + for _ in range(2): + snapshot = segment.model_dump( + mode=mode, by_alias=True, context={"file_field": "attachment"} + ) + segment = ArrayAnySegment.model_validate(snapshot) + + value = segment.value + assert value[0] == {"value_type": "file", "value": file} + assert value[1] == { + "value_type": "object", + "value": {"file": file, "json": file_data}, + } + assert value[2]["value_type"] == "array[any]" + assert value[2]["value"] == [file, file_data] + assert value[3] == {"file": file} + assert value[4] == {"file": file} + assert value[5] == file + assert value[6] == {"attachment": file} + assert list(value[7]) == [file, file_data] + + +def test_snapshots_keep_the_declared_file_fields() -> None: + class InternalFile(File): + credential: str = "private-credential" + + class Attachment(BaseModel): + file: File + + file = InternalFile( + type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.LOCAL_FILE, + reference="upload-id", + ) + attachment = Attachment(file=file) + + snapshot = ArrayAnySegment(value=[attachment]).model_dump(mode="json") + + assert snapshot["value"] == [attachment.model_dump(mode="json")] + restored = ArrayAnySegment.model_validate(snapshot) + assert isinstance(restored.value[0]["file"], File) + assert restored.value[0]["file"].reference == "upload-id" + + +def test_snapshots_keep_the_declared_segment_fields() -> None: + class InternalArray(ArrayAnySegment): + credential: str = "private-credential" + + class Result(BaseModel): + output: ArrayAnySegment + + file = File( + file_type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.LOCAL_FILE, + reference="upload-id", + ) + result = Result(output=InternalArray(value=[file])) + + snapshot = result.model_dump(mode="json") + + assert "credential" not in snapshot["output"] + restored = Result.model_validate(snapshot) + assert isinstance(restored.output.value[0], File) + assert restored.output.value[0].reference == "upload-id" + + +def test_failed_snapshots_leave_file_serialization_unchanged() -> None: + class BrokenAttachment(BaseModel): + file: File + + @model_serializer + def serialize_attachment(self) -> dict[str, File]: + msg = "Cannot serialize attachment" + raise ValueError(msg) + + file = File( + file_type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.LOCAL_FILE, + reference="upload-id", + ) + original = file.model_dump() + + with pytest.raises(PydanticSerializationError, match="Cannot serialize attachment"): + ArrayAnySegment(value=[file, BrokenAttachment(file=file)]).model_dump_json() + + assert file.model_dump() == original + + +@pytest.mark.parametrize("mode", ["python", "json"]) +def test_filtered_exports_allow_plain_json_object_keys( + mode: Literal["python", "json"], +) -> None: + file = File( + file_type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.LOCAL_FILE, + reference="upload-id", + ) + segment = ArrayAnySegment(value=[{7: file}, None]) + + data = segment.model_dump(mode=mode, exclude={"value": {1}}) + + key = 7 if mode == "python" else "7" + assert data["value"] == [{key: file.model_dump(mode=mode)}] + assert "file_paths" not in data + + +@pytest.mark.parametrize("container", [set, frozenset]) +def test_snapshots_preserve_files_in_sets( + container: type[set] | type[frozenset], +) -> None: + class FrozenFile(File): + model_config = ConfigDict(frozen=True) + + file = FrozenFile( + type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.LOCAL_FILE, + reference="upload-id", + ) + file_data = file.model_dump(mode="json") + segment = ArrayAnySegment(value=[container([file]), file_data]) + + restored = ArrayAnySegment.model_validate_json(segment.model_dump_json()) + + assert len(restored.value[0]) == 1 + assert isinstance(restored.value[0][0], File) + assert restored.value[0][0].reference == "upload-id" + assert restored.value[1] == file_data + + +@pytest.mark.parametrize("json_mode", [False, True], ids=["python", "json"]) +def test_mixed_array_snapshots_distinguish_files_from_plain_json( + json_mode: bool, +) -> None: + file = File( + file_type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.LOCAL_FILE, + reference="upload-id", + ) + file_data = file.model_dump(mode="json") + value = [ + file, + file_data, + {"files": [file, file_data], "file_paths": [[0]]}, + {"dify_model_identity": "__dify__file__"}, + ] + segment = ArrayAnySegment(value=value) + + for _ in range(2): + segment = ( + ArrayAnySegment.model_validate_json(segment.model_dump_json()) + if json_mode + else ArrayAnySegment.model_validate(segment.model_dump()) + ) + + assert segment.to_object() == value + + +@pytest.mark.parametrize("json_mode", [False, True], ids=["python", "json"]) +@pytest.mark.parametrize("include", [False, True], ids=["exclude", "include"]) +@pytest.mark.parametrize("keep_index", [0, 1], ids=["file", "json"]) +@pytest.mark.parametrize("selector", ["value", "__all__"]) +def test_partial_array_dumps_do_not_turn_remaining_json_into_files( + json_mode: bool, include: bool, keep_index: int, selector: str +) -> None: + file = File( + file_type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.LOCAL_FILE, + reference="upload-id", + ) + file_data = file.model_dump(mode="json") + segment = ArrayAnySegment(value=[file, file_data]) + mode = "json" if json_mode else "python" + data = ( + segment.model_dump(mode=mode, include={selector: {keep_index}}) + if include + else segment.model_dump(mode=mode, exclude={selector: {1 - keep_index}}) + ) + + restored = ArrayAnySegment.model_validate(data) + + assert restored.to_object() == [file_data] + + +@pytest.mark.parametrize(("file_key", "plain_key"), [(1, "1"), ("1", 1), ("file", 2)]) +def test_file_snapshots_require_string_keys( + file_key: str | int, plain_key: str | int +) -> None: + file = File( + file_type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.LOCAL_FILE, + reference="upload-id", + ) + value = [{file_key: file, plain_key: file.model_dump(mode="json")}] + + with pytest.raises(PydanticSerializationError, match="string"): + ArrayAnySegment(value=value).model_dump_json() + + +def test_plain_mapping_with_integer_keys_remains_json() -> None: + segment = ArrayAnySegment(value=[{1: "plain"}]) + + assert json.loads(segment.model_dump_json())["value"] == [{"1": "plain"}] + + +@pytest.mark.parametrize("use_variable", [False, True], ids=["segment", "variable"]) +def test_serialized_union_values_match_their_json_schema(use_variable: bool) -> None: + adapter = TypeAdapter(Variable if use_variable else SerializableSegment) + value = ( + StringVariable(name="text", value="hello") + if use_variable + else StringSegment(value="hello") + ) + + Draft202012Validator(adapter.json_schema(mode="serialization")).validate( + adapter.dump_python(value, mode="json") + ) From 61274674d641b62d8bc82d0a9c82ca4fa1a34217 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 07:11:15 +0000 Subject: [PATCH 6/6] docs: update document review timestamps --- docs/development.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/development.md b/docs/development.md index 49b45c32..44a31a44 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,5 +1,5 @@ # Development navigation