flamapy 2.9.0.dev0__py3-none-any.whl → 2.9.0.dev2__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.
@@ -63,6 +63,19 @@ class Backend(str, Enum):
63
63
  # Facade backend name -> fm-to-backend transformation extension (the only non-identity mapping).
64
64
  _BACKEND_ALIAS = {"sat": "pysat"}
65
65
 
66
+ # The solver libraries are not thread-safe: Z3 shares one global context, and dd parses
67
+ # every BDD expression with one module-level parser, so two threads building or querying the
68
+ # same kind of backend model corrupt each other (wrong results, or a crash of the whole
69
+ # interpreter). One process-wide lock per backend serialises that work; jobs on different
70
+ # backends still run concurrently.
71
+ _BACKEND_LOCKS: Dict[str, threading.RLock] = {}
72
+ _BACKEND_LOCKS_GUARD = threading.Lock()
73
+
74
+
75
+ def _backend_lock(extension: str) -> threading.RLock:
76
+ with _BACKEND_LOCKS_GUARD:
77
+ return _BACKEND_LOCKS.setdefault(extension, threading.RLock())
78
+
66
79
  # Operations that ran on a fixed backend in 2.6 and accept ``backend=`` since 2.9. In 2.x only a
67
80
  # per-call ``backend=`` changes them: the workspace default and FLAMAPY_BACKEND do not, so code
68
81
  # that set a default backend in 2.6 keeps the same results (the default would otherwise move
@@ -82,6 +95,51 @@ def _raise_errors(setting: Optional[bool]) -> bool:
82
95
  return setting if setting is not None else _env_flag('FLAMAPY_RAISE_ERRORS')
83
96
 
84
97
 
98
+ def _caller_stacklevel() -> int:
99
+ """The ``warnings.warn`` stacklevel, for its caller, of the first frame outside this module:
100
+ the user's call, whichever facade entry point (operation method, iter_configurations) it
101
+ went through."""
102
+ frame = inspect.currentframe()
103
+ frame = frame.f_back if frame is not None else None # the function calling warnings.warn
104
+ level = 1
105
+ while frame is not None and frame.f_globals.get('__name__') == __name__:
106
+ frame = frame.f_back
107
+ level += 1
108
+ return level
109
+
110
+
111
+ @dataclasses.dataclass(frozen=True)
112
+ class _Route:
113
+ """How one call's backend was chosen. It travels with the call (never stored on the
114
+ facade), so concurrent ``run_async`` jobs on one facade cannot see each other's."""
115
+ # The backend name as requested or defaulted; None for an fm-level operation.
116
+ name: Optional[str] = None
117
+ # True when the choice is the query planner's (backend='auto').
118
+ auto: bool = False
119
+ # None (historical default), 'explicit', or 'auto: <planner rationale>'.
120
+ planner: Optional[str] = None
121
+ # Set when the backend ignores part of the model (its manifest does not support the
122
+ # model's language level): the warning to emit; the result is then not exact.
123
+ level_gap: Optional[str] = None
124
+
125
+
126
+ def _stamp(envelope: OperationResult[Any], route: _Route,
127
+ model: VariabilityModel) -> OperationResult[Any]:
128
+ """Record on a result envelope how its backend was chosen and whether it is exact."""
129
+ if route.planner is not None:
130
+ envelope = dataclasses.replace(envelope, planner=route.planner)
131
+ if route.level_gap is not None:
132
+ envelope = dataclasses.replace(envelope, exact=False)
133
+ if getattr(model, '_flamapy_cache_hit', False):
134
+ envelope = dataclasses.replace(envelope, cache_hit=True)
135
+ return envelope
136
+
137
+
138
+ def _warn_level_gap(route: _Route) -> None:
139
+ if route.level_gap is not None:
140
+ warnings.warn(route.level_gap, UserWarning, stacklevel=_caller_stacklevel())
141
+
142
+
85
143
  class FLAMAFeatureModel:
86
144
  """A feature model together with the analysis operations discovered from the installed plugins.
87
145
 
@@ -125,9 +183,6 @@ class FLAMAFeatureModel:
125
183
  # wall time, model hash). Purely informational in 2.9; methods still return bare
126
184
  # values. In 3.0 the envelope becomes the return type.
127
185
  self.last_result: Optional[OperationResult] = None
128
- # How the last operation's backend was chosen: None (historical default),
129
- # 'explicit', or 'auto: <planner rationale>'.
130
- self._last_planner: Optional[str] = None
131
186
  self._model_language_level: Optional[LanguageLevel] = None
132
187
 
133
188
  def _read(self, model_path: str) -> FeatureModel:
@@ -147,21 +202,15 @@ class FLAMAFeatureModel:
147
202
  return Configuration(configuration)
148
203
  return self.discover_metamodel.use_transformation_t2m(configuration, "configuration")
149
204
 
150
- def _model_for(
151
- self, descriptor: OperationDescriptor, backend_arg: Optional[str],
152
- allow_approximate: Optional[bool] = None,
153
- ) -> VariabilityModel:
154
- """Resolve the operation's target model, lazily transforming (and caching) fm->backend.
205
+ def _route(self, descriptor: OperationDescriptor, backend_arg: Optional[str]) -> _Route:
206
+ """Decide which backend a call runs on, without building anything.
155
207
 
156
208
  The backend is the per-call one > workspace default > the ``FLAMAPY_BACKEND``
157
209
  environment variable > the operation's default (for backend-selectable ops), or
158
210
  simply the fixed default. The value ``'auto'`` (opt-in) hands the choice to the
159
- query planner. When the backend resolves to ``None`` (an fm-level op, or a
160
- selectable op with no backend requested) the operation runs on the feature model
161
- directly. Otherwise the name is mapped to a transformation extension (only
162
- ``sat -> pysat`` differs) and cached per extension.
211
+ query planner; ``None`` (an fm-level op, or a selectable op with no backend
212
+ requested) runs the operation on the feature model directly.
163
213
  """
164
- self._last_planner = None
165
214
  defaults_apply = (descriptor.selectable_backend
166
215
  and descriptor.name not in _SELECTABLE_SINCE_2_9)
167
216
  workspace_default = (self.backend or os.environ.get('FLAMAPY_BACKEND')
@@ -171,22 +220,74 @@ class FLAMAFeatureModel:
171
220
  else:
172
221
  resolved = descriptor.default_backend
173
222
  if resolved is None:
174
- return self.fm_model
223
+ return _Route()
175
224
  name = resolved.value if isinstance(resolved, Backend) else str(resolved)
176
225
  if name == Backend.AUTO.value and descriptor.selectable_backend:
177
- return self._model_via_planner(descriptor, self._approximate_allowed(allow_approximate))
178
- if backend_arg or workspace_default:
179
- self._last_planner = 'explicit'
226
+ return _Route(name=name, auto=True)
227
+ return _Route(
228
+ name=name,
229
+ planner='explicit' if backend_arg or workspace_default else None,
230
+ level_gap=self._level_gap(name, descriptor.selectable_backend))
231
+
232
+ def _level_gap(self, name: str, selectable: bool) -> Optional[str]:
233
+ """The warning for a backend whose manifest does not support the model's language
234
+ level (e.g. sat/bdd ignore arithmetic constraints), or None when it does.
235
+
236
+ In 2.9 this only warns, and the result is marked inexact; flamapy 3.0 raises
237
+ NoCompatibleBackendError instead, like backend='auto' does when no installed plugin
238
+ supports the model.
239
+ """
180
240
  extension = _BACKEND_ALIAS.get(name, name)
181
- return self._backend_model(extension)
241
+ try:
242
+ manifest = self.discover_metamodel.plugins.get_plugin_by_extension(extension).manifest
243
+ except PluginNotFound:
244
+ return None # an unknown backend fails later, when its model is built
245
+ model_level = self._language_level()
246
+ if manifest.supports(model_level):
247
+ return None
248
+ advice = ''
249
+ if selectable and self._z3_supports(model_level) and name != Backend.Z3.value:
250
+ advice = " Use backend='auto' or backend='z3'."
251
+ return (f"The '{name}' backend supports ({manifest.supported_level}), but this model "
252
+ f"is ({model_level}): constraints beyond the backend's level are ignored, so "
253
+ f"the result is not exact.{advice}")
254
+
255
+ def _z3_supports(self, model_level: LanguageLevel) -> bool:
256
+ try:
257
+ plugin = self.discover_metamodel.plugins.get_plugin_by_extension(Backend.Z3.value)
258
+ except PluginNotFound:
259
+ return False
260
+ return plugin.manifest.supports(model_level)
261
+
262
+ def _model_for(
263
+ self, descriptor: OperationDescriptor, route: _Route,
264
+ allow_approximate: Optional[bool] = None,
265
+ ) -> tuple[VariabilityModel, _Route]:
266
+ """Build the route's target model, lazily transforming (and caching) fm->backend.
267
+
268
+ A backend name is mapped to a transformation extension (only ``sat -> pysat``
269
+ differs) and cached per extension. Returns the route too: for ``'auto'`` it now
270
+ carries the planner's rationale.
271
+ """
272
+ if route.name is None:
273
+ return self.fm_model, route
274
+ if route.auto:
275
+ return self._model_via_planner(
276
+ descriptor, route, self._approximate_allowed(allow_approximate))
277
+ return self._backend_model(_BACKEND_ALIAS.get(route.name, route.name)), route
182
278
 
183
279
  def _backend_model(self, extension: str) -> VariabilityModel:
184
280
  if extension == self.fm_model.get_extension():
185
281
  return self.fm_model
186
- if extension not in self._backend_models:
187
- self._backend_models[extension] = self.discover_metamodel.use_transformation_m2m(
188
- self.fm_model, extension)
189
- return self._backend_models[extension]
282
+ return self._transformed(self.fm_model, extension)
283
+
284
+ def _transformed(self, source: VariabilityModel, extension: str) -> VariabilityModel:
285
+ """The cached ``extension`` model, built from ``source`` once even under concurrency."""
286
+ with _backend_lock(extension):
287
+ if extension not in self._backend_models:
288
+ self._backend_models[extension] = (
289
+ self.discover_metamodel.use_transformation_m2m(source, extension))
290
+ return self._backend_models[extension]
190
291
 
191
292
  def _language_level(self) -> LanguageLevel:
192
293
  if self._model_language_level is None:
@@ -237,24 +338,29 @@ class FLAMAFeatureModel:
237
338
  raise FlamaException(f"'{operation}' is not a backend-selectable facade operation.")
238
339
  return self._plan_operation(operation, self._approximate_allowed(allow_approximate))
239
340
 
240
- def _model_via_planner(self, descriptor: OperationDescriptor,
241
- allow_approximate: bool = False) -> VariabilityModel:
341
+ def _model_via_planner(self, descriptor: OperationDescriptor, route: _Route,
342
+ allow_approximate: bool = False) -> tuple[VariabilityModel, _Route]:
242
343
  chosen = self._plan_operation(descriptor.name, allow_approximate)
243
- self._last_planner = f'auto: {chosen.rationale}'
344
+ route = dataclasses.replace(route, planner=f'auto: {chosen.rationale}')
244
345
  model = self.fm_model
245
346
  for _, destination in chosen.transformation_chain:
246
- if destination not in self._backend_models:
247
- self._backend_models[destination] = (
248
- self.discover_metamodel.use_transformation_m2m(model, destination))
249
- model = self._backend_models[destination]
250
- return model
347
+ model = self._transformed(model, destination)
348
+ return model, route
251
349
 
252
350
  def _prepare_operation(
253
351
  self, descriptor: OperationDescriptor, backend_arg: Optional[str],
254
352
  call_kwargs: Dict[str, Any], allow_approximate: Optional[bool] = None,
255
- ) -> tuple[Any, VariabilityModel]:
256
- """Resolve the target model and a fully input-wired operation instance."""
257
- model = self._model_for(descriptor, backend_arg, allow_approximate)
353
+ route: Optional[_Route] = None,
354
+ ) -> tuple[Any, VariabilityModel, _Route]:
355
+ """Resolve the target model and a fully input-wired operation instance.
356
+
357
+ ``route`` is passed by a caller that already decided it (and warned) on the user's
358
+ thread; otherwise it is decided, and its warning emitted, here.
359
+ """
360
+ if route is None:
361
+ route = self._route(descriptor, backend_arg)
362
+ _warn_level_gap(route)
363
+ model, route = self._model_for(descriptor, route, allow_approximate)
258
364
  operation = self.discover_metamodel.get_operation(model, descriptor.operation)
259
365
  if descriptor.input_adapter is not None:
260
366
  descriptor.input_adapter(operation, self, call_kwargs)
@@ -267,7 +373,7 @@ class FLAMAFeatureModel:
267
373
  value = self._as_configuration(value)
268
374
  if input_spec.setter is not None:
269
375
  getattr(operation, input_spec.setter)(value)
270
- return operation, model
376
+ return operation, model, route
271
377
 
272
378
  def _run_operation(
273
379
  self, descriptor: OperationDescriptor, call_kwargs: Dict[str, Any]
@@ -282,21 +388,19 @@ class FLAMAFeatureModel:
282
388
  try:
283
389
  backend_arg = call_kwargs.pop('backend', None)
284
390
  allow_approximate = call_kwargs.pop('allow_approximate', None)
285
- operation, model = self._prepare_operation(
391
+ operation, model, route = self._prepare_operation(
286
392
  descriptor, backend_arg, call_kwargs, allow_approximate)
287
393
  # The hash is always the source feature model's (memoized there), whichever
288
394
  # backend model the operation actually runs on.
289
- envelope = run_and_wrap(
290
- operation, model,
291
- operation_name=descriptor.name, plugin=self._plugin_name_for(model),
292
- model_hash=self.fm_model.canonical_hash())
395
+ with _backend_lock(model.get_extension()):
396
+ envelope = run_and_wrap(
397
+ operation, model,
398
+ operation_name=descriptor.name, plugin=self._plugin_name_for(model),
399
+ model_hash=self.fm_model.canonical_hash())
293
400
  if descriptor.result_adapter is not None:
294
401
  envelope = dataclasses.replace(
295
402
  envelope, value=descriptor.result_adapter(envelope.value))
296
- if self._last_planner is not None:
297
- envelope = dataclasses.replace(envelope, planner=self._last_planner)
298
- if getattr(model, '_flamapy_cache_hit', False):
299
- envelope = dataclasses.replace(envelope, cache_hit=True)
403
+ envelope = _stamp(envelope, route, model)
300
404
  self.last_result = envelope
301
405
  return envelope.value
302
406
  except FlamaException as exception:
@@ -324,10 +428,12 @@ class FLAMAFeatureModel:
324
428
  expiry (after requesting cooperative cancellation) — unlike the 2.x synchronous
325
429
  methods, errors are **raised**, not swallowed into ``None``.
326
430
 
327
- Everything after resolving the operation name runs inside the job — including the
431
+ Everything after choosing the backend runs inside the job — including the
328
432
  fm->backend transformation (e.g. BDD compilation, often the expensive step on large
329
433
  models) — so the timeout covers it and preparation errors (unknown backend,
330
- invalid inputs) are raised by ``job.result()``.
434
+ invalid inputs) are raised by ``job.result()``. The envelope (``job.envelope()``)
435
+ carries the same provenance as the synchronous ``last_result``; the warning about a
436
+ backend that ignores part of the model is emitted here, by the call itself.
331
437
  """
332
438
  method = getattr(type(self), operation, None)
333
439
  descriptor = getattr(method, '_facade_descriptor', None)
@@ -336,10 +442,14 @@ class FLAMAFeatureModel:
336
442
  call_kwargs = dict(kwargs)
337
443
  backend_arg = call_kwargs.pop('backend', None)
338
444
  allow_approximate = call_kwargs.pop('allow_approximate', None)
445
+ # Decided (and warned about) on the caller's thread: the route belongs to this job
446
+ # alone, and a warning raised from the worker would point into the thread pool.
447
+ route = self._route(descriptor, backend_arg)
448
+ _warn_level_gap(route)
339
449
 
340
450
  def task(interrupt_event: threading.Event) -> OperationResult[Any]:
341
- prepared, model = self._prepare_operation(
342
- descriptor, backend_arg, call_kwargs, allow_approximate)
451
+ prepared, model, job_route = self._prepare_operation(
452
+ descriptor, backend_arg, call_kwargs, allow_approximate, route)
343
453
  if interrupt_event.is_set():
344
454
  # The deadline expired (or cancel() was called) during preparation: the
345
455
  # caller has already given up, so don't start the operation at all.
@@ -347,10 +457,15 @@ class FLAMAFeatureModel:
347
457
  f"'{descriptor.name}' was cancelled before execution started.")
348
458
  if isinstance(prepared, Interruptible):
349
459
  prepared.set_interrupt_event(interrupt_event)
350
- return run_and_wrap(
351
- prepared, model,
352
- operation_name=descriptor.name, plugin=self._plugin_name_for(model),
353
- model_hash=self.fm_model.canonical_hash())
460
+ with _backend_lock(model.get_extension()):
461
+ if interrupt_event.is_set(): # gave up while waiting for the backend
462
+ raise OperationTimeout(
463
+ f"'{descriptor.name}' was cancelled before execution started.")
464
+ envelope = run_and_wrap(
465
+ prepared, model,
466
+ operation_name=descriptor.name, plugin=self._plugin_name_for(model),
467
+ model_hash=self.fm_model.canonical_hash())
468
+ return _stamp(envelope, job_route, model)
354
469
 
355
470
  return default_engine().submit_call(task, result_adapter=descriptor.result_adapter)
356
471
 
@@ -363,10 +478,11 @@ class FLAMAFeatureModel:
363
478
  :meth:`run_async` (raises, never ``None``).
364
479
  """
365
480
  descriptor = type(self).configurations._facade_descriptor # type: ignore[attr-defined]
366
- operation, model = self._prepare_operation(descriptor, backend or 'sat', {})
481
+ operation, model, _ = self._prepare_operation(descriptor, backend or 'sat', {})
367
482
  if isinstance(operation, StreamingOperation):
368
483
  return operation.iter_execute(model)
369
- operation.execute(model)
484
+ with _backend_lock(model.get_extension()):
485
+ operation.execute(model)
370
486
  return iter(operation.get_result())
371
487
 
372
488
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flamapy
3
- Version: 2.9.0.dev0
3
+ Version: 2.9.0.dev2
4
4
  Summary: Flamapy feature model is a distribution of the flama framework containing all plugins required to analyze feature models. It also offers a richer API and a complete command line interface and documentation.
5
5
  Author-email: Flamapy <flamapy@us.es>
6
6
  License-Expression: GPL-3.0-or-later
@@ -8,21 +8,21 @@ Project-URL: Homepage, https://github.com/flamapy/flamapy-feature-model
8
8
  Requires-Python: >=3.11
9
9
  Description-Content-Type: text/markdown
10
10
  License-File: LICENSE
11
- Requires-Dist: flamapy-fw~=2.9.0.dev0
12
- Requires-Dist: flamapy-fm~=2.9.0.dev0
13
- Requires-Dist: flamapy-sat~=2.9.0.dev0
14
- Requires-Dist: flamapy-bdd~=2.9.0.dev0
15
- Requires-Dist: flamapy-z3~=2.9.0.dev0
11
+ Requires-Dist: flamapy-fw~=2.9.0.dev2
12
+ Requires-Dist: flamapy-fm~=2.9.0.dev2
13
+ Requires-Dist: flamapy-sat~=2.9.0.dev2
14
+ Requires-Dist: flamapy-bdd~=2.9.0.dev2
15
+ Requires-Dist: flamapy-z3~=2.9.0.dev2
16
16
  Provides-Extra: sharpsat
17
- Requires-Dist: flamapy-sharpsat~=2.9.0.dev0; extra == "sharpsat"
17
+ Requires-Dist: flamapy-sharpsat~=2.9.0.dev2; extra == "sharpsat"
18
18
  Provides-Extra: dnnf
19
- Requires-Dist: flamapy-dnnf~=2.9.0.dev0; extra == "dnnf"
19
+ Requires-Dist: flamapy-dnnf~=2.9.0.dev2; extra == "dnnf"
20
20
  Provides-Extra: sdd
21
- Requires-Dist: flamapy-sdd~=2.9.0.dev0; extra == "sdd"
21
+ Requires-Dist: flamapy-sdd~=2.9.0.dev2; extra == "sdd"
22
22
  Provides-Extra: all-solvers
23
- Requires-Dist: flamapy-sharpsat~=2.9.0.dev0; extra == "all-solvers"
24
- Requires-Dist: flamapy-dnnf~=2.9.0.dev0; extra == "all-solvers"
25
- Requires-Dist: flamapy-sdd~=2.9.0.dev0; extra == "all-solvers"
23
+ Requires-Dist: flamapy-sharpsat~=2.9.0.dev2; extra == "all-solvers"
24
+ Requires-Dist: flamapy-dnnf~=2.9.0.dev2; extra == "all-solvers"
25
+ Requires-Dist: flamapy-sdd~=2.9.0.dev2; extra == "all-solvers"
26
26
  Provides-Extra: dev
27
27
  Requires-Dist: pytest; extra == "dev"
28
28
  Requires-Dist: pytest-mock; extra == "dev"
@@ -1,11 +1,11 @@
1
1
  flamapy/commands/__init__.py,sha256=DdRS2Xyt37H_k2YaaFWUcE6xfJALzllraerIup1l_OU,14646
2
2
  flamapy/interfaces/python/__init__.py,sha256=NVQH1l6O9ElD8YvUVBXJN0Y_ETmu3AbyQBZJJ9qiuoU,86
3
3
  flamapy/interfaces/python/_stub.py,sha256=7JMmnmxHFbpC7XHVqozZUooLwPbHS4p1-B8QXH5wQf8,3898
4
- flamapy/interfaces/python/flamapy_feature_model.py,sha256=Kfq-zizQViAx_KdfFZTo_SNkFakFo3FmNt32Z5Jaats,24180
4
+ flamapy/interfaces/python/flamapy_feature_model.py,sha256=m_aPkDi_B11789mHpJPLRws1vKB3PLPAfAtiQGICcdY,29902
5
5
  flamapy/interfaces/python/flamapy_feature_model.pyi,sha256=u-GtNc1wRslPO1I2sIIsNuOxrdT-dR0GZpqzyskHT34,6189
6
- flamapy-2.9.0.dev0.dist-info/licenses/LICENSE,sha256=46mU2C5kSwOnkqkw9XQAJlhBL2JAf1_uCD8lVcXyMRg,7652
7
- flamapy-2.9.0.dev0.dist-info/METADATA,sha256=lRl3wpwDCFvW98uPFWwZBzAYLmzQ2TCrh07g9yR7hso,1731
8
- flamapy-2.9.0.dev0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
- flamapy-2.9.0.dev0.dist-info/entry_points.txt,sha256=CS_W4K9LW9xOf-7ymWD58KklNHBnhMHm0RXAZ9JLgVo,57
10
- flamapy-2.9.0.dev0.dist-info/top_level.txt,sha256=2YBI9dg4GVk28AJuyNu6dldi5Riwt5SP0zpNe2lSU5M,8
11
- flamapy-2.9.0.dev0.dist-info/RECORD,,
6
+ flamapy-2.9.0.dev2.dist-info/licenses/LICENSE,sha256=46mU2C5kSwOnkqkw9XQAJlhBL2JAf1_uCD8lVcXyMRg,7652
7
+ flamapy-2.9.0.dev2.dist-info/METADATA,sha256=LP-2mlXxcwWaCu1wNCIN7h20Gq9fonomlp7eYBjYwfI,1731
8
+ flamapy-2.9.0.dev2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ flamapy-2.9.0.dev2.dist-info/entry_points.txt,sha256=CS_W4K9LW9xOf-7ymWD58KklNHBnhMHm0RXAZ9JLgVo,57
10
+ flamapy-2.9.0.dev2.dist-info/top_level.txt,sha256=2YBI9dg4GVk28AJuyNu6dldi5Riwt5SP0zpNe2lSU5M,8
11
+ flamapy-2.9.0.dev2.dist-info/RECORD,,