8000 [codex] optimize hot AST passes by alvinwan · Pull Request #12 · alvinwan/pymini · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

`pymini` is an AST-based Python minifier for scripts and packages. It preserves
package layout by default, can emit a single-file bundle when asked, and can
shrink Python code by roughly `15%` to `70%` on the checked-in fixtures and
validated package benchmarks.
shrink Python code by roughly `50%` to `74%` on the checked-in fixtures and
validated package benchmarks when aggressive renaming is enabled.

- [Getting Started](#getting-started)
- [Installation](#installation)
Expand Down Expand Up @@ -39,14 +39,15 @@ sources, modules = minify(

# Compression

Current checked-in fixtures:
Current checked-in fixtures, using
`--rename-modules --rename-global-variables --rename-arguments`:

| Input | Original | Minified | Reduction |
| --- | ---: | ---: | ---: |
| `tests/examples/pyminifier.py` | `1,355` bytes | `511` bytes | `62.3%` |
| `tests/examples/pyminify.py` | `1,990` bytes | `981` bytes | `50.7%` |
| `TexSoup/` raw Python source (`*.py`) | `98,181` bytes | `33,107` bytes | `66.3%` |
| `TexSoup/` compressed source (`.tar.gz`) | `23,118` bytes | `11,368` bytes | `50.8%` |
| `tests/examples/pyminifier.py` | `1,355` bytes | `444` bytes | `67.2%` |
| `tests/examples/pyminify.py` | `1,990` bytes | `935` bytes | `53.0%` |
| `TexSoup/` raw Python source (`*.py`) | `98,181` bytes | `25,621` bytes | `73.9%` |
| `TexSoup/` compressed source (`.tar.gz`) | `23,119` bytes | `9,209` bytes | `60.2%` |

For baseline comparisons, speed results, and TexSoup validation details, see
[benchmarks/README.md](./benchmarks/README.md).
Expand Down
31 changes: 19 additions & 12 deletions benchmarks/README.md
8000
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,17 @@ the benchmark harness used to reproduce them.

| Input | Original | `pymini` size | `pymini` speed | `pyminifier` size | `pyminifier` speed | `python-minifier` size | `python-minifier` speed |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| `pyminifier.py` | `1,355` bytes | `511` bytes, `62.3%` | `2.4 ms` | `676` bytes, `50.1%` | `0.4 ms` | `1,020` bytes, `24.7%` | `1.6 ms` |
| `pyminify.py` | `1,990` bytes | `981` bytes, `50.7%` | `5.4 ms` | `1,605` bytes, `19.3%` | `1.2 ms` | `983` bytes, `50.6%` | `4.1 ms` |
| `TexSoup/*.py` | `98,181` bytes | `33,107` bytes, `66.3%` | `399.3 ms` | `34,643` bytes, `64.7%` | `31.3 ms` | `83,303` bytes, `15.2%` | `120.8 ms` |
| `TexSoup.tar.gz` | `23,118` bytes | `11,368` bytes, `50.8%` | `—` | `9,741` bytes, `57.9%` | `—` | `21,532` bytes, `6.9%` | `—` |
| `pyminifier.py` | `1,355` bytes | `444` bytes, `67.2%` | `1.2 ms` | `611` bytes, `54.9%` | `0.4 ms` | `1,020` bytes, `24.7%` | `1.9 ms` |
| `pyminify.py` | `1,990` bytes | `935` bytes, `53.0%` | `4.7 ms` | `1,540` bytes, `22.6%` | `1.3 ms` | `983` bytes, `50.6%` | `5.3 ms` |
| `TexSoup/*.py` | `98,181` bytes | `25,621` bytes, `73.9%` | `95.2 ms` | `34,643` bytes, `64.7%` | `27.8 ms` | `83,303` bytes, `15.2%` | `120.5 ms` |
| `TexSoup.tar.gz` | `23,119` bytes | `9,209` bytes, `60.2%` | `95.2 ms` | `9,725` bytes, `57.9%` | `27.8 ms` | `21,504` bytes, `7.0%` | `120.5 ms` |

`pymini` is benchmarked with `--rename-modules --rename-global-variables --rename-arguments`.
`TexSoup/*.py` compares validated package outputs. `pymini` uses package mode;
the baselines minify each file independently in the preserved package tree. All
three outputs pass the upstream TexSoup test suite (`78` tests).
three outputs pass the upstream TexSoup test suite (`78` tests). The
`TexSoup.tar.gz` row reuses those same minification timings and only changes
the size measurement to the compressed archive.

# Reproduce

Expand All @@ -33,18 +36,19 @@ PYTHONPATH=. .venv/bin/python benchmarks/benchmark_speed.py --pyminifier-root /t
# TexSoup Validation

`pymini` has been validated against the upstream `TexSoup` test suite in
package mode. Current validation: upstream pytest passes (`78` tests), raw
source code is `66.3%` smaller, and compressed source code (`.tar.gz`) is
`50.8%` smaller when measured on clean `.py`-only package snapshots.
package mode with `--rename-modules --rename-global-variables --rename-arguments`.
Current validation: upstream pytest passes (`78` tests), raw source code is
`73.9%` smaller, and compressed source code (`.tar.gz`) is `60.2%` smaller when
measured on clean `.py`-only package snapshots.

<!-- Raw bytes: 98,181 -> 33,107. Compressed bytes: 23,118 -> 11,368. -->
<!-- Raw bytes: 98,181 -> 25,621. Compressed bytes: 23,119 -> 9,209. -->

To reproduce that flow locally:

```bash
git clone https://github.com/alvinwan/TexSoup /tmp/texsoup
mkdir -p /tmp/texsoup-out/TexSoup
pymini package /tmp/texsoup/TexSoup -o /tmp/texsoup-out/TexSoup
pymini package /tmp/texsoup/TexSoup -o /tmp/texsoup-out/TexSoup --rename-modules --rename-global-variables --rename-arguments
cp -R /tmp/texsoup/tests /tmp/texsoup-tests
PYTHONPATH=/tmp/texsoup-out:/tmp/texsoup-tests python3 -m pytest /tmp/texsoup-tests/tests -o addopts=''
```
Expand All @@ -59,8 +63,11 @@ rg --files /tmp/texsoup-out/TexSoup -g '*.py' | xargs cat | wc -c
To compare compressed package snapshots:

```bash
tar -czf /tmp/texsoup-original-package.tar.gz -C /tmp/texsoup TexSoup
tar -czf /tmp/texsoup-minified-package.tar.gz -C /tmp/texsoup-out TexSoup
mkdir -p /tmp/texsoup-compare/original/TexSoup /tmp/texsoup-compare/minified/TexSoup
rsync -a --prune-empty-dirs --include '*/' --include '*.py' --exclude '*' /tmp/texsoup/TexSoup/ /tmp/texsoup-compare/original/TexSoup/
rsync -a --prune-empty-dirs --include '*/' --include '*.py' --exclude '*' /tmp/texsoup-out/TexSoup/ /tmp/texsoup-compare/minified/TexSoup/
tar -czf /tmp/texsoup-original-package.tar.gz -C /tmp/texsoup-compare/original TexSoup
tar -czf /tmp/texsoup-minified-package.tar.gz -C /tmp/texsoup-compare/minified TexSoup
stat -f%z /tmp/texsoup-original-package.tar.gz
stat -f%z /tmp/texsoup-minified-package.tar.gz
```
20 changes: 14 additions & 6 deletions benchmarks/benchmark_speed.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,16 @@
EXAMPLE_DIR = ROOT / "tests" / "examples"
DEFAULT_TEXSOUP_ROOT = Path("/tmp/pymini-texsoup-repo/TexSoup")
DEFAULT_PYMINIFIER_ROOT = Path("/tmp/pymini-pyminifier-src/pyminifier-2.1")
PYMINI_BENCHMARK_KWARGS = {
"keep_module_names": False,
"keep_global_variables": False,
"rename_arguments": True,
}
PYMINI_CLI_FLAGS = [
"--rename-modules",
"--rename-global-variables",
"--rename-arguments",
]


def benchmark_transform(
Expand Down Expand Up @@ -47,7 +57,7 @@ def benchmark_transform(

def pymini_single_file_transform(path: Path):
def transform(source: str) -> str:
outputs, _ = minify(source, path.stem, keep_global_variables=True)
outputs, _ = minify(source, path.stem, **PYMINI_BENCHMARK_KWARGS)
return outputs[0]

return transform
Expand Down Expand Up @@ -98,8 +108,7 @@ def benchmark_package_api(
minify(
sources,
modules,
keep_global_variables=True,
keep_module_names=True,
**PYMINI_BENCHMARK_KWARGS,
)
samples = []
outputs = None
Expand All @@ -108,8 +117,7 @@ def benchmark_package_api(
outputs, _ = minify(
sources,
modules,
keep_global_variables=True,
keep_module_names=True,
**PYMINI_BENCHMARK_KWARGS,
)
samples.append(perf_counter() - start)
raw_bytes = sum(len(source.encode()) for source in sources)
Expand All @@ -131,7 +139,7 @@ def benchmark_package_cli(package_root: Path, *, iterations: int) -> dict[str, f
output_dir = Path(tempfile.mkdtemp(prefix="pymini-bench-"))
try:
start = perf_counter()
rc = cli_main(["package", str(package_root), "-o", str(output_dir)])
rc = cli_main(["package", str(package_root), *PYMINI_CLI_FLAGS, "-o", str(output_dir)])
samples.append(perf_counter() - start)
if rc != 0:
raise RuntimeError(f"pymini CLI returned {rc}")
Expand Down
36 changes: 18 additions & 18 deletions examples/pyminify.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
def a(event,context):
f='RequestType';g='PhysicalResourceId';h='None';i='Status';j='SUCCESS';k='Tags';m='OldResourceProperties';l.info(event);n,o,p,q,r,s,t,u,v=(event,create_cert,add_tags,validate,wait_for_issuance,context,send,reinvoke,acm)
e='RequestType';f='PhysicalResourceId';g='None';h='Status';i='SUCCESS';j='Tags';k='OldResourceProperties';l.info(event);a,m,n,o,p,q,r,s,t=(event,create_cert,add_tags,validate,wait_for_issuance,context,send,reinvoke,acm)
try:
b=hashlib.new('md5',(n['RequestId']+n['StackId']).encode()).hexdigest();c=n['ResourceProperties']
if n[f]=='Create':
n[g]=h;n[g]=o(c,b);p(n[g],c);q(n[g],c)
if r(n[g],s):n[i]=j;return t(n)
else:return u(n,s)
elif n[f]=='Delete':
if n[g]!=h:v.delete_certificate(CertificateArn=n[g])
n[i]=j;return t(n)
elif n[f]=='Update':
if replace_cert(n):
n[g]=o(c,b);p(n[g],c);q(n[g],c)
if not r(n[g],s):return u(n,s)
b=hashlib.new('md5',(a['RequestId']+a['StackId']).encode()).hexdigest();c=a['ResourceProperties']
if a[e]=='Create':
a[f]=g;a[f]=m(c,b);n(a[f],c);o(a[f],c)
if p(a[f],q):a[h]=i;return r(a)
else:return s(a,q)
elif a[e]=='Delete':
if a[f]!=g:t.delete_certificate(CertificateArn=a[f])
a[h]=i;return r(a)
elif a[e]=='Update':
if replace_cert(a):
a[f]=m(c,b);n(a[f],c);o(a[f],c)
if not p(a[f],q):return s(a,q)
else:
if k in n[m]:v.remove_tags_from_certificate(CertificateArn=n[g],Tags=n[m][k])
p(n[g],c)
n[i]=j;return t(n)
if j in a[k]:t.remove_tags_from_certificate(CertificateArn=a[f],Tags=a[k][j])
n(a[f],c)
a[h]=i;return r(a)
else:raise RuntimeError('Unknown RequestType')
except Exception as d:l.exception('');n[i]='FAILED';n['Reason']=str(d);return t(n)
del (n,o,p,q,r,s,t,u,v)
except Exception as d:l.exception('');a[h]='FAILED';a['Reason']=str(d);return r(a)
del (a,m,n,o,p,q,r,s,t)
handler=a
12 changes: 9 additions & 3 deletions pymini/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ def build_parser() -> ArgumentParser:
action='store_true',
help='Rename top-level globals instead of preserving them through public aliases.',
)
parser.add_argument(
'--rename-arguments',
action='store_true',
C97D help='Rename function and method parameter names, including matching internal keyword callers.',
)
parser.add_argument('--single-file', action='store_true', help=SUPPRESS)
parser.add_argument('-o', '--output', help='Path to the output directory', default='./')
parser.add_argument('--version', action='version', version=f'%(prog)s {__version__}')
Expand All @@ -52,11 +57,11 @@ def effective_mode(args) -> str:
return BUNDLE_MODE if args.single_file else args.mode


def resolve_options(args) -> tuple[str, bool, bool, bool]:
def resolve_options(args) -> tuple[str, bool, bool, bool, bool]:
mode = effective_mode(args)
keep_module_names = not args.rename_modules
keep_global_variables = not args.rename_global_variables
return mode, keep_module_names, keep_global_variables, mode == BUNDLE_MODE
return mode, keep_module_names, keep_global_variables, args.rename_arguments, mode == BUNDLE_MODE


def resolve_python_files(path: str) -> tuple[list[Path], Optional[Path]]:
Expand Down Expand Up @@ -143,7 +148,7 @@ def write_outputs(
def main(argv: Optional[Sequence[str]] = None) -> int:
parser = build_parser()
args = parser.parse_args(normalize_argv(argv))
mode, keep_module_names, keep_global_variables, output_single_file = resolve_options(args)
mode, keep_module_names, keep_global_variables, rename_arguments, output_single_file = resolve_options(args)
paths, module_root = resolve_python_files(args.path)
if not paths:
parser.error(f"no Python files matched {args.path!r}")
Expand All @@ -158,6 +163,7 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
modules,
keep_module_names=keep_module_names,
keep_global_variables=keep_global_variables,
rename_arguments=rename_arguments,
output_single_file=output_single_file,
)
try:
Expand Down
Loading
Loading
0