Skip to content

Feat: Metastore - #1424

Merged
nikhilsinhaparseable merged 11 commits into
parseablehq:mainfrom
parmesant:metastore
Sep 11, 2025
Merged

nikhilsinhaparseable merged 11 commits into
parseablehq:mainfrom
parmesant:metastore

Conversation

@parmesant

@parmesant parmesant commented Sep 5, 2025 •

Copy link
Copy Markdown
Contributor

This PR introduces Metastore to Parseable. Anything that is not parquet can be considered as metadata. Up till now, all metadata was stored as objects in object-storage. The new traits Metastore and MetastoreObject allow users to implement their own metastores. By default, Parseable uses Object store as metastore.

Description


This PR has:

  • been tested to ensure log ingestion and log query works.
  • added comments explaining the "why" and the intent of the code wherever would not be obvious for an unfamiliar reader.
  • added documentation for new or modified features or behaviors.

Summary by CodeRabbit

  • New Features

    • Central Metastore added and exposed as a public capability.
  • Refactor

    • Platform-wide migration: metadata reads/writes moved from object-store files to the Metastore across alerts, streams, manifests, schemas, dashboards, filters, targets, correlations, chats, nodes, and tooling.
  • User-visible behavior

    • Listings, metadata endpoints, and persistence now use Metastore-backed data; Metastore failures surface as structured JSON error details.
  • Chores

    • Two new dependencies added to the build.

@coderabbitai

coderabbitai Bot commented Sep 5, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Moves metadata I/O and listing from direct object storage into a new Metastore abstraction, adds Metastore/MetastoreObject traits and ObjectStore-backed Metastore, wires an Arc into Parseable, implements MetastoreObject for many domain types, and propagates MetastoreError handling across handlers, storage, catalog, migration, and query flows.

Changes

Cohort / File(s) Summary
Dependencies
Cargo.toml
Adds erased-serde = "=0.3.16" and dashmap = "6.1.0".
Metastore core & wiring
src/lib.rs, src/metastore/mod.rs, src/metastore/metastore_traits.rs, src/metastore/metastores/mod.rs, src/metastore/metastores/object_store_metastore.rs, src/parseable/mod.rs
Adds public metastore module, MetastoreError/MetastoreErrorDetail, Metastore and MetastoreObject traits (erased-serde trait-object support), ObjectStoreMetastore implementation, and adds Parseable.metastore: Arc<dyn Metastore> with constructor/init updates.
Alerts subsystem
src/alerts/*
Implements MetastoreObject for AlertConfig/ThresholdAlert/Target; makes AlertTrait require MetastoreObject; migrates alert/target CRUD, v1 migration, loading and persistence to PARSEABLE.metastore; adds MetastoreError variants and HTTP mapping.
Catalog / Manifests / Snapshot
src/catalog/*, src/catalog/manifest.rs
Replaces object-store snapshot/manifest I/O with metastore APIs (get_stream_json, get_manifest, put_manifest, get_manifest_path, put_stream_json); removes object-store parameters from public signatures (e.g., update_snapshot).
Query & schema provider
src/query/*, src/query/stream_schema_provider.rs
Switches stream/manifest discovery to metastore (get_all_stream_jsons, get_manifest), updates collect_from_snapshot and related signatures, and adapts manifest aggregation/pruning to operate on Manifest objects returned by metastore.
Enterprise / Hot-tier / utils
src/enterprise/utils.rs, src/hottier.rs
Reworks manifest and stream-json collection to use metastore (get_stream_json, get_all_manifest_files/get_all_stream_jsons), removes previous object-store helpers and parameters.
HTTP handlers & modal
src/handlers/http/*, src/handlers/http/modal/*
Replaces object-store I/O with metastore calls across many handlers; adds MetastoreError variants to handler error enums and returns structured JSON details for metastore failures; updates modal/node metadata flows and cluster metrics/query routing.
Users: dashboards, filters, correlations
src/users/*, src/correlation.rs
Implements MetastoreObject for Dashboard/Filter/CorrelationConfig, migrates CRUD to metastore (load/save/delete), updates signatures (e.g., dashboards.save), exposes filter migration helper, and wires MetastoreError into public errors.
Storage trait & backends
src/storage/object_storage.rs, src/storage/mod.rs, src/storage/{s3,gcs,azure_blob,localfs}.rs, src/storage/store_metadata.rs
Adds list_with_delimiter to ObjectStorage; removes legacy get_all_* manifest helpers; introduces ObjectStorageError::MetastoreError; renames create_schema_from_storage→create_schema_from_metastore; backends implement or stub list_with_delimiter; implements MetastoreObject for StorageMetadata/ObjectStoreFormat (some methods unimplemented).
Migration & staging
src/migration/mod.rs, src/storage/store_metadata.rs
Moves migration I/O to metastore (list_streams, get/put_stream_json, put_schema, put_parseable_metadata); updates put_remote_metadata signature; implements MetastoreObject for StorageMetadata.
Misc small fixes
many files (e.g., src/parseable/streams.rs, src/users/dashboards.rs, src/catalog/manifest.rs)
Minor error-handling fixes (unwrap→?), add CURRENT_DASHBOARD_VERSION, numerous get_object_path/get_object_id impls (some stubbed), and propagate metastore imports and error mappings across modules.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant HTTP as HTTP Handler
  participant MS as Metastore
  participant State as In-memory State

  Client->>HTTP: POST /alerts
  HTTP->>HTTP: validate & build AlertConfig
  HTTP->>MS: put_alert(AlertConfig)
  MS-->>HTTP: ok / MetastoreError (detail)
  alt success
    HTTP->>State: insert/update in-memory + schedule task
    HTTP-->>Client: 201 Created
  else metastore error
    HTTP-->>Client: 4xx/5xx JSON (MetastoreError.to_detail)
  end
Loading
sequenceDiagram
  autonumber
  participant Updater as catalog::update_snapshot
  participant MS as Metastore
  participant Worker as Snapshot Processor

  Updater->>MS: get_stream_json(stream, base?)
  MS-->>Updater: Bytes(JSON)
  Updater->>MS: get_manifest_path(stream, lower, upper)
  MS-->>Updater: manifest_path
  Updater->>MS: get_manifest(stream, lower, upper, Some(manifest_path))
  MS-->>Updater: Manifest / None
  Updater->>Worker: process partition groups (using retrieved Manifests)
  Worker->>MS: put_manifest(...), put_stream_json(...)
  MS-->>Worker: ack / MetastoreError
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~150 minutes

Possibly related PRs

Suggested labels

for next release

Suggested reviewers

  • nikhilsinhaparseable
  • de-sh

"🐰 I hopped through JSON paths galore,
I gathered manifests and stored them in one store.
Alerts and dashboards tucked in rows,
Metastore hums — and onward the data flows.
I twitch my whiskers and code some more."

Pre-merge checks (2 passed, 1 inconclusive)

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Description Check ❓ Inconclusive The PR description gives a high-level summary ("introduces Metastore") and the checklist from the template but does not fully follow the repository template: the detailed "Description" sections (goals, alternative solutions and chosen rationale, and an explicit key-changes list) are not filled out and the checklist remains unchecked, leaving important reviewer-facing details unspecified. Because the description is informative but incomplete for the scope of changes (many public API and migration-affecting edits), the result is inconclusive for review readiness. Please update the PR description to fully follow the template: add explicit goals and the chosen solution rationale, enumerate the major key changes (e.g., new Metastore and MetastoreObject traits, MetastoreError and metastore module, notable public API/signature changes and files affected, and migration steps from object-storage to metastore), indicate any breaking changes and required migrations, and complete the checklist with test results (ingestion/query) and documentation notes; once those details are provided the description check can be re-evaluated.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title "Feat: Metastore" is short, a single concise sentence, and directly reflects the primary change in the changeset (adding a Metastore abstraction and related integrations). It avoids extraneous details and is clear enough for a reviewer scanning history to understand the main intent. It therefore satisfies the repository's title guidance.
Docstring Coverage ✅ Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 29

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (18)
src/handlers/http/modal/query/querier_logstream.rs (1)

69-107: Ensure Metastore Metadata Is Purged in Querier Delete Handler
In src/handlers/http/modal/query/querier_logstream.rs (lines 69–107), after deleting storage and local dirs but before notifying ingestors, invoke a delete_stream (or equivalent) async method on the Metastore to remove persistent metadata (stream.json, schemas, manifests). The current Metastore trait (src/metastore/metastore_traits.rs) only defines initiate_connection and list_objects, so introduce and implement a delete_stream API for atomic, idempotent cleanup.

src/handlers/http/modal/utils/rbac_utils.rs (1)

34-38: Writes also bypass Metastore here.

Align writes with the new read-path to support non-object-store metastores.

 pub async fn put_metadata(metadata: &StorageMetadata) -> Result<(), ObjectStorageError> {
-    storage::put_remote_metadata(metadata).await?;
-    storage::put_staging_metadata(metadata)?;
-    Ok(())
+    PARSEABLE
+        .metastore
+        .put_parseable_metadata(metadata)
+        .await
+        .map_err(|e| ObjectStorageError::MetastoreError(Box::new(e.to_detail())))
 }
src/alerts/target.rs (1)

98-120: Delete ordering can leave dangling persisted state on failure

Currently removes from memory, then deletes from metastore. If delete_target() fails, the entry vanishes from memory but remains persisted.

-        let target = self
-            .target_configs
-            .write()
-            .await
-            .remove(target_id)
-            .ok_or(AlertError::InvalidTargetID(target_id.to_string()))?;
-        PARSEABLE.metastore.delete_target(&target).await?;
-        Ok(target)
+        // Fetch a clone first, persist delete, then remove from memory
+        let target = {
+            let map = self.target_configs.read().await;
+            map.get(target_id)
+                .cloned()
+                .ok_or(AlertError::InvalidTargetID(target_id.to_string()))?
+        };
+        PARSEABLE.metastore.delete_target(&target).await?;
+        let _ = self.target_configs.write().await.remove(target_id);
+        Ok(target)
src/handlers/http/modal/ingest_server.rs (1)

307-329: Prevent panic on missing token and reconcile all ingestor metadata
Avoid using unwrap() on the "token" field—this will panic if the key is absent or not a string. Instead, parse every metadata entry to collect its "token" string, return an error if any entry lacks a valid token or if multiple distinct tokens are found, then compare the computed Basic credential against that single, verified token.

src/prism/home/mod.rs (1)

339-343: Preserve MetastoreError semantics instead of wrapping into Anyhow

You already added PrismHomeError::MetastoreError(#[from]). Let ? convert MetastoreError directly so status codes and JSON details are preserved.

-        .list_streams()
-        .await
-        .map_err(|e| PrismHomeError::Anyhow(anyhow::Error::new(e)))?
+        .list_streams()
+        .await?
src/handlers/http/logstream.rs (3)

89-95: Avoid panic: propagate Metastore errors instead of unwrap()

Using unwrap() will 500/panic the handler on metastore failures. Propagate as StreamError::MetastoreError.

Apply:

-    let res = PARSEABLE
-        .metastore
-        .list_streams()
-        .await
-        .unwrap()
+    let res = PARSEABLE
+        .metastore
+        .list_streams()
+        .await?

399-426: Hot-tier enable flow: fix available_size math and make in-memory flip after persistence succeeds

  • available_size should reflect remaining capacity (size - used).
  • set_hot_tier(true) before persistence can leave memory inconsistent if downstream ops fail.

Apply:

-    stream.set_hot_tier(true);
     let Some(hot_tier_manager) = HotTierManager::global() else {
         return Err(StreamError::HotTierNotEnabled(stream_name));
     };
     let existing_hot_tier_used_size = hot_tier_manager
         .validate_hot_tier_size(&stream_name, hottier.size)
         .await?;
     hottier.used_size = existing_hot_tier_used_size;
-    hottier.available_size = hottier.size;
+    hottier.available_size = hottier.size.saturating_sub(existing_hot_tier_used_size);
     hottier.version = Some(CURRENT_HOT_TIER_VERSION.to_string());
     hot_tier_manager
         .put_hot_tier(&stream_name, &mut hottier)
         .await?;
 
     let mut stream_metadata: ObjectStoreFormat = serde_json::from_slice(
         &PARSEABLE
             .metastore
             .get_stream_json(&stream_name, false)
             .await?,
     )?;
     stream_metadata.hot_tier_enabled = true;
 
     PARSEABLE
         .metastore
         .put_stream_json(&stream_metadata, &stream_name)
         .await?;
+
+    // Flip in-memory flag only after all side effects succeed
+    stream.set_hot_tier(true);

452-481: On hot-tier delete, also flip metastore flag hot_tier_enabled = false

Symmetry with put_stream_hot_tier prevents stale metadata.

Apply:

     hot_tier_manager.delete_hot_tier(&stream_name).await?;
 
+    // Reflect deletion in metastore metadata
+    let mut stream_metadata: ObjectStoreFormat = serde_json::from_slice(
+        &PARSEABLE
+            .metastore
+            .get_stream_json(&stream_name, false)
+            .await?,
+    )?;
+    stream_metadata.hot_tier_enabled = false;
+    PARSEABLE
+        .metastore
+        .put_stream_json(&stream_metadata, &stream_name)
+        .await?;
+
     Ok((
         format!("hot tier deleted for stream {stream_name}"),
         StatusCode::OK,
     ))
src/enterprise/utils.rs (1)

81-91: Don’t swallow metastore errors from get_all_stream_jsons.

Swallowing Err hides real failures and yields partial results. Propagate as ObjectStorageError (MetastoreError) and continue.

-    let obs = PARSEABLE.metastore.get_all_stream_jsons(stream, None).await;
-    if let Ok(obs) = obs {
-        for ob in obs {
-            if let Ok(object_store_format) = serde_json::from_slice::<ObjectStoreFormat>(&ob) {
-                let snapshot = object_store_format.snapshot;
-                for manifest in snapshot.manifest_list {
-                    merged_snapshot.manifest_list.push(manifest);
-                }
-            }
-        }
-    }
+    let obs = PARSEABLE
+        .metastore
+        .get_all_stream_jsons(stream, None)
+        .await
+        .map_err(|e| ObjectStorageError::MetastoreError(Box::new(e)))?;
+    for ob in obs {
+        if let Ok(object_store_format) = serde_json::from_slice::<ObjectStoreFormat>(&ob) {
+            let snapshot = object_store_format.snapshot;
+            merged_snapshot.manifest_list.extend(snapshot.manifest_list);
+        }
+    }
src/catalog/mod.rs (2)

300-347: Fragile path check can duplicate manifests; always fetch via Metastore.

Relying on contains(manifest_path("")) can skip updates for metastore-backed paths, causing duplicate manifests for the same partition. Remove the path heuristic and use Metastore as the single source of truth.

-    let manifest_file_name = manifest_path("").to_string();
-    let should_update = manifests[pos].manifest_path.contains(&manifest_file_name);
-
-    if should_update {
-        if let Some(mut manifest) = PARSEABLE
+    if let Some(mut manifest) = PARSEABLE
             .metastore
             .get_manifest(
                 stream_name,
                 manifests[pos].time_lower_bound,
                 manifests[pos].time_upper_bound,
             )
             .await
             .map_err(|e| ObjectStorageError::MetastoreError(Box::new(e.to_detail())))?
-        {
+    {
         // Update existing manifest
         for change in partition_changes {
             manifest.apply_change(change);
         }
         PARSEABLE
             .metastore
             .put_manifest(
                 &manifest,
                 stream_name,
                 manifests[pos].time_lower_bound,
                 manifests[pos].time_upper_bound,
             )
             .await
             .map_err(|e| ObjectStorageError::MetastoreError(Box::new(e.to_detail())))?;
 
         manifests[pos].events_ingested = events_ingested;
         manifests[pos].ingestion_size = ingestion_size;
         manifests[pos].storage_size = storage_size;
         Ok(None)
-        } else {
-            // Manifest not found, create new one
-            create_manifest(
-                partition_lower,
-                partition_changes,
-                stream_name,
-                false,
-                meta.clone(),
-                events_ingested,
-                ingestion_size,
-                storage_size,
-            )
-            .await
-        }
-    } else {
-        // Create new manifest for different partition
-        create_manifest(
-            partition_lower,
-            partition_changes,
-            stream_name,
-            false,
-            ObjectStoreFormat::default(),
-            events_ingested,
-            ingestion_size,
-            storage_size,
-        )
-        .await
-    }
+    } else {
+        // Manifest not found, create new one
+        create_manifest(
+            partition_lower,
+            partition_changes,
+            stream_name,
+            false,
+            meta.clone(),
+            events_ingested,
+            ingestion_size,
+            storage_size,
+        )
+        .await
+    }

482-499: Inconsistent persistence: read from Metastore, write to object storage.

remove_manifest_from_snapshot loads stream JSON via Metastore but writes snapshot via storage.put_snapshot(...). This will diverge state between Metastore and object store.

-        storage.put_snapshot(stream_name, meta.snapshot).await?;
+        PARSEABLE
+            .metastore
+            .put_stream_json(&meta, stream_name)
+            .await
+            .map_err(|e| ObjectStorageError::MetastoreError(Box::new(e.to_detail())))?;
src/handlers/http/cluster/mod.rs (3)

510-522: Don't panic on malformed stream.json; return a typed error instead.

Using expect(...) will crash the node on a single bad entry. Propagate SerdeError as StreamError to keep the cluster healthy.

-        let stream_metadata: ObjectStoreFormat =
-            serde_json::from_slice(&ob).expect("stream.json is valid json");
+        let stream_metadata: ObjectStoreFormat =
+            serde_json::from_slice(&ob).map_err(StreamError::SerdeError)?;

1065-1099: Type mismatch: QuerierStatus holds QuerierMetadata but you populate it with NodeMetadata.

This won’t compile. Either change QuerierStatus.metadata to NodeMetadata everywhere or request QuerierMetadata from get_node_info. The latter is minimal.

-    let querier_metadata: Vec<NodeMetadata> = get_node_info(NodeType::Querier).await?;
+    let querier_metadata: Vec<QuerierMetadata> =
+        get_node_info::<QuerierMetadata>(NodeType::Querier).await?;
...
-    let liveness_results: Vec<(String, bool, NodeMetadata)> = stream::iter(querier_metadata)
+    let liveness_results: Vec<(String, bool, QuerierMetadata)> =
+        stream::iter(querier_metadata)

1016-1037: Invalid if-let chain; this won’t compile on stable.

Rewrite to first unwrap Result, then guard on is_empty().

-                let cluster_metrics = fetch_cluster_metrics().await;
-                if let Ok(metrics) = cluster_metrics
-                    && !metrics.is_empty()
-                {
+                let cluster_metrics = fetch_cluster_metrics().await;
+                if let Ok(metrics) = cluster_metrics {
+                    if metrics.is_empty() {
+                        return Ok(());
+                    }
                     info!("Cluster metrics fetched successfully from all ingestors");
                     if let Ok(metrics_bytes) = serde_json::to_vec(&metrics) {
src/alerts/mod.rs (1)

987-1079: Do not hold a write lock across awaits; also don’t swallow metastore errors.

load() acquires a write lock on self.alerts and then awaits multiple times (metastore calls, serde, sender.send). This can deadlock and blocks readers. In addition, unwrap_or_default() on get_alerts() silently hides metastore failures and can boot with zero alerts.

Refactor to:

  • Fetch and migrate alerts without any lock.
  • Acquire a short write lock only to insert.
  • Propagate (or at least log) metastore errors.

Apply this diff:

@@
-    async fn load(&self) -> anyhow::Result<()> {
-        let mut map = self.alerts.write().await;
-
-        // Get alerts path and read raw bytes for migration handling
-        let raw_objects = PARSEABLE.metastore.get_alerts().await.unwrap_or_default();
+    async fn load(&self) -> anyhow::Result<()> {
+        // Read raw alerts from metastore; fail fast on storage issues
+        let raw_objects = PARSEABLE
+            .metastore
+            .get_alerts()
+            .await
+            .map_err(|e| anyhow::anyhow!("failed to read alerts from metastore: {e}"))?;
@@
-            // Create alert task iff alert's state is not paused
+            // Create alert task iff alert's state is not paused
             if alert.get_state().eq(&AlertState::Disabled) {
-                map.insert(*alert.get_id(), alert);
+                {
+                    let mut map = self.alerts.write().await;
+                    map.insert(*alert.get_id(), alert);
+                }
                 continue;
             }
@@
-            map.insert(*alert.get_id(), alert);
+            {
+                let mut map = self.alerts.write().await;
+                map.insert(*alert.get_id(), alert);
+            }
src/storage/azure_blob.rs (1)

687-689: Fix absolute_url: pass &str, not RelativePath.

object_store::path::Path::parse expects &str. Current call likely won’t compile.

Apply this diff:

-    fn absolute_url(&self, prefix: &RelativePath) -> object_store::path::Path {
-        object_store::path::Path::parse(prefix).unwrap()
-    }
+    fn absolute_url(&self, prefix: &RelativePath) -> object_store::path::Path {
+        object_store::path::Path::parse(prefix.as_str()).unwrap()
+    }
src/storage/object_storage.rs (2)

143-156: Defensive parsing for date=… in filenames to avoid panics

Indexing [0]/[1] will panic on unexpected names. Parse safely and error out cleanly.

-    let mut file_date_part = filename.split('.').collect::<Vec<&str>>()[0];
-    file_date_part = file_date_part.split('=').collect::<Vec<&str>>()[1];
+    let file_date_part = filename
+        .split('.')
+        .next()
+        .and_then(|s| s.split_once('=').map(|(_, v)| v))
+        .ok_or_else(|| ObjectStorageError::Custom(format!("unexpected data file name: {filename}")))?;

989-1010: Avoid panic on Schema::try_merge; return proper error and consider missing-base handling

unwrap() will crash the process on merge conflicts. Map errors and, ideally, handle “schema not found” by seeding with the incoming schema.

-    let stream_schema = PARSEABLE
-        .metastore
-        .get_schema(stream_name)
-        .await
-        .map_err(|e| ObjectStorageError::MetastoreError(Box::new(e.to_detail())))?;
-
-    let new_schema = Schema::try_merge(vec![
-        schema,
-        serde_json::from_slice::<Schema>(&stream_schema)?,
-    ])
-    .unwrap();
+    let stream_schema = PARSEABLE
+        .metastore
+        .get_schema(stream_name)
+        .await
+        .map_err(|e| ObjectStorageError::MetastoreError(Box::new(e.to_detail())))?;
+
+    let new_schema = Schema::try_merge(vec![
+        serde_json::from_slice::<Schema>(&stream_schema)?,
+        schema,
+    ])
+    .map_err(|e| ObjectStorageError::Custom(format!("Schema merge failed: {e}")))?;

Follow-up: If get_schema can return a not-found error, treat that case by writing the incoming schema directly instead of failing. Want a patch for that as well?

🧹 Nitpick comments (46)
Cargo.toml (1)

61-61: Relax erased-serde version pin
Use a caret‐range to allow patch fixes within 0.3.x (<0.4) while avoiding unintended 0.4.x upgrades with a potentially higher MSRV:

- erased-serde = "=0.3.16"
+ erased-serde = "^0.3.16"  # equivalent to >=0.3.16, <0.4

0.3.16 is unyanked and this lets you pick up all subsequent 0.3-patches.

src/handlers/http/modal/query/querier_logstream.rs (1)

165-189: Good switch to metastore-backed retrieval; improve diagnostics on parse failures

Using PARSEABLE.metastore.get_all_stream_jsons is the right direction. Minor nit: include an identifier (e.g., source node or object id) in the error to aid debugging when a particular stream.json is malformed.

Example:

- error!("Failed to parse stream metadata: {:?}", e);
+ error!("Failed to parse stream metadata for {}: {:?}", stream_name, e);
src/handlers/http/ingest.rs (1)

517-526: JSON error body for MetastoreError matches other handlers

Consistent with logstream/filters handlers. Consider centralizing this pattern to avoid repetition across enums, but not blocking.

src/storage/mod.rs (1)

289-291: New error variant is fine; consider Display over Debug for the detail.

Using {:?} may leak internal structure. Prefer {0} if MetastoreErrorDetail implements Display, else keep as-is.

-    #[error("MetastoreError: {0:?}")]
+    #[error("MetastoreError: {0}")]
     MetastoreError(Box<MetastoreErrorDetail>),
src/handlers/http/mod.rs (1)

92-95: Handle empty schema list explicitly for clearer errors.

Schema::try_merge errors on empty input; return a targeted error when no schemas exist for the stream.

 pub async fn fetch_schema(stream_name: &str) -> anyhow::Result<arrow_schema::Schema> {
-    let res: Vec<Schema> = PARSEABLE.metastore.get_all_schemas(stream_name).await?;
+    let res: Vec<Schema> = PARSEABLE.metastore.get_all_schemas(stream_name).await?;
+    if res.is_empty() {
+        anyhow::bail!("No schema found for stream '{}'", stream_name);
+    }
 
     let new_schema = Schema::try_merge(res)?;
     Ok(new_schema)
 }
src/handlers/http/users/dashboards.rs (2)

271-278: Make JSON error responses consistent with the rest of the codebase

Other modules explicitly set ContentType::json() when serializing metastore errors. Align for consistency.

-        match self {
-            DashboardError::MetastoreError(e) => {
-                actix_web::HttpResponse::build(self.status_code()).json(e.to_detail())
-            }
+        match self {
+            DashboardError::MetastoreError(e) => {
+                actix_web::HttpResponse::build(self.status_code())
+                    .insert_header(ContentType::json())
+                    .json(e.to_detail())
+            }

236-254: Remove dead DashboardError::ObjectStorage variant
DashboardError::ObjectStorage is never constructed or propagated—no code path in src/handlers/http/users/dashboards.rs invokes or maps an ObjectStorageError into this variant—so it can be removed to reduce noise.

src/handlers/http/alerts.rs (1)

263-263: Delete ordering — consider stopping the task before removing from memory

You delete in metastore, then from memory, then cancel the scheduled task. Flipping the last two reduces the window where a running task may reference a now-missing memory entry.

src/prism/home/mod.rs (1)

229-231: LGTM: switch to metastore for stream metadata

Using get_all_stream_jsons(&stream, None) aligns with the new abstraction. Consider paging/streaming later if this grows large, but fine for now.

src/query/mod.rs (3)

549-563: Parallelize manifest fetches to reduce latency.

Fetching each manifest sequentially increases tail latency. Fire them concurrently and collect.

-    let mut all_manifest_files = Vec::new();
-    for manifest_item in merged_snapshot.manifests(&time_filter) {
-        // (fetch each serially)
-    }
+    use futures::future;
+    let futures = merged_snapshot
+        .manifests(&time_filter)
+        .into_iter()
+        .map(|mi| async move {
+            PARSEABLE
+                .metastore
+                .get_manifest(stream_name, mi.time_lower_bound, mi.time_upper_bound)
+                .await
+                .and_then(|m| m.ok_or_else(|| QueryError::CustomError("Missing manifest".into())))
+        });
+    let all_manifest_files: Vec<Manifest> = future::try_join_all(futures).await?;

525-542: Guard against duplicate manifest entries when merging snapshots.

If multiple stream JSONs contain overlapping manifest_list entries, duplicates can slip in. Deduplicate by (time_lower_bound, time_upper_bound) or by manifest path before iterating.

-    if let Ok(obs) = obs {
-        for ob in obs {
-            if let Ok(object_store_format) = serde_json::from_slice::<ObjectStoreFormat>(&ob) {
-                let snapshot = object_store_format.snapshot;
-                for manifest in snapshot.manifest_list {
-                    merged_snapshot.manifest_list.push(manifest);
-                }
-            }
-        }
-    }
+    if let Ok(obs) = obs {
+        use std::collections::BTreeSet;
+        let mut seen = BTreeSet::new();
+        for ob in obs {
+            if let Ok(object_store_format) = serde_json::from_slice::<ObjectStoreFormat>(&ob) {
+                for m in object_store_format.snapshot.manifest_list {
+                    // adjust key as appropriate (e.g., include m.manifest_path if available)
+                    let key = (m.time_lower_bound, m.time_upper_bound);
+                    if seen.insert(key) {
+                        merged_snapshot.manifest_list.push(m);
+                    }
+                }
+            }
+        }
+    }

564-575: Remove stale commented-out code.

The old object-store path is fully replaced. Keeping large commented blocks adds noise.

-    // let all_manifest_files = collect_manifest_files(
-    //     object_store,
-    //     merged_snapshot
-    //         .manifests(&time_filter)
-    //         .into_iter()
-    //         .sorted_by_key(|file| file.time_lower_bound)
-    //         .map(|item| item.manifest_path)
-    //         .collect(),
-    // )
-    // .await
-    // .map_err(|err| anyhow::Error::msg(err.to_string()))?;
+    // (old object-store manifest collection removed)
src/hottier.rs (2)

276-285: Wrap metastore errors without type erasure or misclassification.

Mapping metastore errors into ObjectStorageError::MetastoreError(Box::new(e.to_detail())) risks losing the original type and may not match the variant’s expected payload. Prefer a dedicated HotTierError variant or map directly to HotTierError::Anyhow while preserving the original error string. Also, variable name s3_manifest_file_list no longer reflects the source.

-        let mut s3_manifest_file_list = PARSEABLE
+        let mut manifest_map = PARSEABLE
             .metastore
             .get_all_manifest_files(&stream)
             .await
-            .map_err(|e| {
-            HotTierError::ObjectStorageError(ObjectStorageError::MetastoreError(Box::new(
-                e.to_detail(),
-            )))
-        })?;
+            .map_err(|e| HotTierError::Anyhow(e.into()))?;

Optionally, introduce a dedicated error variant:

 pub enum HotTierError {
+    #[error("{0}")]
+    Metastore(#[from] crate::metastore::error::MetastoreError),
 }

308-312: Avoid duplicate downloads when the same file appears in multiple manifests.

If a file is present in multiple Manifest objects for a date, the current extend(...) can enqueue duplicates (later skipped by exists(), but still extra work). Dedup by file_path when building storage_combined_manifest.

-        for storage_manifest in manifest_files {
-            storage_combined_manifest
-                .files
-                .extend(storage_manifest.files.clone());
-        }
+        use std::collections::HashSet;
+        let mut seen = HashSet::new();
+        for storage_manifest in manifest_files {
+            for f in &storage_manifest.files {
+                if seen.insert(&f.file_path) {
+                    storage_combined_manifest.files.push(f.clone());
+                }
+            }
+        }
src/handlers/http/logstream.rs (1)

50-83: Stream delete should also purge metastore entries for the stream

Currently only storage/staging/memory are cleaned. Please also remove the stream’s metastore record(s) to avoid orphaned metadata. If a single-call API exists (e.g., metastore.delete_stream or equivalent), use that; otherwise delete all related stream JSON objects via the metastore.

I can wire this once you confirm the metastore API name(s) intended for stream deletion.

src/handlers/http/users/filters.rs (1)

71-71: Consider 201 Created for POST

Minor UX: returning Created better reflects resource creation.

Apply:

-    Ok((web::Json(filter), StatusCode::OK))
+    Ok((web::Json(filter), StatusCode::CREATED))
src/handlers/http/modal/mod.rs (1)

366-383: Tighten error handling and logs in load_from_storage

Improve observability; avoid shadowing and log the concrete error.

Apply:

-    async fn load_from_storage(node_type: NodeType) -> Vec<NodeMetadata> {
-        let obs = PARSEABLE.metastore.get_node_metadata(node_type).await;
-
-        let mut metadata = vec![];
-        if let Ok(obs) = obs {
-            for object in obs {
-                //convert to NodeMetadata
-                match serde_json::from_slice::<NodeMetadata>(&object) {
-                    Ok(node_metadata) => metadata.push(node_metadata),
-                    Err(e) => error!("Failed to deserialize NodeMetadata: {:?}", e),
-                }
-            }
-        } else {
-            error!("Couldn't read from storage");
-        }
+    async fn load_from_storage(node_type: NodeType) -> Vec<NodeMetadata> {
+        let mut metadata = vec![];
+        match PARSEABLE.metastore.get_node_metadata(node_type).await {
+            Ok(objects) => {
+                for object in objects {
+                    match serde_json::from_slice::<NodeMetadata>(&object) {
+                        Ok(node_metadata) => metadata.push(node_metadata),
+                        Err(e) => error!("Failed to deserialize NodeMetadata from metastore: {:?}", e),
+                    }
+                }
+            }
+            Err(e) => {
+                error!("Couldn't read node metadata from metastore: {}", e);
+            }
+        }
         // Return the metadata
         metadata
     }
src/storage/gcs.rs (1)

246-272: Remove dead commented code.

Commented legacy listing code adds noise and can mislead future edits. Prefer deleting it (git history preserves it).

-    // async fn _list_streams(&self) -> Result<HashSet<LogStream>, ObjectStorageError> {
-    //     let mut result_file_list = HashSet::new();
-    //     let resp = self.client.list_with_delimiter(None).await?;
-    //
-    //     let streams = resp
-    //         .common_prefixes
-    //         .iter()
-    //         .flat_map(|path| path.parts())
-    //         .map(|name| name.as_ref().to_string())
-    //         .filter(|name| name != PARSEABLE_ROOT_DIRECTORY && name != USERS_ROOT_DIR)
-    //         .collect::<Vec<_>>();
-    //
-    //     for stream in streams {
-    //         let stream_path =
-    //             object_store::path::Path::from(format!("{}/{}", &stream, STREAM_ROOT_DIRECTORY));
-    //         let resp = self.client.list_with_delimiter(Some(&stream_path)).await?;
-    //         if resp
-    //             .objects
-    //             .iter()
-    //             .any(|name| name.location.filename().unwrap().ends_with("stream.json"))
-    //         {
-    //             result_file_list.insert(stream);
-    //         }
-    //     }
-    //
-    //     Ok(result_file_list)
-    // }
src/enterprise/utils.rs (1)

122-154: Tighten the map-building loop (avoid filter_map+for_each side-effects).

Minor readability/perf: iterate once and insert directly; the current pattern allocates and returns dummy values.

-    selected_files
-        .into_iter()
-        .filter_map(|file| {
+    for file in selected_files {
             let date = file.file_path.split("/").collect_vec();
             // … compute file_date …
             if file_date < time_range.start {
-                None
+                continue;
             } else {
                 let date = date.as_slice()[1..4].iter().map(|s| s.to_string());
                 let date = RelativePathBuf::from_iter(date);
                 parquet_files.entry(date).or_default().push(file);
-                Some("")
             }
-        })
-        .for_each(|_| {});
+    }
src/metastore/mod.rs (1)

58-64: Avoid leaking internal structure in Display text for Error variant.

#[error("{self:?}")] dumps internals. Prefer the message field.

-    #[error("{self:?}")]
+    #[error("{message}")]
     Error {
         status_code: StatusCode,
         message: String,
         flow: String,
     },
src/catalog/mod.rs (1)

350-360: Preserve metastore-aware metadata when creating for a “different partition.”

If you retain this branch elsewhere, prefer meta.clone() over ObjectStoreFormat::default() to keep time_partition and stats intact.

src/correlation.rs (2)

98-111: Return 404 for missing correlations.

Currently returns AnyhowError → 500. Prefer a dedicated NotFound variant mapped to 404.


353-362: Nice: JSON error bodies for Metastore errors.

Consider unifying other errors to JSON too for consistency, but this is fine for now.

src/handlers/http/cluster/mod.rs (3)

1010-1011: Typo in user-facing log: “schedular” → “scheduler”.

Minor polish; logs are part of the UX.

-    info!("Setting up schedular for cluster metrics ingestion");
+    info!("Setting up scheduler for cluster metrics ingestion");

768-775: Variable name nit: rename dresses → metrics.

Improves readability.

-    let dresses = fetch_cluster_metrics().await.map_err(|err| {
+    let metrics = fetch_cluster_metrics().await.map_err(|err| {
         error!("Fatal: failed to fetch cluster metrics: {:?}", err);
         PostError::Invalid(err.into())
     })?;
 
-    Ok(actix_web::HttpResponse::Ok().json(dresses))
+    Ok(actix_web::HttpResponse::Ok().json(metrics))

813-836: Delete node metadata for all roles concurrently to reduce tail latency.

Current sequential awaits add ~4x latency on slow stores. Use try_join! to short-circuit on first error and run deletions in parallel.

-    // Delete ingestor metadata
-    let removed_ingestor = PARSEABLE
-        .metastore
-        .delete_node_metadata(&domain_name, NodeType::Ingestor)
-        .await?;
-
-    // Delete indexer metadata
-    let removed_indexer = PARSEABLE
-        .metastore
-        .delete_node_metadata(&domain_name, NodeType::Indexer)
-        .await?;
-
-    // Delete querier metadata
-    let removed_querier = PARSEABLE
-        .metastore
-        .delete_node_metadata(&domain_name, NodeType::Querier)
-        .await?;
-
-    // Delete prism metadata
-    let removed_prism = PARSEABLE
-        .metastore
-        .delete_node_metadata(&domain_name, NodeType::Prism)
-        .await?;
+    // Delete all node-type metadata concurrently
+    let (removed_ingestor, removed_indexer, removed_querier, removed_prism) =
+        futures::try_join!(
+            PARSEABLE
+                .metastore
+                .delete_node_metadata(&domain_name, NodeType::Ingestor),
+            PARSEABLE
+                .metastore
+                .delete_node_metadata(&domain_name, NodeType::Indexer),
+            PARSEABLE
+                .metastore
+                .delete_node_metadata(&domain_name, NodeType::Querier),
+            PARSEABLE
+                .metastore
+                .delete_node_metadata(&domain_name, NodeType::Prism),
+        )?;
src/parseable/mod.rs (1)

107-151: DRY: metastore construction duplicated across all storage variants.

Tiny helper reduces repetition and keeps the wiring consistent.

// Add once near this module (outside diffs for clarity)
fn build_default_metastore(p: &impl ObjectStorageProvider) -> Arc<dyn Metastore> {
    Arc::new(ObjectStoreMetastore { storage: p.construct_client() })
}
-        // for now create a metastore without using a CLI arg
-        let metastore = ObjectStoreMetastore {
-            storage: args.storage.construct_client(),
-        };
+        let metastore = build_default_metastore(&args.storage);
...
-            Arc::new(metastore),
+            metastore,
src/metastore/metastores/object_store_metastore.rs (4)

336-341: Fix error message for clarity

The flow string mentions “get_all_streams” but the function is get_all_stream_jsons.

-                    message: "Incorrect server mode passed as input. Only `Ingest` is allowed."
-                        .into(),
-                    flow: "get_all_streams with mode".into(),
+                    message: "Incorrect server mode passed as input. Only `Ingest` is allowed."
+                        .into(),
+                    flow: "get_all_stream_jsons with mode".into(),

509-518: More precise schema filter

contains(".schema") is brittle. Match the actual suffix.

-                Box::new(|file_name: String| file_name.contains(".schema")),
+                Box::new(|file_name: String| file_name.ends_with("schema.json")),

617-634: Delete all matching node metadata, not just the first

Returning after the first match can leave stale entries and inconsistent results.

If backward-compatible, iterate and delete all matches, and return whether any were deleted. I can provide a patch if you confirm desired semantics.


126-135: Avoid hard-coded directory literals

Use the shared constant for dashboards dir for consistency.

-            let dashboards_path = users_dir.join(&user).join("dashboards");
+            let dashboards_path = users_dir.join(&user).join(crate::handlers::http::users::DASHBOARDS_DIR);
src/migration/mod.rs (1)

29-29: Remove dead code and unused import

to_bytes isn’t used here; the Serialize import is only for it.

-use serde::Serialize;
-#[inline(always)]
-pub fn to_bytes(any: &(impl ?Sized + Serialize)) -> Bytes {
-    serde_json::to_vec(any)
-        .map(|any| any.into())
-        .expect("serialize cannot fail")
-}

Also applies to: 413-418

src/users/dashboards.rs (2)

70-84: Avoid unwrap()s in MetastoreObject impl

Make panics actionable with expect messages since the trait can’t return Result.

-        RelativePathBuf::from_iter([
-            USERS_ROOT_DIR,
-            self.author.as_ref().unwrap(),
-            DASHBOARDS_DIR,
-            &format!("{}.json", self.dashboard_id.unwrap()),
-        ])
+        RelativePathBuf::from_iter([
+            USERS_ROOT_DIR,
+            self.author
+                .as_ref()
+                .expect("dashboard.author must be set"),
+            DASHBOARDS_DIR,
+            &format!(
+                "{}.json",
+                self.dashboard_id
+                    .expect("dashboard.dashboard_id must be set")
+            ),
+        ])
         .to_string()
     }
 
     fn get_object_id(&self) -> String {
-        self.dashboard_id.unwrap().to_string()
+        self.dashboard_id
+            .expect("dashboard.dashboard_id must be set")
+            .to_string()
     }

236-243: Enforce title uniqueness per user, not globally

Prevents cross-user collisions.

-        let has_duplicate = dashboards
-            .iter()
-            .any(|d| d.title == dashboard.title && d.dashboard_id != dashboard.dashboard_id);
+        let has_duplicate = dashboards.iter().any(|d| {
+            d.author == dashboard.author
+                && d.title == dashboard.title
+                && d.dashboard_id != dashboard.dashboard_id
+        });
src/alerts/mod.rs (1)

105-141: Avoid side effects in migrate_from_v1 (optional).

The migration helper both transforms and persists (put_alert). Consider returning the migrated AlertConfig and letting the caller persist. This improves testability and keeps the function pure.

src/query/stream_schema_provider.rs (1)

513-529: Log failures when get_all_stream_jsons() errs (optional).

Currently ignored. Emit a warning to aid debugging in Query/Prism modes.

Apply this diff:

-        if PARSEABLE.options.mode == Mode::Query || PARSEABLE.options.mode == Mode::Prism {
-            let obs = PARSEABLE
-                .metastore
-                .get_all_stream_jsons(&self.stream, None)
-                .await;
-            if let Ok(obs) = obs {
+        if PARSEABLE.options.mode == Mode::Query || PARSEABLE.options.mode == Mode::Prism {
+            match PARSEABLE
+                .metastore
+                .get_all_stream_jsons(&self.stream, None)
+                .await
+            {
+                Ok(obs) => {
                     for ob in obs {
                         if let Ok(object_store_format) =
                             serde_json::from_slice::<ObjectStoreFormat>(&ob)
                         {
                             let snapshot = object_store_format.snapshot;
                             for manifest in snapshot.manifest_list {
                                 merged_snapshot.manifest_list.push(manifest);
                             }
                         }
                     }
-            }
+                }
+                Err(e) => tracing::warn!(
+                    "get_all_stream_jsons failed for {}: {}",
+                    self.stream,
+                    e
+                ),
+            }
         } else {
src/storage/azure_blob.rs (1)

709-719: list_dirs returns nested components, not just immediate children (optional).

Flattening parts() yields deeper-level names. For “dirs at root/prefix”, pick only the first component.

Apply this diff:

-        Ok(resp
-            .common_prefixes
-            .iter()
-            .flat_map(|path| path.parts())
-            .map(|name| name.as_ref().to_string())
-            .collect::<Vec<_>>())
+        Ok(resp
+            .common_prefixes
+            .iter()
+            .filter_map(|p| p.parts().next())
+            .map(|name| name.as_ref().to_string())
+            .collect::<Vec<_>>())

Repeat the same change for list_dirs_relative().

src/storage/object_storage.rs (6)

272-276: Align list_with_delimiter signature with object_store to avoid needless clones

object_store::ObjectStore expects Option<&Path>. Mirror that to prevent Path moves/copies and to match wrappers like metrics_layer.

-    async fn list_with_delimiter(
-        &self,
-        prefix: Option<object_store::path::Path>,
-    ) -> Result<ListResult, ObjectStorageError>;
+    async fn list_with_delimiter(
+        &self,
+        prefix: Option<&object_store::path::Path>,
+    ) -> Result<ListResult, ObjectStorageError>;

Note: implementors (S3/GCS/Azure/LocalFS) and call sites will need corresponding small changes (passing Some(&path) vs Some(path)).


294-300: Simplify schema cloning; avoid Arc clone + deref dance

Use as_ref().clone() to get an owned Schema cleanly.

-        let s = &*schema.clone();
-        PARSEABLE
-            .metastore
-            .put_schema(s.clone(), stream_name)
+        let owned_schema: Schema = schema.as_ref().clone();
+        PARSEABLE
+            .metastore
+            .put_schema(owned_schema, stream_name)
             .await
             .map_err(|e| ObjectStorageError::MetastoreError(Box::new(e.to_detail())))?;

606-613: Naming/doc mismatch

Doc says “create schema from storage” but the function name says “from_metastore” and it writes back into the metastore. Align doc/name to avoid confusion.


550-604: Don’t silently ignore errors from get_all_stream_jsons

into_iter().next() on Result drops Err and returns None. This masks metastore failures. Prefer explicit match and log/propagate errors.

-        if let Some(stream_metadata_obs) = PARSEABLE
-            .metastore
-            .get_all_stream_jsons(stream_name, Some(Mode::Ingest))
-            .await
-            .into_iter()
-            .next()
-            && !stream_metadata_obs.is_empty()
+        let fetch = PARSEABLE
+            .metastore
+            .get_all_stream_jsons(stream_name, Some(Mode::Ingest))
+            .await;
+        if let Ok(stream_metadata_obs) = &fetch
+            && !stream_metadata_obs.is_empty()
         {
             for stream_metadata_bytes in stream_metadata_obs.iter() {
                 let stream_ob_metadata =

Optionally log fetch.err() to aid diagnostics.


315-328: Potential lost-update writes to stream.json; consider optimistic concurrency

All these read-modify-write updates to stream.json have no versioning/CAS. Concurrent writers can clobber each other (e.g., retention and stats updates racing).

Mitigations:

  • Add a revision/etag field in ObjectStoreFormat and enforce “if-match” semantics in Metastore.put_stream_json.
  • Or serialize updates via a per-stream async mutex in PARSEABLE.
    Want me to draft a small revision/CAS design?

Also applies to: 337-350, 359-372, 403-416, 425-440, 447-461, 509-514


688-710: Minor: avoid full sort to find min/max dates

You can derive min/max in one pass to reduce allocations for very large catalogs. Low impact but easy win.

Example:

let (min_date, max_date) = parsed_dates.iter().fold((None, None), |acc, d| { /* update min/max */ acc });
src/metastore/metastore_traits.rs (3)

25-26: Use a single async_trait macro source across the codebase

Other files use async_trait::async_trait. Switch from tonic::async_trait for consistency and to avoid needless dependency coupling.

-use tonic::async_trait;
+use async_trait::async_trait;

(No functional change; just macro import.)

Also applies to: 36-36


152-155: Consider requiring Send on MetastoreObject

These objects are serialized before awaits today, but adding Send is a safe default for future async usage.

-pub trait MetastoreObject: ErasedSerialize + Sync {
+pub trait MetastoreObject: ErasedSerialize + Send + Sync {

68-93: Clarify stream.json selection semantics in docs

The get_stream_json/get_all_stream_jsons docs are good; add a note that the metastore MUST honor server Mode when resolving the active stream.json to prevent cross-mode leakage.

Comment thread src/alerts/alert_types.rs Resolved
Comment thread src/alerts/mod.rs Resolved
Comment thread src/alerts/target.rs Resolved
Comment thread src/alerts/target.rs Resolved
Comment thread src/catalog/manifest.rs Resolved
Comment thread src/storage/gcs.rs Resolved
Comment thread src/storage/localfs.rs Resolved
Comment thread src/storage/object_storage.rs Resolved
Comment thread src/storage/store_metadata.rs Resolved
Comment thread src/users/filters.rs Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link