eGkritsis opened a new issue, #55795:
URL: https://github.com/apache/arrow/issues/55795

   ### Describe the bug, including details regarding any error messages, 
version, and platform.
   
   ### Description
   Constructing a pyarrow.Array with a deeply nested list type 
(list<list<list<...<int64>...>>>) consumes memory wildly disproportionate to 
the amount of actual data involved, including for a completely empty array 
(zero elements). 
   
   Building the type object alone is cheap at every depth tested; the cost 
appears specifically when an array is associated with that type.
   
   Measured on two independent machines, memory grows SUPERLINEARLY with 
nesting depth (exponent ~1.2-1.5 across runs - see data below), not the 
flat/near-constant cost one would expect for an array holding zero rows.
   
   ### PoC
   
   ```python
   
   #!/usr/bin/env python3
   """
   How to run
       python3 -m venv /tmp/pyarrow-poc-venv
       /tmp/pyarrow-poc-venv/bin/pip install pyarrow
       /tmp/pyarrow-poc-venv/bin/python 
poc_pyarrow_nested_array_memory_amplification.py
   """
   
   import platform
   import resource
   import subprocess
   import sys
   
   
   TYPE_ONLY_CODE = r"""
   import sys
   import pyarrow as pa
   depth = int(sys.argv[1])
   t = pa.int64()
   for _ in range(depth):
       t = pa.list_(t)
   print("OK")
   """
   
   ARRAY_CODE = r"""
   import sys, resource
   import pyarrow as pa
   depth = int(sys.argv[1])
   t = pa.int64()
   for _ in range(depth):
       t = pa.list_(t)
   arr = pa.array([], type=t)
   mem_mb = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024
   print(f"OK peak_mem_mb={mem_mb:.1f}")
   """
   
   
   def probe(code: str, depth: int, timeout: float = 30.0):
       return subprocess.run(
           [sys.executable, "-c", code, str(depth)],
           capture_output=True,
           text=True,
           timeout=timeout,
       )
   
   
   def main():
       print("=== pyarrow nested-array memory amplification PoC ===")
       print(f"Python:  {platform.python_version()} ({sys.executable})")
       try:
           import pyarrow
           print(f"pyarrow: {pyarrow.__version__}")
       except Exception as e:
           print(f"Could not import pyarrow: {e}")
       print(f"Platform: {platform.platform()}")
   
       print("\n--- Step 1: type construction alone (expected: cheap at every 
depth) ---")
       for depth in [1000, 5000, 20000]:
           try:
               result = probe(TYPE_ONLY_CODE, depth)
               ok = result.returncode == 0 and "OK" in result.stdout
               print(f"  depth={depth:>7}  ->  {'OK (cheap)' if ok else 
'unexpected failure'}")
           except subprocess.TimeoutExpired:
               print(f"  depth={depth:>7}  ->  TIMEOUT")
   
       print("\n--- Step 2: empty array construction (expected: memory grows 
superlinearly) ---")
       depths = [500, 1000, 1500, 2000, 2500, 3000, 5000, 10000]
       results = []
       for depth in depths:
           try:
               result = probe(ARRAY_CODE, depth)
               if result.returncode == 0 and "peak_mem_mb" in result.stdout:
                   mem = float(result.stdout.strip().split("peak_mem_mb=")[1])
                   results.append((depth, mem))
                   print(f"  depth={depth:>6}  ->  peak_mem={mem:>8.1f} MB")
               else:
                   print(f"  depth={depth:>6}  ->  unexpected: 
rc={result.returncode}, "
                         f"{result.stderr.strip()[-150:] if result.stderr else 
result.stdout.strip()[-150:]}")
           except subprocess.TimeoutExpired:
               print(f"  depth={depth:>6}  ->  TIMEOUT")
           except MemoryError:
               print(f"  depth={depth:>6}  ->  MemoryError")
   
       if len(results) >= 2:
           import math
           xs = [math.log(d) for d, _ in results]
           ys = [math.log(m) for _, m in results]
           n = len(xs)
           mx, my = sum(xs) / n, sum(ys) / n
           num = sum((x - mx) * (y - my) for x, y in zip(xs, ys))
           den = sum((x - mx) ** 2 for x in xs)
           slope = num / den
           print(f"\nMemory-vs-depth scaling exponent: ~{slope:.2f} "
                 f"(1.0 = linear, 2.0 = quadratic)")
           first_depth, first_mem = results[0]
           last_depth, last_mem = results[-1]
           print(f"For comparison: depth increased 
{last_depth/first_depth:.1f}x, "
                 f"memory increased {last_mem/first_mem:.1f}x")
   
   if __name__ == "__main__":
       main()
   
   ```
   
   Expected Outcome:
   
   ```text
   
   === pyarrow nested-array memory amplification PoC ===
   Python:  3.12.3 (/tmp/pyarrow-poc-venv/bin/python)
   pyarrow: 25.0.1
   Platform: Linux-7.0.0-31-generic-x86_64-with-glibc2.39
   
   --- Step 1: type construction alone (expected: cheap at every depth) ---
     depth=   1000  ->  OK (cheap)
     depth=   5000  ->  OK (cheap)
     depth=  20000  ->  OK (cheap)
   
   --- Step 2: empty array construction (expected: memory grows superlinearly) 
---
     depth=   500  ->  peak_mem=    76.4 MB
     depth=  1000  ->  peak_mem=   168.8 MB
     depth=  1500  ->  peak_mem=   322.4 MB
     depth=  2000  ->  peak_mem=   536.8 MB
     depth=  2500  ->  peak_mem=   812.4 MB
     depth=  3000  ->  peak_mem=  1149.1 MB
     depth=  5000  ->  peak_mem=  3105.8 MB
     depth= 10000  ->  peak_mem= 12270.0 MB
   
   Memory-vs-depth scaling exponent: ~1.73 (1.0 = linear, 2.0 = quadratic)
   For comparison: depth increased 20.0x, memory increased 160.6x
   
   ```
   
   Also reproduced on Linux 6.18.44.
   
   
   
   ### Versions
   
   Ecosystem: pip
   
   package: pyarrow
   
   project: apache arrow
   
   pyarrow >= 25.0.1
   Python: 3.12.3
   Platform (A): Linux-6.18.44-fc-v24-x86_64-with-glibc2.39
   Platform (B): Linux-7.0.0-31-generic-x86_64-with-glibc2.39
   
   
   
   ### CWE  
   
   CWE-400 (Uncontrolled Resource Consumption)
   
   CWE-770 (Allocation of Resources Without Limits or Throttling)
   
   ### Component(s)
   
   Python


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to