pineapple-apple 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
apple/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ # Apple DSL — Python pipeline declaration for Pineapple
2
+ from apple._version import __version__
3
+ from apple.flow import Flow, SubFlow
4
+
5
+ __all__ = ["Flow", "SubFlow", "__version__"]
apple/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
apple/base.py ADDED
@@ -0,0 +1,94 @@
1
+ """Base operator class for Apple DSL.
2
+
3
+ All generated operator classes inherit from BaseOp. The _apply method records
4
+ operator invocations for later compilation to JSON.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import inspect
10
+ from dataclasses import dataclass, field
11
+ from typing import Any
12
+
13
+
14
+ @dataclass
15
+ class OpCall:
16
+ """Record of a single operator invocation in a flow."""
17
+ type_name: str
18
+ params: dict[str, Any]
19
+ common_input: list[str] = field(default_factory=list)
20
+ common_output: list[str] = field(default_factory=list)
21
+ item_input: list[str] = field(default_factory=list)
22
+ item_output: list[str] = field(default_factory=list)
23
+ item_defaults: dict[str, Any] | None = None
24
+ common_defaults: dict[str, Any] | None = None
25
+ # Engine-level flags
26
+ recall: bool = False
27
+ sources: list[str] | None = None
28
+ skip: str | None = None
29
+ for_branch_control: bool = False
30
+ debug: bool = False
31
+ # Debug info
32
+ code_info: str = ""
33
+ # Explicit name (overrides auto-generated name)
34
+ name: str = ""
35
+
36
+ def unique_name(self) -> str:
37
+ """Return explicit name if set, otherwise generate type_name_HASH6."""
38
+ if self.name:
39
+ return self.name
40
+ h = hashlib.md5(repr(self).encode()).hexdigest()[:6].upper()
41
+ return f"{self.type_name}_{h}"
42
+
43
+
44
+ class BaseOp:
45
+ """Base class for all operator types in the Apple DSL.
46
+
47
+ Subclasses define _name and _params_schema. The __call__ method delegates
48
+ to _apply, which records the call into the owning flow.
49
+ """
50
+ _name: str = ""
51
+ _params_schema: dict[str, Any] = {}
52
+
53
+ def __init__(self, flow: Any):
54
+ self._flow = flow
55
+
56
+ def _apply(
57
+ self,
58
+ params: dict[str, Any],
59
+ common_input: list[str] | None = None,
60
+ common_output: list[str] | None = None,
61
+ item_input: list[str] | None = None,
62
+ item_output: list[str] | None = None,
63
+ item_defaults: dict[str, Any] | None = None,
64
+ common_defaults: dict[str, Any] | None = None,
65
+ recall: bool = False,
66
+ sources: list[str] | None = None,
67
+ debug: bool = False,
68
+ name: str = "",
69
+ ) -> Any:
70
+ # Capture caller location for $code_info
71
+ code_info = ""
72
+ try:
73
+ frame = inspect.stack()[1]
74
+ code_info = f"{frame.filename}:{frame.lineno} in {frame.function}(): .{self._name}(...)"
75
+ except (IndexError, AttributeError):
76
+ pass
77
+
78
+ call = OpCall(
79
+ type_name=self._name,
80
+ params=params,
81
+ common_input=common_input or [],
82
+ common_output=common_output or [],
83
+ item_input=item_input or [],
84
+ item_output=item_output or [],
85
+ item_defaults=item_defaults,
86
+ common_defaults=common_defaults,
87
+ recall=recall,
88
+ sources=sources,
89
+ debug=debug,
90
+ code_info=code_info,
91
+ name=name,
92
+ )
93
+ self._flow._ops.append(call)
94
+ return self._flow
apple/compiler.py ADDED
@@ -0,0 +1,177 @@
1
+ """Compile a Flow into the Pine JSON config format.
2
+
3
+ Steps:
4
+ 1. Flatten sub_flows into single operator sequence
5
+ 2. Lower control flow (if_/elseif_/else_/end_if_) to Lua operators + skip fields
6
+ 3. Auto-generate unique operator names: {type_name}_{hash6}
7
+ 4. Validate field coverage and write-without-read
8
+ 5. Dead-code detection (if output contract declared)
9
+ 6. Emit JSON with pipeline_config, pipeline_group, flow_contract
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ from datetime import datetime, timezone
15
+ from typing import Any
16
+
17
+ from apple.base import OpCall
18
+ from apple._version import __version__
19
+ from apple.validator import (
20
+ ValidationError,
21
+ detect_dead_code,
22
+ validate_field_coverage,
23
+ validate_write_without_read,
24
+ )
25
+
26
+
27
+ def compile_flow(flow: Any) -> dict[str, Any]:
28
+ """Compile a Flow object into a Pine JSON config dict."""
29
+ # 1. Flatten ops from flow + sub_flows
30
+ all_ops: list[OpCall] = []
31
+ sub_flow_boundaries: dict[str, list[int]] = {} # name -> [start, end)
32
+
33
+ if flow._sub_flows:
34
+ for sf in flow._sub_flows:
35
+ start = len(all_ops)
36
+ all_ops.extend(sf._ops)
37
+ sub_flow_boundaries[sf._name] = [start, len(all_ops)]
38
+ if flow._ops:
39
+ start = len(all_ops)
40
+ all_ops.extend(flow._ops)
41
+ sub_flow_boundaries[f"_main_{flow._name}"] = [start, len(all_ops)]
42
+
43
+ # 2. Generate unique names
44
+ named_ops: list[tuple[str, OpCall]] = []
45
+ name_counts: dict[str, int] = {}
46
+ for op in all_ops:
47
+ name = op.unique_name()
48
+ if op.name:
49
+ # Explicit name — must be unique
50
+ if name in name_counts:
51
+ raise ValidationError(
52
+ f"duplicate explicit operator name: {name!r}"
53
+ )
54
+ if name in name_counts:
55
+ name_counts[name] += 1
56
+ name = f"{name}_{name_counts[name]}"
57
+ else:
58
+ name_counts[name] = 0
59
+ named_ops.append((name, op))
60
+
61
+ # 3. Validate
62
+ validate_field_coverage(
63
+ named_ops,
64
+ flow._common_input or [],
65
+ flow._item_input or [],
66
+ )
67
+ validate_write_without_read(
68
+ named_ops,
69
+ flow._common_input or [],
70
+ flow._item_input or [],
71
+ )
72
+ dead = detect_dead_code(
73
+ named_ops,
74
+ flow._common_output,
75
+ flow._item_output,
76
+ )
77
+ if dead:
78
+ raise ValidationError(
79
+ f"dead operators detected (output not consumed): {dead}"
80
+ )
81
+
82
+ # 4. Build operators dict
83
+ operators: dict[str, Any] = {}
84
+ for name, op in named_ops:
85
+ entry: dict[str, Any] = {
86
+ "type_name": op.type_name,
87
+ "$metadata": {
88
+ "common_input": op.common_input,
89
+ "common_output": op.common_output,
90
+ "item_input": op.item_input,
91
+ "item_output": op.item_output,
92
+ },
93
+ }
94
+ if op.code_info:
95
+ entry["$code_info"] = op.code_info
96
+ if op.recall:
97
+ entry["recall"] = True
98
+ if op.sources:
99
+ entry["sources"] = [
100
+ _resolve_source(op.sources, named_ops, s)
101
+ for s in op.sources
102
+ ]
103
+ if op.skip:
104
+ entry["skip"] = op.skip
105
+ if op.for_branch_control:
106
+ entry["for_branch_control"] = True
107
+ if op.item_defaults:
108
+ entry["item_defaults"] = op.item_defaults
109
+ if op.common_defaults:
110
+ entry["common_defaults"] = op.common_defaults
111
+ if op.debug:
112
+ entry["debug"] = True
113
+ # Business params
114
+ for k, v in op.params.items():
115
+ entry[k] = v
116
+ operators[name] = entry
117
+
118
+ # 5. Build pipeline_map
119
+ pipeline_map: dict[str, Any] = {}
120
+ for sf_name, (start, end) in sub_flow_boundaries.items():
121
+ pipeline_map[sf_name] = {
122
+ "pipeline": [named_ops[i][0] for i in range(start, end)]
123
+ }
124
+
125
+ # 6. Build pipeline_group
126
+ pipeline_group = {
127
+ "main": {
128
+ "pipeline": list(pipeline_map.keys())
129
+ }
130
+ }
131
+
132
+ # 7. Build flow_contract
133
+ flow_contract: dict[str, Any] = {
134
+ "common_input": flow._common_input or [],
135
+ "item_input": flow._item_input or [],
136
+ }
137
+ if flow._common_output is not None:
138
+ flow_contract["common_output"] = flow._common_output
139
+ else:
140
+ flow_contract["common_output"] = []
141
+ if flow._item_output is not None:
142
+ flow_contract["item_output"] = flow._item_output
143
+ else:
144
+ flow_contract["item_output"] = []
145
+
146
+ return {
147
+ "_PINEAPPLE_VERSION": __version__,
148
+ "_PINEAPPLE_CREATE_TIME": datetime.now(timezone.utc).strftime(
149
+ "%Y-%m-%dT%H:%M:%SZ"
150
+ ),
151
+ "pipeline_config": {
152
+ "operators": operators,
153
+ "pipeline_map": pipeline_map,
154
+ },
155
+ "pipeline_group": pipeline_group,
156
+ "flow_contract": flow_contract,
157
+ }
158
+
159
+
160
+ def compile_to_json(flow: Any, indent: int = 2) -> str:
161
+ """Compile a Flow and return the JSON string."""
162
+ return json.dumps(compile_flow(flow), indent=indent, ensure_ascii=False)
163
+
164
+
165
+ def _resolve_source(
166
+ source_refs: list[str],
167
+ named_ops: list[tuple[str, OpCall]],
168
+ source_type_hint: str,
169
+ ) -> str:
170
+ """Resolve a source reference to the actual named operator.
171
+
172
+ Sources in the DSL reference operator type names. We find the matching
173
+ named operator. If ambiguous, error.
174
+ """
175
+ # Source refs are already resolved operator names from the flow
176
+ # (they get resolved during flow.merge_dedup call which passes recall names)
177
+ return source_type_hint
apple/control.py ADDED
@@ -0,0 +1,91 @@
1
+ """Control flow constructs for Apple DSL.
2
+
3
+ Provides if_ / elseif_ / else_ / end_if_ that compile to Lua control
4
+ operators + skip fields, per design_doc/06_json_config.md.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from dataclasses import dataclass, field
10
+ from typing import Any
11
+
12
+ from apple.base import OpCall
13
+
14
+
15
+ @dataclass
16
+ class ControlBlock:
17
+ """Tracks state for one if/elseif/else/end_if block."""
18
+ block_id: int # unique across the flow
19
+ branches: list[ControlBranch] = field(default_factory=list)
20
+ closed: bool = False
21
+
22
+
23
+ @dataclass
24
+ class ControlBranch:
25
+ """One branch (if / elseif / else) within a ControlBlock."""
26
+ kind: str # "if", "elseif", "else"
27
+ condition: str | None # Lua condition string, None for else
28
+ ctrl_field: str # e.g. "_if_1", "_elif_2", "_else_3"
29
+ ctrl_index: int # global control op counter
30
+
31
+
32
+ def extract_fields(condition: str) -> list[str]:
33
+ """Extract field names referenced in a Lua condition.
34
+
35
+ Identifies identifiers that look like common field names (not Lua keywords
36
+ or literals). Simple heuristic: word tokens that aren't Lua reserved words.
37
+ """
38
+ lua_keywords = {
39
+ "and", "break", "do", "else", "elseif", "end", "false", "for",
40
+ "function", "goto", "if", "in", "local", "nil", "not", "or",
41
+ "repeat", "return", "then", "true", "until", "while",
42
+ "math", "string", "table", "io", "os", "type", "tostring",
43
+ "tonumber", "print", "pairs", "ipairs", "next", "select",
44
+ "unpack", "pcall", "xpcall", "error", "assert",
45
+ }
46
+ tokens = re.findall(r"[a-zA-Z_]\w*", condition)
47
+ return list(dict.fromkeys(t for t in tokens if t not in lua_keywords))
48
+
49
+
50
+ def make_control_op(
51
+ branch: ControlBranch,
52
+ prior_ctrl_fields: list[str],
53
+ condition: str | None,
54
+ ) -> OpCall:
55
+ """Build the Lua OpCall for a control branch."""
56
+ common_input = list(prior_ctrl_fields)
57
+ if condition:
58
+ common_input.extend(extract_fields(condition))
59
+ # Deduplicate while preserving order
60
+ seen: set[str] = set()
61
+ deduped: list[str] = []
62
+ for f in common_input:
63
+ if f not in seen:
64
+ seen.add(f)
65
+ deduped.append(f)
66
+ common_input = deduped
67
+
68
+ # Build Lua script
69
+ if branch.kind == "if":
70
+ lua_body = f"if ({condition}) then return false else return true end"
71
+ elif branch.kind == "elseif":
72
+ prior_check = " and ".join(f"({f} == true)" for f in prior_ctrl_fields)
73
+ lua_body = f"if ({prior_check}) and ({condition}) then return false else return true end"
74
+ else: # else
75
+ prior_check = " and ".join(f"({f} == true)" for f in prior_ctrl_fields)
76
+ lua_body = f"if ({prior_check}) then return false else return true end"
77
+
78
+ lua_script = f"function evaluate() {lua_body} end"
79
+
80
+ return OpCall(
81
+ type_name="transform_by_lua",
82
+ params={
83
+ "lua_script": lua_script,
84
+ "function_for_item": "",
85
+ "function_for_common": "evaluate",
86
+ },
87
+ common_input=common_input,
88
+ common_output=[branch.ctrl_field],
89
+ for_branch_control=True,
90
+ code_info=f"[{branch.kind}] {condition or ''}",
91
+ )
apple/flow.py ADDED
@@ -0,0 +1,236 @@
1
+ """Flow and SubFlow classes for Apple DSL pipeline declaration.
2
+
3
+ Usage:
4
+ flow = Flow(
5
+ name="example",
6
+ common_input=["user_id", "user_age"],
7
+ item_output=["item_score"],
8
+ )
9
+ flow.recall_static(
10
+ item_output=["item_id", "item_score"],
11
+ items=[{"item_id": "a", "item_score": 1.0}],
12
+ )
13
+ flow.filter_condition(
14
+ item_input=["item_status"],
15
+ field="item_status", value="offline",
16
+ )
17
+ json_config = flow.compile()
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import inspect
22
+ import sys
23
+ from typing import Any
24
+
25
+ from apple.base import BaseOp, OpCall
26
+ from apple.compiler import compile_flow, compile_to_json
27
+ from apple.control import (
28
+ ControlBlock,
29
+ ControlBranch,
30
+ extract_fields,
31
+ make_control_op,
32
+ )
33
+
34
+
35
+ def _capture_code_info(type_name: str, stack_depth: int = 2) -> str:
36
+ """Capture the caller's source location for $code_info.
37
+
38
+ Walks up the call stack to find the first frame outside apple/ package,
39
+ which is the user's DSL code.
40
+ """
41
+ try:
42
+ frame = inspect.stack()[stack_depth]
43
+ filename = frame.filename
44
+ lineno = frame.lineno
45
+ func_name = frame.function
46
+ return f"{filename}:{lineno} in {func_name}(): .{type_name}(...)"
47
+ except (IndexError, AttributeError):
48
+ return ""
49
+
50
+
51
+ class _FlowBase:
52
+ """Shared chaining logic for Flow and SubFlow."""
53
+
54
+ def __init__(self, name: str):
55
+ self._name = name
56
+ self._ops: list[OpCall] = []
57
+ # Control flow state
58
+ self._ctrl_counter = 0
59
+ self._ctrl_stack: list[ControlBlock] = []
60
+
61
+ def __getattr__(self, name: str) -> Any:
62
+ """Dynamic operator dispatch: flow.some_op(...) creates an OpCall."""
63
+ if name.startswith("_"):
64
+ raise AttributeError(name)
65
+
66
+ def op_caller(**kwargs: Any) -> _FlowBase:
67
+ return self._add_op(name, **kwargs)
68
+
69
+ return op_caller
70
+
71
+ def _add_op(self, type_name: str, **kwargs: Any) -> _FlowBase:
72
+ """Record an operator call."""
73
+ # Capture caller location for $code_info
74
+ code_info = _capture_code_info(type_name)
75
+
76
+ # Separate metadata kwargs from business params
77
+ meta_keys = {
78
+ "name", "common_input", "common_output", "item_input", "item_output",
79
+ "item_defaults", "common_defaults", "sources", "debug",
80
+ }
81
+ meta = {}
82
+ params = {}
83
+ for k, v in kwargs.items():
84
+ if k in meta_keys:
85
+ meta[k] = v
86
+ elif k == "recall":
87
+ # Accept but ignore — recall is now type-driven from prefix
88
+ pass
89
+ else:
90
+ params[k] = v
91
+
92
+ # Recall is inferred from operator name prefix, not user-passed
93
+ is_recall = type_name.startswith("recall_")
94
+
95
+ call = OpCall(
96
+ type_name=type_name,
97
+ params=params,
98
+ common_input=meta.get("common_input", []),
99
+ common_output=meta.get("common_output", []),
100
+ item_input=meta.get("item_input", []),
101
+ item_output=meta.get("item_output", []),
102
+ item_defaults=meta.get("item_defaults"),
103
+ common_defaults=meta.get("common_defaults"),
104
+ recall=is_recall,
105
+ sources=meta.get("sources"),
106
+ debug=meta.get("debug", False),
107
+ code_info=code_info,
108
+ name=meta.get("name", ""),
109
+ )
110
+
111
+ # Apply skip field if inside a control block
112
+ if self._ctrl_stack:
113
+ block = self._ctrl_stack[-1]
114
+ if block.branches:
115
+ branch = block.branches[-1]
116
+ call.skip = branch.ctrl_field
117
+ if branch.ctrl_field not in call.common_input:
118
+ call.common_input = [branch.ctrl_field] + call.common_input
119
+
120
+ self._ops.append(call)
121
+ return self
122
+
123
+ # --- Control flow ---
124
+
125
+ def if_(self, condition: str) -> _FlowBase:
126
+ """Start an if block."""
127
+ self._ctrl_counter += 1
128
+ block = ControlBlock(block_id=self._ctrl_counter)
129
+ ctrl_field = f"_if_{block.block_id}"
130
+
131
+ branch = ControlBranch(
132
+ kind="if",
133
+ condition=condition,
134
+ ctrl_field=ctrl_field,
135
+ ctrl_index=self._ctrl_counter,
136
+ )
137
+ block.branches.append(branch)
138
+ self._ctrl_stack.append(block)
139
+
140
+ # Emit the control operator
141
+ ctrl_op = make_control_op(branch, [], condition)
142
+ self._ops.append(ctrl_op)
143
+ return self
144
+
145
+ def elseif_(self, condition: str) -> _FlowBase:
146
+ """Add an elseif branch."""
147
+ if not self._ctrl_stack:
148
+ raise ValueError("elseif_ without matching if_")
149
+ block = self._ctrl_stack[-1]
150
+ if block.closed:
151
+ raise ValueError("elseif_ after end_if_")
152
+
153
+ self._ctrl_counter += 1
154
+ prior_fields = [b.ctrl_field for b in block.branches]
155
+ ctrl_field = f"_elif_{self._ctrl_counter}"
156
+
157
+ branch = ControlBranch(
158
+ kind="elseif",
159
+ condition=condition,
160
+ ctrl_field=ctrl_field,
161
+ ctrl_index=self._ctrl_counter,
162
+ )
163
+ block.branches.append(branch)
164
+
165
+ ctrl_op = make_control_op(branch, prior_fields, condition)
166
+ self._ops.append(ctrl_op)
167
+ return self
168
+
169
+ def else_(self) -> _FlowBase:
170
+ """Add an else branch."""
171
+ if not self._ctrl_stack:
172
+ raise ValueError("else_ without matching if_")
173
+ block = self._ctrl_stack[-1]
174
+ if block.closed:
175
+ raise ValueError("else_ after end_if_")
176
+
177
+ self._ctrl_counter += 1
178
+ prior_fields = [b.ctrl_field for b in block.branches]
179
+ ctrl_field = f"_else_{self._ctrl_counter}"
180
+
181
+ branch = ControlBranch(
182
+ kind="else",
183
+ condition=None,
184
+ ctrl_field=ctrl_field,
185
+ ctrl_index=self._ctrl_counter,
186
+ )
187
+ block.branches.append(branch)
188
+
189
+ ctrl_op = make_control_op(branch, prior_fields, None)
190
+ self._ops.append(ctrl_op)
191
+ return self
192
+
193
+ def end_if_(self) -> _FlowBase:
194
+ """Close the current if block."""
195
+ if not self._ctrl_stack:
196
+ raise ValueError("end_if_ without matching if_")
197
+ block = self._ctrl_stack.pop()
198
+ block.closed = True
199
+ return self
200
+
201
+
202
+ class SubFlow(_FlowBase):
203
+ """A reusable fragment of operator declarations.
204
+
205
+ SubFlows don't declare input/output contracts — that's done at the
206
+ top-level Flow.
207
+ """
208
+ pass
209
+
210
+
211
+ class Flow(_FlowBase):
212
+ """A complete pipeline declaration with input/output contract."""
213
+
214
+ def __init__(
215
+ self,
216
+ name: str,
217
+ common_input: list[str] | None = None,
218
+ item_input: list[str] | None = None,
219
+ common_output: list[str] | None = None,
220
+ item_output: list[str] | None = None,
221
+ sub_flows: list[SubFlow] | None = None,
222
+ ):
223
+ super().__init__(name)
224
+ self._common_input = common_input or []
225
+ self._item_input = item_input or []
226
+ self._common_output = common_output
227
+ self._item_output = item_output
228
+ self._sub_flows = sub_flows or []
229
+
230
+ def compile(self) -> str:
231
+ """Compile this flow to a JSON config string."""
232
+ return compile_to_json(self)
233
+
234
+ def compile_dict(self) -> dict[str, Any]:
235
+ """Compile this flow to a JSON config dict."""
236
+ return compile_flow(self)
apple/validator.py ADDED
@@ -0,0 +1,129 @@
1
+ """DSL-side validation for Apple flows.
2
+
3
+ Checks:
4
+ 1. Field coverage: every operator input must come from flow contract or upstream output.
5
+ 2. Write-without-read: writing a field that already exists without reading it.
6
+ 3. Dead code detection: operators whose output is not consumed by flow output or downstream.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from apple.base import OpCall
11
+
12
+
13
+ class ValidationError(Exception):
14
+ """Raised when DSL validation fails."""
15
+ pass
16
+
17
+
18
+ def validate_field_coverage(
19
+ ops: list[tuple[str, OpCall]],
20
+ flow_common_input: list[str],
21
+ flow_item_input: list[str],
22
+ ) -> None:
23
+ """Check that every operator input is provided by flow contract or upstream output."""
24
+ available_common: set[str] = set(flow_common_input)
25
+ available_item: set[str] = set(flow_item_input)
26
+
27
+ for name, op in ops:
28
+ # Check common inputs
29
+ for field in op.common_input:
30
+ if field.startswith("_"):
31
+ continue # internal control fields handled by compiler
32
+ if field not in available_common:
33
+ raise ValidationError(
34
+ f"operator {name!r}: common_input field {field!r} not provided "
35
+ f"by flow contract or upstream output"
36
+ )
37
+ # Check item inputs
38
+ for field in op.item_input:
39
+ if field.startswith("_"):
40
+ continue
41
+ if field not in available_item:
42
+ raise ValidationError(
43
+ f"operator {name!r}: item_input field {field!r} not provided "
44
+ f"by flow contract or upstream output"
45
+ )
46
+ # Register outputs
47
+ available_common.update(op.common_output)
48
+ available_item.update(op.item_output)
49
+
50
+
51
+ def validate_write_without_read(
52
+ ops: list[tuple[str, OpCall]],
53
+ flow_common_input: list[str],
54
+ flow_item_input: list[str],
55
+ ) -> None:
56
+ """Detect writing a field that already exists (from upstream operator output)
57
+ without reading it. Flow-contract inputs are not flagged — operators are
58
+ allowed to output fields that match flow inputs without reading them."""
59
+ # Track fields written by operators (not flow contract)
60
+ written_by_ops_common: set[str] = set()
61
+ written_by_ops_item: set[str] = set()
62
+
63
+ for name, op in ops:
64
+ for field in op.common_output:
65
+ if field.startswith("_"):
66
+ continue
67
+ if field in written_by_ops_common and field not in op.common_input:
68
+ raise ValidationError(
69
+ f"operator {name!r}: writes common field {field!r} "
70
+ f"without reading it (field already exists from upstream)"
71
+ )
72
+ for field in op.item_output:
73
+ if field.startswith("_"):
74
+ continue
75
+ if field in written_by_ops_item and field not in op.item_input:
76
+ raise ValidationError(
77
+ f"operator {name!r}: writes item field {field!r} "
78
+ f"without reading it (field already exists from upstream)"
79
+ )
80
+ written_by_ops_common.update(op.common_output)
81
+ written_by_ops_item.update(op.item_output)
82
+
83
+
84
+ def detect_dead_code(
85
+ ops: list[tuple[str, OpCall]],
86
+ flow_common_output: list[str] | None,
87
+ flow_item_output: list[str] | None,
88
+ ) -> list[str]:
89
+ """Detect operators whose output is never consumed.
90
+
91
+ Returns list of dead operator names. Only checks if flow output contract
92
+ is declared (non-None).
93
+ """
94
+ if flow_common_output is None and flow_item_output is None:
95
+ return []
96
+
97
+ # Build set of "needed" fields
98
+ needed_common: set[str] = set(flow_common_output or [])
99
+ needed_item: set[str] = set(flow_item_output or [])
100
+
101
+ # Also, fields consumed by downstream operators are needed
102
+ for _, op in ops:
103
+ needed_common.update(op.common_input)
104
+ needed_item.update(op.item_input)
105
+
106
+ dead: list[str] = []
107
+ for name, op in ops:
108
+ if op.for_branch_control:
109
+ continue # control ops are never dead
110
+ if op.recall:
111
+ continue # recall ops are always needed
112
+ if not op.common_output and not op.item_output:
113
+ continue # observe ops (no output at all) are exempt
114
+
115
+ produces_needed = False
116
+ for field in op.common_output:
117
+ if field in needed_common:
118
+ produces_needed = True
119
+ break
120
+ if not produces_needed:
121
+ for field in op.item_output:
122
+ if field in needed_item:
123
+ produces_needed = True
124
+ break
125
+
126
+ if not produces_needed and (op.common_output or op.item_output):
127
+ dead.append(name)
128
+
129
+ return dead
@@ -0,0 +1,7 @@
1
+ Metadata-Version: 2.4
2
+ Name: pineapple-apple
3
+ Version: 0.1.0
4
+ Summary: Apple DSL — Python pipeline declaration for Pineapple engine
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.10
@@ -0,0 +1,11 @@
1
+ apple/__init__.py,sha256=fKlL71YG0YFVGLJwyEbkvd_GC3LBvxgDZhBJlY1hwws,180
2
+ apple/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
3
+ apple/base.py,sha256=kBcbnWSh4HZCoOTDwLlDAEAdzWUCLw_IpLOnZ6scFx4,3009
4
+ apple/compiler.py,sha256=6YMM9PBCTwSFw2KZKvoCY0t5fW2vx-EHRGIw0f4n6dw,5551
5
+ apple/control.py,sha256=YH2njcBibmzfdsNUcshdGHAl2h4-Hj6YBv1KQ8GgiKQ,3155
6
+ apple/flow.py,sha256=N2IBJJ8dcYsSWBTbEyO1aUhG89agVPqZOzhOV1Wpcgs,7374
7
+ apple/validator.py,sha256=sUt-Ot11mb43hmhaNLB1zNnQsB-PWpN25nzCIpe8_5o,4736
8
+ pineapple_apple-0.1.0.dist-info/METADATA,sha256=D1W2l6cQtTkE27iqvEgEK0I7aFE0SAZxQiOtquD6KmM,208
9
+ pineapple_apple-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
10
+ pineapple_apple-0.1.0.dist-info/licenses/LICENSE,sha256=L7XribiMHrSXRde_qCXbpC2RoaSVWWbjM-OpZpTE6p8,10761
11
+ pineapple_apple-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 Liam Huang
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.