streaming-sql-engine 0.1.27__tar.gz → 0.1.29__tar.gz

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.
Files changed (131) hide show
  1. {streaming_sql_engine-0.1.27/streaming_sql_engine.egg-info → streaming_sql_engine-0.1.29}/PKG-INFO +1 -1
  2. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/__init__.py +1 -1
  3. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/benchmark_all_configurations.py +208 -3
  4. streaming_sql_engine-0.1.29/debug_where.py +48 -0
  5. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/evaluator.py +14 -1
  6. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/executor.py +118 -20
  7. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/operators.py +55 -7
  8. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/operators_polars.py +53 -22
  9. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/planner.py +16 -94
  10. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/polars_expression_translator.py +21 -3
  11. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/pyproject.toml +1 -1
  12. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/setup.py +1 -1
  13. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29/streaming_sql_engine.egg-info}/PKG-INFO +1 -1
  14. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/streaming_sql_engine.egg-info/SOURCES.txt +14 -0
  15. streaming_sql_engine-0.1.29/test_evaluator_direct.py +64 -0
  16. streaming_sql_engine-0.1.29/test_lookup_join_where.py +225 -0
  17. streaming_sql_engine-0.1.29/test_polars_where.py +86 -0
  18. streaming_sql_engine-0.1.29/test_where_debug_simple.py +87 -0
  19. streaming_sql_engine-0.1.29/test_where_fix.py +67 -0
  20. streaming_sql_engine-0.1.29/test_where_string.py +107 -0
  21. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/DEPLOYMENT.md +0 -0
  22. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/MANIFEST.in +0 -0
  23. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/QUICK_DEPLOY.md +0 -0
  24. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/QUICK_FIX.md +0 -0
  25. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/README.md +0 -0
  26. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/benchmark_all_configurations_1k.py +0 -0
  27. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/APACHE_DRILL_COMPARISON.md +0 -0
  28. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/API_JOIN_OPERATIONS.md +0 -0
  29. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/ARCHITECTURAL_RECOMMENDATION.md +0 -0
  30. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/ARCHITECTURE_DECISION.md +0 -0
  31. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/ARCHITECTURE_SYNCED.md +0 -0
  32. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/BEST_USE_CASES.md +0 -0
  33. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/BETTER_FILTER_APPROACH.md +0 -0
  34. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/CARTESIAN_PRODUCTS_CAUSES.md +0 -0
  35. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/CHANGES_SUMMARY.md +0 -0
  36. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/COMPREHENSIVE_ARTICLE.md +0 -0
  37. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/COMPREHENSIVE_DOCUMENTATION.md +0 -0
  38. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/COMPREHENSIVE_GUIDE.md +0 -0
  39. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/DEVELOPER_GUIDE.md +0 -0
  40. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/DUCKDB_COMPARISON.md +0 -0
  41. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/ENGINE_OPTIONS_REFERENCE.md +0 -0
  42. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/FINAL_IMPLEMENTATION_RECOMMENDATIONS.md +0 -0
  43. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/FINAL_RECOMMENDATION.md +0 -0
  44. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/FIRST_MATCH_ONLY_WARNINGS.md +0 -0
  45. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/HANDLING_DUPLICATES_WITHOUT_CARTESIAN.md +0 -0
  46. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/HOW_PROTOCOL_DETECTION_WORKS.md +0 -0
  47. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/HOW_TO_ADD_TO_PROJECT.md +0 -0
  48. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/INSTALLATION.md +0 -0
  49. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/JSONL_EXECUTOR_ANALYSIS.md +0 -0
  50. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/JSONL_EXECUTOR_REMOVED.md +0 -0
  51. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/LIBRARY_DOCUMENTATION.md +0 -0
  52. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/MEDIUM_ARTICLE.md +0 -0
  53. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/MEDIUM_ARTICLE_SIMPLIFIED.md +0 -0
  54. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/MIGRATION_GUIDE.md +0 -0
  55. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/MMAP_WITHOUT_POLARS_SLOW.md +0 -0
  56. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/MOST_STABLE_AND_PERFORMANT.md +0 -0
  57. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/MULTI_SOURCE_EXAMPLE_README.md +0 -0
  58. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/MYSQL_USAGE.md +0 -0
  59. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/OPTIMIZATIONS_BREAKDOWN.md +0 -0
  60. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/OPTIMIZATIONS_NOT_DATABASE_ONLY.md +0 -0
  61. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/OPTIMIZATIONS_VS_POLARS.md +0 -0
  62. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/OPTIMIZER_AUTOMATED.md +0 -0
  63. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/PERFORMANCE.md +0 -0
  64. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/PERFORMANCE_COMPARISON.md +0 -0
  65. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/POLARS_AND_MMAP_GUIDE.md +0 -0
  66. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/POLARS_VS_POLARS_MMAP.md +0 -0
  67. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/PROTOCOL_AND_OPTIMIZATIONS_EXPLAINED.md +0 -0
  68. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/PROTOCOL_EXPLANATION.md +0 -0
  69. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/PUBLISHING.md +0 -0
  70. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/PYPI_CHECKLIST.md +0 -0
  71. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/QUICK_PUBLISH.md +0 -0
  72. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/QUICK_START.md +0 -0
  73. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/SIMPLE_PROTOCOL_GUIDE.md +0 -0
  74. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/SIMPLE_SOURCE_FUNCTIONS.md +0 -0
  75. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/SOURCE_COMBINATIONS_GUIDE.md +0 -0
  76. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/TECHNICAL_DOCUMENTATION.md +0 -0
  77. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/USER_GUIDE.md +0 -0
  78. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/WHAT_IS_WHERE_TO_PARAMS.md +0 -0
  79. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/WHEN_POLARS_IS_USED.md +0 -0
  80. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/WHERE_POLARS_IS_USED.md +0 -0
  81. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/WHY_API_CONVERTER_NEEDED.md +0 -0
  82. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/WHY_MANUAL_PARSING.md +0 -0
  83. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/WHY_ORIGINAL_IS_FASTER.md +0 -0
  84. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/WHY_PROTOCOL_IN_SOURCES.md +0 -0
  85. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/documentation/XML_MONGO_USE_CASE.md +0 -0
  86. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/engine.py +0 -0
  87. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/mmap_index.py +0 -0
  88. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/operators_mmap.py +0 -0
  89. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/optimized_export.py +0 -0
  90. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/optimizer.py +0 -0
  91. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/parser.py +0 -0
  92. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/polars_operators.py +0 -0
  93. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/pre_release_test.py +0 -0
  94. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/protocol_helpers.py +0 -0
  95. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/quick_test.py +0 -0
  96. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/requirements.txt +0 -0
  97. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/setup.cfg +0 -0
  98. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/streaming_sql_engine.egg-info/dependency_links.txt +0 -0
  99. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/streaming_sql_engine.egg-info/requires.txt +0 -0
  100. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/streaming_sql_engine.egg-info/top_level.txt +0 -0
  101. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_engine_options.py +0 -0
  102. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_full_pipeline.py +0 -0
  103. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_merge_buffer.py +0 -0
  104. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_merge_join_debug.py +0 -0
  105. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_merge_join_detailed_debug.py +0 -0
  106. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_merge_join_direct.py +0 -0
  107. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_merge_join_issue.py +0 -0
  108. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_merge_join_simple.py +0 -0
  109. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_merge_join_with_user_data.py +0 -0
  110. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_mmap_debug.py +0 -0
  111. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_mmap_direct.py +0 -0
  112. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_mmap_get_matches.py +0 -0
  113. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_mmap_get_matches_direct.py +0 -0
  114. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_mmap_get_rows_variants.py +0 -0
  115. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_mmap_index.py +0 -0
  116. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_mmap_index_lookup.py +0 -0
  117. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_mmap_join_benchmark_match.py +0 -0
  118. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_mmap_join_debug.py +0 -0
  119. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_mmap_join_simple.py +0 -0
  120. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_mmap_join_simple_fixed.py +0 -0
  121. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_mmap_join_trace.py +0 -0
  122. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_mmap_key_extraction.py +0 -0
  123. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_mmap_required_columns.py +0 -0
  124. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_mmap_simple_query.py +0 -0
  125. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_polars_fixes.py +0 -0
  126. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_polars_schema_fix.py +0 -0
  127. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_readme_cases.py +0 -0
  128. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_required_columns_analysis.py +0 -0
  129. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_where_clause_1k.py +0 -0
  130. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_where_debug.py +0 -0
  131. {streaming_sql_engine-0.1.27 → streaming_sql_engine-0.1.29}/tests/test_where_pushdown.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: streaming-sql-engine
3
- Version: 0.1.27
3
+ Version: 0.1.29
4
4
  Summary: A lightweight SQL execution engine for streaming row-by-row queries with joins across multiple data sources
5
5
  Home-page: https://github.com/Ierofantis/streaming-sql-engine/tree/master
6
6
  Author: Theodore Pantazopoulo
@@ -27,5 +27,5 @@ try:
27
27
  except ImportError:
28
28
  __all__ = ["Engine"]
29
29
 
30
- __version__ = "0.1.21"
30
+ __version__ = "0.1.29"
31
31
 
@@ -70,6 +70,140 @@ def get_cpu_percent():
70
70
  return psutil.cpu_percent(interval=0.1)
71
71
 
72
72
 
73
+ def analyze_results(output_file, expected_products_checked_1):
74
+ """Analyze results for inconsistencies."""
75
+ issues = []
76
+
77
+ if not os.path.exists(output_file):
78
+ return {
79
+ "total_rows": 0,
80
+ "unique_products": 0,
81
+ "products_with_images": 0,
82
+ "products_without_images": 0,
83
+ "issues": [f"Output file not found: {output_file}"]
84
+ }
85
+
86
+ rows = []
87
+ with open(output_file, "r", encoding="utf-8") as f:
88
+ for line in f:
89
+ if line.strip():
90
+ rows.append(json.loads(line))
91
+
92
+ total_rows = len(rows)
93
+
94
+ # Check row count consistency
95
+ if total_rows == 0:
96
+ issues.append("[ERROR] No rows returned")
97
+
98
+ # Check for missing images (should have images for products with checked=1)
99
+ products_with_images = set()
100
+ products_without_images = set()
101
+
102
+ for row in rows:
103
+ product_id = row.get("product_id")
104
+ image = row.get("image")
105
+
106
+ if image is None:
107
+ products_without_images.add(product_id)
108
+ else:
109
+ products_with_images.add(product_id)
110
+
111
+ # Check for duplicate product_ids (should have multiple rows per product if multiple images)
112
+ product_counts = {}
113
+ for row in rows:
114
+ pid = row.get("product_id")
115
+ product_counts[pid] = product_counts.get(pid, 0) + 1
116
+
117
+ return {
118
+ "total_rows": total_rows,
119
+ "unique_products": len(product_counts),
120
+ "products_with_images": len(products_with_images),
121
+ "products_without_images": len(products_without_images),
122
+ "issues": issues
123
+ }
124
+
125
+
126
+ def compare_results(all_results):
127
+ """Compare results across all configurations to ensure consistency."""
128
+ valid_results = [r for r in all_results if "error" not in r and r.get("rows", 0) > 0]
129
+
130
+ if len(valid_results) < 2:
131
+ return {"consistent": True, "issues": []}
132
+
133
+ # Get row counts
134
+ row_counts = [r["rows"] for r in valid_results]
135
+ unique_products = [r.get("analysis", {}).get("unique_products", 0) for r in valid_results]
136
+
137
+ issues = []
138
+
139
+ # Group configurations by expected behavior
140
+ # IMPORTANT: "Filter pushdown" and "column pruning" are performance optimizations.
141
+ # They should NOT change the final output row count for the same SQL query.
142
+ #
143
+ # Configs 1-4: No pushdown/pruning protocol (WHERE applied after join in engine)
144
+ # Configs 5-6: Pushdown/pruning protocol enabled (WHERE can be applied while scanning)
145
+ # Config 7: first_match_only changes semantics (may reduce duplicate joined rows)
146
+
147
+ baseline_configs = [r for r in valid_results if "Merge Join" in r['name'] or "Lookup Join" in r['name'] or "Polars Join" in r['name'] or "MMAP Join" in r['name']]
148
+ optimized_configs = [r for r in valid_results if "Column Pruning" in r['name'] or "Filter Pushdown" in r['name']]
149
+ first_match_configs = [r for r in valid_results if "All Optimizations" in r['name']]
150
+
151
+ # Check consistency within baseline configs (should all return same)
152
+ if len(baseline_configs) > 1:
153
+ baseline_row_counts = [r["rows"] for r in baseline_configs]
154
+ if len(set(baseline_row_counts)) > 1:
155
+ issues.append(f"[WARNING] Baseline configs row count mismatch: {dict(zip([r['name'] for r in baseline_configs], baseline_row_counts))}")
156
+
157
+ # Check consistency within optimized configs (should all return same)
158
+ if len(optimized_configs) > 1:
159
+ optimized_row_counts = [r["rows"] for r in optimized_configs]
160
+ if len(set(optimized_row_counts)) > 1:
161
+ issues.append(f"[WARNING] Optimized configs row count mismatch: {dict(zip([r['name'] for r in optimized_configs], optimized_row_counts))}")
162
+
163
+ # Check that first_match configs return fewer rows than optimized (due to first_match_only)
164
+ if optimized_configs and first_match_configs:
165
+ optimized_avg = sum(r["rows"] for r in optimized_configs) / len(optimized_configs)
166
+ first_match_avg = sum(r["rows"] for r in first_match_configs) / len(first_match_configs)
167
+ if first_match_avg >= optimized_avg:
168
+ issues.append(f"[WARNING] First match configs should return fewer rows, but got {first_match_avg:.0f} vs optimized {optimized_avg:.0f}")
169
+
170
+ # Compare actual data content (sample first 100 rows from each)
171
+ if len(valid_results) > 1:
172
+ sample_data = {}
173
+ for result in valid_results:
174
+ if result.get("output_file") and os.path.exists(result["output_file"]):
175
+ samples = []
176
+ with open(result["output_file"], "r", encoding="utf-8") as f:
177
+ for i, line in enumerate(f):
178
+ if i >= 100:
179
+ break
180
+ if line.strip():
181
+ samples.append(json.loads(line))
182
+ sample_data[result["name"]] = samples
183
+
184
+ # Compare samples
185
+ if len(sample_data) > 1:
186
+ first_config = list(sample_data.keys())[0]
187
+ first_samples = sample_data[first_config]
188
+
189
+ for config_name, samples in list(sample_data.items())[1:]:
190
+ if len(samples) != len(first_samples):
191
+ issues.append(f"[WARNING] Sample size mismatch: {first_config} has {len(first_samples)} rows, {config_name} has {len(samples)} rows")
192
+ else:
193
+ # Compare product_ids
194
+ first_pids = sorted([r.get("product_id") for r in first_samples])
195
+ other_pids = sorted([r.get("product_id") for r in samples])
196
+ if first_pids != other_pids:
197
+ issues.append(f"[WARNING] Product ID mismatch between {first_config} and {config_name}")
198
+
199
+ return {
200
+ "consistent": len(issues) == 0,
201
+ "issues": issues,
202
+ "row_counts": dict(zip([r['name'] for r in valid_results], row_counts)),
203
+ "unique_products": dict(zip([r['name'] for r in valid_results], unique_products))
204
+ }
205
+
206
+
73
207
  def run_benchmark(name, engine_config, source_config, query, products_file, images_file):
74
208
  """
75
209
  Run a benchmark with specific configuration.
@@ -153,9 +287,15 @@ def run_benchmark(name, engine_config, source_config, query, products_file, imag
153
287
  f.write(json.dumps(row, ensure_ascii=False) + "\n")
154
288
  export_time = time.time() - export_start
155
289
 
156
- import os
157
290
  file_size_mb = os.path.getsize(output_file) / (1024 * 1024)
158
291
 
292
+ # Analyze results (calculate expected_products_checked_1 from products_file)
293
+ expected_products_checked_1 = sum(
294
+ 1 for line in open(products_file)
295
+ if line.strip() and json.loads(line).get("checked") == 1
296
+ )
297
+ analysis = analyze_results(output_file, expected_products_checked_1)
298
+
159
299
  results = {
160
300
  "name": name,
161
301
  "rows": row_count,
@@ -166,11 +306,15 @@ def run_benchmark(name, engine_config, source_config, query, products_file, imag
166
306
  "avg_cpu_percent": avg_cpu,
167
307
  "rows_per_second": row_count / elapsed_time if elapsed_time > 0 else 0,
168
308
  "output_file": output_file,
169
- "output_file_size_mb": file_size_mb
309
+ "output_file_size_mb": file_size_mb,
310
+ "analysis": analysis
170
311
  }
171
312
 
172
313
  print(f" Results:")
173
314
  print(f" Rows processed: {row_count:,}")
315
+ print(f" Unique products: {analysis['unique_products']}")
316
+ print(f" Products with images: {analysis['products_with_images']}")
317
+ print(f" Products without images: {analysis['products_without_images']}")
174
318
  print(f" Time: {elapsed_time:.2f} seconds")
175
319
  print(f" Speed: {results['rows_per_second']:,.0f} rows/second")
176
320
  print(f" Peak memory: {peak_memory:.2f} MB")
@@ -178,6 +322,11 @@ def run_benchmark(name, engine_config, source_config, query, products_file, imag
178
322
  print(f" Avg CPU: {avg_cpu:.1f}%")
179
323
  print(f" Exported to: {output_file} ({file_size_mb:.2f} MB)")
180
324
 
325
+ if analysis['issues']:
326
+ print(f" [WARNING] Issues found:")
327
+ for issue in analysis['issues']:
328
+ print(f" {issue}")
329
+
181
330
  return results
182
331
 
183
332
  except Exception as e:
@@ -194,7 +343,8 @@ def run_benchmark(name, engine_config, source_config, query, products_file, imag
194
343
  "avg_cpu_percent": 0,
195
344
  "rows_per_second": 0,
196
345
  "output_file": None,
197
- "output_file_size_mb": 0
346
+ "output_file_size_mb": 0,
347
+ "analysis": {"issues": [f"Error: {str(e)}"]}
198
348
  }
199
349
 
200
350
 
@@ -213,6 +363,28 @@ def main():
213
363
  print("Run: python generate_test_data_100k.py")
214
364
  return
215
365
 
366
+ # Calculate expected values
367
+ products_checked_1 = sum(
368
+ 1 for line in open(products_file)
369
+ if line.strip() and json.loads(line).get("checked") == 1
370
+ )
371
+
372
+ # Build images index
373
+ images_by_product = {}
374
+ for line in open(images_file):
375
+ if line.strip():
376
+ img = json.loads(line)
377
+ pid = img.get("product_id")
378
+ if pid not in images_by_product:
379
+ images_by_product[pid] = []
380
+ images_by_product[pid].append(img)
381
+
382
+ expected_rows = sum(
383
+ len(images_by_product.get(json.loads(line).get("product_id"), []))
384
+ for line in open(products_file)
385
+ if line.strip() and json.loads(line).get("checked") == 1
386
+ )
387
+
216
388
  # Query to test
217
389
  query = """
218
390
  SELECT
@@ -234,6 +406,10 @@ def main():
234
406
  print(f" Products: {products_file}")
235
407
  print(f" Images: {images_file}")
236
408
  print()
409
+ print(f"Expected:")
410
+ print(f" Products with checked=1: {products_checked_1}")
411
+ print(f" Expected joined rows: ~{expected_rows}")
412
+ print()
237
413
  print(f"Query:")
238
414
  print(query)
239
415
  print()
@@ -386,6 +562,35 @@ def main():
386
562
  f"{result['memory_overhead_mb']:>12.2f} {result['avg_cpu_percent']:>8.1f} "
387
563
  f"{result['rows_per_second']:>12,.0f} {output_info:<30}")
388
564
 
565
+ print()
566
+ print("=" * 70)
567
+ print("RESULT VALIDATION")
568
+ print("=" * 70)
569
+ print()
570
+
571
+ # Compare results across configurations
572
+ comparison = compare_results(all_results)
573
+
574
+ if comparison["consistent"]:
575
+ print("[OK] All configurations returned consistent results!")
576
+ print(f" Row counts: {comparison['row_counts']}")
577
+ print(f" Unique products: {comparison['unique_products']}")
578
+ else:
579
+ print("[WARNING] Some inconsistencies found between configurations:")
580
+ for issue in comparison["issues"]:
581
+ print(f" {issue}")
582
+ print()
583
+ print(" Row counts by configuration:")
584
+ for name, count in comparison['row_counts'].items():
585
+ print(f" {name}: {count:,}")
586
+
587
+ # Explain expected differences
588
+ print()
589
+ print(" Expected differences:")
590
+ print(" - Configs 1-4: No filter pushdown to source; WHERE is evaluated in-engine after join")
591
+ print(" - Configs 5-6: Filter pushdown/column pruning enabled; WHERE may be applied while scanning (same final rows, less work)")
592
+ print(" - Config 7: first_match_only enabled; may return fewer rows (1 match per product)")
593
+
389
594
  print()
390
595
  print("=" * 70)
391
596
  print("RECOMMENDATIONS")
@@ -0,0 +1,48 @@
1
+ """Debug WHERE clause issue"""
2
+
3
+ import json
4
+ from streaming_sql_engine import Engine
5
+
6
+ def load_jsonl_file(filename):
7
+ """Simple JSONL loader without protocol support."""
8
+ with open(filename, "r", encoding="utf-8") as f:
9
+ for line in f:
10
+ if line.strip():
11
+ row = json.loads(line)
12
+ print(f"Source row columns: {list(row.keys())}")
13
+ print(f"Has 'checked': {'checked' in row}")
14
+ yield row
15
+ break # Just first row for debugging
16
+
17
+ # Initialize engine
18
+ engine = Engine(debug=True, use_polars=False, first_match_only=False)
19
+
20
+ # Register sources (without protocol support)
21
+ engine.register("products", lambda: load_jsonl_file("products_3_1k.jsonl"))
22
+ engine.register("images", lambda: load_jsonl_file("images_3_1k.jsonl"))
23
+
24
+ # Query with WHERE clause
25
+ query = """
26
+ SELECT
27
+ products.product_id,
28
+ products.product_sku,
29
+ products.title,
30
+ images.image,
31
+ images.image_type
32
+ FROM products
33
+ LEFT JOIN images ON products.product_id = images.product_id
34
+ WHERE products.checked = 1
35
+ """
36
+
37
+ print("Executing query...")
38
+ print()
39
+
40
+ row_count = 0
41
+ for row in engine.query(query):
42
+ row_count += 1
43
+ print(f"Result row {row_count} columns: {list(row.keys())}")
44
+ print(f"Has 'checked': {'checked' in row or 'products.checked' in row}")
45
+ if row_count >= 3:
46
+ break
47
+
48
+ print(f"\nTotal rows returned: {row_count}")
@@ -103,7 +103,20 @@ def evaluate_expression(expr, row):
103
103
 
104
104
  elif expr_type is _LITERAL_TYPE:
105
105
  # Literal value
106
- return expr.this
106
+ value = expr.this
107
+ # sqlglot stores numeric literals as strings, so convert them back to numbers
108
+ if isinstance(value, str):
109
+ # Try to convert string to number if it looks like a number
110
+ try:
111
+ # Check if it's a float (has decimal point or scientific notation)
112
+ if '.' in value or 'e' in value.lower() or 'E' in value:
113
+ return float(value)
114
+ # Otherwise try integer
115
+ return int(value)
116
+ except (ValueError, TypeError):
117
+ # Not a number, return as string
118
+ pass
119
+ return value
107
120
 
108
121
  elif expr_type is _EQ_TYPE:
109
122
  # Equality: left = right
@@ -88,6 +88,10 @@ def execute_plan(
88
88
  # Can't inspect signature, assume no protocol
89
89
  return False
90
90
 
91
+ # Track whether we actually pushed the WHERE clause to the source
92
+ # If source doesn't support protocol, we need to keep pushable WHERE in plan.where_expr
93
+ where_was_pushed = False
94
+
91
95
  # Apply optimizations if protocol is supported
92
96
  if source_supports_optimizations(root_source_fn) and (root_required_columns or pushable_where_sql):
93
97
  if debug:
@@ -103,6 +107,7 @@ def execute_plan(
103
107
  )
104
108
 
105
109
  root_source_fn = optimized_source_fn
110
+ where_was_pushed = bool(pushable_where_sql) # Mark that WHERE was pushed
106
111
 
107
112
  # Start with scan of root table
108
113
  if debug:
@@ -121,9 +126,14 @@ def execute_plan(
121
126
 
122
127
  # Apply joins in order
123
128
  # Track WHERE clauses that have been pushed to sources
129
+ # IMPORTANT: Initialize remaining_where_expr from plan.where_expr AFTER we know
130
+ # whether pushable WHERE was pushed. If pushable WHERE wasn't pushed, we'll restore it later.
131
+ # For now, start with plan.where_expr (which might be None if optimizer moved everything to pushable_where_expr)
124
132
  remaining_where_expr = plan.where_expr
125
- if debug and remaining_where_expr:
133
+ if debug:
126
134
  print(f" [DEBUG] Initial remaining_where_expr: {remaining_where_expr}")
135
+ print(f" [DEBUG] plan.pushable_where_expr: {plan.pushable_where_expr}")
136
+ print(f" [DEBUG] where_was_pushed: {where_was_pushed}")
127
137
 
128
138
  for i, join_info in enumerate(plan.joins, 1):
129
139
  # Get required columns for joined table (needed for optimizations)
@@ -221,26 +231,108 @@ def execute_plan(
221
231
  )
222
232
 
223
233
  # Update plan.where_expr to only include clauses not pushed to sources
224
- plan.where_expr = remaining_where_expr
234
+ # If pushable WHERE clause wasn't actually pushed (source doesn't support protocol),
235
+ # we need to keep it in plan.where_expr so it gets applied after scanning/joining
236
+ if not where_was_pushed and plan.pushable_where_expr:
237
+ # Source doesn't support protocol, so pushable WHERE wasn't pushed
238
+ # Combine pushable WHERE with remaining WHERE
239
+ from .optimizer import _combine_expressions
240
+ import sqlglot.expressions as exp
241
+ if remaining_where_expr:
242
+ plan.where_expr = _combine_expressions([plan.pushable_where_expr, remaining_where_expr], exp.And)
243
+ else:
244
+ plan.where_expr = plan.pushable_where_expr
245
+ if debug:
246
+ print(f" [DEBUG] Restored pushable WHERE clause to plan.where_expr (wasn't pushed)")
247
+ print(f" [DEBUG] Final plan.where_expr: {plan.where_expr}")
248
+ else:
249
+ # WHERE was pushed or there was no pushable WHERE, use remaining WHERE
250
+ plan.where_expr = remaining_where_expr
251
+ if debug:
252
+ print(f" [DEBUG] Using remaining_where_expr: {plan.where_expr}")
225
253
 
226
254
  # Apply WHERE filter if present (non-pushable conditions)
227
255
  # Must be applied AFTER joins since remaining WHERE conditions may reference joined tables
228
256
  if plan.where_expr:
229
257
  if debug:
230
258
  print(f" [FILTER] Applying WHERE clause (non-pushable conditions)")
259
+ print(f" [DEBUG] WHERE expression type: {type(plan.where_expr)}")
260
+ print(f" [DEBUG] WHERE expression: {plan.where_expr}")
261
+ if hasattr(plan.where_expr, 'this') and hasattr(plan.where_expr, 'expression'):
262
+ left = plan.where_expr.this
263
+ right = plan.where_expr.expression
264
+ print(f" [DEBUG] Left: {left} (type={type(left)})")
265
+ print(f" [DEBUG] Right: {right} (type={type(right)})")
266
+ if hasattr(right, 'this'):
267
+ print(f" [DEBUG] Right value: {right.this} (type={type(right.this)})")
268
+
269
+ # Apply WHERE filter
270
+ # IMPORTANT: For table-prefixed columns (like products.checked), we use Python FilterIterator
271
+ # to ensure correctness. Polars filtering can be unreliable with table-prefixed columns
272
+ # because the column names in the DataFrame might not match the filter expression.
273
+ # Python FilterIterator uses evaluate_expression() which correctly handles table prefixes.
274
+
275
+ # Check if WHERE expression has table-prefixed columns
276
+ # IMPORTANT: Table-prefixed columns (like products.checked) require Python FilterIterator
277
+ # because Polars filtering has issues with table prefixes and type mismatches
278
+ # We check by looking at the left side of the equality expression
279
+ has_table_prefix = False
280
+ try:
281
+ from sqlglot import expressions as exp
282
+ # Simple check: if WHERE expression is an equality and left side is a Column with table prefix
283
+ if isinstance(plan.where_expr, exp.EQ):
284
+ left = plan.where_expr.this
285
+ if isinstance(left, exp.Column) and left.table:
286
+ has_table_prefix = True
287
+ if debug:
288
+ print(f" [DEBUG] Table prefix detected: {left.table}.{left.name}")
289
+ # Also check recursively for other expression types
290
+ elif hasattr(plan.where_expr, 'this'):
291
+ left = plan.where_expr.this
292
+ if isinstance(left, exp.Column) and left.table:
293
+ has_table_prefix = True
294
+ if debug:
295
+ print(f" [DEBUG] Table prefix detected in nested expression: {left.table}.{left.name}")
296
+
297
+ if debug and not has_table_prefix:
298
+ print(f" [DEBUG] No table prefix detected in WHERE expression")
299
+ except Exception as e:
300
+ # If check fails, assume it might have table prefixes (safer)
301
+ has_table_prefix = True
302
+ if debug:
303
+ print(f" [DEBUG] Table prefix check failed: {e}, assuming True (safer)")
231
304
 
232
- # Use Polars batch filtering if available and beneficial
233
- if (use_polars and POLARS_AVAILABLE and PolarsBatchFilterIterator is not None):
305
+ # Use Polars filtering only if no table prefixes AND Polars is available
306
+ # IMPORTANT: Always use Python FilterIterator for table-prefixed columns to ensure correctness
307
+ # Polars filtering has issues with:
308
+ # 1. Table-prefixed column names (products.checked vs checked)
309
+ # 2. Type mismatches (string '1' vs int 1)
310
+ # Python FilterIterator handles both correctly
311
+ if (not has_table_prefix and use_polars and POLARS_AVAILABLE and PolarsBatchFilterIterator is not None):
234
312
  if debug:
235
- print(f" [POLARS] Using Polars vectorized filtering (SIMD-accelerated)")
313
+ print(f" [POLARS] Attempting Polars vectorized filtering (no table prefixes detected)")
236
314
  try:
237
315
  iterator = PolarsBatchFilterIterator(iterator, plan.where_expr, batch_size=10000, debug=debug)
316
+ if debug:
317
+ print(f" [POLARS] ✓ Polars filtering initialized successfully")
238
318
  except Exception as e:
239
319
  if debug:
240
- print(f" [POLARS] ✗ Filtering failed: {e}, using Python")
320
+ print(f" [POLARS] ✗ Filtering failed: {e}, falling back to Python FilterIterator")
321
+ import traceback
322
+ traceback.print_exc()
323
+ # Fallback to Python filter - this MUST work
241
324
  iterator = FilterIterator(iterator, plan.where_expr, debug=debug)
242
325
  else:
326
+ # Use Python filter iterator (more reliable for table-prefixed columns and type handling)
327
+ if debug:
328
+ if has_table_prefix:
329
+ print(f" [FILTER] Using Python FilterIterator (table-prefixed columns detected: products.checked)")
330
+ else:
331
+ print(f" [FILTER] Using Python FilterIterator (Polars not available or not requested)")
243
332
  iterator = FilterIterator(iterator, plan.where_expr, debug=debug)
333
+ else:
334
+ if debug:
335
+ print(f" [DEBUG] No WHERE clause to apply (plan.where_expr is None)")
244
336
 
245
337
  # Apply projection
246
338
  if debug:
@@ -381,21 +473,27 @@ def _build_join_iterator(
381
473
 
382
474
  # Decide between Polars and Python implementation
383
475
  # When use_polars=True, Polars is prioritized (unless mmap explicitly requested via filename)
384
- if debug:
385
- if use_polars:
386
- if POLARS_AVAILABLE:
387
- print(f" [POLARS] Checking if Polars should be used...")
388
- try:
389
- should_use = should_use_polars(right_source, threshold=10000)
390
- if not should_use:
391
- print(f" [POLARS] Right side too small or estimation failed, using Python join instead")
392
- except Exception as e:
393
- print(f" [POLARS] Estimation failed: {e}, using Python join instead")
394
- else:
395
- print(f" [POLARS] Polars not available (not installed), falling back to Python")
476
+ # IMPORTANT: Call should_use_polars() only ONCE to avoid double I/O
477
+ should_use_polars_result = False
478
+ if use_polars and POLARS_AVAILABLE:
479
+ if debug:
480
+ print(f" [POLARS] Checking if Polars should be used...")
481
+ try:
482
+ should_use_polars_result = should_use_polars(right_source, threshold=10000)
483
+ if debug:
484
+ if not should_use_polars_result:
485
+ print(f" [POLARS] Right side too small or estimation failed, using Python join instead")
486
+ except Exception as e:
487
+ if debug:
488
+ print(f" [POLARS] Estimation failed: {e}, using Python join instead")
489
+ should_use_polars_result = False
490
+ elif debug:
491
+ if not use_polars:
492
+ print(f" [POLARS] use_polars=False, using Python join")
493
+ elif not POLARS_AVAILABLE:
494
+ print(f" [POLARS] Polars not available (not installed), falling back to Python")
396
495
 
397
- if (use_polars and POLARS_AVAILABLE and
398
- should_use_polars(right_source, threshold=10000)):
496
+ if (use_polars and POLARS_AVAILABLE and should_use_polars_result):
399
497
  if debug:
400
498
  iterator_type = "POLARS LOOKUP JOIN"
401
499
  print(f" [POLARS] ✓ Using {iterator_type} (SIMD-accelerated)")
@@ -83,15 +83,63 @@ class FilterIterator:
83
83
 
84
84
  def __next__(self):
85
85
  while True:
86
- row = next(self.source)
86
+ try:
87
+ row = next(self.source)
88
+ except StopIteration:
89
+ if self.debug and self._rows_processed == 0:
90
+ print(f" [DEBUG] FilterIterator: Source iterator is empty (no rows from upstream)")
91
+ raise
92
+ except Exception as e:
93
+ if self.debug:
94
+ print(f" [ERROR] FilterIterator: Failed to get row from source: {e}")
95
+ import traceback
96
+ traceback.print_exc()
97
+ raise
98
+
87
99
  self._rows_processed += 1
88
100
 
89
- if evaluate_expression(self.where_expr, row):
90
- self._rows_passed += 1
91
- if self.debug and self._rows_passed % 10000 == 0:
92
- print(f" Filter: {self._rows_passed:,} passed / {self._rows_processed:,} processed")
93
- return row
94
- # Row filtered out - continue loop
101
+ try:
102
+ if self.debug and self._rows_processed <= 3:
103
+ print(f" [DEBUG] FilterIterator: Processing row {self._rows_processed}, keys={list(row.keys())[:5]}")
104
+ print(f" [DEBUG] WHERE expression: {self.where_expr}")
105
+ print(f" [DEBUG] WHERE expression type: {type(self.where_expr)}")
106
+ if hasattr(self.where_expr, 'this'):
107
+ left = self.where_expr.this
108
+ print(f" [DEBUG] WHERE left side: {left} (type={type(left)})")
109
+ if hasattr(left, 'name'):
110
+ print(f" [DEBUG] Left column name: {left.name}, table: {getattr(left, 'table', None)}")
111
+ if hasattr(self.where_expr, 'expression'):
112
+ right = self.where_expr.expression
113
+ print(f" [DEBUG] WHERE right side: {right} (type={type(right)})")
114
+ if hasattr(right, 'this'):
115
+ print(f" [DEBUG] Right value: {right.this} (type={type(right.this)})")
116
+
117
+ result = evaluate_expression(self.where_expr, row)
118
+
119
+ if self.debug and self._rows_processed <= 3:
120
+ print(f" [DEBUG] FilterIterator: Expression result={result} (type={type(result)})")
121
+ if 'products.checked' in row:
122
+ print(f" [DEBUG] products.checked={row.get('products.checked')} (type={type(row.get('products.checked'))})")
123
+ elif 'checked' in row:
124
+ print(f" [DEBUG] checked={row.get('checked')} (type={type(row.get('checked'))})")
125
+
126
+ if result:
127
+ self._rows_passed += 1
128
+ if self.debug and self._rows_passed % 10000 == 0:
129
+ print(f" Filter: {self._rows_passed:,} passed / {self._rows_processed:,} processed")
130
+ return row
131
+ # Row filtered out - continue loop
132
+ if self.debug and self._rows_processed <= 5:
133
+ # Debug first few filtered rows
134
+ print(f" [DEBUG] Row filtered out: keys={list(row.keys())[:5]}, expr_result={result}")
135
+ except Exception as e:
136
+ if self.debug:
137
+ print(f" [ERROR] Filter evaluation failed: {e}")
138
+ print(f" [ERROR] Row keys: {list(row.keys())[:10]}")
139
+ import traceback
140
+ traceback.print_exc()
141
+ # On error, skip row (conservative)
142
+ continue
95
143
 
96
144
 
97
145
  class ProjectIterator: