Skip to content

Let any sink hold files: FileStoreSink protocol and a chunked filesystem - #112

Merged
Vedaant-J merged 53 commits into
mainfrom
vedaant/mlops-filestore-sink
Nov 3, 2026
Merged

Vedaant-J merged 53 commits into
mainfrom
vedaant/mlops-filestore-sink

Conversation

@Vedaant-J

@Vedaant-J Vedaant-J commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Stack: main (#53 merged) → #112 → #114 → #50 → #60 → #64 → #115. Merge bottom to top.

Summary

Prediction exports and model bundles can only go to S3, GCS, ADLS or local paths: the engine checks the connector type. Databricks volumes and Snowflake stages hold files too, but one upload is capped (5 GiB on volumes) or has no multipart. This PR lets any sink say which of its paths are files, and gives such stores one shared filesystem:

  • kumoapi.plugin.FileStoreSink: an optional protocol, holds_files(connector, path) (from the path alone) and filesystem(connector, path) (a pyarrow.fs.FileSystem).
  • kumo_core.chunked_fs.ChunkedFileHandler: a pyarrow filesystem over five store calls (size, list, put, ranged read, remove). A file up to part_bytes is one plain object; a larger one is stored as parts under <name>.chunks/<generation>/ and committed by an empty _SUCCESS written last.
  • kumo_core.object_store_sink.FilesystemSink: the existing object-store writers over any sink's filesystem(). Bundles upload _provenance.json last.
  • kumo_core.object_store_sink.FileStoreRouting: a mixin that sends a sink's file paths to FilesystemSink and its other paths to its own table methods.
  • ObjectStoreSinkBackend.preflight_write_files: an export into an occupied output directory is refused before scoring, on every object store.

No volume or stage sink ships here; #114 and #115 add them.

Usage

class StageSink:                                    # an existing table sink
    def holds_files(self, connector, path):
        return path.startswith('@')
    def filesystem(self, connector, path):
        return PyFileSystem(StageHandler(connector)), path.rstrip('/')

PredictionOutputConfig(connector, output_paths={"predictions": "@stage/kumo/scores/"})
trainer.fit(..., export_config=ModelOutputConfig(connector, path="@stage/kumo/models/m1"))
Trainer.load_from_connector(connector, path="@stage/kumo/models/m1")

Back-compat

Situation Behaviour
S3, GCS, ADLS or local publish and fetch Unchanged (ObjectStoreSinkBackend holds every path).
output_paths on a sink that does not hold the path ValueError, as before; the message now mentions volume and stage paths.
Sink whose package extra is not installed The install hint is raised, not the file-destination error.
Export into an output directory that already holds files (S3, GCS, ADLS or a sink's file store) Refused before scoring, whatever the write mode, with the same Output directory ... already contains data from another export error that was raised after scoring.
A sink without FileStoreSink A table destination, as before.
A chunked file read while it is rewritten The previous file until the new _SUCCESS lands.
A write that fails part way Nothing committed; a stream that supports abort is aborted; the previous file stays readable; the error is raised.
A .chunks/ file read by Spark or an older engine A directory of parts; files up to part_bytes are plain objects.

Testing

  • kumo-core/tests/test_chunked_fs.py: empty, sub-part, one-part and multi-part files; reads across part boundaries; newest committed generation wins; failed writes keep the old file and abort the stream; listings, deletes, streamed writes, spool location; concurrent rewrites.
  • kumo-engine/test/test_filestore_sink.py: output configs, a bundle round trip, trainer publish and load, and prediction export, the occupied-directory refusal before scoring, and a file-only sink refusing a table through a filesystem-only sink over an in-memory store.

Change map: see the kumo-pr-change-map comment.

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Oct 24, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@Vedaant-J
Vedaant-J temporarily deployed to gha-kumo-workflow-tests October 24, 2026 17:17 — with GitHub Actions Inactive
@coderabbitai

coderabbitai Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Superseded by the change map below.

@Vedaant-J

Vedaant-J commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Change map

File Function / scope What changed Why
packages/kumo-api/kumoapi/plugin.py FileStoreSink New optional protocol: holds_files, filesystem Lets any sink hold files for some paths
packages/kumo-core/src/kumo_core/artifacts.py PROVENANCE_FILE New constant _provenance.json One name for every artifact's manifest
packages/kumo-core/src/kumo_core/chunked_fs.py ChunkedFileHandler, set_spool_dir, spool_root New pyarrow filesystem over put/list/read/remove; large files as committed parts; a commit drops only older committed generations and reads skip incomplete ones Stores that cap object size or lack multipart
packages/kumo-core/src/kumo_core/object_store_sink.py holds_files, filesystem, preflight_write_files, FilesystemSink, FileStoreRouting, open_sized, upload_file, upload_bundle Object-store writers over any sink's filesystem(); occupied output directory refused before scoring on every store; manifest uploaded last Reuse export and bundle code for volumes and stages
packages/kumo-engine/kumo/engine/connector/__init__.py is_file_destination, file_store Pick file store or table per path Replaces the connector-type check
packages/kumo-engine/kumo/engine/trainer/output_config.py PredictionOutputConfig, TrainingTableOutputConfig Accept any path a sink holds; new writer() Exports to volume and stage paths
packages/kumo-engine/kumo/engine/trainer/trainer.py _require_publisher, _preflight, fit, predict, PredictionResult._export Publisher check, preflight and export writer come from the sink protocols Publish and export by file path on any sink
packages/kumo-engine/kumo/engine/_scratch.py _spool_parts Chunked writers spool under <scratch>/spool Follows kumo.configure(scratch_dir=)
packages/kumo-core/tests/test_chunked_fs.py new tests Layouts, boundary reads, failed writes and opens, generations, overlapping writers, concurrency Covers the chunked filesystem contract
packages/kumo-engine/test/test_filestore_sink.py new tests Configs, bundles, trainer, export over a filesystem-only sink End to end without a real store
packages/kumo-engine/test/test_prediction_completion.py fake sink Fake file sink implements FileStoreSink Export path now asks the sink
tests/public/Dockerfile.dockerignore public image allowlist Ships chunked_fs.py object_store_sink imports it
packages/kumo-adls/tests/test_native_output.py ADLS sink tests Copy through the shared upload_file Follows the upload helper's move
packages/kumo-engine/test/test_adls_connector.py ADLS connector test An ADLS Gen2 root is a file destination and a bundle round-trips through it ADLS artifact roots use the shared file-store path

Vedaant-J added a commit that referenced this pull request Oct 24, 2026
…cope

Snapshot export took (connector, path), gated on object-store sinks,
and was the only place a snapshot reached durable storage.

- GraphSnapshot.export(SnapshotOutputConfig(connector, path)), in the
  style of the other output configs; any sink that holds files at the
  path (FileStoreSink, #112) can take it, and every upload tells a
  chunked store its size so files up to one part stay plain.
- Graph.snapshot(mlops=): with MLOps on, the snapshot is exported under
  <root>/snapshots/ unless a complete export of the same format and id
  is there; failures warn.
- ConcurrentExportError is a RuntimeError (no retry role).
  GraphSnapshot.graph_key/data_version are private. The README section
  moves to docs/mlops.md.

Verified: test_snapshot_export.py (30: config form, a filesystem-only
chunked sink round trip, stored once in a block, existing export,
retry and repair cases), snapshot manifest and training-table suites.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Vedaant-J
Vedaant-J added this pull request to stack #113 October 24, 2026 19:06

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Note

Quiet mode is enabled, so only the most important comments were posted inline. Other review comments are grouped below.

Other comments: 2
packages/kumo-core/src/kumo_core/chunked_fs.py: 2

104-114: Minor · Stability & Availability · Quick win

Fix the stale-layout race between _layout and _forget.

_layout computes a layout without a lock and then stores it in the cache. A writer can finish and call _forget(path) between the compute step and the store step. The reader then stores the old layout after the invalidation.

Nothing removes that entry afterward. The _Reader uses the cached sizes. If the new file is larger, a read returns truncated data without an error. If the sizes differ in another way, the read raises OSError.

The race needs a reader and a writer on the same path in one process. test_layout_cache_survives_concurrent_opens_and_writes does not cover it. In that test, each thread reads and writes only its own file.

Use an invalidation counter. Store the layout only if no _forget call ran during the compute step.

Proposed fix
     def _layout(self, path: str) -> Optional[List[Tuple[str, int]]]:
         cache = self.__dict__.setdefault('_layouts', {})
         layout = cache.get(path)
         if layout is not None:
             return layout
+        epoch = self.__dict__.get('_epoch', 0)
         size = self._size(path)
         layout = ([(path, size)] if size is not None else _logical_parts(
             self._list(path + CHUNKS), path + CHUNKS))
-        if layout is not None:
+        if layout is not None and self.__dict__.get('_epoch', 0) == epoch:
             cache[path] = layout
         return layout

In _forget, increment the counter before it removes entries:

        self.__dict__['_epoch'] = self.__dict__.get('_epoch', 0) + 1

If you need exact atomicity across threads, guard the counter update and the cache store with one threading.Lock.

Add a test in which one thread writes a path while other threads read the same path.


321-341: Minor · Data Integrity & Integration · Quick win

Guard failed _Writer construction from finalization.

When _open_part() fails after _clear(), _Writer remains partially initialized. io.RawIOBase finalization calls _Writer.close(), whose final branch uploads the empty spool as the plain object. _clear() has already removed the old chunked representation.

super().close() directly calls the inherited close method and does not re-enter _Writer.close(). Keep the resource setup inside the guard:

Suggested fix
-        self._dir = tempfile.mkdtemp(prefix='kumo-chunked-',
-                                     dir=spool_root(handler))
-        self._spool = open(os.path.join(self._dir, 'spool'), 'wb')
-        self._filled = 0
-        self._parts = 0
-        self._written = 0
-        self._part: Optional[BinaryIO] = None
-        self._streams = type(handler)._stream is not ChunkedFileHandler._stream
-        self._limit = (min(handler.plain_bytes, handler.part_bytes)
-                       if self._streams else handler.part_bytes)
-        self._plain: Optional[BinaryIO] = None
-        if self._streams and size is not None:
-            if size <= handler.part_bytes:
-                self._plain = handler._stream(path)
-            else:
-                self._clear()
-                self._part = self._open_part()
+        directory: Optional[str] = None
+        spool: Optional[BinaryIO] = None
+        try:
+            directory = tempfile.mkdtemp(prefix='kumo-chunked-',
+                                         dir=spool_root(handler))
+            self._dir = directory
+            spool = open(os.path.join(directory, 'spool'), 'wb')
+            self._spool = spool
+            self._filled = 0
+            self._parts = 0
+            self._written = 0
+            self._part: Optional[BinaryIO] = None
+            self._streams = type(handler)._stream is not ChunkedFileHandler._stream
+            self._limit = (min(handler.plain_bytes, handler.part_bytes)
+                           if self._streams else handler.part_bytes)
+            self._plain: Optional[BinaryIO] = None
+            if self._streams and size is not None:
+                if size <= handler.part_bytes:
+                    self._plain = handler._stream(path)
+                else:
+                    self._clear()
+                    self._part = self._open_part()
+        except BaseException:
+            if spool is not None:
+                spool.close()
+            if directory is not None:
+                shutil.rmtree(directory, ignore_errors=True)
+            super().close()
+            raise

This prevents the empty-object replacement. It does not restore data already removed by _clear().


Review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between 893be81 and d2153fe.

Files selected for processing: 10
  • packages/kumo-api/kumoapi/plugin.py
  • packages/kumo-core/src/kumo_core/artifacts.py
  • packages/kumo-core/src/kumo_core/chunked_fs.py
  • packages/kumo-core/src/kumo_core/object_store_sink.py
  • packages/kumo-core/tests/test_chunked_fs.py
  • packages/kumo-engine/kumo/engine/_scratch.py
  • packages/kumo-engine/kumo/engine/connector/__init__.py
  • packages/kumo-engine/kumo/engine/trainer/output_config.py
  • packages/kumo-engine/test/test_filestore_sink.py
  • packages/kumo-engine/test/test_prediction_completion.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 6 remain after this review.

Vedaant-J and others added 3 commits October 28, 2026 16:00
fit() read test_df.parquet from best_trainer.log_dir, which is whichever
refit stage ran last, not necessarily the model the bundle publishes. With
refit_full the published model has seen the test split, so its holdout is
meaningless.

Read the holdout from the published model's log dir (Trainer.published_fit_mode,
also used to pick the prediction model) and return none for refit_full.
get_log_dir takes an optional fit_mode override.

Verified: test_holdout_df (fit / refit_trainval with explain / refit_full),
test_training_explanations, test_semantic_carry_forward: 35 passed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Snapshot exports, model bundles and export manifests could only go to
object stores: the engine checked for ObjectStoreSinkBackend, and
output configs accepted output_paths only for S3, GCS, ADLS and local
connectors. A store that is not an object store (a Databricks volume, a
Snowflake stage) had no way in, even with a pyarrow filesystem to offer.

kumoapi.plugin.FileStoreSink is an optional sink capability:
holds_files(connector, path) says from the path alone whether it is a
file location rather than a table, and filesystem(connector, path)
returns the pyarrow filesystem. ObjectStoreSinkBackend implements it.
kumo.engine.connector.is_file_destination/file_store are the engine's
one file-vs-table gate; PredictionOutputConfig(output_paths=) and the
TrainingTableOutputConfig directory slash use it, so object stores
behave as before. kumo_core gains FilesystemSink (the object-store file
writers over any filesystem()), upload_bundle/download_bundle (the
manifest file last), open_sized (tells a chunked filesystem the size)
and PROVENANCE_FILE. The chunked filesystem streams a sized file of up
to one part as one plain object, writes frames through a local spool so
they stay plain too, spools under the engine scratch directory read at
each write, and reads parts into the caller's buffer with one copy.

Verified: test_chunked_fs.py (26), test_filestore_sink.py (protocol,
output configs, bundles and Parquet over a filesystem-only sink), file
connector, completion, preflight, registry and kumo-core export suites.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
test_artifacts.py's fake trainer borrows Trainer methods; select_fit_mode
now calls published_fit_mode, so the fake needs it too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Vedaant-J
Vedaant-J force-pushed the vedaant/mlops-filestore-sink branch from db74c6c to fc4d709 Compare October 28, 2026 16:25
@Vedaant-J
Vedaant-J temporarily deployed to gha-kumo-workflow-tests November 2, 2026 19:54 — with GitHub Actions Inactive

@Victsm Victsm left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two remaining data-integrity blockers. The chunked-filesystem implementation is unchanged from the independently reproduced version; the latest ADLS test does not cover these cases.

  1. Failed constructor: start with a.bin = b"preserve-me"; make _stream() raise while constructing _Writer(..., size=1). Finalization leaves a.bin = b"", because _failed is false and close() publishes the empty spool. Keep construction failed until fallible setup succeeds, clean up on failure, and test that finalization preserves the old bytes.
  2. Overlapping writers: with 16-byte parts, B writes 19 bytes; A commits the same destination and deletes B's unfinished first part; B writes 18 more bytes and commits. B's intended 37-byte file reads as 21 bytes despite _SUCCESS. Cleanup must preserve other unfinished/newer generations; readers should reject a committed part layout with gaps. Add that exact same-path regression.

These corroborate the two open bot findings: #112 (comment) and #112 (comment) . No new transactional filesystem subsystem is requested.

Approval prerequisites: fix both cases, pass the focused regressions plus the existing chunked-filesystem suite, propagate the correction through the stack, and complete required CI. The filesystem-only model/prediction adapter issues are already addressed; those are not additional open blockers.

Reviewed head: 3d3c9d896b8d3a0490f19864419457828c15dd91.

Vedaant-J and others added 2 commits November 2, 2026 20:07
@Vedaant-J
Vedaant-J temporarily deployed to gha-kumo-workflow-tests November 2, 2026 20:09 — with GitHub Actions Inactive
Vedaant-J added a commit that referenced this pull request Nov 2, 2026
Vedaant-J added a commit that referenced this pull request Nov 2, 2026
Vedaant-J added a commit that referenced this pull request Nov 2, 2026
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	packages/kumo-engine/docs/mlops.md
Vedaant-J added a commit that referenced this pull request Nov 2, 2026
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	packages/kumo-engine/docs/mlops.md
Vedaant-J added a commit that referenced this pull request Nov 2, 2026
Victsm
Victsm previously approved these changes Nov 3, 2026

@Victsm Victsm left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed this head. Failed-open cleanup preserves the existing file, and overlapping chunked writers no longer delete another active generation. Focused regressions and package/native CI cover the fixes. No remaining correctness blocker found in this scoped review.

@Vedaant-J
Vedaant-J temporarily deployed to gha-kumo-workflow-tests November 3, 2026 01:01 — with GitHub Actions Inactive
Vedaant-J added a commit that referenced this pull request Nov 3, 2026
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Vedaant-J added a commit that referenced this pull request Nov 3, 2026
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	packages/kumo-core/src/kumo_core/object_store_sink.py
@Vedaant-J
Vedaant-J temporarily deployed to gha-kumo-workflow-tests November 3, 2026 03:13 — with GitHub Actions Inactive

@Victsm Victsm left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed 09eef3a. The constructor-failure and overlapping-writer data-loss fixes remain intact; independent probes preserve the original object and the complete 37-byte concurrent payload. Reviewed the sink-routing consolidation and dependent-stack integration. No remaining code blocker found in this bounded pass. The restricted-BigQuery identity configuration failure remains a separate CI gate.

@Vedaant-J
Vedaant-J merged commit 43e66f1 into main Nov 3, 2026
122 of 123 checks passed
@Vedaant-J
Vedaant-J deleted the vedaant/mlops-filestore-sink branch November 3, 2026 19:49
Vedaant-J added a commit that referenced this pull request Nov 3, 2026
…114)

**Stack:** main (#53 merged) → #112 → **#114** → #50 → #60 → #64 → #115.
Sits between #112 and #50. Merge bottom to top.

## Summary

A `/Volumes/<catalog>/<schema>/<volume>/...` path is reachable only
through the FUSE mount on Databricks compute, so a training job on a
laptop, EC2 box or CI cannot publish a model or export scores to the
volume a Databricks job reads. This PR makes such a path a file
destination of `DatabricksConnector` from any machine. The sink
implements #112's `FileStoreSink` and reads and writes the volume
through the Databricks Files API with the connector's identity, reusing
#112's writers. Files up to 4 GiB are plain objects that Spark reads
directly; larger ones are stored as 4 GiB parts (the Files API caps one
upload at 5 GiB). No SQL warehouse is used.

## Usage

```python
root = "/Volumes/main/kumo/artifacts"
trainer.fit(training_table, snapshot=snapshot, export_config=ModelOutputConfig(
    databricks, path=f"{root}/models/churn"))
trainer = Trainer.load_from_connector(databricks, path=f"{root}/models/churn")
trainer.predict(prediction_table, snapshot=snapshot, output_config=PredictionOutputConfig(
    databricks, output_paths={"predictions": f"{root}/scores/"}))
```

The identity needs `USE CATALOG`, `USE SCHEMA`, `READ VOLUME` (load) and
`WRITE VOLUME` (export).

## Back-compat

| Situation | Behaviour |
|---|---|
| Table name on a `DatabricksConnector` | Unchanged: COPY INTO through
the staging volume. |
| Unity Catalog registry publish and fetch (`location=`) | Unchanged. |
| `/Volumes/...` path on a `DatabricksConnector` | Was refused; now
written through the Files API. |
| `/Volumes/...` string root on Databricks compute | Unchanged: a
`FileConnector` over FUSE. |
| Export into a volume directory that already holds files | Fails before
scoring starts: `Output directory '/Volumes/.../scores/' already
contains data from another export. Choose an empty destination path.` |
| Upload or download failure | `FileNotFoundError`, `PermissionError` or
`OSError` with the volume path; no signed URL in the message. A failed
write cancels its upload, so nothing is committed. |
| A file larger than 4 GiB read by Spark | A directory of
`<name>.chunks/<generation>/` parts; only kumo reads it as one file. |

## Testing

- `kumo-databricks/tests/test_volume.py` (10 tests, in-memory Files API
in `tests/fakes.py`): reads across part boundaries; sized writes plain
up to a part; failed and refused uploads; a download that ignores
`Range` is refused; directories and missing paths; bundle publish and
fetch, Parquet and frame exports through a volume path; an occupied
directory refused before scoring.
- Live with the rest of the series applied, on a test workspace with
synthetic data, off-cluster and in a cluster job: 3.0 GiB and 4.29 GiB
files round-trip with matching CRCs, a read across the 4 GiB part
boundary is exact, and a `kumo.mlops` fit and predict with the artifact
root on a volume writes snapshots, models and predictions there.

Change map: see the `kumo-pr-change-map` comment.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Vedaant-J added a commit that referenced this pull request Nov 3, 2026
**Stack:** main (#53 merged) → #112 → #114 → **#50** → #60 → #64 → #115.
Merge bottom to top.

## Summary

Every graph snapshot, training table and model bundle now carries a
self-contained `_provenance.json` that leads back to the source table
versions (and locations, wherever the source backend can name them),
query, plan and engine build that produced it. Today a model has no id,
an artifact records no lineage, an index works only on the machine that
built it, and scoring needs the training job's `Graph`.

This PR adds `kumo.MLOps` / `with kumo.mlops(...)` to store each
artifact once under one artifact root (`s3://`, `gs://`, local, or a
`(connector, path)` file store from #112); `GraphSnapshot.export` /
`load_from_connector` to move a checksummed index between machines;
`snapshot.source_changes(graph)` to see which tables changed since a
snapshot; and `Trainer.predict(snapshot)` to score a stored snapshot
with the trained query. `MLOps(on_error='raise')` turns a failed store
into a `RuntimeError` after the call finishes. Off unless asked for.

**Design decision:** for this release MLOps is opt-in per call or per
block (`mlops=` or `with kumo.mlops(...)`). A call outside both runs
without MLOps, and `on_error="raise"` does not detect that. A model- or
workflow-bound association with an explicit `mlops=False` was considered
and is left as a follow-up. See "Per call, not per model" in
`docs/mlops.md`.

## Usage

```python
cfg = kumo.MLOps("s3://<bucket>/kumo")             # store=True: snapshots, tables, models
with kumo.mlops(cfg):                               # or mlops=cfg on one call
    snapshot = graph.snapshot()
    result = trainer.fit(pq.generate_training_table(snapshot), snapshot=snapshot)

# Later, on another machine with no Graph code:
snapshot = GraphSnapshot.load_from_connector(cfg, id=result.snapshot_id)
trainer = Trainer.load_from_connector(cfg, path=f"models/{result.id}")
scores = trainer.predict(snapshot)
```

## Back-compat

Without a block or `mlops=`, existing calls behave as before.

| Situation | Behaviour |
|---|---|
| Index built before this PR | Reused, not rebuilt; its manifest is
backfilled with `"reconstructed": true`. |
| Bundle published before this PR | Loads and predicts identically; id
computed at load, `manifest` is `None`. |
| Artifact from this PR read by an older engine | Extra files are
ignored. |
| A single S3 or GCS object source | Versioned by VersionId or entity
tag, so its snapshot gets a new id once. |
| `verify_model_bundle` return value | 64 hex instead of a 16-hex digest
no caller used. |
| `DatabricksConnector(identity=...)` | Unchanged; `identity` is now
optional (ambient auth). |
| Manifest, sidecar or root write fails | A warning; the call completes
as before. A failed store raises a `RuntimeError` instead, once the call
has finished, with `MLOps(on_error='raise')`. |

## Testing

- kumo-engine: `test_snapshot_export.py` (round trip, reuse, interrupted
and concurrent exports, corrupt markers, `source_changes`, `on_error`),
`test_snapshot_manifest.py`, `test_training_table_export.py`,
`test_holdout_df.py` (published model's holdout, loaded and fetched
holdout, empty test split), `test_bundle_provenance.py`,
`test_query_from_snapshot.py`, `test_filestore_sink.py` (identical
bundle reused), `test_mlops.py`, `test_graph_mismatch.py`,
`test_artifacts.py`.
- kumo-core typed source versions, bundle ids and export sidecars;
kumo-s3 `test_sink_delete.py`; Snowflake, Databricks and BigQuery
identity tests assert `version_kind`.
- DiskGraph: Rust
`range_checksums_cover_every_listed_file_and_the_manifest`; pybind
`test_exception_exports.py`.
- Env-gated live S3 and GCS round trips in
`test_snapshot_export_live.py`.

Change map: see the `kumo-pr-change-map` comment.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Vedaant-J added a commit that referenced this pull request Nov 3, 2026
)

**Stack:** main (#53 merged) → #112 → #114 → #50 → **#60** → #64 → #115.
Merge bottom to top.

## Summary

This PR adds **experiment tracking and model registration for
`Trainer.fit`**. Before it, a fit reported progress only as progress-bar
text on stdout and could not record itself anywhere a team already
looks, and a chosen threshold had nowhere to live in the bundle.

- `kumo.MLOps(tracking=..., registry=...)` records each fit as one run
in MLflow (Databricks, SageMaker managed MLflow, any server) or
Snowflake Experiment Tracking. The run gets params, per-split metrics,
the search trials, and data summaries (split, health and column tables,
notes, and the source tables as datasets) read from the stats files the
builds already write. The model is then registered under an alias in
that tracker's registry.
- An MLflow-registered model is also a pyfunc, a platform adapter that
loads and scores it through MLflow's model API (for example Spark jobs)
without the training code. It does not replace `Trainer.predict`, the
batch prediction API.
`kumo.engine.integrations.mlflow.log_model(trainer, snapshot=...,
experiment_name=...)` logs one outside a fit, creating the experiment if
it is missing.
- `fit(callbacks=)` and `graph.snapshot(callbacks=)` receive progress
events. `fit(scoring_defaults=)` stores a threshold or top-k in the
bundle.

## Usage

```python
import kumo.engine as kumo
from kumo.engine.integrations.mlflow import MlflowTracking

cfg = kumo.MLOps("s3://<bucket>/kumo", tracking=MlflowTracking("users-churn"),
                 registry=kumo.ModelRegistryLocation("users-churn", alias="candidate"),
                 on_error="raise")
with kumo.mlops(cfg):
    snapshot = graph.snapshot()
    result = kumo.Trainer(plan).fit(table, snapshot=snapshot,
                                    scoring_defaults=kumo.ScoringDefaults(binary_classification_threshold=0.5))
result.registered_model   # PublishedModel(name='users-churn', version='1', uri='models:/users-churn/1', ...)
champion = kumo.Trainer.load_from_connector(cfg, location=kumo.ModelRegistryLocation("users-churn", alias="champion"))
```

Snowflake uses `SnowflakeTracking(connector, experiment_name=...)`. A
custom tracker implements `kumo.engine.tracking.Tracking`.

## Back-compat

| Situation | Behaviour |
|---|---|
| MLOps off, or `kumo.MLOps` without `tracking` and `registry` |
Unchanged. |
| A tracker raises, errors or hangs | Tracking runs on a background
thread on rank 0, so the fit is unaffected. `on_error="warn"` (default)
warns once; `"raise"` raises after the result is stored. |
| Binary `predict` without a threshold | Writes the probabilities and a
null `TARGET_PRED`; before, it raised. |
| Existing bundles (no `scoring-defaults.json`, no `dependencies`) |
Load and predict as before, with the same bundle ids. An explicit
argument always overrides a bundle default. |
| A bundle with `scoring-defaults.json` read by an older engine | The
file is listed and hash-checked, and the older engine ignores it. |
| Registry versions published before this PR | Listed and fetched as
before, with no `kumo_bundle_id`. |
| kumo-engine without the `mlflow` or `snowflake` extra | `import
kumo.engine` works. Building a tracker raises an `ImportError` naming
the extra. |

## Testing

- New engine tests: `test_fit_events.py`, `test_tracking_contract.py`,
`test_mlflow_tracking.py`, `test_mlflow_target.py`,
`test_mlflow_model.py`, `test_snowflake_tracking.py`,
`test_scoring_defaults.py`, `test_data_summaries.py`,
`test_summary_tables.py`, `test_model_agnostic_mlops.py`;
`test_trainer_registry.py` grows with registration, alias and
`registry=` cases.
- The MLflow tests use a real local SQLite store and a real CPU fit, and
check that the logged model scores the same as `Trainer.predict`.
Snowflake tests use a recording fake of `snowflake.ml.experiment` whose
signatures are checked against the installed library.
- Package tests: the kumo-snowflake and kumo-databricks registry tests
cover the bundle id, aliases and name checks. The kumo-core tests cover
searched params, prediction columns, the worker-handle fallback and
export column types.
- CI adds an `mlflow-floor` job that runs the MLflow suites on
mlflow-skinny 3.5.0.

## Also fixes

- pidfd fallback for sandboxes that refuse `pidfd_open`;
`encoder_selection` install hint; Optuna `ExperimentalWarning` filter
scoped to `analyze()`.
- kumo-core: stamping extra columns now stays in Arrow, so the all-null
TARGET_PRED a threshold-less binary predict writes keeps its bool type.
- kumo-core: searchers record the values each trial sampled, so tracked
trial runs and trial_started events carry their searched params.

Change map: see the `kumo-pr-change-map` comment.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Vedaant-J added a commit that referenced this pull request Nov 3, 2026
**Stack:** main (#53, #112, #114, #50, #60 merged) → **#64** → #115.
Merge bottom to top.

## Summary

Teams that score on a schedule cannot tell which model and data produced
a table of scores, whether the scores moved, or how good they were once
outcomes arrived. This PR records and monitors prediction runs:

- Every `Trainer.predict` writes a `PredictionManifest`
(`_provenance.json`): model, snapshot and source-table versions, scoring
options, destinations, skipped entities, and exact counts of its scores
on fixed bins. With MLOps on, the run is also stored under
`<root>/predictions/<id>/` and tracked.
- This is the durable path that `score_drift` and `evaluate` read. The
platform DataFrame adapters (the MLflow pyfunc's `predict`, a
warehouse's batch call) return scores but record no Kumo prediction run.
- Every model manifest keeps exact counts of its holdout scores as the
baseline. `Trainer.score_drift` gives PSI, KS and Wasserstein against
the holdout and a previous run, plus input-column drift;
`Trainer.evaluate` gives realized metrics once outcomes are in a newer
snapshot, with a DiskGraph join that keeps memory bounded. For link
prediction, PSI against the holdout is a plain number with no shift
verdict, since the holdout covers only entities with a future target;
every other task, multilabel included, gets one.
- Every tracker logs prediction and monitoring runs through shared hooks
(`SingleRunHooks`), with a Markdown run card, build time and size as
`prep.*` tags, and each dataset's role (`training examples`, `graph
context`, `scoring graph`, `labels`, ...) in the card's Lineage block.
Metric names are the same on MLflow and Snowflake, with `_at_` for `@`
(`test/map_at_10`).
- Chart data is logged as step metrics, not images:
`pred/score_histogram` (per class as `pred/score_histogram/<class>` for
multi-class and multilabel; step = score in hundredths),
`pred/prediction_histogram` (regression; step = the bin on the training
target's bins) and, for recommendations, `pred/item_popularity` (step =
item rank, top 100). Where the fit counted its holdout, `pred/holdout_*`
carries the holdout's counts on the same steps, scaled to the run's
total. The card's "Charts: step = ..." note says what each step is, and
`docs/mlops.md` shows how to overlay `pred/X` and `pred/holdout_X` in
the MLflow Chart view.
- `Trainer.evaluate` covers every task type. Entities the snapshot lacks
are skipped and counted, every skipped row is listed as Parquet under
`skipped/`, and `predict` raises only when nothing can be scored.
- On MLflow, a monitoring call folds into its prediction run, and the
fit's `test/*` holdout metrics are also logged on its logged model
without a dataset link, so the Models tab and Compare versions show one
`test/<metric>` column per version; the training table remains the run's
input dataset. Snowflake runs carry the card and a `kumo.model` param,
and tracking stops with a clear error at the experiment's 500-run limit.
The MLflow experiment note is a short list of the run filters.
- `examples/mlops` ships fit and score job templates for Databricks
Jobs, SageMaker Pipelines and Snowflake Tasks; `docs/mlops.md` has
recipes that feed exported evaluations to Databricks and Snowflake
warehouse monitors.

## Usage

```python
cfg = kumo.MLOps("s3://<bucket>/kumo", tracking=MlflowTracking("churn"))
with kumo.mlops(cfg):
    run = trainer.predict(snapshot, output_config=kumo.PredictionOutputConfig(conn, path="scores"))
    drift = trainer.score_drift(run, previous=earlier_run)        # psi, ks, wasserstein, features, reasons
    evaluation = trainer.evaluate(run, labels_snapshot=newer)     # metrics, matured, labelled_fraction
evaluation.export(kumo.PredictionOutputConfig(conn, path="scores_evaluated", write_mode=kumo.WriteMode.APPEND))
later = kumo.PredictionResult.load_from_connector(cfg, path=f"predictions/{run.id}")
```

## Back-compat

| Situation | Behaviour |
|---|---|
| Table destination | Replaced, as before. `WriteMode.APPEND` adds
`PREDICTION_ID` and `BUNDLE_ID`. |
| File destination that already holds data | Refused before scoring by
default or with `APPEND`; `OVERWRITE` empties it first. |
| Bundle from before this PR | Loads and scores as before; drift vs
holdout is `None` with a reason. |
| Manifest, statistics or store write fails | Warning, or the error
under `on_error="raise"` after outputs are written; predictions
unchanged. |
| Custom `Tracking` with fit hooks only | Still valid; prediction and
monitoring hooks are optional. |
| Custom `Tracking` reading `record.summaries` | `Series`, `Histogram`
and `Confusion` are new summary types; skip types you don't handle. |
| `diskgraph.compute_col_stats_for_parquet` callers | New options are
keyword-only and off; default output is byte-identical. |

## Testing

- kumo-core: `test_score_counts.py`, `test_evaluation_counts.py`,
`test_prediction_counts.py`, `test_score_drift.py` check every count and
drift statistic against a brute-force recount.
- kumo-engine: `test_monitoring.py` (27 tests: maturity, anchors,
exports, metric definitions, exact drift), `test_prediction_manifest.py`
(12), `test_tracking_contract.py`, `test_mlflow_tracking.py`,
`test_snowflake_tracking.py`, `test_card.py`, `test_score_stats.py`,
`test_dataset_lineage.py`, `test_summary_tables.py`,
`test_prediction_table_output.py`.
- `test_job_templates.py` runs `fit_job.py` then `score_job.py` end to
end on local Parquet.
- DiskGraph: `test_col_stats_options.py` pins the default statistics
output by SHA-256; Rust tests cover the evaluation join and value bins.

Change map: see the `kumo-pr-change-map` comment.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Vedaant-J added a commit that referenced this pull request Nov 3, 2026
…with run_batch (#115)

**Stack:** main (#53, #112, #114, #50, #60 merged) → #64 → **#115**.
Merge bottom to top.

## Summary

Teams whose data lives only in Snowflake have nowhere to keep Kumo
artifacts and cannot score a registered Kumo model inside Snowflake.
This PR adds both:

- **Stages as a file store.** A `@DB.SCHEMA.STAGE/...` path is a file
destination of `SnowflakeConnector` (#112's `FileStoreSink`, as #114
does for volumes): bundles, snapshot and prediction exports, and the
MLOps artifact root. Writes use `PUT`; reads use presigned ranged URLs,
falling back to one `GET` per file. Files up to 4 GiB are plain objects;
larger ones are parts only kumo reads.
- **Runnable registry versions.** With kumo-engine installed, a version
registered in the Snowflake Model Registry is a `KumoModel` that scores
entity ids against a stage snapshot in Snowpark Container Services
(`ModelVersion.run_batch` on a GPU pool). kumo-snowflake finds the
builder through the `kumo_snowflake.registry_models` entry point.
Registering a bundle again reuses its version when the serving
environment matches.

In the container, the snapshot and the stage assets are read with the
container's own Snowflake identity (`_snowflake_serving.py`).

## Usage

```python
sf = kumo.SnowflakeConnector(warehouse="WH", database="ML", schema_name="MODELS")
cfg = kumo.MLOps((sf, "@ML.MODELS.KUMO"), tracking=SnowflakeTracking(sf, experiment_name="CHURN"),
                 registry=kumo.ModelRegistryLocation("CHURN_GNN", alias="champion"))
with kumo.mlops(cfg):                    # the version serves the fit's snapshot on the stage
    result = trainer.fit(train_table, snapshot=snapshot)

mv = Registry(session, database_name="ML", schema_name="MODELS").get_model("CHURN_GNN").version("champion")
mv.run_batch(session.sql("SELECT ID::STRING AS ENTITY FROM ML.MODELS.USERS"), compute_pool="KUMO_GPU_POOL",
             output_spec=OutputSpec(stage_location="@ML.MODELS.KUMO_OUT/churn/"))
```

## Back-compat

| Situation | Behaviour |
|---|---|
| Table name on a `SnowflakeConnector` | Unchanged. |
| `@DB.SCHEMA.STAGE/...` path | Was refused; now written to the stage. |
| Registering from a non-Linux-x86_64 host, or with a `python_version`
or `cuda_version` other than the installed one | Raises at registration.
|
| Export into a stage directory that already holds files | Refused
before scoring by default or with `APPEND`; `OVERWRITE` empties it
first, as on every file store. |
| `SNOWFLAKE_FULL` stage | Writes work; reads raise `OSError` naming
`SNOWFLAKE_SSE`. |
| Registry publish without kumo-engine, or if the builder fails | The
non-scoring carrier, as before (with a warning). |
| Same bundle registered again | Existing version if the serving
environment matches; else a new `V<n>`. |
| `ModelOutputConfig`, `SnowflakeTracking` | New optional
`serving_snapshot` / `serving_options`; existing calls unchanged. |
| `run_batch` output | Scores only; not a Kumo prediction run for
`evaluate` or `score_drift`. |

## Testing

- `kumo-snowflake/tests/test_stage_fs.py` (in-memory stage): routing,
bundles and Parquet through a stage path, listings, exact removes,
ranged and `GET` reads, the occupied-directory rule, refusals, no signed
URL in errors.
- `kumo-snowflake/tests/test_registry.py`: version reuse, builder
arguments, environment refusal, carrier fallback, bundle-only fetch.
- `kumo-engine/test/test_snowflake_model.py` and
`test_model_agnostic_mlops.py`: a version packaged by snowflake-ml
scores like `Trainer.predict`; serving options; staged assets load
through the loading connector; a stage root registers versions serving
its snapshot.
- Live on a Snowflake test account with synthetic data: stage file store
and an MLOps root on a stage; `run_batch` binary (300/300 rows, labels
equal to local `predict`) and regression on a GPU pool; all steps as a
role with only the documented grants.

Change map: see the `kumo-pr-change-map` comment.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

This branch was previously deployed

1 inactive deployment
gha-kumo-workflow-tests — 09eef3a2 Deployed Nov 3, 2026 by Vedaant-J via import #1330
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants