Metadata-Version: 2.4
Name: freshspark
Version: 0.2.0
Summary: Create truly fresh local Spark sessions with isolated temp dirs and reliable teardown.
Author: Odos Matthews
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright 2026 Odos Matthews
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Project-URL: Homepage, https://github.com/eddiethedean/freshspark
Project-URL: Issues, https://github.com/eddiethedean/freshspark/issues
Keywords: pyspark,spark,spark-session,spark local,spark cleanup
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pyspark<4,>=3.5
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: ruff>=0.9; extra == "dev"
Requires-Dist: mypy>=1.8; extra == "dev"
Dynamic: license-file

# freshspark

[![CI](https://github.com/eddiethedean/freshspark/actions/workflows/ci.yml/badge.svg)](https://github.com/eddiethedean/freshspark/actions/workflows/ci.yml)
[![PyPI version](https://img.shields.io/pypi/v/freshspark.svg)](https://pypi.org/project/freshspark/)
[![Python versions](https://img.shields.io/pypi/pyversions/freshspark.svg)](https://pypi.org/project/freshspark/)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)

Small helpers for **local PySpark** that start each run in a clean sandbox and tear sessions down reliably: isolated warehouse temp dirs, optional embedded Derby kept out of the working tree, in-memory catalog by default, randomized Spark UI port, and aggressive Py4J / JVM shutdown so the process can exit normally.

**Use it when** notebooks or scripts leave metastore locks, `derby.log` in the wrong place, Spark UI port collisions, or JVMs that refuse to die after `SparkSession.stop()`.

---

## Requirements

| | |
| --- | --- |
| **Python** | 3.9 or newer |
| **JDK** | On `PATH` (or via `JAVA_HOME`). Spark 3.x line: Java 8, 11, or 17; **PySpark 3.5+** is also validated against **Java 21**. |
| **PySpark** | Declared dependency is **PySpark 3.5.x** (`pyspark>=3.5,<4`) for predictable local startup. Spark 4 is not pinned here; if you override to PySpark 4.x, use Java 17 or 21 and expect to manage compatibility yourself. |

---

## Install

```bash
pip install freshspark
```

**Development** (editable install, tests, Ruff):

```bash
pip install -e ".[dev]"
ruff format --check freshspark tests
ruff check freshspark tests
mypy freshspark tests
pytest
```

---

## Quick start

```python
from freshspark import fresh_local_spark, get_fresh_local_spark

# Context manager: new session every `with` block, cleanup on exit
with fresh_local_spark(app_name="etl", preset="dev") as spark:
    spark.range(10).show()

# Manual lifecycle: always call cleanup() when finished (or use try/finally)
spark, cleanup = get_fresh_local_spark(app_name="demo", preset="fat")
try:
    spark.range(1000).summary().show()
finally:
    cleanup()
```

---

## Public API

| Symbol | Role |
| --- | --- |
| `fresh_local_spark(...)` | Context manager yielding a **new** `SparkSession` per `with` block (no reuse). |
| `get_fresh_local_spark(...)` | Returns `(spark, cleanup)`. You **must** call `cleanup()` when done unless you use the context manager. |
| `reset_active_session()` | Stops the active session, closes the gateway, and **clears in-process reuse cache** entries that pointed at that session (or are already dead). Safe to call repeatedly. |
| `ensure_fresh(...)` | Decorator that runs the wrapped function inside `fresh_local_spark`; injects `spark` as a keyword argument. Do not pass `spark=` yourself (a `TypeError` is raised if you do). |

---

## Configuration highlights

### Presets

`preset` is one of `tiny`, `dev`, or `fat`. They set driver memory and `maxResultSize` to sensible defaults. Any other string logs a **warning** and applies no preset keys (you can still set everything via `extra_confs`).

| Preset | `spark.driver.memory` | `spark.driver.maxResultSize` |
| --- | --- | --- |
| `tiny` | `1g` | `512m` |
| `dev` | `2g` | `1g` |
| `fat` | `4g` | `2g` |

### Catalog and warehouse

- **Default** (`hive_metastore=False`): `spark.sql.catalogImplementation=in-memory` and an isolated `spark.sql.warehouse.dir` under a temp root—no embedded Derby in the default path, so you avoid the usual Derby lock files in the project directory.
- **Hive-style metastore** (`hive_metastore=True`): warehouse and Derby home (`-Dderby.system.home=...`) both live under the same isolated temp tree.

If you pass `extra_confs` with `spark.driver.extraJavaOptions` while `hive_metastore=True`, that value is **merged** after the required Derby system home flag so your JVM flags do not accidentally wipe metastore configuration.

### Other knobs

- **`enable_ui` / `print_ui_url`**: Spark UI on a free port (`spark.ui.port=0`); optionally print the URL once the session is up.
- **`extra_confs`**: flat `dict[str, str]` merged last so you can override presets or Spark defaults.
- **`reuse_within_process=True`**: same Python process + same `app_name` returns the same `(spark, cleanup)` until `cleanup()` or `reset_active_session()` runs; dead cached sessions are replaced automatically on the next request.

---

## CLI

```bash
# Python REPL with `spark` already constructed
freshspark repl --preset fat

# Stop the active SparkSession in this interpreter (also reconciles reuse cache)
freshspark reset
```

| Command | Common flags |
| --- | --- |
| `freshspark repl` | `--app-name`, `--preset tiny|dev|fat`, `--hive`, `--no-ui` |
| `freshspark reset` | _(none)_ |

---

## Jupyter and long-running kernels

Prefer an explicit cleanup cell so temp dirs and the JVM are released even if the kernel stays alive:

```python
from freshspark import get_fresh_local_spark

spark, cleanup = get_fresh_local_spark(app_name="nb", preset="dev")
# ... work ...
cleanup()
```

If another library left a sticky session in this kernel, call `reset_active_session()` here. The `freshspark reset` CLI only affects the interpreter where that command runs (for example a terminal REPL), not a separate Jupyter kernel.

---

## Environment variables

| Variable | Effect |
| --- | --- |
| `FRESHSPARK_SKIP_JAVA_CHECK` | If set to `1`, `true`, or `yes`, an unsupported Java / Spark pairing **warns** instead of raising during session construction. |

---

## Why this exists

Local PySpark is great until it is not: JVMs that linger, Derby files under `cwd`, warehouse dirs shared across runs, and UI ports that collide. **freshspark** centralizes a small set of Spark configs and lifecycle rules so each run gets an isolated temp layout and a cleanup path that actually runs (including an `atexit` safety net, with idempotent cleanup so manual `cleanup()` plus process exit does not misbehave).

---

## Project links

- **Homepage / source:** [github.com/eddiethedean/freshspark](https://github.com/eddiethedean/freshspark)
- **Issues:** [github.com/eddiethedean/freshspark/issues](https://github.com/eddiethedean/freshspark/issues)

---

## License

Apache 2.0 (see [LICENSE](LICENSE)).
