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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
"""

Integration tests for Feature Engineering MCP Server.

Tests the complete feature engineering pipeline with real data flows.

"""

import pytest
import pandas as pd
import numpy as np
import tempfile
import os
import asyncio
from unittest.mock import patch, AsyncMock
from uuid import uuid4

from mcp_servers.feature_engineering.server import FeatureEngineeringMCPServer
from shared.models import UserContext, FeatureSet
from shared.database import SupabaseManager


class TestFeatureEngineeringIntegration:
    """Integration tests for feature engineering workflows."""
    
    @pytest.fixture
    def sample_dataset(self):
        """Create a realistic sample dataset for testing."""
        np.random.seed(42)
        n_samples = 1000
        
        # Create correlated features
        x1 = np.random.normal(100, 15, n_samples)
        x2 = 0.7 * x1 + np.random.normal(0, 5, n_samples)  # Correlated with x1
        x3 = np.random.exponential(2, n_samples)
        
        # Create categorical features
        categories = np.random.choice(['Low', 'Medium', 'High'], n_samples, p=[0.3, 0.4, 0.3])
        binary_cat = np.random.choice(['Yes', 'No'], n_samples)
        
        # Create target with some relationship to features
        target = (0.3 * x1 + 0.2 * x2 + 0.1 * x3 + 
                 np.where(categories == 'High', 20, 0) + 
                 np.random.normal(0, 10, n_samples))
        target = (target > target.median()).astype(int)
        
        return pd.DataFrame({
            'sales_amount': x1,
            'marketing_spend': x2,
            'customer_age': x3,
            'product_category': categories,
            'premium_customer': binary_cat,
            'target': target
        })
    
    @pytest.fixture
    def sample_hypotheses(self):
        """Create realistic hypotheses based on business scenarios."""
        return [
            {
                "id": str(uuid4()),
                "text": "There is a significant correlation between sales_amount and marketing_spend",
                "test_type": "correlation",
                "variables": ["sales_amount", "marketing_spend"],
                "expected_outcome": "Positive correlation exists",
                "business_relevance": "Understanding marketing ROI",
                "is_significant": True,
                "p_value": 0.001
            },
            {
                "id": str(uuid4()),
                "text": "There are significant differences in sales_amount across product_category groups",
                "test_type": "anova",
                "variables": ["product_category", "sales_amount"],
                "expected_outcome": "Significant differences across categories",
                "business_relevance": "Product performance analysis",
                "is_significant": True,
                "p_value": 0.01
            },
            {
                "id": str(uuid4()),
                "text": "There is a significant difference in customer_age between premium_customer groups",
                "test_type": "t_test",
                "variables": ["premium_customer", "customer_age"],
                "expected_outcome": "Age difference between premium and regular customers",
                "business_relevance": "Customer segmentation insights",
                "is_significant": True,
                "p_value": 0.02
            }
        ]
    
    @pytest.fixture
    def temp_dataset_file(self, sample_dataset):
        """Create a temporary dataset file."""
        with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f:
            sample_dataset.to_csv(f.name, index=False)
            yield f.name
        os.unlink(f.name)
    
    @pytest.fixture
    def mock_database(self, temp_dataset_file):
        """Create a comprehensive mock database."""
        db = AsyncMock()
        
        # Mock dataset retrieval
        db.get_dataset.return_value = {
            "id": "dataset-123",
            "name": "sales_data.csv",
            "file_path": temp_dataset_file,
            "metadata": {
                "rows": 1000,
                "columns": 6,
                "column_names": ["sales_amount", "marketing_spend", "customer_age", 
                               "product_category", "premium_customer", "target"]
            }
        }
        
        # Mock database operations
        db.store_feature_engineering_plan.return_value = "plan-123"
        db.create_dataset.return_value = "engineered-dataset-123"
        db.store_engineered_features.return_value = ["feature-1", "feature-2"]
        db.store_feature_complexity_metrics.return_value = "metrics-123"
        db.store_feature_validation.return_value = "validation-123"
        
        return db
    
    @pytest.fixture
    def server(self):
        """Create server instance."""
        return FeatureEngineeringMCPServer()
    
    @pytest.fixture
    def user_context(self):
        """Create user context."""
        return UserContext(user_id="integration_test_user", email="test@example.com")
    
    @pytest.mark.asyncio
    async def test_complete_feature_engineering_pipeline(

        self, server, user_context, sample_hypotheses, mock_database

    ):
        """Test the complete feature engineering pipeline from hypothesis to validation."""
        
        with patch('shared.database.get_database', return_value=mock_database):
            # Step 1: Generate features based on hypotheses
            generation_result = await server._generate_features(
                user_context,
                {
                    "dataset_id": "dataset-123",
                    "hypotheses": sample_hypotheses,
                    "max_features": 20,
                    "complexity_threshold": 0.7
                }
            )
            
            # Verify feature generation results
            assert "plan_id" in generation_result
            assert "feature_set" in generation_result
            assert "features_generated" in generation_result
            assert generation_result["features_generated"] > 0
            
            feature_set = generation_result["feature_set"]
            assert "interaction_features" in feature_set
            assert "transformation_features" in feature_set
            assert "aggregation_features" in feature_set
            
            # Verify we have different types of features
            breakdown = generation_result["breakdown"]
            assert breakdown["interaction_features"] > 0  # Should have correlation-based interactions
            assert breakdown["transformation_features"] > 0  # Should have log/square transforms
            assert breakdown["aggregation_features"] > 0  # Should have group-based features
            
            # Step 2: Apply feature engineering
            with patch.object(server, '_load_dataframe') as mock_load:
                # Load the actual dataset for feature engineering
                original_df = pd.read_csv(mock_database.get_dataset.return_value["file_path"])
                mock_load.return_value = original_df
                
                engineering_result = await server._apply_feature_engineering(
                    user_context,
                    {
                        "dataset_id": "dataset-123",
                        "feature_set": feature_set
                    }
                )
                
                # Verify engineering results
                assert "engineered_dataset_id" in engineering_result
                assert "features_created" in engineering_result
                assert "final_shape" in engineering_result
                assert "complexity_metrics" in engineering_result
                
                # Should have created new features
                assert engineering_result["features_created"] > 0
                
                # Final dataset should have more columns than original
                final_shape = engineering_result["final_shape"]
                assert final_shape["columns"] > len(original_df.columns)
                
                # Step 3: Validate features for data leakage
                mock_database.get_engineered_features.return_value = [
                    {
                        "feature_name": "sales_amount_x_marketing_spend",
                        "feature_type": "interaction",
                        "source_columns": ["sales_amount", "marketing_spend"],
                        "formula": "sales_amount * marketing_spend",
                        "hypothesis_basis": "Correlation hypothesis"
                    }
                ]
                
                # Mock loading both original and engineered datasets
                engineered_df = original_df.copy()
                engineered_df["sales_amount_x_marketing_spend"] = (
                    engineered_df["sales_amount"] * engineered_df["marketing_spend"]
                )
                mock_load.side_effect = [original_df, engineered_df]
                
                validation_result = await server._validate_features(
                    user_context,
                    {
                        "original_dataset_id": "dataset-123",
                        "engineered_dataset_id": engineering_result["engineered_dataset_id"],
                        "target_column": "target"
                    }
                )
                
                # Verify validation results
                assert "has_data_leakage" in validation_result
                assert "leakage_warnings" in validation_result
                assert "validation_errors" in validation_result
                assert "validation_passed" in validation_result
                
                # Should pass validation (no direct target leakage)
                assert validation_result["validation_passed"] is True
    
    @pytest.mark.asyncio
    async def test_feature_explanation_generation(

        self, server, user_context, mock_database

    ):
        """Test feature explanation generation."""
        
        # Mock engineered features with detailed information
        mock_database.get_engineered_features.return_value = [
            {
                "feature_name": "sales_marketing_interaction",
                "feature_type": "interaction",
                "source_columns": ["sales_amount", "marketing_spend"],
                "formula": "sales_amount * marketing_spend",
                "hypothesis_basis": "Strong correlation between sales and marketing indicates multiplicative effect",
                "description": "Interaction between sales amount and marketing spend to capture synergistic effects",
                "importance_score": 0.85
            },
            {
                "feature_name": "customer_age_log",
                "feature_type": "transformation",
                "source_columns": ["customer_age"],
                "formula": "log(customer_age)",
                "hypothesis_basis": "Age distribution is right-skewed, log transformation normalizes",
                "description": "Log transformation of customer age for better model performance",
                "importance_score": 0.62
            },
            {
                "feature_name": "sales_mean_by_category",
                "feature_type": "aggregation",
                "source_columns": ["product_category", "sales_amount"],
                "formula": "mean(sales_amount) grouped by product_category",
                "hypothesis_basis": "ANOVA test showed significant differences across product categories",
                "description": "Average sales amount for each product category",
                "importance_score": 0.73
            }
        ]
        
        mock_database.get_dataset.return_value = {
            "metadata": {"feature_engineering_applied": True}
        }
        
        with patch('shared.database.get_database', return_value=mock_database):
            result = await server._explain_features(
                user_context,
                {"engineered_dataset_id": "engineered-123"}
            )
            
            # Verify explanation results
            assert "engineered_dataset_id" in result
            assert "total_features" in result
            assert "feature_explanations" in result
            assert "feature_breakdown" in result
            
            assert result["total_features"] == 3
            
            explanations = result["feature_explanations"]
            assert len(explanations) == 3
            
            # Verify each explanation has required fields
            for explanation in explanations:
                assert "feature_name" in explanation
                assert "description" in explanation
                assert "hypothesis_basis" in explanation
                assert "importance_score" in explanation
            
            # Verify feature breakdown
            breakdown = result["feature_breakdown"]
            assert breakdown["interaction"] == 1
            assert breakdown["transformation"] == 1
            assert breakdown["aggregation"] == 1
    
    @pytest.mark.asyncio
    async def test_complexity_metrics_tracking(

        self, server, user_context, mock_database

    ):
        """Test complexity metrics calculation and tracking."""
        
        # Mock complexity metrics
        mock_database.get_feature_complexity_metrics.return_value = {
            "total_features": 45,
            "original_features": 6,
            "engineered_features": 39,
            "interaction_features": 15,
            "transformation_features": 12,
            "aggregation_features": 12,
            "complexity_score": 0.45,
            "dimensionality_reduction_applied": False
        }
        
        with patch('shared.database.get_database', return_value=mock_database):
            result = await server._get_complexity_metrics(
                user_context,
                {"engineered_dataset_id": "engineered-123"}
            )
            
            # Verify complexity metrics
            assert "engineered_dataset_id" in result
            assert "complexity_metrics" in result
            assert "recommendations" in result
            
            metrics = result["complexity_metrics"]
            assert metrics["total_features"] == 45
            assert metrics["original_features"] == 6
            assert metrics["engineered_features"] == 39
            assert metrics["complexity_score"] == 0.45
            
            # Should have recommendations for this complexity level
            recommendations = result["recommendations"]
            assert isinstance(recommendations, list)
    
    @pytest.mark.asyncio
    async def test_data_leakage_detection_scenarios(

        self, server, user_context, mock_database, sample_dataset

    ):
        """Test various data leakage detection scenarios."""
        
        # Create datasets with different leakage scenarios
        original_df = sample_dataset.copy()
        
        # Scenario 1: Direct target leakage
        leaky_df = original_df.copy()
        leaky_df["target_copy"] = leaky_df["target"]  # Perfect correlation
        
        # Scenario 2: Future information leakage (group stats including target)
        future_leak_df = original_df.copy()
        future_leak_df["target_mean_by_category"] = future_leak_df.groupby("product_category")["target"].transform("mean")
        
        # Scenario 3: Legitimate feature (no leakage)
        clean_df = original_df.copy()
        clean_df["sales_marketing_ratio"] = clean_df["sales_amount"] / (clean_df["marketing_spend"] + 1e-8)
        
        test_scenarios = [
            ("direct_leakage", leaky_df, True),
            ("future_leakage", future_leak_df, True),
            ("clean_features", clean_df, False)
        ]
        
        for scenario_name, test_df, should_have_leakage in test_scenarios:
            # Create temporary file for test dataset
            with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f:
                test_df.to_csv(f.name, index=False)
                temp_file = f.name
            
            try:
                # Mock engineered features based on scenario
                if scenario_name == "direct_leakage":
                    mock_features = [
                        {
                            "feature_name": "target_copy",
                            "feature_type": "interaction",
                            "source_columns": ["target"],
                            "formula": "target"
                        }
                    ]
                elif scenario_name == "future_leakage":
                    mock_features = [
                        {
                            "feature_name": "target_mean_by_category",
                            "feature_type": "aggregation",
                            "source_columns": ["product_category", "target"],
                            "formula": "mean(target) grouped by product_category"
                        }
                    ]
                else:
                    mock_features = [
                        {
                            "feature_name": "sales_marketing_ratio",
                            "feature_type": "interaction",
                            "source_columns": ["sales_amount", "marketing_spend"],
                            "formula": "sales_amount / marketing_spend"
                        }
                    ]
                
                mock_database.get_engineered_features.return_value = mock_features
                
                with patch('shared.database.get_database', return_value=mock_database):
                    with patch.object(server, '_load_dataframe') as mock_load:
                        mock_load.side_effect = [original_df, test_df]
                        
                        result = await server._validate_features(
                            user_context,
                            {
                                "original_dataset_id": "original-123",
                                "engineered_dataset_id": "engineered-123",
                                "target_column": "target"
                            }
                        )
                        
                        # Verify leakage detection
                        if should_have_leakage:
                            assert result["has_data_leakage"] is True or len(result["leakage_warnings"]) > 0
                        else:
                            assert result["has_data_leakage"] is False
                            assert result["validation_passed"] is True
            
            finally:
                os.unlink(temp_file)
    
    @pytest.mark.asyncio
    async def test_dimensionality_reduction_integration(

        self, server, user_context, mock_database, sample_dataset

    ):
        """Test dimensionality reduction when feature count is high."""
        
        # Create a dataset with many features to trigger dimensionality reduction
        high_dim_df = sample_dataset.copy()
        
        # Add many random features to trigger dimensionality reduction
        np.random.seed(42)
        for i in range(100):
            high_dim_df[f"random_feature_{i}"] = np.random.normal(0, 1, len(sample_dataset))
        
        # Create feature set with many features
        feature_set = FeatureSet(
            interaction_features=[
                {
                    "name": f"interaction_{i}",
                    "type": "multiplication",
                    "variables": ["sales_amount", "marketing_spend"],
                    "formula": "sales_amount * marketing_spend",
                    "hypothesis_basis": "Test interaction",
                    "description": f"Test interaction feature {i}"
                }
                for i in range(30)
            ],
            transformation_features=[
                {
                    "name": f"transform_{i}",
                    "type": "square_transform",
                    "variables": ["sales_amount"],
                    "formula": "sales_amount^2",
                    "hypothesis_basis": "Test transformation",
                    "description": f"Test transformation feature {i}"
                }
                for i in range(30)
            ],
            aggregation_features=[]
        )
        
        with patch('shared.database.get_database', return_value=mock_database):
            with patch.object(server, '_load_dataframe') as mock_load:
                mock_load.return_value = high_dim_df
                
                result = await server._apply_feature_engineering(
                    user_context,
                    {
                        "dataset_id": "dataset-123",
                        "feature_set": feature_set.model_dump()
                    }
                )
                
                # Should trigger dimensionality reduction
                assert result["dimensionality_reduction_applied"] is True
                
                # Final feature count should be reduced
                complexity_metrics = result["complexity_metrics"]
                assert complexity_metrics["dimensionality_reduction_applied"] is True
                
                # Should have reasonable number of final features
                final_columns = result["final_shape"]["columns"]
                assert final_columns < len(high_dim_df.columns) + 60  # Original + all new features
    
    @pytest.mark.asyncio
    async def test_error_handling_and_recovery(

        self, server, user_context, mock_database

    ):
        """Test error handling and recovery mechanisms."""
        
        # Test missing dataset error
        mock_database.get_dataset.return_value = None
        
        with patch('shared.database.get_database', return_value=mock_database):
            with pytest.raises(ValueError, match="Dataset not found"):
                await server._generate_features(
                    user_context,
                    {
                        "dataset_id": "nonexistent-dataset",
                        "hypotheses": []
                    }
                )
        
        # Test invalid feature set error
        mock_database.get_dataset.return_value = {
            "file_path": "/nonexistent/file.csv"
        }
        
        with patch('shared.database.get_database', return_value=mock_database):
            with pytest.raises(ValueError, match="Failed to load dataset"):
                await server._apply_feature_engineering(
                    user_context,
                    {
                        "dataset_id": "dataset-123",
                        "feature_set": {"interaction_features": [], "transformation_features": [], "aggregation_features": []}
                    }
                )
        
        # Test validation with non-engineered dataset
        mock_database.get_dataset.return_value = {
            "metadata": {"feature_engineering_applied": False}
        }
        
        with patch('shared.database.get_database', return_value=mock_database):
            with pytest.raises(ValueError, match="not an engineered dataset"):
                await server._explain_features(
                    user_context,
                    {"engineered_dataset_id": "not-engineered-123"}
                )


if __name__ == "__main__":
    pytest.main([__file__])