atlan-application-sdk 0.1.1rc39__py3-none-any.whl → 0.1.1rc40__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.
@@ -0,0 +1,295 @@
1
+ # Output Code Review Guidelines - Data Output Processing
2
+
3
+ ## Context-Specific Patterns
4
+
5
+ This directory contains output processing implementations for various data formats (JSON, Parquet, Iceberg). Output processors must handle data uploads efficiently while maintaining data integrity and correct destination paths.
6
+
7
+ ### Phase 1: Critical Output Safety Issues
8
+
9
+ **Object Store Path Management:**
10
+
11
+ - **Correct destination paths**: Upload paths must respect user-configured output prefixes
12
+ - **Path construction accuracy**: Object store keys must be calculated correctly, not hardcoded
13
+ - **User prefix preservation**: Respect user-provided output directories and naming conventions
14
+ - **Path validation**: Ensure upload paths don't conflict with existing data
15
+
16
+ **Data Integrity and Security:**
17
+
18
+ - All output data must be validated before upload
19
+ - File permissions and access controls must be properly set
20
+ - Data serialization must be consistent and recoverable
21
+ - Prevent overwriting critical data without confirmation
22
+ - Maintain data lineage information in output metadata
23
+
24
+ ```python
25
+ # ✅ DO: Proper object store upload path handling
26
+ class JsonOutput:
27
+ async def upload_to_object_store(
28
+ self,
29
+ data: List[dict],
30
+ output_prefix: str, # User-provided output location
31
+ filename: str
32
+ ) -> dict:
33
+ """Upload data with correct path handling."""
34
+
35
+ # Construct full object store path respecting user's output prefix
36
+ object_store_key = os.path.join(output_prefix, filename)
37
+
38
+ # Serialize data
39
+ json_data = orjson.dumps(data, option=orjson.OPT_APPEND_NEWLINE)
40
+
41
+ # Upload to correct location
42
+ result = await self.object_store.upload_file(
43
+ data=json_data,
44
+ destination=object_store_key # Respect user's intended location
45
+ )
46
+
47
+ return result
48
+
49
+ # ❌ REJECT: Incorrect path handling
50
+ class BadJsonOutput:
51
+ async def upload_to_object_store(self, data: List[dict], filename: str):
52
+ # Wrong: hardcoded or derived path, ignoring user configuration
53
+ object_store_key = get_object_store_prefix(f"/tmp/{filename}") # Ignores output_prefix!
54
+
55
+ result = await self.object_store.upload_file(
56
+ data=orjson.dumps(data),
57
+ destination=object_store_key # Wrong destination!
58
+ )
59
+ return result
60
+ ```
61
+
62
+ ### Phase 2: Output Architecture Patterns
63
+
64
+ **Performance Optimization Requirements:**
65
+
66
+ - **Parallelization opportunities**: Flag sequential upload operations that could be parallelized
67
+ - **Batch processing**: Group related uploads to reduce overhead
68
+ - **Streaming uploads**: Use streaming for large datasets instead of loading into memory
69
+ - **Connection optimization**: Reuse object store connections across operations
70
+
71
+ **Resource Management:**
72
+
73
+ - Use proper connection pooling for object store operations
74
+ - Implement timeout handling for upload operations
75
+ - Clean up temporary files after upload
76
+ - Handle partial upload failures gracefully
77
+ - Monitor memory usage during large data serialization
78
+
79
+ ```python
80
+ # ✅ DO: Parallel upload processing
81
+ async def upload_multiple_datasets_parallel(
82
+ self,
83
+ datasets: List[Tuple[List[dict], str]], # (data, filename) pairs
84
+ output_prefix: str
85
+ ) -> List[dict]:
86
+ """Upload multiple datasets in parallel for better performance."""
87
+
88
+ async def upload_single_dataset(data: List[dict], filename: str) -> dict:
89
+ """Upload a single dataset with error handling."""
90
+ try:
91
+ object_store_key = os.path.join(output_prefix, filename)
92
+ serialized_data = orjson.dumps(data, option=orjson.OPT_APPEND_NEWLINE)
93
+
94
+ return await self.object_store.upload_file(
95
+ data=serialized_data,
96
+ destination=object_store_key
97
+ )
98
+ except Exception as e:
99
+ logger.error(f"Failed to upload {filename}: {e}")
100
+ raise
101
+
102
+ # Parallel processing with controlled concurrency
103
+ semaphore = asyncio.Semaphore(5) # Limit concurrent uploads
104
+
105
+ async def upload_with_semaphore(data: List[dict], filename: str) -> dict:
106
+ async with semaphore:
107
+ return await upload_single_dataset(data, filename)
108
+
109
+ tasks = [upload_with_semaphore(data, filename) for data, filename in datasets]
110
+ return await asyncio.gather(*tasks)
111
+
112
+ # ❌ REJECT: Sequential upload processing
113
+ async def upload_multiple_datasets_sequential(
114
+ self,
115
+ datasets: List[Tuple[List[dict], str]],
116
+ output_prefix: str
117
+ ) -> List[dict]:
118
+ """Sequential uploads - should be flagged for parallelization."""
119
+ results = []
120
+ for data, filename in datasets: # FLAG: Could be parallelized
121
+ object_store_key = os.path.join(output_prefix, filename)
122
+ result = await self.object_store.upload_file(data, object_store_key)
123
+ results.append(result)
124
+ return results
125
+ ```
126
+
127
+ ### Phase 3: Output Testing Requirements
128
+
129
+ **Data Output Testing:**
130
+
131
+ - Test with various data formats and sizes
132
+ - Test serialization and deserialization consistency
133
+ - Test partial upload scenarios and recovery
134
+ - Mock object store operations in unit tests
135
+ - Include integration tests with real object store
136
+ - Test data corruption detection and prevention
137
+
138
+ **Performance Testing:**
139
+
140
+ - Include tests for large dataset uploads
141
+ - Test memory usage during serialization
142
+ - Test concurrent upload operations
143
+ - Verify timeout handling works correctly
144
+ - Test connection pool behavior under load
145
+
146
+ ### Phase 4: Performance and Scalability
147
+
148
+ **Data Upload Efficiency:**
149
+
150
+ - Use streaming uploads for large datasets
151
+ - Implement proper chunking for oversized data
152
+ - Use compression for large text-based outputs
153
+ - Monitor upload progress and provide feedback
154
+ - Optimize serialization performance (use orjson over json)
155
+
156
+ **Object Store Optimization:**
157
+
158
+ - Use connection pooling for object store clients
159
+ - Implement proper retry logic for upload failures
160
+ - Use parallel uploads where appropriate
161
+ - Monitor upload metrics and error rates
162
+ - Handle bandwidth limitations gracefully
163
+
164
+ ### Phase 5: Output Maintainability
165
+
166
+ **Error Handling and Recovery:**
167
+
168
+ - Implement comprehensive error handling for all upload operations
169
+ - Provide meaningful error messages with upload context
170
+ - Handle partial upload failures gracefully
171
+ - Implement proper retry logic for transient failures
172
+ - Log all upload operations with destination information
173
+
174
+ **Configuration Management:**
175
+
176
+ - Externalize all output-related configuration
177
+ - Support different output destinations and formats
178
+ - Validate output configuration before processing
179
+ - Document all supported output parameters
180
+ - Handle environment-specific output requirements
181
+
182
+ ---
183
+
184
+ ## Output-Specific Anti-Patterns
185
+
186
+ **Always Reject:**
187
+
188
+ - **Path derivation errors**: Deriving object store paths from local temporary paths
189
+ - **Sequential uploads**: Uploading multiple files sequentially when parallel uploads are possible
190
+ - **Memory inefficiency**: Loading entire datasets into memory for serialization
191
+ - **Missing upload verification**: Not verifying successful uploads
192
+ - **Poor error recovery**: Not handling partial upload failures gracefully
193
+ - **Resource leaks**: Not cleaning up temporary files or connections
194
+
195
+ **Object Store Upload Anti-Patterns:**
196
+
197
+ ```python
198
+ # ❌ REJECT: Incorrect upload path handling
199
+ class BadOutputProcessor:
200
+ async def upload_results(self, results: List[dict]):
201
+ # Wrong: derives upload path from temporary local path
202
+ local_temp_file = "/tmp/results.json"
203
+ upload_key = get_object_store_prefix(local_temp_file) # Incorrect!
204
+
205
+ await self.object_store.upload_file(results, upload_key)
206
+
207
+ # ✅ REQUIRE: Correct upload path handling
208
+ class GoodOutputProcessor:
209
+ async def upload_results(
210
+ self,
211
+ results: List[dict],
212
+ output_prefix: str, # User-specified destination
213
+ filename: str = "results.json"
214
+ ):
215
+ # Use actual user-configured output location
216
+ upload_key = os.path.join(output_prefix, filename)
217
+
218
+ await self.object_store.upload_file(
219
+ data=orjson.dumps(results),
220
+ destination=upload_key # Correct destination
221
+ )
222
+ ```
223
+
224
+ **Performance Anti-Patterns:**
225
+
226
+ ```python
227
+ # ❌ REJECT: Sequential upload processing
228
+ async def upload_multiple_files_sequential(file_data_pairs: List[Tuple]):
229
+ results = []
230
+ for data, filename in file_data_pairs: # Should be parallelized
231
+ result = await upload_single_file(data, filename)
232
+ results.append(result)
233
+ return results
234
+
235
+ # ✅ REQUIRE: Parallel upload processing with proper error handling
236
+ async def upload_multiple_files_parallel(
237
+ file_data_pairs: List[Tuple],
238
+ max_concurrency: int = 5
239
+ ) -> List[dict]:
240
+ semaphore = asyncio.Semaphore(max_concurrency)
241
+
242
+ async def upload_with_semaphore(data, filename):
243
+ async with semaphore:
244
+ try:
245
+ return await upload_single_file(data, filename)
246
+ except Exception as e:
247
+ logger.error(f"Upload failed for {filename}: {e}")
248
+ return {"filename": filename, "status": "failed", "error": str(e)}
249
+
250
+ tasks = [upload_with_semaphore(data, filename) for data, filename in file_data_pairs]
251
+ return await asyncio.gather(*tasks)
252
+ ```
253
+
254
+ **Memory Management Anti-Patterns:**
255
+
256
+ ```python
257
+ # ❌ REJECT: Loading entire dataset for serialization
258
+ async def bad_large_dataset_upload(large_dataset: List[dict]):
259
+ # Loads entire dataset into memory
260
+ json_data = orjson.dumps(large_dataset) # Could exceed memory limits
261
+ await upload_data(json_data)
262
+
263
+ # ✅ REQUIRE: Streaming serialization for large datasets
264
+ async def good_large_dataset_upload(large_dataset: List[dict], chunk_size: int = 1000):
265
+ """Stream large datasets to avoid memory issues."""
266
+
267
+ async def serialize_chunk(chunk: List[dict]) -> bytes:
268
+ return orjson.dumps(chunk, option=orjson.OPT_APPEND_NEWLINE)
269
+
270
+ # Process in chunks to manage memory
271
+ for i in range(0, len(large_dataset), chunk_size):
272
+ chunk = large_dataset[i:i + chunk_size]
273
+ serialized_chunk = await serialize_chunk(chunk)
274
+
275
+ await upload_chunk(
276
+ data=serialized_chunk,
277
+ chunk_index=i // chunk_size
278
+ )
279
+ ```
280
+
281
+ ## Educational Context for Output Reviews
282
+
283
+ When reviewing output code, emphasize:
284
+
285
+ 1. **Data Integrity Impact**: "Incorrect upload path handling can cause data to be stored in wrong locations, making it inaccessible to downstream processes. This breaks data pipelines and can cause data loss."
286
+
287
+ 2. **Performance Impact**: "Sequential uploads create unnecessary bottlenecks. For enterprise datasets with multiple output files, parallelization can significantly reduce processing time and improve user experience."
288
+
289
+ 3. **Resource Impact**: "Poor memory management during serialization can cause out-of-memory errors with large datasets. Streaming and chunking are essential for enterprise-scale data output."
290
+
291
+ 4. **User Experience Impact**: "Output path errors are often discovered late in processing, causing wasted computation and frustrating delays. Proper validation and clear error messages improve reliability."
292
+
293
+ 5. **Scalability Impact**: "Output patterns that work for small datasets can fail at enterprise scale. Always design output processes to handle the largest expected dataset sizes efficiently."
294
+
295
+ 6. **Data Pipeline Impact**: "Output processing is the final step in data pipelines. Failures here can invalidate all upstream processing work. Robust error handling and verification are critical for pipeline reliability."
@@ -29,6 +29,7 @@ class IcebergOutput(Output):
29
29
  mode: str = "append",
30
30
  total_record_count: int = 0,
31
31
  chunk_count: int = 0,
32
+ retain_local_copy: bool = False,
32
33
  ):
33
34
  """Initialize the Iceberg output class.
34
35
 
@@ -39,6 +40,8 @@ class IcebergOutput(Output):
39
40
  mode (str, optional): Write mode for the iceberg table. Defaults to "append".
40
41
  total_record_count (int, optional): Total record count written to the iceberg table. Defaults to 0.
41
42
  chunk_count (int, optional): Number of chunks written to the iceberg table. Defaults to 0.
43
+ retain_local_copy (bool, optional): Whether to retain the local copy of the files.
44
+ Defaults to False.
42
45
  """
43
46
  self.total_record_count = total_record_count
44
47
  self.chunk_count = chunk_count
@@ -47,6 +50,7 @@ class IcebergOutput(Output):
47
50
  self.iceberg_table = iceberg_table
48
51
  self.mode = mode
49
52
  self.metrics = get_metrics()
53
+ self.retain_local_copy = retain_local_copy
50
54
 
51
55
  async def write_dataframe(self, dataframe: "pd.DataFrame"):
52
56
  """
@@ -93,6 +93,7 @@ class JsonOutput(Output):
93
93
  path_gen: Callable[[int | None, int], str] = path_gen,
94
94
  start_marker: Optional[str] = None,
95
95
  end_marker: Optional[str] = None,
96
+ retain_local_copy: bool = False,
96
97
  **kwargs: Dict[str, Any],
97
98
  ):
98
99
  """Initialize the JSON output handler.
@@ -113,6 +114,8 @@ class JsonOutput(Output):
113
114
  Defaults to 0.
114
115
  path_gen (Callable, optional): Function to generate file paths.
115
116
  Defaults to path_gen function.
117
+ retain_local_copy (bool, optional): Whether to retain the local copy of the files.
118
+ Defaults to False.
116
119
  """
117
120
  self.output_path = output_path
118
121
  self.output_suffix = output_suffix
@@ -133,6 +136,7 @@ class JsonOutput(Output):
133
136
  self.start_marker = start_marker
134
137
  self.end_marker = end_marker
135
138
  self.metrics = get_metrics()
139
+ self.retain_local_copy = retain_local_copy
136
140
 
137
141
  if not self.output_path:
138
142
  raise ValueError("output_path is required")
@@ -282,6 +286,7 @@ class JsonOutput(Output):
282
286
  await ObjectStore.upload_prefix(
283
287
  source=self.output_path,
284
288
  destination=get_object_store_prefix(self.output_path),
289
+ retain_local_copy=self.retain_local_copy,
285
290
  )
286
291
 
287
292
  except Exception as e:
@@ -367,6 +372,7 @@ class JsonOutput(Output):
367
372
  await ObjectStore.upload_file(
368
373
  source=output_file_name,
369
374
  destination=get_object_store_prefix(output_file_name),
375
+ retain_local_copy=self.retain_local_copy,
370
376
  )
371
377
 
372
378
  self.buffer.clear()
@@ -60,6 +60,7 @@ class ParquetOutput(Output):
60
60
  chunk_start: Optional[int] = None,
61
61
  start_marker: Optional[str] = None,
62
62
  end_marker: Optional[str] = None,
63
+ retain_local_copy: bool = False,
63
64
  ):
64
65
  """Initialize the Parquet output handler.
65
66
 
@@ -79,6 +80,8 @@ class ParquetOutput(Output):
79
80
  Defaults to None.
80
81
  end_marker (Optional[str], optional): End marker for query extraction.
81
82
  Defaults to None.
83
+ retain_local_copy (bool, optional): Whether to retain the local copy of the files.
84
+ Defaults to False.
82
85
  """
83
86
  self.output_path = output_path
84
87
  self.output_suffix = output_suffix
@@ -99,6 +102,7 @@ class ParquetOutput(Output):
99
102
  self.end_marker = end_marker
100
103
  self.statistics = []
101
104
  self.metrics = get_metrics()
105
+ self.retain_local_copy = retain_local_copy
102
106
 
103
107
  # Create output directory
104
108
  self.output_path = os.path.join(self.output_path, self.output_suffix)
@@ -295,13 +299,19 @@ class ParquetOutput(Output):
295
299
  # Upload the entire directory (contains multiple parquet files created by Daft)
296
300
  if write_mode == WriteMode.OVERWRITE:
297
301
  # Delete the directory from object store
298
- await ObjectStore.delete_prefix(
299
- prefix=get_object_store_prefix(self.output_path)
300
- )
302
+ try:
303
+ await ObjectStore.delete_prefix(
304
+ prefix=get_object_store_prefix(self.output_path)
305
+ )
306
+ except FileNotFoundError as e:
307
+ logger.info(
308
+ f"No files found under prefix {get_object_store_prefix(self.output_path)}: {str(e)}"
309
+ )
301
310
 
302
311
  await ObjectStore.upload_prefix(
303
312
  source=self.output_path,
304
313
  destination=get_object_store_prefix(self.output_path),
314
+ retain_local_copy=self.retain_local_copy,
305
315
  )
306
316
 
307
317
  except Exception as e: