← Canary GrowDirect CRDM Reference
Canary

Canary Retail Data Model

Technical Reference — April 2026
Version 3.0 Confidential Patent Pending 63/991,596 99 Tables · 3 Schemas

1. Three-Schema Architecture

The canary PostgreSQL database is organized into three schemas with distinct responsibilities. Total: 99 tables.

app
49
Tenant identity, configuration, detection rules, alerts, case management, credit system, AI memory, audit
  • Core tenant & identity (9 tables)
  • Locations & employees (5 tables)
  • Source systems (2 tables)
  • Products & customers (2 tables)
  • Card profiles (2 tables)
  • Detection & alerts (4 tables)
  • Feature flags & config (3 tables)
  • Namespacing (2 tables)
  • Notifications (2 tables)
  • Webhooks & schema drift (3 tables)
  • Fox case management (6 tables)
  • Goose credit system (5 tables)
  • Owl AI (4 tables)
  • Other (7 tables)
sales
30
Append-only transaction ledger, line items, tenders, cash drawers, disputes, gift cards, loyalty, invoices, ETL pipeline
  • Core transactions (4 tables)
  • Line item detail (6 tables)
  • Invoices & journal (2 tables)
  • Devices & terminal (3 tables)
  • Cash drawers (2 tables)
  • Payouts & disputes (3 tables)
  • Gift cards & loyalty (3 tables)
  • Employees & inventory (2 tables)
  • Bitcoin inscription (2 tables)
  • ETL pipeline (3 tables)
metrics
20
Star schema analytics, daily/hourly/period aggregations, ML feature vectors, risk scores, baselines, scorecards
  • Fact tables (6 tables)
  • Dimensions (3 tables)
  • Risk & ML (7 tables)
  • Scorecards (4 tables)

2. Table Inventory

Schema: app (49 tables)

Core Tenant & Identity

TablePurpose~Cols
merchantsMaster merchant/tenant record~12
merchant_settingsPer-merchant UI and behavior settings~23
organizationsOrganization grouping above merchants~9
usersUser accounts~13
rolesRole definitions for RBAC~5
user_rolesUser↔Role join~5
square_oauth_tokensSquare OAuth access/refresh tokens per merchant~7
external_identitiesExternal IdP mapping (Google, etc.)~7
interest_signupsPre-launch email capture~5

Locations & Employees

TablePurpose~Cols
locationsPhysical merchant locations with address, timezone, and status~18
location_hierarchyParent/child location grouping~9
employeesEmployee records synced from Square~10
user_employee_linksUser↔Employee link for portal access~5
employee_location_assignmentsEmployee↔Location active assignments~5

Source Systems

TablePurpose~Cols
source_systemsRegistered data source types (Square, future adapters)~6
merchant_sourcesPer-merchant source configuration and credentials~10

Products & Customers

TablePurpose~Cols
productsProduct catalog synced from Square catalog API~9
customersCustomer records synced from Square~7

Card Profiles

TablePurpose~Cols
card_profilesCard fingerprint/BIN profiles for fraud pattern detection~13
blocked_entitiesBlocked cards, customers, or device fingerprints~9

Detection & Alerts

TablePurpose~Cols
detection_rulesRule definitions — 37 rules across 10 categories~10
merchant_rule_configPer-merchant threshold overrides for each rule~9
alertsGenerated alert records with severity, status, and context~19
alert_historyAlert state transition audit trail~9

Feature Flags & Config

TablePurpose~Cols
feature_flagsGlobal feature flag definitions~8
merchant_feature_flagsPer-merchant flag overrides~7
app_configGlobal key-value configuration store~8

Namespacing

TablePurpose~Cols
namespace_registrationsNamespace records for multi-tenant data isolation~12
namespace_aliasesNamespace alias mappings~8

Notifications

TablePurpose~Cols
notification_logSent notification history (email, SMS, push)~16
notification_scheduleScheduled and recurring notification configuration~18

Webhooks & Schema Drift

TablePurpose~Cols
webhook_eventsInbound Square webhook log — raw payload, processing status~12
schema_fingerprintsDatabase schema hash snapshots for drift detection~9
schema_drift_alertsDetected schema change events and resolution status~8

Fox — Case Management

Fox is the internal investigation module. Cases are opened from alerts or manually, collect evidence, track subjects, and produce a documented timeline.
TablePurpose~Cols
fox_casesInvestigation case records with status, type, severity~19
fox_case_actionsActions taken on a case (notes, escalations, closures)~15
fox_case_alertsAlerts linked to a case~10
fox_case_timelineChronological event log for a case~14
fox_evidenceEvidence items — documents, screenshots, transaction refs~21
fox_evidence_access_logAccess audit trail for evidence items~12
fox_subjectsInvestigation subjects (employees, customers, devices)~9

Goose — Credit System

Goose is the usage-metering layer. Operations (Owl queries, report generation, data exports) consume credits from a merchant wallet funded via Lightning Network invoices through Strike.
TablePurpose~Cols
merchant_walletsSat-denominated merchant wallets — balance, status, limits~13
wallet_transactionsDebit/credit ledger — append-only, immutable~15
gas_schedulePer-operation cost schedule (sats per action type)~8
macaroon_tokensL402 bearer tokens for API authentication~12
strike_invoicesStrike Lightning invoices for wallet top-ups~16

Owl — AI

Owl is the AI agent layer. It runs queries against sales and metrics data, logs findings, and maintains per-merchant memory to improve detection over time.
TablePurpose~Cols
owl_sessionsAI agent sessions — prompt, context window, status~16
owl_findingsLogged findings from Owl analysis runs~11
owl_merchant_memoryPer-merchant persistent memory (pgvector embeddings)~13
owl_action_logAgent actions taken per session~11

Other (app schema)

TablePurpose~Cols
vault_memoriesALX agent memory store~11
audit_logGeneral application audit trail~11
gift_cardsGift card entity records~11
subscriptionsMerchant subscription plan and billing state~16
transfer_ordersSquare transfer order records~12
bank_accountsLinked bank accounts for payout reconciliation~15

Schema: sales (30 tables)

Core Transactions

The transactions table is the central ledger. It is append-only — no updates, no deletes. All downstream tables reference it by foreign key.
TablePurpose~Cols
transactionsPayment records — master ledger. Append-only.56
transaction_tendersTender breakdown per transaction (card, cash, gift card, etc.)~13
transaction_line_itemsLine items — products, quantities, prices, modifiers~18
refund_linksRefund↔original transaction linkage~12

Line Item Detail

TablePurpose~Cols
line_item_discountsDiscounts applied to individual line items~15
line_item_taxesTaxes applied to individual line items~12
line_item_modifiersModifiers applied to individual line items~12
order_service_chargesService charges at the order level~17
order_rewardsLoyalty rewards applied to orders~7
order_returnsReturned items at the order level~12

Invoices & Electronic Journal

TablePurpose~Cols
invoicesSquare invoice records — status, payment schedule, recipients~29
ej_linksElectronic journal cross-reference links~14

Devices & Terminal

TablePurpose~Cols
devicesPOS device registry — device ID, type, firmware, location~19
terminal_checkoutsTerminal checkout sessions~33
terminal_refundsTerminal refund sessions~18

Cash Drawers

TablePurpose~Cols
cash_drawer_shiftsCash drawer shift sessions — open/close amounts, variance~20
cash_drawer_eventsIndividual events within a shift (opens, deposits, removals)~14

Payouts & Disputes

TablePurpose~Cols
payoutsSquare payout records — amount, status, bank routing~12
disputesChargeback records — reason, amount, status, deadline~14
evidence_recordsDispute evidence submitted to Square~15

Gift Cards & Loyalty

TablePurpose~Cols
gift_card_activitiesGift card activity log — activations, loads, redemptions, voids~19
loyalty_accountsCustomer loyalty account records~14
loyalty_eventsLoyalty point earn and redemption events~14

Employees & Inventory

TablePurpose~Cols
employee_timecardsClock-in/clock-out records per employee per shift~13
inventory_adjustmentsInventory count adjustments from Square~13

Bitcoin Inscription

Canary supports optional inscription of transaction data to the Bitcoin blockchain as permanent audit records. This feature is in development.
TablePurpose~Cols
inscription_poolInscription configuration and queue management~21
event_inscriptionsIndividual inscription records and Bitcoin txids~16

ETL Pipeline

TablePurpose~Cols
ingestion_logPer-fetch tracking — endpoint, params, record count, duration~18
etl_batchesBatch execution records — status, error counts, timing~16
dead_letter_queueFailed webhook events queued for retry or manual review~18

Schema: metrics (20 tables)

Fact Tables

The metrics schema is a star schema. Fact tables are precomputed aggregations, updated nightly. They power dashboards and detection baselines without hitting the sales ledger at query time.
TablePurpose~Cols
daily_metricsPer-merchant daily aggregations — revenue, counts, averages, variances~180
hourly_metricsPer-merchant hourly aggregations — volume and velocity~79
employee_daily_metricsPer-employee daily performance and exception metrics~166
product_daily_metricsPer-product daily sales aggregations~71
period_metricsRolling 7d/30d/90d aggregations per merchant~203
employee_period_metricsRolling period aggregations per employee~165

Dimensions

TablePurpose~Cols
dim_dateCalendar spine — day, week, month, quarter, year, fiscal periods~19
dim_locationLocation dimension for metrics joins~12
dim_employeeEmployee dimension for metrics joins~11

Risk & ML

TablePurpose~Cols
transaction_featuresML feature vectors per transaction — 55 engineered features~55
feature_definitionsFeature metadata — name, type, description, formula~12
ml_modelsModel version registry — algorithm, training date, performance metrics~14
entity_risk_scoresCurrent risk scores per entity (employee, customer, device)~13
risk_score_historyRisk score change history — score, delta, trigger~12
metric_baselinesStatistical baselines per merchant and location~16
velocity_baselinesRate-of-change baselines for velocity detection rules~19

Scorecards

TablePurpose~Cols
weekly_scorecardWeekly merchant performance scorecard~12
monthly_scorecardMonthly merchant performance scorecard~12
scorecard_thresholdsConfigurable scorecard threshold definitions~16
dashboard_configPer-merchant dashboard layout and widget configuration~13

3. Detection Rules

37 rules across 10 categories. Rules are defined in app.detection_rules and configured per merchant in app.merchant_rule_config. Thresholds are adjustable; rule logic is fixed in the Chirp detection engine.

Category Rule Description
PaymentPAY-001Transaction amount exceeds configurable threshold
PaymentPAY-002Refund without original transaction reference
PaymentPAY-003Refund amount exceeds original sale amount
PaymentPAY-004Multiple refunds to same card within time window
PaymentPAY-005High refund rate by employee (period basis)
PaymentPAY-006Round-dollar transaction pattern (potential skimming)
PaymentPAY-007Tender type mismatch (card used as cash, etc.)
PaymentPAY-008Split tender threshold — order split into micro-transactions
PaymentPAY-009Discount rate exceeds authorized maximum
PaymentPAY-010No-sale (cash drawer open) without transaction
PaymentPAY-011Transaction velocity spike — rate exceeds baseline by threshold
Cash DrawerCASH-001Shift variance exceeds configurable tolerance
Cash DrawerCASH-002Drawer open frequency exceeds baseline
Cash DrawerCASH-003Cash removal without supervisor authorization
Cash DrawerCASH-004Shift ended without drawer close event
OrderORD-001Order deleted after payment recorded
OrderORD-002Line item removed after order opened
OrderORD-003Order price modified post-tender
OrderORD-004Zero-price line item added to completed order
TimecardTIME-001Transaction processed outside clocked-in window
TimecardTIME-002Overlapping timecard entries for same employee
TimecardTIME-003Shift hours exceed configurable maximum
VoidVOID-001Void rate by employee exceeds threshold
VoidVOID-002High-value void without manager authorization
Gift CardGC-001Gift card activated without corresponding sale
Gift CardGC-002Gift card balance depleted and reloaded within short window
LoyaltyLOY-001Loyalty points accrued without matching transaction
LoyaltyLOY-002Points redemption velocity exceeds baseline
LoyaltyLOY-003Points adjustment without system event trigger
LoyaltyLOY-004Multiple accounts with shared contact information
CompositeCOMP-001Correlated pattern: refund + void + cash removal within single shift
DisputeDISP-001Chargeback rate by location exceeds threshold
DisputeDISP-002Dispute on transaction with no card-present signature
DisputeDISP-003Repeated disputes from same card fingerprint
InvoiceINV-001Invoice cancelled after partial payment received
InvoiceINV-002Invoice amount modified after sending
InvoiceINV-003Duplicate invoice to same customer within time window

4. Data Flow

Square POS webhook event TSP Parser
Validates signature, parses payload, normalizes to CRDM canonical shape
sales schema
Append-only write to transactions, tenders, line items, and related tables
Chirp (detection engine)
Evaluates 37 rules against new data; compares to baselines in metrics schema
app.alerts
Alert records written; notifications dispatched via notification_log
Fox (case management)
Alerts escalated to cases; evidence collected; timeline maintained
Goose (credit metering) operations consume credits from merchant_wallets
Gas schedule defines cost per operation type; debits written to wallet_transactions; wallets funded via Strike Lightning invoices
Nightly aggregation job refreshes metrics schema
Computes daily/hourly/period metrics, updates baselines, recalculates risk scores

5. POS-Agnostic Architecture

The CRDM canonical schema does not depend on Square-specific data structures. Square fields are mapped during ingestion by the TSP (Transaction Source Parser). A Clover, Toast, or Shopify adapter would implement the same parsing interface and write to the same sales schema tables.

AdapterStatusNotes
SquareLiveWebhook + polling. Full coverage of payments, orders, cash drawers, timecards, disputes, loyalty, gift cards.
CloverPlannedSchema mappings designed. Not yet implemented.
ToastPlannedRestaurant-specific fields (covers, courses) map to service charges and modifiers.
ShopifyPlannedE-commerce adapter; cash drawer and timecard sections would be null.

The app.source_systems and app.merchant_sources tables manage adapter registration and per-merchant source configuration. Multi-source ingestion (e.g., a merchant running Square and an e-commerce channel) is supported by the schema design.