Metadata-Version: 2.1
Name: graphreduce
Version: 1.10.19
Summary: Leveraging graph data structures for complex feature engineering pipelines.
Home-page: https://github.com/wesmadrigal/graphreduce
Author: Wes Madrigal
Author-email: wes@madconsulting.ai
License: MIT
Project-URL: Changelog, https://github.com/wesmadrigal/graphreduce/blob/master/CHANGELOG.md
Project-URL: Documentation, https://wesmadrigal.github.io/graphreduce/
Project-URL: Source, https://github.com/wesmadrigal/graphreduce
Project-URL: Issue Tracker, https://github.com/wesmadrigal/graphreduce/issues
Keywords: feature engineering,mlops,entity linking,graph algorithms
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Education
Classifier: Intended Audience :: Information Technology
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Description-Content-Type: text/markdown
Provides-Extra: duckdb
Provides-Extra: trino
Provides-Extra: spark
Provides-Extra: daft
Provides-Extra: ml
Provides-Extra: relbench
Provides-Extra: dev
Provides-Extra: all
License-File: LICENSE

# GraphReduce

GraphReduce turns related tables into a single, model-ready feature table.
You describe tables as nodes, foreign-key relationships as edges, and the
entity you want to model as the parent node. GraphReduce then filters data to
the correct point in time, aggregates child rows, and joins the results back to
the parent.

It is designed for relational machine-learning workloads where correctness is
as important as scale:

- **Known output grain.** Reduced relations produce one row per parent key.
- **Point-in-time features.** Historical features and future labels use
  separate windows around a cutoff.
- **Traceable columns.** Every node has a unique prefix that records column
  lineage after joins.
- **Automatic or custom features.** Start with schema-aware aggregation, then
  replace any node operation with application-specific logic.
- **Multiple execution engines.** Use dataframe backends or compile the graph
  into SQL.

[Documentation](https://wesmadrigal.github.io/GraphReduce/) ·
[Quickstart](https://wesmadrigal.github.io/GraphReduce/tutorial_index/) ·
[Examples](https://wesmadrigal.github.io/GraphReduce/end_to_end_examples/)

![GraphReduce modeling and feature rollup](./docs/graphreduce_modeling_overview.svg)

## Mental model

Suppose the source data contains customers and orders:

```text
customers (one row per customer)
    id  name

orders (many rows per customer)
    id  customer_id  ts  amount
```

Model the relationship as:

```text
customers.id  1 ───── *  orders.customer_id
     parent                 relation
```

With `customers` as the parent and `reduce=True` on the edge, GraphReduce:

1. loads and prefixes both tables;
2. keeps order rows inside the historical feature window;
3. aggregates orders by `customer_id`;
4. left-joins those features to customers; and
5. optionally computes labels from a separate future window.

The result remains at customer grain: one row per customer.

## Installation

Install the dataframe-oriented core:

```bash
pip install graphreduce
```

Install only the optional integrations you need:

```bash
pip install "graphreduce[duckdb]"
pip install "graphreduce[spark]"
pip install "graphreduce[daft]"
pip install "graphreduce[trino]"
pip install "graphreduce[relbench]"
```

`graphreduce[all]` installs all optional integrations. For local development:

```bash
git clone https://github.com/wesmadrigal/graphreduce.git
cd graphreduce
pip install -e ".[dev]"
```

## Quickstart

The example below expects two local CSV files with the columns shown in the
mental model above.

```python
import datetime as dt

from graphreduce.enum import ComputeLayerEnum, PeriodUnit
from graphreduce.graph_reduce import GraphReduce
from graphreduce.node import DynamicNode

customers = DynamicNode(
    fpath="customers.csv",
    fmt="csv",
    pk="id",
    prefix="cust",
    compute_layer=ComputeLayerEnum.pandas,
)

orders = DynamicNode(
    fpath="orders.csv",
    fmt="csv",
    pk="id",
    prefix="ord",
    date_key="ts",
    compute_layer=ComputeLayerEnum.pandas,
)

graph = GraphReduce(
    name="customer_features",
    parent_node=customers,
    compute_layer=ComputeLayerEnum.pandas,
    cut_date=dt.datetime(2024, 1, 1),
    compute_period_val=365,
    compute_period_unit=PeriodUnit.day,
    auto_features=True,
    label_node=orders,
    label_field="id",
    label_operation="count",
    label_period_val=30,
    label_period_unit=PeriodUnit.day,
)

graph.add_node(customers)
graph.add_node(orders)
graph.add_entity_edge(
    parent_node=customers,
    relation_node=orders,
    parent_key="id",
    relation_key="customer_id",
    reduce=True,
)

graph.do_transformations()
features = graph.parent_node.df
print(features.head())
```

Important details:

- `parent_node=customers` sets the output grain.
- `prefix` values must be unique across the graph.
- `date_key="ts"` makes the orders node eligible for time filtering.
- `compute_period_val=365` uses non-null order timestamps strictly before the
  cutoff.
- `label_period_val=30` uses label rows strictly after the cutoff.
- `reduce=True` aggregates orders before joining them to customers.
- The materialized dataframe is available at `graph.parent_node.df`.

Because labels are joined from an aggregate relation, a parent with no event in
the label window receives a null label. Convert that null to zero only when “no
event” has that meaning for your target.

For a runnable version backed by repository sample data, see
[Hello World](https://wesmadrigal.github.io/GraphReduce/end_to_end_examples/hello_world/).

## Choose an execution path

![One GraphReduce graph with interchangeable compute engines](./docs/assets/images/compute_engine_pluggability.png)

The graph topology, time-window configuration, and intended output grain stay
stable across engines. Backend-specific expressions, clients, storage access,
and materialization behavior may still need engine-specific configuration.

| Need | Node type | Entry point |
| --- | --- | --- |
| Automatic dataframe features | `DynamicNode` | `do_transformations()` |
| Custom dataframe operations | `GraphReduceNode` subclass | `do_transformations()` |
| SQL compilation and execution | `SQLNode` or backend subclass | `do_transformations_sql()` |

Available compute layers are defined by `ComputeLayerEnum`. The most developed
paths in the current documentation are pandas, Dask, Spark, Daft, DuckDB,
SQLite, Athena, Redshift, Snowflake, Databricks SQL, PostgreSQL, MySQL, and
Trino. Backend-specific clients and optional dependencies still need to be
configured by the application.

## Where to go next

- [Fundamentals](https://wesmadrigal.github.io/GraphReduce/fundamentals/):
  execution order, cardinality, and time semantics.
- [Abstractions](https://wesmadrigal.github.io/GraphReduce/abstractions/): the
  responsibilities of graphs, nodes, and edges.
- [Configuration](https://wesmadrigal.github.io/GraphReduce/configuration/):
  common graph, node, edge, and execution settings.
- [Quickstart](https://wesmadrigal.github.io/GraphReduce/tutorial_index/): a
  runnable two-table walkthrough using repository sample data.
- [SQL auto-feature families](https://wesmadrigal.github.io/GraphReduce/sql_auto_feature_families/):
  schema-aware, temporal, conditional, sequence, episode, semantic, and
  context features.
- [End-to-end examples](https://wesmadrigal.github.io/GraphReduce/end_to_end_examples/):
  complete multi-table and multi-backend workflows.

## Citation

If GraphReduce contributes to your research or production work, please cite
the project:

```bibtex
@software{madrigal_graphreduce_2026,
  author  = {Madrigal, Wes},
  title   = {GraphReduce: Relational Feature Engineering for Tabular Machine Learning},
  year    = {2026},
  url     = {https://github.com/wesmadrigal/GraphReduce}
}
```

For reproducible research, cite the specific GitHub release or commit used.

## Project status

GraphReduce is under active development. The public surface is broad, and
backend behavior is not perfectly uniform. Test a small representative graph
on your chosen backend before scaling a production job. Please report defects
and documentation gaps in the
[issue tracker](https://github.com/wesmadrigal/graphreduce/issues).

## License

GraphReduce is distributed under the MIT License. See
[LICENSE](./LICENSE) for the complete terms.


# Changelog

Notable changes to GraphReduce are documented here. The package build appends
this file to the README shown on PyPI, and the same notes should be copied into
the corresponding GitHub Release.

## [1.10.19] - 2026-11-05

### Added

- Added `GraphReduce.run()` and `run_until(node, operation)` for inclusive
  execution stops at node operations. `ExecutionResult` exposes the dataframe
  or SQL reference, including reduced output before it joins into its parent.
- Added `GraphReduce.load_data()` and optional `sample_size` configuration for
  relational sampling: limit root rows and recursively retain all matching
  descendants using scalar or composite relationship keys. Shared descendants
  retain rows matching any sampled parent path without multiplying source rows.
- Relational sampling supports SQL, pandas, and Dask on acyclic graphs whose
  ordinary nodes are reachable from the root. SQL applies filters in the query;
  pandas filters after loading. Independent executions require fresh graphs.
- Documented [partial execution and relational sampling](docs/tutorial_execution_sampling.md).
- Added an opt-in Olist pytest benchmark comparing full-data `run_until` with
  `sample_size=100`, reporting repeated execution timings and validating that
  sampled aggregates match the corresponding full-data results.

## [1.10.18] - 2026-10-27

### Added

- Bounded base CDF sketches with training-fitted cutpoints and frozen replay.
- Relational distribution sketches, learned-message pooling, and neighbor-context
  helpers used by downstream relational representation search.
- Explicit strict/inclusive event cutoffs and finer-grained source visibility.

### Changed

- SQL feature inference supports bounded state/context and configurable
  categorical/text handling without forcing every representation into one graph.
- DuckDB joins inspect schema metadata after semantic types have been initialized,
  avoiding repeated sample materialization. Cold inference and custom node sample
  overrides retain their original behavior.

### Fixed

- Scope wide eager DuckDB reductions with many distinct aggregates to one SQL
  worker, then restore the caller's thread setting on success or failure. This
  avoids multiplying aggregation state without changing expressions or rows.
- Keep cold semantic inference, user sampling overrides and ordinary queries
  on their existing paths; schema inspection does not replace value discovery.

This release is prepared in the review branch. The downstream KurveRSC campaign
completed all 21 tasks without failures. The qualified release checks pass
157 tests (2 skipped); full classification/regression smokes through the current
RelArena adapter preserve the frozen payload's keyed predictions exactly. Release metadata is separate from
PyPI publication.

## [1.10.14] - 2026-09-01

### Changed

- Removed the unused `abstract.jwrotator` runtime dependency. GraphReduce has
  no imports from that package; removing it also keeps downstream optional
  integrations free of an unnecessary GPL dependency.

## [1.10.13] - 2026-09-01

### Fixed

- Normalize Boolean temporal values to numeric `0.0`/`1.0` expressions before
  generating windowed averages, variances, sums, and trends. This prevents
  DuckDB from receiving invalid operations such as `AVG(BOOLEAN)` while
  retaining Boolean activity signal.

## [1.10.12] - 2026-08-31

### Added

- Added the optional graph- and node-level
  `feature_propagation_max_functions_per_column` budget. It prevents an
  already-derived feature from branching into every compatible aggregate at
  each additional graph hop.
- Propagation budgets prioritize the aggregation that preserves the feature's
  semantics: max-to-max, min-to-min, sum-to-sum, count-to-sum, and
  average/share-to-average.

## [1.10.11] - 2026-08-31

### Added

- Added the optional graph- and node-level
  `feature_family_max_features_per_column` budget for SQL automatic features.
  It independently caps each selected source column's derived expansion while
  leaving source-column selection under `feature_family_max_columns`.
- Conditional-family source budgets now count distinct source columns rather
  than individual category predicates. Bounded conditional and temporal
  expansions are ordered to retain category and lookback breadth under a cap.

## [1.10.10] - 2026-08-31

### Added

- Added bounded lifetime relationship diversity and repeat-ratio features to
  the SQL `base` family, excluding primary keys and effectively unique sample
  identifiers that merely restate row counts.
- Added observed-history age, lifetime event intensity, and boolean positive
  shares to the SQL `base` family.
- Added windowed relationship diversity, repeat ratios, per-day activity,
  observation counts, variance, and recent-versus-prior trends to the SQL
  `temporal` family.
- Added SQLite and DuckDB coverage for fixed and per-entity dynamic cutoffs,
  including historical outcomes whose availability timestamp is used as the
  leakage-safe node date key.

## [1.10.9] - 2026-08-31

### Fixed

- Prevented SQL automatic feature inference from emitting numeric value
  aggregates for columns whose inference samples contain no observed values.
  This avoids persisting invalid operations such as `AVG(VARCHAR)` when an
  all-null SQL string sample is represented by pandas with a numeric
  placeholder dtype.

## [1.10.3] - 2026-08-27

### Added

- Added optional graph-wide SQL auto-feature configuration for feature
  families, family budgets, time-series periods, categorical cardinality and
  top-value limits, text features, and inferred annotation limits.

### Changed

- Graph-level feature settings now propagate to every node during graph
  hydration when explicitly supplied, while omitted settings preserve each
  node's existing configuration.

## [1.10.2] - 2026-08-17

### Added

- Added an automatic point-in-time age feature for graph parent nodes that
  define a date key.

### Changed

- Extended node time-series periods with the graph compute horizon, expressed
  in whole days, whenever that horizon exceeds one year.

## [1.10.1] - 2026-08-15

### Added

- Added training-sample schema profiling with typed, model-agnostic feature
  manifests for structural, numerical, boolean, categorical, timestamp, and
  text columns.
- Added explicit cutoff-safety declarations for unavailable or future-derived
  source columns.
- Added `GraphReduceNode.infer_feature_manifest()` to profile a node and
  optionally apply its safe source-column plan.

### Changed

- Exposed feature manifests and schema profiling through the top-level
  `graphreduce` package API.
- Documented how typed manifests compose with the existing automatic
  categorical indicators and category-gated numeric reductions.

## [1.10.0] - 2026-08-13

### Added

- Added ordered composite primary keys and relationship keys while preserving
  the existing scalar-key API.
- Added native multi-column joins and reductions for pandas, Dask, Spark,
  Daft, and SQL compute layers.
- Added composite-key support for automatic features, labels, time-series
  grouping, frozen execution plans, and dynamic date-node propagation.
- Added early validation for invalid key definitions, mismatched relationship
  key arity, and missing join columns.

### Changed

- Added `colabbrs()` and `key_sql()` helpers for custom node implementations
  that operate on scalar or composite keys.
- Composite primary-key episode features retain row-count metrics but skip
  dialect-dependent distinct-primary-key metrics with an explicit warning.

### Fixed

- Fixed reverse-edge joins so their parent and relation key mappings are
  correctly inverted.
- Prevented automatic feature generation from aggregating composite reduction
  key components as value columns.

## [1.9.17] - 2026-07-28

### Added

- Added opt-in SQL auto-feature families for conditional, temporal, episode,
  semantic, sequence, and peer-context features.
- Added automatic categorical, text, and gated-numeric SQL annotations with
  configurable cardinality and feature limits.
- Added a `relbench` optional dependency group for RelBench, CatBoost,
  PyArrow, and scikit-learn integrations.
- Added RelBench task selection and parallel training-frame generation
  utilities to the end-to-end examples.

### Changed

- Isolated temporary SQL tables with a per-execution namespace so concurrent
  GraphReduce runs do not collide.
- Improved generated SQL feature schemas across cut dates and bounded wide
  training frames to keep feature generation predictable.

### Fixed

- Fixed SQL inference sampling for wide or sparsely populated relations.
- Fixed date-node key propagation through undated intermediate SQL nodes.
- Fixed SQL auto-feature type handling for string-backed numeric semantic
  types, identifier-like columns, and collection-valued columns.
- Propagated Athena, Redshift, and DuckDB query failures instead of allowing
  invalid feature plans to continue.
- Handled constant regression targets in the RelBench training workflow.

For older versions, see the
[PyPI release history](https://pypi.org/project/graphreduce/#history).
