Flagship ProjectProduction System

Nytr: Evidence-Driven Nutrition & Training Decision Platform

A personal decision system separating authoritative source data, deterministic computation, and user-approved policy changes so constrained decisions do not depend on non-authoritative estimates. Combines Penn State dining menus, Apple HealthKit telemetry, and Hevy workout data via a FastAPI modular monolith, Supabase PostgreSQL, and a native SwiftUI iOS client.

Backend Suite

1,041 Tests

Math Precision

Deterministic Decimal

Sync Engine

Dual Anchors

Database Security

RLS & Tombstones

1. Overview & System Philosophy

Many consumer nutrition tools couple unverified inputs with heuristic auto-adjustments, silently mutating historical records or altering daily calorie targets based on noisy wearable burn estimates (“exercise-calorie eat-back”). When decision logic relies on non-authoritative estimates, recommendations quickly diverge from measurable progress.

Nytr separates authoritative source data, deterministic computation, and user-approved policy changes so constrained decisions do not depend on non-authoritative estimates:

Core Principle

DATA → DETERMINISTIC CALCULATION → DECISION

Raw facts are ingested with immutable provenance. Math runs deterministically in pure domain logic. Decisions belong exclusively to the human user.

Nytr is not a generic calorie tracker, an LLM chatbot wrapper, or an automated health dashboard. It is an operational decision platform deployed for daily life at Penn State Harrisburg, specifically bounded to campus dining (Stacks Market), Apple HealthKit weight observations, and Hevy strength logs.

2. Explicit Source Authority

Distributed data systems fail when multiple sources claim ownership over the same domain concept. Nytr prevents source confusion through a strict, non-negotiable authority matrix:

Upstream SourceExclusive AuthorityDeliberately Forbidden Scope
Penn State Dining (Stacks)Menu availability, serving units, recipe names, published macro profilesCannot dictate meal timing, user schedule, or daily calorie targets
Apple HealthKit (via iOS Companion)Historical body mass, workout session timing contextActive calorie burn cannot alter food recommendations; no on-device trend math
Hevy Official APIWorkout exercise sets, reps, load, and volume progression revisionsCannot alter HealthKit session authority or create unlogged sessions
FastAPI / PostgreSQL BackendDeterministic plan scoring, target policies, 28-day trends, audit logsCannot auto-apply target modifications without explicit user approval

3. Architecture & Public-Safe Topology

Nytr avoids fragile microservices in favor of a Python + FastAPI modular monolith backed by Supabase PostgreSQL and a native SwiftUI iOS companion client:

┌────────────────────────┐      ┌─────────────────────────┐      ┌─────────────────────────┐
│   Penn State Stacks    │      │    Apple HealthKit      │      │     Hevy Cloud API      │
│  Daily Menu Scraper    │      │   (Native iOS Client)   │      │ (Official Developer API)│
└───────────┬────────────┘      └────────────┬────────────┘      └────────────┬────────────┘
            │ Bounded Ingestion              │ Idempotent Sync                │ Append-Only Sync
            ▼ Compliance Gate                ▼ Dual Anchors                   ▼ Token Redacted
┌──────────────────────────────────────────────────────────────────────────────────────────┐
│                                FastAPI Modular Monolith                                  │
│                                                                                          │
│  ┌──────────────────────┐  ┌───────────────────────┐  ┌───────────────────────────────┐  │
│  │   Dining Ingestion   │  │   HealthKit Receiver  │  │    Training Syncer (Hevy)     │  │
│  │  • Complete vs Usable│  │  • Tombstone Deletion │  │  • Session Revisions          │  │
│  │  • Mid Identity Reuse│  │  • kg Unit Canonical  │  │  • Volume & Progression Math  │  │
│  └──────────┬───────────┘  └───────────┬───────────┘  └───────────────┬───────────────┘  │
│             │                          │                              │                  │
│             ▼                          ▼                              ▼                  │
│  ┌────────────────────────────────────────────────────────────────────────────────────┐  │
│  │                               Pure Domain Engine                                   │  │
│  │  • Deterministic Decimal Arithmetic (exact numeric precision)                      │  │
│  │  • Schedule Resolution (Class schedule + workout timing context)                   │  │
│  │  • Strict Dietary Eligibility Gates (Diet-Specific Filtering)                     │  │
│  │  • Bounded Candidate Scoring & Frozen Plan Generation (SHA-256 Fingerprint)        │  │
│  │  • 28-Day Theil-Sen Body-Mass Trend & Explicit Target Review Policy                │  │
│  └─────────────────────────────────────┬──────────────────────────────────────────────┘  │
└────────────────────────────────────────┼─────────────────────────────────────────────────┘
                                         │ Authenticated RLS / Backend Service Connection
                                         ▼
┌──────────────────────────────────────────────────────────────────────────────────────────┐
│                                 Supabase PostgreSQL                                      │
│  • Immutable Plan Runs, Items & Target Policy Versions (Append-Only)                     │
│  • Controlled Tombstone Updates (tombstoned_at) on HealthKit Sync Records                │
│  • Shared Dining Menus & Station Cache (Read via Backend Service Connection)             │
│  • User-Owned Tables Protected by Row-Level Security (RLS) Bound to Auth Identity        │
└──────────────────────────────────────────────────────────────────────────────────────────┘

4. Key Engineering Challenges

Dual-Anchor HealthKit Synchronization & Tombstone Semantics

Syncing mobile health telemetry over cellular networks requires distinguishing between transient query state and durable storage:

  • Transient vs Durable Anchors: The iOS companion uses an in-memory HKQueryAnchor during anchored queries. However, the durable sync anchor (health.sync.*.durableState.v1) advances in device keychain storage only after the backend confirms a successful database transaction commit. If a crash occurs mid-flight, the batch safely replays without duplication.
  • Idempotent Tombstone Deletions: When samples are deleted in Apple Health, a tombstone record is committed (tombstoned_at). If an out-of-order add arrives for an already-tombstoned UUID, the backend immediately drops it—preventing ghost resurrection of deleted data.

Database-Enforced Immutability & Row-Level Security

Traditional web apps mutate historical logs when user settings or nutritional profiles change. In Nytr, historical truth is permanent:

  • PostgreSQL Row-Level Security: User-owned tables enforce RLS policies bound directly to the authenticated user ID. Plan runs, daily items, and target policy versions are strictly immutable insert-only records.
  • Controlled Tombstone Semantics: Health telemetry synchronizations avoid physical row deletion in favor of explicit tombstoned_at timestamps, maintaining historical auditability. Shared global dining menus and station caches are accessed via a dedicated backend service connection without per-user RLS.
  • Versioned Pinning: When a daily plan is generated, it pins the exact nutrition_profile_version_id and target_policy_version_id. Historical plans never re-query modern food profiles; they represent a verifiable snapshot sealed with a SHA-256 fingerprint.

Deterministic Decimal Arithmetic & No Exercise Eat-Back

Using Decimal/numeric arithmetic avoids binary floating-point rounding error in persisted nutrition and body-mass calculations:

  • End-to-End Decimal Types: All continuous quantities (calories, protein, carbs, fats, body mass) parse through Python’s Decimal module and persist into PostgreSQL numeric(6,3) columns, maintaining exact precision across domain calculations and database storage.
  • Strict Anti-Eat-Back Doctrine: Workouts observed via HealthKit or Hevy provide timing context (e.g., qualifying a dated lunch slot as a post_workout_lunch with 40% daily calorie allocation). Workouts never add extra calories to the daily target. This protects lean-bulk goals from exercise overcompensation.

28-Day Theil–Sen Body-Mass Evidence Window & Target Reviews

Instead of automatic recalibration that alters meal sizes without warning, Nytr runs an on-demand 28-day body-mass evidence window using robust Theil–Sen slope estimation:

  • The median-of-slopes Theil–Sen estimator calculates an outlier-resistant rate of change (kg/week) over a 28-day rolling window, remaining resilient against single-day hydration fluctuations.
  • If the trend indicates a persistent rate outside target boundaries, the backend formulates a bounded review proposal (strictly limited to ±100 kcal).
  • The review is purely advisory. The proposal can only become active policy when the authenticated user explicitly approves it on iOS, which atomically writes a new versioned target policy row and a mandatory decision-log rationale.

5. Verification & Production Discipline

Because Nytr is trusted with personal health and nutrition in production, it is backed by a rigorous test and verification suite:

1,041

Backend Tests

Pytest suite covering domain algorithms, candidate scoring, date windows, idempotency, and PostgreSQL RLS integration.

Dual Anchors

Sync Engine

Durable anchors and idempotent writes support replay-safe mobile synchronization.

Hardware

Physical Validation

Physical-device validated with real iPhone hardware, authentic Apple HealthKit permissions, and Stacks Market food offerings.

6. Engineering Lessons

1. Use deterministic computation where constraints must be exact: Meal scoring, dietary exclusions, target math, and historical reconstruction operate over verified, versioned data rather than probabilistic model output.

2. Treat data provenance as a tier-1 property: In production systems, knowingwhere a datum originated (e.g. verified Stacks label vs user estimated portion vs HealthKit sensor) is just as critical as the value itself.

3. Contained failure modes: Append-only history, controlled tombstones, and idempotent writes prevent specific mutation, replay, and accidental-overwrite failure modes.