frontrun 0.4.0__tar.gz → 0.4.1__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 (54) hide show
  1. {frontrun-0.4.0 → frontrun-0.4.1}/Cargo.lock +2 -2
  2. {frontrun-0.4.0 → frontrun-0.4.1}/Cargo.toml +1 -1
  3. {frontrun-0.4.0 → frontrun-0.4.1}/PKG-INFO +1 -1
  4. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/__init__.py +4 -2
  5. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/_deadlock.py +3 -1
  6. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/_redis_parsing.py +8 -4
  7. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/_sql_anomaly.py +2 -2
  8. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/_sql_cursor.py +1 -1
  9. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/_sql_cursor_async.py +9 -4
  10. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/_sql_params.py +2 -0
  11. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/_trace_format.py +32 -33
  12. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/async_dpor.py +2 -1
  13. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/cli.py +11 -11
  14. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/common.py +2 -2
  15. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/contrib/sqlalchemy/_sync.py +13 -1
  16. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/dpor.py +4 -1
  17. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/trace_markers.py +2 -2
  18. {frontrun-0.4.0 → frontrun-0.4.1}/LICENSE +0 -0
  19. {frontrun-0.4.0 → frontrun-0.4.1}/README.md +0 -0
  20. {frontrun-0.4.0 → frontrun-0.4.1}/crates/dpor/Cargo.toml +0 -0
  21. {frontrun-0.4.0 → frontrun-0.4.1}/crates/dpor/src/access.rs +0 -0
  22. {frontrun-0.4.0 → frontrun-0.4.1}/crates/dpor/src/engine.rs +0 -0
  23. {frontrun-0.4.0 → frontrun-0.4.1}/crates/dpor/src/lib.rs +0 -0
  24. {frontrun-0.4.0 → frontrun-0.4.1}/crates/dpor/src/object.rs +0 -0
  25. {frontrun-0.4.0 → frontrun-0.4.1}/crates/dpor/src/path.rs +0 -0
  26. {frontrun-0.4.0 → frontrun-0.4.1}/crates/dpor/src/thread.rs +0 -0
  27. {frontrun-0.4.0 → frontrun-0.4.1}/crates/dpor/src/vv.rs +0 -0
  28. {frontrun-0.4.0 → frontrun-0.4.1}/crates/dpor/src/wakeup_tree.rs +0 -0
  29. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/Makefile +0 -0
  30. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/_cooperative.py +0 -0
  31. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/_io_detection.py +0 -0
  32. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/_preload_io.py +0 -0
  33. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/_real_threading.py +0 -0
  34. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/_redis_client.py +0 -0
  35. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/_redis_client_async.py +0 -0
  36. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/_report.py +0 -0
  37. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/_report_template.html +0 -0
  38. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/_schema.py +0 -0
  39. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/_sql_insert_tracker.py +0 -0
  40. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/_sql_parsing.py +0 -0
  41. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/_sql_predicates.py +0 -0
  42. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/_tracing.py +0 -0
  43. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/async_scheduler.py +0 -0
  44. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/async_shuffler.py +0 -0
  45. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/async_trace_markers.py +0 -0
  46. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/bytecode.py +0 -0
  47. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/contrib/__init__.py +0 -0
  48. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/contrib/django/__init__.py +0 -0
  49. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/contrib/django/_async.py +0 -0
  50. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/contrib/django/_sync.py +0 -0
  51. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/contrib/sqlalchemy/__init__.py +0 -0
  52. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/contrib/sqlalchemy/_async.py +0 -0
  53. {frontrun-0.4.0 → frontrun-0.4.1}/frontrun/pytest_plugin.py +0 -0
  54. {frontrun-0.4.0 → frontrun-0.4.1}/pyproject.toml +0 -0
@@ -10,14 +10,14 @@ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
10
10
 
11
11
  [[package]]
12
12
  name = "frontrun-dpor"
13
- version = "0.4.0"
13
+ version = "0.4.1"
14
14
  dependencies = [
15
15
  "pyo3",
16
16
  ]
17
17
 
18
18
  [[package]]
19
19
  name = "frontrun-io"
20
- version = "0.4.0"
20
+ version = "0.4.1"
21
21
  dependencies = [
22
22
  "libc",
23
23
  "once_cell",
@@ -3,4 +3,4 @@ members = ["crates/dpor"]
3
3
  resolver = "2"
4
4
 
5
5
  [workspace.package]
6
- version = "0.4.0"
6
+ version = "0.4.1"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: frontrun
3
- Version: 0.4.0
3
+ Version: 0.4.1
4
4
  Classifier: Development Status :: 3 - Alpha
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: Programming Language :: Python :: 3
@@ -1,15 +1,17 @@
1
1
  """
2
2
  Frontrun: Deterministic concurrency testing for Python.
3
3
 
4
- Trace markers::
4
+ Trace markers (sync)::
5
5
 
6
6
  from frontrun.common import Schedule, Step
7
7
  from frontrun import TraceExecutor
8
8
 
9
- Async trace markers::
9
+ Async trace markers (pass a dict of task names to coroutines)::
10
10
 
11
11
  from frontrun import TraceExecutor
12
12
  from frontrun.common import Schedule, Step
13
+ executor = TraceExecutor(schedule)
14
+ executor.run({"task1": coro_factory1, "task2": coro_factory2})
13
15
 
14
16
  DPOR (Dynamic Partial Order Reduction) systematic exploration::
15
17
 
@@ -180,7 +180,7 @@ class WaitForGraph:
180
180
 
181
181
  for neighbor in self._edges.get(start, ()):
182
182
  if dfs(neighbor):
183
- return [start, *path]
183
+ return [start, *path, start]
184
184
  return None
185
185
 
186
186
 
@@ -202,6 +202,8 @@ def format_cycle(
202
202
  parts.append(f"thread {ident}")
203
203
  elif kind == "row_lock" and lock_names and ident in lock_names:
204
204
  parts.append(f"row_lock {lock_names[ident]}")
205
+ elif kind == "row_lock":
206
+ parts.append(f"row_lock 0x{ident:x}")
205
207
  elif kind == "lock" and lock_id_map and ident in lock_id_map:
206
208
  parts.append(f"lock {lock_id_map[ident]}")
207
209
  else:
@@ -261,22 +261,24 @@ def parse_redis_access(cmd_name: str, cmd_args: tuple[object, ...]) -> RedisAcce
261
261
  )
262
262
 
263
263
  # LMPOP / ZMPOP — numkeys key [key ...] LEFT|RIGHT [COUNT count]
264
+ # These pop elements: read the value + remove it (write), like BLPOP/BRPOP.
264
265
  if upper in ("LMPOP", "ZMPOP") and len(cmd_args) >= 2:
265
266
  try:
266
267
  numkeys = int(str(cmd_args[0]))
267
268
  except (ValueError, TypeError):
268
269
  numkeys = 1
269
270
  keys = [str(cmd_args[1 + i]) for i in range(min(numkeys, len(cmd_args) - 1))]
270
- return RedisAccessResult(read_keys=[], write_keys=keys, is_transaction_control=False)
271
+ return RedisAccessResult(read_keys=keys, write_keys=keys, is_transaction_control=False)
271
272
 
272
273
  # BZMPOP — timeout numkeys key [key ...] MIN|MAX [COUNT count]
274
+ # Blocking pop: read the value + remove it (write), like BLPOP/BRPOP.
273
275
  if upper == "BZMPOP" and len(cmd_args) >= 3:
274
276
  try:
275
277
  numkeys = int(str(cmd_args[1]))
276
278
  except (ValueError, TypeError):
277
279
  numkeys = 1
278
280
  keys = [str(cmd_args[2 + i]) for i in range(min(numkeys, len(cmd_args) - 2))]
279
- return RedisAccessResult(read_keys=[], write_keys=keys, is_transaction_control=False)
281
+ return RedisAccessResult(read_keys=keys, write_keys=keys, is_transaction_control=False)
280
282
 
281
283
  # Blocking pop commands — first arg(s) are keys, last is timeout.
282
284
  # These are read+write: they return the popped value (read) and remove
@@ -399,8 +401,10 @@ def parse_redis_access(cmd_name: str, cmd_args: tuple[object, ...]) -> RedisAcce
399
401
  )
400
402
 
401
403
  # OBJECT HELP, OBJECT ENCODING, etc. — first real key is second arg.
402
- if upper == "OBJECT" and len(cmd_args) >= 2:
403
- return RedisAccessResult(read_keys=[str(cmd_args[1])], write_keys=[], is_transaction_control=False)
404
+ if upper == "OBJECT":
405
+ if len(cmd_args) >= 2:
406
+ return RedisAccessResult(read_keys=[str(cmd_args[1])], write_keys=[], is_transaction_control=False)
407
+ return RedisAccessResult(read_keys=[], write_keys=[], is_transaction_control=False)
404
408
 
405
409
  # WAIT, WAITAOF — no keys.
406
410
  if upper in ("WAIT", "WAITAOF"):
@@ -310,8 +310,8 @@ def classify_sql_anomaly(events: list[TraceEvent]) -> SqlAnomaly | None:
310
310
  threads=cycle_threads,
311
311
  )
312
312
 
313
- # Write skew: RW-only cycle across different tables
314
- if cycle_etypes == {"RW"} and len(cycle_tables) >= 2:
313
+ # Write skew: RW-only cycle (may span one or more tables)
314
+ if cycle_etypes == {"RW"}:
315
315
  tbls = ", ".join(f"'{t}'" for t in sorted(cycle_tables))
316
316
  return SqlAnomaly(
317
317
  kind="write_skew",
@@ -625,7 +625,7 @@ def _report_sql_access(
625
625
  pred_rows = rows
626
626
  has_row_level = True
627
627
 
628
- lock_update = access.lock_intent is LockIntent.UPDATE
628
+ lock_update = access.lock_intent in (LockIntent.UPDATE, LockIntent.UPDATE_SKIP_LOCKED)
629
629
 
630
630
  # Track which tables already reported their bridge resource in this op.
631
631
  reported_bridges: set[str] = set()
@@ -325,10 +325,15 @@ def _patch_asyncpg() -> None:
325
325
 
326
326
  async def _patched_executemany(self: Any, command: Any, args: Any, **kwargs: Any) -> Any:
327
327
  reported = _report_sql_access(command, None, is_executemany=True, paramstyle="dollar")
328
- if reported:
329
- with _suppress_endpoint_io():
330
- return await orig_em(self, command, args, **kwargs)
331
- return await orig_em(self, command, args, **kwargs)
328
+ _acquire_pending_row_locks()
329
+ try:
330
+ if reported:
331
+ with _suppress_endpoint_io():
332
+ return await orig_em(self, command, args, **kwargs)
333
+ return await orig_em(self, command, args, **kwargs)
334
+ except Exception:
335
+ _release_dpor_row_locks()
336
+ raise
332
337
 
333
338
  _patched_executemany.__name__ = "executemany"
334
339
  _patched_executemany.__qualname__ = orig_em.__qualname__
@@ -106,6 +106,8 @@ def _resolve_numeric(sql: str, parameters: Any, pattern: re.Pattern[str]) -> str
106
106
 
107
107
  def replacer(m: re.Match[str]) -> str:
108
108
  idx = int(m.group(1)) - 1
109
+ if idx < 0:
110
+ raise IndexError("placeholder index must be >= 1")
109
111
  return _python_to_sql_literal(params[idx])
110
112
 
111
113
  return pattern.sub(replacer, sql)
@@ -142,21 +142,18 @@ class TraceRecorder:
142
142
  with self._lock:
143
143
  step = self._step
144
144
  self._step += 1
145
-
146
- ev = TraceEvent(
147
- step_index=step,
148
- thread_id=thread_id,
149
- filename=code.co_filename,
150
- lineno=frame.f_lineno,
151
- function_name=code.co_name,
152
- opcode=opcode or "",
153
- access_type=access_type,
154
- attr_name=attr_name,
155
- obj_type_name=obj_type_name,
156
- call_chain=call_chain,
157
- )
158
- # Append under the recorder lock for ordering consistency
159
- with self._lock:
145
+ ev = TraceEvent(
146
+ step_index=step,
147
+ thread_id=thread_id,
148
+ filename=code.co_filename,
149
+ lineno=frame.f_lineno,
150
+ function_name=code.co_name,
151
+ opcode=opcode or "",
152
+ access_type=access_type,
153
+ attr_name=attr_name,
154
+ obj_type_name=obj_type_name,
155
+ call_chain=call_chain,
156
+ )
160
157
  self.events.append(ev)
161
158
 
162
159
  def record_io(
@@ -174,20 +171,19 @@ class TraceRecorder:
174
171
  with self._lock:
175
172
  step = self._step
176
173
  self._step += 1
177
- ev = TraceEvent(
178
- step_index=step,
179
- thread_id=thread_id,
180
- filename="<C extension>",
181
- lineno=0,
182
- function_name="",
183
- opcode="IO",
184
- access_type=kind,
185
- attr_name=resource_id,
186
- obj_type_name="IO",
187
- call_chain=call_chain,
188
- detail=detail,
189
- )
190
- with self._lock:
174
+ ev = TraceEvent(
175
+ step_index=step,
176
+ thread_id=thread_id,
177
+ filename="<C extension>",
178
+ lineno=0,
179
+ function_name="",
180
+ opcode="IO",
181
+ access_type=kind,
182
+ attr_name=resource_id,
183
+ obj_type_name="IO",
184
+ call_chain=call_chain,
185
+ detail=detail,
186
+ )
191
187
  self.events.append(ev)
192
188
 
193
189
  def record_from_opcode(
@@ -517,11 +513,14 @@ def _collapse_runs(lines: list[SourceLineEvent], *, max_lines: int) -> list[Sour
517
513
  result.append(CollapsedRun(count=len(run) - 2, thread_id=tid))
518
514
  result.append(run[-1])
519
515
 
520
- # Final cap: if still too long, take first half + last half
516
+ # Final cap: if still too long, take first half + last half.
517
+ # Account for the CollapsedRun placeholder taking one slot.
521
518
  if len(result) > max_lines:
522
- half = max_lines // 2
523
- omitted = len(result) - max_lines
524
- result = result[:half] + [CollapsedRun(count=omitted, thread_id=-1)] + result[-half:]
519
+ first_half = max_lines // 2
520
+ second_half = max_lines - first_half - 1 # -1 for the CollapsedRun
521
+ omitted = len(result) - first_half - second_half
522
+ tail = result[-second_half:] if second_half > 0 else []
523
+ result = result[:first_half] + [CollapsedRun(count=omitted, thread_id=-1)] + tail
525
524
 
526
525
  return result
527
526
 
@@ -1333,7 +1333,8 @@ async def explore_async_dpor(
1333
1333
  if not engine.next_execution():
1334
1334
  break
1335
1335
  finally:
1336
- _set_active_trace_filter(None)
1336
+ if trace_packages is not None:
1337
+ _set_active_trace_filter(None)
1337
1338
  set_lock_timeout(prev_lock_timeout)
1338
1339
  _unpatch_asyncio_lock()
1339
1340
  if detect_sql and _sql_async_available:
@@ -139,17 +139,17 @@ def main(argv: list[str] | None = None) -> int:
139
139
 
140
140
  if not argv:
141
141
  print("Usage: frontrun <command> [args...]", file=sys.stderr)
142
- print()
143
- print("Run a command with frontrun I/O interception enabled.")
144
- print()
145
- print("Examples:")
146
- print(" frontrun pytest -vv tests/")
147
- print(" frontrun python -c \"import requests; requests.get('http://example.com')\"")
148
- print(" frontrun uvicorn myapp:app")
149
- print()
150
- print("Environment variables:")
151
- print(f" {FRONTRUN_ACTIVE_ENV}=1 Set automatically; signals frontrun is active")
152
- print(f" {FRONTRUN_PRELOAD_LIB_ENV} Override path to libfrontrun_io.so/.dylib")
142
+ print(file=sys.stderr)
143
+ print("Run a command with frontrun I/O interception enabled.", file=sys.stderr)
144
+ print(file=sys.stderr)
145
+ print("Examples:", file=sys.stderr)
146
+ print(" frontrun pytest -vv tests/", file=sys.stderr)
147
+ print(" frontrun python -c \"import requests; requests.get('http://example.com')\"", file=sys.stderr)
148
+ print(" frontrun uvicorn myapp:app", file=sys.stderr)
149
+ print(file=sys.stderr)
150
+ print("Environment variables:", file=sys.stderr)
151
+ print(f" {FRONTRUN_ACTIVE_ENV}=1 Set automatically; signals frontrun is active", file=sys.stderr)
152
+ print(f" {FRONTRUN_PRELOAD_LIB_ENV} Override path to libfrontrun_io.so/.dylib", file=sys.stderr)
153
153
  return 1
154
154
 
155
155
  preload_lib = _find_preload_library()
@@ -93,7 +93,7 @@ class InterleavingResult:
93
93
  """
94
94
 
95
95
  property_holds: bool
96
- counterexample: list[int] | None = None
96
+ counterexample: list[int] | Schedule | None = None
97
97
  num_explored: int = 0
98
98
  unique_interleavings: int = 0
99
99
  failures: list[tuple[int, list[int]]] = field(default_factory=list)
@@ -104,7 +104,7 @@ class InterleavingResult:
104
104
 
105
105
  def __repr__(self) -> str:
106
106
  ce = self.counterexample
107
- if ce is not None and len(ce) > 10:
107
+ if ce is not None and isinstance(ce, list) and len(ce) > 10:
108
108
  ce_repr = f"[{', '.join(map(str, ce[:5]))}, ...({len(ce)} steps)]"
109
109
  else:
110
110
  ce_repr = repr(ce)
@@ -87,10 +87,22 @@ def sqlalchemy_dpor(
87
87
  try:
88
88
  conn_ctx = engine.connect()
89
89
  conn = conn_ctx.__enter__()
90
+ except BaseException:
91
+ unsuppress_sync_reporting()
92
+ raise
93
+ # conn_ctx is now entered — guarantee __exit__ via outer finally.
94
+ try:
90
95
  if lock_timeout is not None:
91
96
  conn.exec_driver_sql(f"SET lock_timeout = '{int(lock_timeout)}ms'")
92
- finally:
97
+ except BaseException:
93
98
  unsuppress_sync_reporting()
99
+ suppress_sync_reporting()
100
+ try:
101
+ conn_ctx.__exit__(None, None, None)
102
+ finally:
103
+ unsuppress_sync_reporting()
104
+ raise
105
+ unsuppress_sync_reporting()
94
106
  # Wrap SA Connection methods that trigger internal locks.
95
107
  # conn.execute() acquires statement compilation locks.
96
108
  # conn.commit()/rollback() acquires transaction state locks.
@@ -1338,6 +1338,8 @@ class _IOAnchoredReplayScheduler(DporScheduler):
1338
1338
  self._active_io_thread = None
1339
1339
  self._current_thread = self._next_thread_after_io
1340
1340
  self._next_thread_after_io = None
1341
+ if self._current_thread is None and len(self._threads_done) >= self.num_threads:
1342
+ self._finished = True
1341
1343
  self._condition.notify_all()
1342
1344
  finally:
1343
1345
  _scheduler_tls._in_dpor_machinery = False
@@ -3831,7 +3833,8 @@ def explore_dpor(
3831
3833
  if not engine.next_execution():
3832
3834
  break
3833
3835
  finally:
3834
- _set_active_trace_filter(None)
3836
+ if trace_packages is not None:
3837
+ _set_active_trace_filter(None)
3835
3838
  set_lock_timeout(prev_lock_timeout)
3836
3839
  if preload_dispatcher is not None:
3837
3840
  preload_dispatcher.stop()
@@ -699,7 +699,7 @@ def explore_marker_interleavings(
699
699
  if stop_on_first:
700
700
  return InterleavingResult(
701
701
  property_holds=False,
702
- counterexample=schedule, # type: ignore[arg-type]
702
+ counterexample=schedule,
703
703
  num_explored=num_explored,
704
704
  unique_interleavings=num_explored,
705
705
  )
@@ -707,7 +707,7 @@ def explore_marker_interleavings(
707
707
  if failures:
708
708
  return InterleavingResult(
709
709
  property_holds=False,
710
- counterexample=failures[0][1], # type: ignore[arg-type]
710
+ counterexample=failures[0][1],
711
711
  num_explored=num_explored,
712
712
  unique_interleavings=num_explored,
713
713
  failures=failures, # type: ignore[arg-type]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes