File size: 13,137 Bytes
f3bcb28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Feature Enforcement Engine.

Enforces strict use-case / feature restrictions per application.
Each application declares allowed features with their constraints.

Uses ConditionMatcher for unified validation logic.
"""

from typing import Optional
from pydantic import BaseModel
from enum import Enum
import logging

from .decision import (
    DecisionBuilder,
    DecisionSource,
    DecisionType,
    DecisionCodes,
)
from backend.core.base import ConditionMatcher

logger = logging.getLogger(__name__)


class FeatureAction(str, Enum):
    """Allowed actions for features."""

    GENERATE = "generate"
    SUMMARIZE = "summarize"
    CLASSIFY = "classify"
    EXTRACT = "extract"
    TRANSLATE = "translate"
    EMBED = "embed"
    CHAT = "chat"
    COMPLETE = "complete"


class FeatureConfig(BaseModel):
    """Configuration for a feature."""

    name: str
    description: Optional[str] = None
    enabled: bool = True

    # Allowed actions for this feature
    allowed_actions: list[FeatureAction] = list(FeatureAction)

    # Model restrictions for this feature
    allowed_models: list[str] = []  # Empty = all allowed
    denied_models: list[str] = []

    # Token limits specific to this feature
    max_input_tokens: Optional[int] = None
    max_output_tokens: Optional[int] = None

    # Environment restrictions
    allowed_environments: list[str] = []  # Empty = all allowed
    denied_environments: list[str] = []

    # Output constraints
    require_json_output: bool = False
    json_schema: Optional[dict] = None  # JSON schema for output validation

    # Rate limits specific to this feature
    rate_limit_per_minute: Optional[int] = None
    rate_limit_per_hour: Optional[int] = None

    # Cost controls
    max_cost_per_request_usd: Optional[float] = None


class FeatureRegistry(BaseModel):
    """Registry of allowed features for an application."""

    app_id: str

    # Strict mode: only declared features allowed
    strict_mode: bool = True

    # Default feature (used when none specified)
    default_feature: Optional[str] = None

    # Registered features
    features: dict[str, FeatureConfig] = {}

    # Global model restrictions (apply to all features)
    global_allowed_models: list[str] = []
    global_denied_models: list[str] = []


class FeatureCheckResult(BaseModel):
    """Result of feature check."""

    allowed: bool
    feature: str
    reason: Optional[str] = None
    warnings: list[str] = []
    config: Optional[FeatureConfig] = None


class FeatureEngine:
    """
    Feature Enforcement Engine.

    Validates that requests match declared features and their constraints.
    """

    def __init__(self):
        # In-memory registry (TODO: load from DB)
        self.registries: dict[str, FeatureRegistry] = {}

    def register_app(self, registry: FeatureRegistry) -> None:
        """Register an application's feature configuration."""
        self.registries[registry.app_id] = registry

    def get_registry(self, app_id: str) -> Optional[FeatureRegistry]:
        """Get feature registry for an application."""
        return self.registries.get(app_id)

    def add_feature(self, app_id: str, config: FeatureConfig) -> None:
        """Add or update a feature for an application."""
        if app_id not in self.registries:
            self.registries[app_id] = FeatureRegistry(app_id=app_id)
        self.registries[app_id].features[config.name] = config

    def remove_feature(self, app_id: str, feature_name: str) -> bool:
        """Remove a feature from an application."""
        if app_id in self.registries:
            if feature_name in self.registries[app_id].features:
                del self.registries[app_id].features[feature_name]
                return True
        return False

    def check_feature(
        self,
        app_id: str,
        feature: str,
        action: Optional[str] = None,
        model: Optional[str] = None,
        environment: Optional[str] = None,
        input_tokens: Optional[int] = None,
        output_tokens: Optional[int] = None,
    ) -> FeatureCheckResult:
        """
        Check if a feature request is allowed.

        Args:
            app_id: Application ID
            feature: Feature name
            action: Action type (generate, summarize, etc.)
            model: Model being requested
            environment: Environment (dev, staging, prod)
            input_tokens: Estimated input tokens
            output_tokens: Max output tokens requested

        Returns:
            FeatureCheckResult with allowed status and details
        """
        registry = self.registries.get(app_id)

        # No registry = no restrictions (non-strict mode by default)
        if not registry:
            return FeatureCheckResult(
                allowed=True,
                feature=feature,
                warnings=["No feature registry configured for this app"],
            )

        # Use default feature if none specified
        effective_feature = feature or registry.default_feature
        if not effective_feature:
            if registry.strict_mode:
                return FeatureCheckResult(
                    allowed=False,
                    feature=feature or "unknown",
                    reason="No feature specified and no default configured (strict mode)",
                )
            return FeatureCheckResult(
                allowed=True,
                feature="default",
                warnings=["No feature specified, using permissive default"],
            )

        # Check if feature exists
        config = registry.features.get(effective_feature)
        if not config:
            if registry.strict_mode:
                return FeatureCheckResult(
                    allowed=False,
                    feature=effective_feature,
                    reason=f"Feature '{effective_feature}' not registered (strict mode)",
                )
            return FeatureCheckResult(
                allowed=True,
                feature=effective_feature,
                warnings=[f"Feature '{effective_feature}' not registered"],
            )

        # Check if feature is enabled
        if not config.enabled:
            return FeatureCheckResult(
                allowed=False,
                feature=effective_feature,
                reason=f"Feature '{effective_feature}' is disabled",
                config=config,
            )

        warnings = []

        # Check action
        if action:
            try:
                action_enum = FeatureAction(action)
                if action_enum not in config.allowed_actions:
                    return FeatureCheckResult(
                        allowed=False,
                        feature=effective_feature,
                        reason=f"Action '{action}' not allowed for feature '{effective_feature}'",
                        config=config,
                    )
            except ValueError:
                warnings.append(f"Unknown action '{action}'")

        # Check model restrictions using ConditionMatcher
        if model:
            # Global restrictions first
            ok, reason = ConditionMatcher.matches_model(
                model,
                allowed=registry.global_allowed_models or None,
                denied=registry.global_denied_models or None,
            )
            if not ok:
                return FeatureCheckResult(
                    allowed=False,
                    feature=effective_feature,
                    reason=reason or f"Model '{model}' not allowed globally",
                    config=config,
                )

            # Feature-specific restrictions
            ok, reason = ConditionMatcher.matches_model(
                model,
                allowed=config.allowed_models or None,
                denied=config.denied_models or None,
            )
            if not ok:
                return FeatureCheckResult(
                    allowed=False,
                    feature=effective_feature,
                    reason=reason
                    or f"Model '{model}' not allowed for feature '{effective_feature}'",
                    config=config,
                )

        # Check environment restrictions using ConditionMatcher
        if environment:
            ok, reason = ConditionMatcher.matches_environment(
                environment,
                allowed=config.allowed_environments or None,
                denied=config.denied_environments or None,
            )
            if not ok:
                return FeatureCheckResult(
                    allowed=False,
                    feature=effective_feature,
                    reason=reason
                    or f"Environment '{environment}' not allowed for feature '{effective_feature}'",
                    config=config,
                )

        # Check token limits using ConditionMatcher
        ok, reason = ConditionMatcher.matches_tokens(
            input_tokens=input_tokens,
            output_tokens=output_tokens,
            max_input=config.max_input_tokens,
            max_output=config.max_output_tokens,
        )
        if not ok:
            return FeatureCheckResult(
                allowed=False,
                feature=effective_feature,
                reason=reason
                or f"Token limit exceeded for feature '{effective_feature}'",
                config=config,
            )

        return FeatureCheckResult(
            allowed=True,
            feature=effective_feature,
            warnings=warnings if warnings else None,
            config=config,
        )

    def check_feature_with_decision(
        self,
        builder: DecisionBuilder,
        app_id: str,
        feature: str,
        **kwargs,
    ) -> FeatureCheckResult:
        """
        Check feature and add to decision builder.

        Integrates with the Decision Engine for full traceability.
        """
        import time

        start = time.time()

        result = self.check_feature(app_id, feature, **kwargs)

        duration_ms = (time.time() - start) * 1000

        # Add trace
        builder.add_trace(
            source=DecisionSource.FEATURE,
            checked=f"feature:{feature}",
            result=DecisionType.ALLOW if result.allowed else DecisionType.DENY,
            matched=not result.allowed,
            condition=f"app={app_id}, feature={feature}",
            actual_value=feature,
            expected_value=list(
                self.registries.get(
                    app_id, FeatureRegistry(app_id=app_id)
                ).features.keys()
            ),
            duration_ms=duration_ms,
        )

        # Add to decision
        if not result.allowed:
            builder.deny(
                source=DecisionSource.FEATURE,
                code=DecisionCodes.FEATURE_NOT_ALLOWED,
                message=result.reason,
                details={
                    "feature": result.feature,
                    "app_id": app_id,
                },
            )

        # Add warnings
        for warning in result.warnings or []:
            builder.warn(
                source=DecisionSource.FEATURE,
                code=DecisionCodes.FEATURE_UNKNOWN,
                message=warning,
            )

        return result

    def list_features(self, app_id: str) -> list[FeatureConfig]:
        """List all features for an application."""
        registry = self.registries.get(app_id)
        if not registry:
            return []
        return list(registry.features.values())


# Singleton instance
feature_engine = FeatureEngine()


# Helper to create a default feature registry for testing
def create_default_registry(app_id: str) -> FeatureRegistry:
    """Create a default feature registry with common features."""
    return FeatureRegistry(
        app_id=app_id,
        strict_mode=False,
        default_feature="general",
        features={
            "general": FeatureConfig(
                name="general",
                description="General purpose LLM usage",
                allowed_actions=list(FeatureAction),
            ),
            "chat": FeatureConfig(
                name="chat",
                description="Conversational chat",
                allowed_actions=[FeatureAction.CHAT, FeatureAction.GENERATE],
            ),
            "summarization": FeatureConfig(
                name="summarization",
                description="Text summarization",
                allowed_actions=[FeatureAction.SUMMARIZE],
                max_output_tokens=1000,
            ),
            "classification": FeatureConfig(
                name="classification",
                description="Text classification",
                allowed_actions=[FeatureAction.CLASSIFY],
                require_json_output=True,
                max_output_tokens=100,
            ),
            "extraction": FeatureConfig(
                name="extraction",
                description="Information extraction",
                allowed_actions=[FeatureAction.EXTRACT],
                require_json_output=True,
            ),
        },
    )