Skip to content

Strongly-Typed Node Structs with Direct Spoke Table Deserialization #673

Closed

Description

@malibio

Overview

Refactor typed node structs (TaskNode, SchemaNode) to deserialize directly from spoke tables with hub data via record link, eliminating the intermediate JSON properties step. Integrate these typed structs throughout the entire stack (MCP handlers, behaviors, Tauri commands).

Problem Statement

Current Architecture (Weak Typing):

DB spoke (task.status) 
  → Query hub, then query spoke (2 queries!)
  → Hydrate into Node.properties as JSON
  → TaskNode wraps Node
  → TaskNode.status() reads from node.properties["status"]

This defeats the purpose of having typed structs - we go through JSON intermediaries instead of leveraging Rust's type system. Additionally, the current get_node() does 2 queries when it could do 1.

Desired Architecture (Strong Typing):

DB spoke (task.status + task.node.* for hub fields)
  → Single query with record link
  → Deserialize directly to TaskNode struct
  → TaskNode.status is a TaskStatus enum field
  → MCP handlers return TaskNode (not generic Node)
  → Behaviors validate TaskNode directly

Proposed Solution

Phase 1: Define Strongly-Typed Structs ✅ DONE

Create structs that mirror DB spoke tables with hub fields via record link:

pub struct TaskNode {
    // Hub fields (from task.node.*)
    pub id: String,
    pub content: String,
    pub version: i64,
    pub created_at: DateTime<Utc>,
    pub modified_at: DateTime<Utc>,
    
    // Spoke fields (direct from task table)
    pub status: TaskStatus,
    pub priority: Option<i32>,
    pub due_date: Option<DateTime<Utc>>,
    pub assignee: Option<String>,
}

pub struct SchemaNode {
    // Hub fields
    pub id: String,
    pub content: String,
    pub version: i64,
    pub created_at: DateTime<Utc>,
    pub modified_at: DateTime<Utc>,
    
    // Spoke fields
    pub is_core: bool,
    pub schema_version: u32,
    pub fields: Vec<SchemaField>,
    pub description: String,
}

Phase 2: Single-Query Pattern ✅ DONE

For typed structs (spoke-first query):

-- Single query: spoke fields + hub fields via node pointer
SELECT 
    id, status, priority, due_date, assignee,
    node.content AS content,
    node.version AS version,
    node.created_at AS created_at,
    node.modified_at AS modified_at
FROM task:`some-id`;

For generic get_node() - Two-query approach (DECIDED):

We investigated single-query options (FETCH data, LET/IF/RETURN) but found:

  • FETCH data fails because Thing types can't deserialize to serde_json::Value
  • LET/IF/RETURN requires enumerating all spoke types in the query

For embedded SurrealDB (RocksDB), the second query is an in-process call (~microseconds overhead). Two queries is acceptable and scales without code changes as new spoke types are added.

Phase 3: Service Layer Methods ✅ DONE

impl NodeService {
    pub async fn get_task_node(&self, id: &str) -> Result<Option<TaskNode>>;
    pub async fn get_schema_node(&self, id: &str) -> Result<Option<SchemaNode>>;
    pub async fn get_node(&self, id: &str) -> Result<Option<Node>>; // Generic fallback
}

Phase 4: MCP Handler Integration ✅ DONE

MCP handlers now return typed structs via node_to_typed_value() helper:

fn node_to_typed_value(node: Node) -> Result<Value, MCPError> {
    match node.node_type.as_str() {
        "task" => {
            let task = TaskNode::from_node(node)?;
            serde_json::to_value(task)
        }
        "schema" => {
            let schema = SchemaNode::from_node(node)?;
            serde_json::to_value(schema)
        }
        _ => serde_json::to_value(node) // Generic for text, header, etc.
    }
}

Applied in: handle_get_node, handle_query_nodes, handle_get_nodes_batch

Phase 5: Behavior Integration ✅ DONE

Behaviors now validate typed structs directly:

impl TaskNodeBehavior {
    pub fn validate_task_node(&self, task: &TaskNode) -> Result<(), ValidationError> {
        // Direct field access - compile-time type safety
        if let Some(priority) = task.priority {
            if !(1..=4).contains(&priority) {
                return Err(ValidationError::InvalidProperties(...));
            }
        }
        Ok(())
    }
}

impl NodeBehavior for TaskNodeBehavior {
    fn validate(&self, node: &Node) -> Result<(), ValidationError> {
        // Convert to typed and validate
        match TaskNode::from_node(node.clone()) {
            Ok(task) => self.validate_task_node(&task),
            Err(_) => // fallback validation
        }
    }
}

Same pattern applied to SchemaNodeBehavior::validate_schema_node().

Acceptance Criteria

Phase 1-3 (DONE):

  • TaskNode struct with strongly-typed fields (not wrapping Node)
  • SchemaNode struct with strongly-typed fields
  • Single-query pattern using spoke table with hub record link
  • get_task_node() method returning TaskNode directly
  • get_schema_node() method returning SchemaNode directly
  • Existing get_node() preserved for generic/unknown types
  • Update architecture documentation to reflect this pattern

Phase 4-6 (DONE):

  • MCP handlers return typed structs for task/schema types
  • TaskNodeBehavior validates TaskNode directly (not generic Node)
  • get_node() uses single query DECIDED: Two queries acceptable for embedded DB
  • All existing tests pass
  • Code passes bun run quality:fix
  • Tests pass (cargo test --lib)

Technical Notes

Spoke Table Record Links (Bidirectional)

Hub → Spoke:

DEFINE FIELD IF NOT EXISTS data ON TABLE node TYPE option<record>;

Spoke → Hub:

DEFINE FIELD IF NOT EXISTS node ON TABLE task TYPE option<record>;

Both directions support single-query patterns:

  • SELECT *, data.* FROM node:id (hub→spoke)
  • SELECT *, node.* FROM task:id (spoke→hub)

Types That Need Strong Typing

Type Spoke Table Strong Typing Reason
task ✅ Yes ✅ YES Complex props (status enum, dates)
schema ✅ Yes ✅ YES Nested structures (fields array)
text ❌ No ❌ NO Just content
header ❌ No ❌ NO Just content
date ❌ No ❌ NO Just ID validation
code-block ❌ No ❌ NO Simple language property

Simple content-only types use generic Node - no benefit from strong typing.

Dependencies

Related Issues

Activity

  1. self-assigned this
    on Nov 29, 2025
  2. added 7 commits that reference this issue on Nov 29, 2025
    3a264ce
    a3767a4
    847b0e1
    e63ea88
    99a84dd
    3f2a7f6
    ba6529a
  3. added a commit that references this issue on Nov 30, 2025
    f62d145
  4. added 2 commits that reference this issue on Feb 4, 2026
    193793c
    9afaf8a
  5. added a commit that references this issue on Feb 26, 2026
    c89def8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

architecturebackendenhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions