streaming-sql-engine 0.1.6__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,386 @@
1
+ """
2
+ Memory-mapped file index for efficient, low-memory lookups.
3
+
4
+ Instead of storing full row dictionaries in memory, stores file positions
5
+ and reads rows on-demand from disk using memory-mapped files.
6
+
7
+ Memory reduction: 90-99% (only positions stored, not full objects)
8
+ Can use Polars for faster index building (SIMD-accelerated scanning).
9
+ """
10
+
11
+ import mmap
12
+ import json
13
+ from typing import Dict, List, Set, Optional, Any
14
+ from collections import defaultdict
15
+ from pathlib import Path
16
+
17
+ # Try importing Polars for faster index building
18
+ try:
19
+ import polars as pl
20
+ POLARS_AVAILABLE = True
21
+ except ImportError:
22
+ POLARS_AVAILABLE = False
23
+
24
+
25
+ class MmapPositionIndex:
26
+ """
27
+ Position-based index using memory-mapped files.
28
+
29
+ Stores file positions instead of full objects, reducing memory by 90-99%.
30
+ Reads rows on-demand from disk when needed.
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ filename: str,
36
+ key_column: str,
37
+ debug: bool = False,
38
+ use_polars: bool = True
39
+ ):
40
+ """
41
+ Args:
42
+ filename: Path to JSONL file
43
+ key_column: Column name to index on (e.g., 'product_id')
44
+ debug: Enable debug output
45
+ use_polars: If True, use Polars for faster index building (SIMD-accelerated)
46
+ """
47
+ self.filename = filename
48
+ self.key_column = key_column
49
+ self.debug = debug
50
+ self.use_polars = use_polars and POLARS_AVAILABLE
51
+
52
+ # Index: {key_value: [file_position1, file_position2, ...]}
53
+ # Positions are integers (8 bytes each), not full objects
54
+ self.position_index: Dict[Any, List[int]] = defaultdict(list)
55
+
56
+ # Build index by scanning file and recording positions
57
+ if self.use_polars:
58
+ self._build_index_polars()
59
+ else:
60
+ self._build_index()
61
+
62
+ def _build_index_polars(self):
63
+ """Build position index using Polars for faster grouping (SIMD-accelerated)."""
64
+ if self.debug:
65
+ print(f" Building mmap position index with Polars (fast grouping) for {self.filename}...")
66
+
67
+ try:
68
+ # Scan file to collect positions and key values
69
+ # Then use Polars for fast grouping
70
+ with open(self.filename, 'rb') as f:
71
+ mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
72
+ current_pos = 0
73
+ row_count = 0
74
+
75
+ # Collect in batches for Polars processing
76
+ batch_size = 500000
77
+ batch_data = [] # List of (key_value, position) tuples
78
+
79
+ while True:
80
+ line_start = current_pos
81
+ line_end = mm.find(b'\n', current_pos)
82
+
83
+ if line_end == -1:
84
+ # Last line
85
+ if current_pos < len(mm):
86
+ line = mm[current_pos:].decode('utf-8', errors='ignore')
87
+ if line.strip():
88
+ try:
89
+ obj = json.loads(line)
90
+ key_value = obj.get(self.key_column)
91
+ if key_value is not None:
92
+ batch_data.append((key_value, line_start))
93
+ row_count += 1
94
+ except (ValueError, KeyError):
95
+ pass
96
+ break
97
+
98
+ line = mm[line_start:line_end].decode('utf-8', errors='ignore')
99
+
100
+ try:
101
+ obj = json.loads(line)
102
+ key_value = obj.get(self.key_column)
103
+ if key_value is not None:
104
+ batch_data.append((key_value, line_start))
105
+ row_count += 1
106
+ except (ValueError, KeyError):
107
+ pass
108
+
109
+ current_pos = line_end + 1
110
+
111
+ # Process batch with Polars when it reaches batch_size
112
+ if len(batch_data) >= batch_size:
113
+ self._process_batch_polars(batch_data)
114
+ batch_data = []
115
+
116
+ if self.debug and row_count % 1000000 == 0:
117
+ print(f" Indexed {row_count:,} rows...")
118
+
119
+ # Process remaining batch
120
+ if batch_data:
121
+ self._process_batch_polars(batch_data)
122
+
123
+ mm.close()
124
+
125
+ if self.debug:
126
+ unique_keys = len(self.position_index)
127
+ total_rows = sum(len(positions) for positions in self.position_index.values())
128
+ print(f" Mmap index built (Polars): {total_rows:,} rows, {unique_keys:,} unique keys")
129
+
130
+ except Exception as e:
131
+ if self.debug:
132
+ print(f" Polars index building failed: {e}, falling back to standard")
133
+ # Fallback to standard method
134
+ self._build_index()
135
+
136
+ def _process_batch_polars(self, batch_data: List[tuple]):
137
+ """Process a batch using Polars for fast grouping (SIMD-accelerated)."""
138
+ try:
139
+ # Convert to Polars DataFrame for fast grouping
140
+ # batch_data is list of (key_value, position) tuples
141
+ df = pl.DataFrame({
142
+ 'key': [d[0] for d in batch_data],
143
+ 'position': [d[1] for d in batch_data]
144
+ })
145
+
146
+ # Group by key (SIMD-accelerated)
147
+ grouped = df.group_by('key', maintain_order=False)
148
+
149
+ # Add positions to index
150
+ for group_key, group_df in grouped:
151
+ if group_key is not None:
152
+ positions = group_df['position'].to_list()
153
+ self.position_index[group_key].extend(positions)
154
+ except Exception as e:
155
+ # If Polars fails, fall back to standard processing
156
+ for key_value, position in batch_data:
157
+ if key_value is not None:
158
+ self.position_index[key_value].append(position)
159
+
160
+ def _build_index(self):
161
+ """Build position index by scanning file (standard method)."""
162
+ if self.debug:
163
+ print(f" Building mmap position index for {self.filename}...")
164
+
165
+ try:
166
+ with open(self.filename, 'rb') as f:
167
+ mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
168
+ current_pos = 0
169
+ row_count = 0
170
+
171
+ while True:
172
+ line_start = current_pos
173
+ line_end = mm.find(b'\n', current_pos)
174
+
175
+ if line_end == -1:
176
+ # Last line (no newline)
177
+ if current_pos < len(mm):
178
+ line = mm[current_pos:].decode('utf-8', errors='ignore')
179
+ if line.strip():
180
+ try:
181
+ obj = json.loads(line)
182
+ key_value = obj.get(self.key_column)
183
+ if key_value is not None:
184
+ self.position_index[key_value].append(line_start)
185
+ row_count += 1
186
+ except (ValueError, KeyError):
187
+ pass
188
+ break
189
+
190
+ # Read line
191
+ line = mm[line_start:line_end].decode('utf-8', errors='ignore')
192
+
193
+ try:
194
+ obj = json.loads(line)
195
+ key_value = obj.get(self.key_column)
196
+ if key_value is not None:
197
+ self.position_index[key_value].append(line_start)
198
+ row_count += 1
199
+ except (ValueError, KeyError):
200
+ pass
201
+
202
+ current_pos = line_end + 1
203
+
204
+ if self.debug and row_count % 100000 == 0:
205
+ print(f" Indexed {row_count:,} rows...")
206
+
207
+ mm.close()
208
+
209
+ if self.debug:
210
+ unique_keys = len(self.position_index)
211
+ print(f" Mmap index built: {row_count:,} rows, {unique_keys:,} unique keys")
212
+
213
+ except Exception as e:
214
+ if self.debug:
215
+ print(f" Error building mmap index: {e}")
216
+ self.position_index = {}
217
+
218
+ def get_positions(self, key_value: Any) -> List[int]:
219
+ """
220
+ Get file positions for a key value.
221
+
222
+ Args:
223
+ key_value: Join key value
224
+
225
+ Returns:
226
+ List of file positions (integers)
227
+ """
228
+ return self.position_index.get(key_value, [])
229
+
230
+ def get_rows(self, key_value: Any, required_columns: Optional[Set[str]] = None) -> List[Dict]:
231
+ """
232
+ Get rows for a key value by reading from disk.
233
+
234
+ Args:
235
+ key_value: Join key value
236
+ required_columns: Optional set of columns to include (column pruning)
237
+
238
+ Returns:
239
+ List of row dictionaries
240
+ """
241
+ positions = self.get_positions(key_value)
242
+ if not positions:
243
+ return []
244
+
245
+ rows = []
246
+
247
+ try:
248
+ with open(self.filename, 'rb') as f:
249
+ mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
250
+
251
+ for pos in positions:
252
+ mm.seek(pos)
253
+ line_end = mm.find(b'\n', pos)
254
+
255
+ if line_end == -1:
256
+ line = mm[pos:].decode('utf-8', errors='ignore')
257
+ else:
258
+ line = mm[pos:line_end].decode('utf-8', errors='ignore')
259
+
260
+ try:
261
+ row = json.loads(line)
262
+
263
+ # Column pruning
264
+ if required_columns:
265
+ row = {k: v for k, v in row.items() if k in required_columns}
266
+
267
+ rows.append(row)
268
+ except (ValueError, KeyError):
269
+ continue
270
+
271
+ mm.close()
272
+
273
+ except Exception as e:
274
+ if self.debug:
275
+ print(f" Error reading rows from mmap: {e}")
276
+
277
+ return rows
278
+
279
+ def get_rows_batch_optimized(
280
+ self,
281
+ key_values: List[Any],
282
+ required_columns: Optional[Set[str]] = None
283
+ ) -> Dict[Any, List[Dict]]:
284
+ """
285
+ Get rows for multiple key values efficiently (sorted by position).
286
+
287
+ This is more efficient than calling get_rows() multiple times
288
+ because it sorts positions and reads sequentially.
289
+
290
+ Args:
291
+ key_values: List of join key values
292
+ required_columns: Optional set of columns to include
293
+
294
+ Returns:
295
+ Dictionary mapping key_value to list of rows
296
+ """
297
+ if not key_values:
298
+ return {}
299
+
300
+ # Collect all positions with their key values
301
+ all_positions = []
302
+ key_to_positions = {}
303
+
304
+ for key_value in key_values:
305
+ positions = self.get_positions(key_value)
306
+ if positions:
307
+ key_to_positions[key_value] = positions
308
+ all_positions.extend([(key_value, pos) for pos in positions])
309
+
310
+ # Sort by position for sequential disk reads
311
+ all_positions.sort(key=lambda x: x[1])
312
+
313
+ # Read rows in position order
314
+ results = defaultdict(list)
315
+
316
+ try:
317
+ with open(self.filename, 'rb') as f:
318
+ mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
319
+
320
+ for key_value, pos in all_positions:
321
+ mm.seek(pos)
322
+ line_end = mm.find(b'\n', pos)
323
+
324
+ if line_end == -1:
325
+ line = mm[pos:].decode('utf-8', errors='ignore')
326
+ else:
327
+ line = mm[pos:line_end].decode('utf-8', errors='ignore')
328
+
329
+ try:
330
+ row = json.loads(line)
331
+
332
+ # Column pruning
333
+ if required_columns:
334
+ row = {k: v for k, v in row.items() if k in required_columns}
335
+
336
+ results[key_value].append(row)
337
+ except (ValueError, KeyError):
338
+ continue
339
+
340
+ mm.close()
341
+
342
+ except Exception as e:
343
+ if self.debug:
344
+ print(f" Error reading batch from mmap: {e}")
345
+
346
+ return dict(results)
347
+
348
+ def __len__(self):
349
+ """Return number of unique keys in index."""
350
+ return len(self.position_index)
351
+
352
+ def get_total_rows(self) -> int:
353
+ """Return total number of rows indexed."""
354
+ return sum(len(positions) for positions in self.position_index.values())
355
+
356
+
357
+ def create_mmap_index_from_source(
358
+ source_fn,
359
+ key_column: str,
360
+ filename: Optional[str] = None,
361
+ debug: bool = False
362
+ ) -> Optional[MmapPositionIndex]:
363
+ """
364
+ Create mmap index from a source function.
365
+
366
+ If source is a file-based generator, we can use the file directly.
367
+ Otherwise, we'd need to write to a temp file first.
368
+
369
+ Args:
370
+ source_fn: Source function that returns iterator of rows
371
+ key_column: Column name to index on
372
+ filename: Optional filename if source is file-based
373
+ debug: Enable debug output
374
+
375
+ Returns:
376
+ MmapPositionIndex if file-based, None otherwise
377
+ """
378
+ # Check if source is file-based
379
+ # This is a heuristic - in practice, you'd pass filename explicitly
380
+ if filename and Path(filename).exists():
381
+ return MmapPositionIndex(filename, key_column, debug=debug)
382
+
383
+ # For non-file sources, we'd need to write to temp file first
384
+ # For now, return None (fallback to in-memory index)
385
+ return None
386
+