From da20d1cacaf043347128587f58b971eccf7c5aa6 Mon Sep 17 00:00:00 2001 From: Waozi Date: Mon, 28 Sep 2026 19:15:10 -0300 Subject: [PATCH] Port more storage, habit and breathing tests to Ziran; fix habit record merging and the legacy path list Habit records from a sync response are now applied together, so habits sharing a name merge with their days instead of orphaning them. LegacyPaths now matches raylib's FilePathList so the legacy scan reads the real count. --- src/storage/legacy_session_files.zi | 2 + src/storage/storage_core.zi | 31 ++- tests/breath_rounds_behavior.zi | 121 +++++++++ tests/breath_rounds_zi_test.sh | 27 ++ tests/breath_timing_behavior.zi | 2 + tests/habit_sessions_behavior.zi | 146 ++++++++++ tests/habit_sessions_zi_test.sh | 44 +++ tests/storage_habits_behavior.zi | 19 ++ tests/storage_more_behavior.zi | 408 ++++++++++++++++++++++++++++ tests/storage_more_zi_test.sh | 44 +++ tests/storage_sync_behavior.zi | 189 +++++++++++++ tests/storage_test_support.zi | 19 ++ tests/sync_test_host.zi | 98 ++++++- 13 files changed, 1140 insertions(+), 10 deletions(-) create mode 100644 tests/breath_rounds_behavior.zi create mode 100755 tests/breath_rounds_zi_test.sh create mode 100644 tests/habit_sessions_behavior.zi create mode 100755 tests/habit_sessions_zi_test.sh create mode 100644 tests/storage_more_behavior.zi create mode 100755 tests/storage_more_zi_test.sh diff --git a/src/storage/legacy_session_files.zi b/src/storage/legacy_session_files.zi index 642067302..f06e5873a 100644 --- a/src/storage/legacy_session_files.zi +++ b/src/storage/legacy_session_files.zi @@ -6,7 +6,9 @@ c :: #system_library "c"; +// The layout of raylib's FilePathList, which the host returns by value. LegacyPaths :: struct { + capacity: u32 count: u32 paths: **u8 } diff --git a/src/storage/storage_core.zi b/src/storage/storage_core.zi index 486ac30e8..7be6db882 100644 --- a/src/storage/storage_core.zi +++ b/src/storage/storage_core.zi @@ -1726,7 +1726,7 @@ storage_apply_decrypted_record :: (collection: string, plaintext: string) -> s32 response: StorageJsonBuilder = StorageJsonBuilder.{} record_response: string ok: s32 - if array_name.count == 0 || plaintext.count == 0 || storage_json_valid(plaintext) == 0 { + if array_name.count == 0 || plaintext.count == 0 { return 0 } response.ok = 1 @@ -1740,6 +1740,11 @@ storage_apply_decrypted_record :: (collection: string, plaintext: string) -> s32 return 0 } record_response = AppTextFromCString(response.data, cast(s32)(response.len + 1)) + // `plaintext` is one record, or several separated by commas. + if storage_json_valid(record_response) == 0 { + storage_json_builder_free(*response) + return 0 + } if storage_compare_text(array_name, "habits") == 0 { ok = ifx (storage_reconcile_remote_habit_ids(record_response) != 0 && storage_apply_sync_habits_json(record_response) != 0) then (1) else (0) } else if storage_compare_text(array_name, "habit_days") == 0 { @@ -1824,6 +1829,11 @@ storage_decrypt_record :: (collection: string, record_id: string, key_id: string storage_apply_encrypted_records_query: string = "SELECT json_extract(value,'$.collection'),json_extract(value,'$.id'),json_extract(value,'$.key_id'),json_extract(value,'$.nonce'),json_extract(value,'$.ciphertext'),COALESCE(json_extract(value,'$.content_hash'),'')FROM json_each(?1,?2)"; storage_apply_encrypted_records :: (response_json: string) -> s32 { + habit_batch_storage: StorageJsonBuilder = StorageJsonBuilder.{} + habit_batch: *StorageJsonBuilder = *habit_batch_storage + habit_batch_count: s32 = 0 + habit_batch_collection: string = "" + habit_batch_storage.ok = 1 statement: *void = null ok: s32 = 1 array_path: string = "$.data.encrypted_records" @@ -1892,6 +1902,17 @@ storage_apply_encrypted_records :: (response_json: string) -> s32 { if ok == 0 { LogStorageText(LOG_WARNING, "SYNC: encrypted record decrypt failed: ", collection) + } else if storage_compare_text(storage_decrypted_array_name(collection), "habits") == 0 { + // Habits are applied together, once every record has arrived, so + // habits that share a name are merged rather than replacing + // each other before their days are in. + if habit_batch_count > 0 { + storage_json_builder_append_text(habit_batch, ",") + } + storage_json_builder_append_text(habit_batch, + AppTextFromCString(plaintext, 2147483647)) + habit_batch_count += 1 + habit_batch_collection = collection } else { ok = storage_apply_decrypted_record(collection, AppTextFromCString(plaintext, 2147483647)) @@ -1903,6 +1924,14 @@ storage_apply_encrypted_records :: (response_json: string) -> s32 { free(cast(*void)plaintext) index += 1 } + if ok != 0 && habit_batch_count > 0 && habit_batch.ok != 0 && habit_batch.data != null { + ok = storage_apply_decrypted_record(habit_batch_collection, + AppTextFromCString(habit_batch.data, cast(s32)(habit_batch.len + 1))) + if ok == 0 { + LogStorage(LOG_WARNING, "SYNC: encrypted habit records apply failed") + } + } + storage_json_builder_free(habit_batch) } { index: s32 = 0 diff --git a/tests/breath_rounds_behavior.zi b/tests/breath_rounds_behavior.zi new file mode 100644 index 000000000..8678126d9 --- /dev/null +++ b/tests/breath_rounds_behavior.zi @@ -0,0 +1,121 @@ +#import, file "../src/core/types.zi"; +#import, file "../src/core/breath_timing.zi"; + +using BreathAnimation; + +// Steps the session while it stays in `phase` (or `limit` steps). +AdvanceWhilePhase :: (state: BreathSession, phase: s32, limit: s32) -> BreathSession { + steps: s32 = 0 + while state.phase == phase && steps < limit && state.completed == 0 { + state = BreathSessionStep(state) + steps += 1 + } + return state +} + +// How many steps the session spends in `phase`. +StepsInPhase :: (state: BreathSession, phase: s32, limit: s32) -> s32 { + steps: s32 = 0 + while state.phase == phase && steps < limit && state.completed == 0 { + state = BreathSessionStep(state) + steps += 1 + } + return steps +} + +// Runs one round from Starting to the next round's Starting (or completion), +// ending the hold at once as a tap would. +RunOneRound :: (state: BreathSession) -> BreathSession { + state = AdvanceWhilePhase(state, BreathPhaseStarting, 4000) + state = AdvanceWhilePhase(state, BreathPhaseBreathe, 200000) + if state.phase == BreathPhaseHold { state = BreathEndHold(state) } + state = AdvanceWhilePhase(state, BreathPhaseRecover, 200000) + state = AdvanceWhilePhase(state, BreathPhaseNext, 200000) + return state +} + +DigitsValue :: (digits: []u8) -> s32 { + total: s32 = 0 + index: s32 = 0 + while index < 3 { + digit: s32 = 0 + if digits[index] >= cast(u8)48 && digits[index] <= cast(u8)57 { + digit = cast(s32)digits[index] - 48 + } + total = total * 10 + digit + index += 1 + } + return total +} + +// Round flow: the first countdown is always 3 s; later rounds use the +// configured pause; a zero pause skips it; results are recorded; the final +// round completes and then stays put. +RoundChecks :: () -> s32 { + state: BreathSession = BreathSessionInit() + state.pause_seconds = 15 + state.breath_half_ticks = 120 + state.max_rounds = 3 + if StepsInPhase(state, BreathPhaseStarting, 4000) != 3 * 60 { return 1 } + state = AdvanceWhilePhase(state, BreathPhaseStarting, 4000) + if state.phase != BreathPhaseBreathe { return 2 } + state.round = 0 + if BreathPauseSeconds(state) != 3 { return 3 } + + state = BreathSessionInit() + state.pause_seconds = 15 + state.breath_half_ticks = 120 + state.max_rounds = 3 + state.phase = BreathPhaseStarting + state.round = 0 + state = RunOneRound(state) + if state.round != 1 { return 4 } + if BreathPauseSeconds(state) != 15 { return 5 } + if StepsInPhase(state, BreathPhaseStarting, 4000) != 15 * 60 { return 6 } + + state = BreathSessionInit() + state.pause_seconds = 0 + state.breath_half_ticks = 120 + state.max_rounds = 2 + state.phase = BreathPhaseStarting + state.round = 0 + state = RunOneRound(state) + if state.round != 1 { return 7 } + if BreathPauseSeconds(state) != 0 { return 8 } + if StepsInPhase(state, BreathPhaseStarting, 4000) > 1 { return 9 } + + state = BreathSessionInit() + state.pause_seconds = 2 + state.breath_half_ticks = 120 + state.max_rounds = 3 + state.phase = BreathPhaseStarting + state.round = 0 + state = RunOneRound(state) + if DigitsValue(state.results[0][:]) < 0 { return 10 } + state = RunOneRound(state) + if state.round != 2 { return 11 } + if DigitsValue(state.results[1][:]) < 0 { return 12 } + + state = BreathSessionInit() + state.pause_seconds = 2 + state.breath_half_ticks = 120 + state.max_rounds = 2 + state.phase = BreathPhaseStarting + state.round = 0 + state = RunOneRound(state) + if state.completed != 0 { return 13 } + state = RunOneRound(state) + if state.completed == 0 { return 14 } + phase_before: s32 = state.phase + round_before: s32 = state.round + state = BreathSessionStep(state) + if state.phase != phase_before || state.round != round_before { return 15 } + state = BreathClearCompleted(state) + if state.completed != 0 { return 16 } + return 0 +} + +#program_export +Check :: () -> s32 { + return RoundChecks() +} diff --git a/tests/breath_rounds_zi_test.sh b/tests/breath_rounds_zi_test.sh new file mode 100755 index 000000000..9682c34bb --- /dev/null +++ b/tests/breath_rounds_zi_test.sh @@ -0,0 +1,27 @@ +#!/bin/sh +set -eu + +# Breathing round flow (countdowns, pauses, results, completion) as native +# code. Too many steps for the portable interpreter, so this is native only. +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +bin=${1:-"$root/build/ziran-toolchain/bin"} +work=$root/build/breath-rounds-zi-test +include=${ZIRAN_INCLUDE:-"$root/build/packages/ziran/include"} + +rm -rf "$work" +mkdir -p "$work/c" +"$bin/zi2c" --no-main --root "$root/tests" --module-path "$root/src" \ + -o "$work/c" "$root/tests/breath_rounds_behavior.zi" +cat > "$work/c/main.c" <<'C' +#include +#include "breath_rounds_behavior.h" +int main(void) +{ + int result = Check(); + if (result != 0) fprintf(stderr, "breath rounds check %d failed\n", result); + return result == 0 ? 0 : 1; +} +C +"${CC:-cc}" -std=c11 -I"$include" -I"$work/c" "$work/c"/*.c -o "$work/test" +env -u DISPLAY -u WAYLAND_DISPLAY "$work/test" +echo "breath rounds Ziran test passed" diff --git a/tests/breath_timing_behavior.zi b/tests/breath_timing_behavior.zi index 404bdb04b..929e63a56 100644 --- a/tests/breath_timing_behavior.zi +++ b/tests/breath_timing_behavior.zi @@ -1,6 +1,8 @@ #import, file "../src/core/types.zi"; #import, file "../src/core/breath_timing.zi"; +using BreathAnimation; + #program_export Answer :: () -> s32 { if BreathHalfTicksForSpeed(0) != 180 || diff --git a/tests/habit_sessions_behavior.zi b/tests/habit_sessions_behavior.zi new file mode 100644 index 000000000..3fabff756 --- /dev/null +++ b/tests/habit_sessions_behavior.zi @@ -0,0 +1,146 @@ +#import "byte_text_linux" +#import, file "storage_test_support.zi"; +#import, file "../src/app/text_buffers.zi"; +#import, file "../src/app/app_types.zi"; +#import, file "../src/app/exercise_types.zi"; +#import, file "../src/app/app_modal_state.zi"; +#import, file "../src/storage/data.zi"; +#import, file "../src/storage/db.zi"; +#import, file "../src/storage/storage_core.zi"; +#import, file "../src/storage/storage_sessions.zi"; +#import, file "../src/habits/habit_types.zi"; +#import, file "../src/habits/habit_memory.zi"; +#import, file "../src/habits/habit_model.zi"; +#import, file "../src/habits/habit_days.zi"; +#import, file "../src/habits/habit_linked_rules.zi"; +#import, file "../src/habits/habit_sessions.zi"; + +using ExerciseType; +using HabitSyncMode; + +app_state: InnerBreeze; +context: HabitLinkedContext; +auto_sync_count: s32; + +// The application's sync trigger; the test only counts how often it fires. +#program_export "app_auto_sync" +host_auto_sync :: (app: *InnerBreeze) -> s32 { + unused app + auto_sync_count += 1 + return 1 +} + +record :: (day: s32, hour: s32, activity: s32, first: s32, second: s32) { + rounds: [2]s32 = .[first, second] + count: s32 = 1 + if second > 0 { count = 2 } + check_true("save session", storage_save_session_at_for_activity(day, hour, 10, 20, + *rounds[0], count, 0, activity, null, 0) != 0) +} + +prepare_habit :: (habit: *Habit, sync_mode: s32, sync_activity: s32) { + habit.* = Habit.{} + unused AppCopyText("habit-1", habit.id[:]) + unused AppCopyText("Linked", habit.name[:]) + habit.sync_mode = sync_mode + habit.sync_activity = sync_activity +} + +test_collect_filters_and_summarizes :: () { + root := make_root("habit-sessions-collect") + check_true("init db", storage_init(root) != 0) + record(20260828, 8, EXERCISE_PATTERNS, 10, 20) + record(20260828, 9, EXERCISE_MEDITATION, 99, 0) + record(20260829, 8, EXERCISE_PATTERNS, 30, 0) + // A session whose activity is unknown counts as Wim Hof. + exec_db_sql("INSERT INTO sessions(id,user_id,started_at,local_date,topic,activity,source,imported_at,rounds_hash,deleted_at,updated_at) VALUES('invalid-whm',(SELECT id FROM users LIMIT 1),1788000000,20260830,0,-1,'local',1,'x',0,1);INSERT INTO session_rounds(session_id,round_index,seconds) VALUES('invalid-whm',0,40);") + habit: Habit + prepare_habit(*habit, 1, habit_activity_mask_for(EXERCISE_PATTERNS)) + habit_collect_linked_entries(*habit, 0, *context) + check_int("filtered linked count", context.count, 2) + check_int("filtered total seconds", context.total_seconds, 60) + check_int("filtered best seconds", context.best_seconds, 30) + // Entries come newest first: one round on the 29th, two on the 28th. + check_int("entry round counts", context.entries[0].round_count + context.entries[1].round_count, 3) + check_int("newest entry has one round", context.entries[0].round_count, 1) + check_true("has included day", HabitLinkedHasDay(*context, 20260828)) + check_true("does not have filtered day", !HabitLinkedHasDay(*context, 20260830)) + check_int("count for included day", HabitLinkedSessionCountForDay(*context, 20260828), 1) + + prepare_habit(*habit, 1, habit_activity_mask_for(EXERCISE_WIM_HOF)) + habit_collect_linked_entries(*habit, 20260830, *context) + check_int("unknown activity falls back to Wim Hof", context.count, 1) + check_int("day filter excludes other days", HabitLinkedSessionCountForDay(*context, 20260828), 0) + storage_close() +} + +test_effective_counts_and_actions :: () { + root := make_root("habit-sessions-counts") + check_true("init db", storage_init(root) != 0) + app_state = InnerBreeze.{} + prepare_habit(*app_state.habits.items[0], 1, habit_activity_mask_for(EXERCISE_PATTERNS)) + app_state.habits.count = 1 + app_state.habits.selected = 0 + record(20260828, 8, EXERCISE_PATTERNS, 10, 0) + record(20260828, 9, EXERCISE_PATTERNS, 20, 0) + habit := *app_state.habits.items[0] + habit_collect_linked_entries(habit, 20260828, *context) + habit_set_day_count(*app_state.habits, 0, 20260828, 1) + check_int("linked count wins", HabitEffectiveDayCount(habit, 20260828, *context), 2) + habit_set_day_count(*app_state.habits, 0, 20260828, 4) + check_int("manual count wins", HabitEffectiveDayCount(habit, 20260828, *context), 4) + habit_apply_count_action(*app_state, 0, 20260828, -10, 2) + check_int("count action respects the minimum", HabitDayCount(habit, 20260828), 2) + habits_free(*app_state.habits) + storage_close() +} + +test_session_change_keeps_manual_extra :: () { + root := make_root("habit-sessions-changed") + check_true("init db", storage_init(root) != 0) + app_state = InnerBreeze.{} + prepare_habit(*app_state.habits.items[0], 1, habit_activity_mask_for(EXERCISE_PATTERNS)) + app_state.habits.count = 1 + app_state.habit_detail_index = 0 + app_state.habit_detail_day = 20260828 + record(20260828, 8, EXERCISE_PATTERNS, 10, 0) + record(20260828, 9, EXERCISE_PATTERNS, 20, 0) + habit_set_day_count(*app_state.habits, 0, 20260828, 4) + auto_sync_count = 0 + habit_session_changed(*app_state, 1) + check_int("session change keeps the manual extra", HabitDayCount(*app_state.habits.items[0], 20260828), 5) + check_int("session change syncs", auto_sync_count, 1) + habit_session_changed(*app_state, -1) + check_int("unknown old count only syncs", auto_sync_count, 2) + habits_free(*app_state.habits) + storage_close() +} + +test_navigation_helpers :: () { + app_state = InnerBreeze.{} + app_state.habit_session_edit.active = 1 + app_state.habit_session_edit.round = 3 + habit_session_cancel_edit(*app_state) + check_int("cancel clears active", app_state.habit_session_edit.active, 0) + check_int("cancel sets the round sentinel", app_state.habit_session_edit.round, -1) + + app_state.habit_session_edit.active = 1 + app_state.habit_session_edit.round = 2 + unused AppCopyText("old-path", app_state.habit_detail_session_path[:]) + habit_open_linked_edit_page(*app_state, 4, 20260828) + check_int("open stores the habit index", app_state.habit_detail_index, 4) + check_int("open stores the day", app_state.habit_detail_day, 20260828) + check_true("open clears the selected session", app_state.habit_detail_session_path[0] == cast(u8)0) + check_int("open resets the edit round", app_state.habit_session_edit.round, -1) +} + +#program_export +Check :: () -> s32 { + guard := support_begin("/tmp/inbe-habit-sessions-zi-test/") + if guard != 0 { return guard } + test_collect_filters_and_summarizes() + test_effective_counts_and_actions() + test_session_change_keeps_manual_extra() + test_navigation_helpers() + return failures +} diff --git a/tests/habit_sessions_zi_test.sh b/tests/habit_sessions_zi_test.sh new file mode 100755 index 000000000..29695c493 --- /dev/null +++ b/tests/habit_sessions_zi_test.sh @@ -0,0 +1,44 @@ +#!/bin/sh +set -eu + +# Storage import/export and migration behaviour, run against a real +# SQLite database in a temporary directory. +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +ziran=${1:-"$root/build/ziran-toolchain/bin/ziran"} +liboqs=${2:-"$root/vendor-builds/linux/x86_64/inbe-liboqs/lib/liboqs.a"} +work=$root/build/habit-sessions-zi-test +include=$root/build/packages/ziran/include + +rm -rf "$work" +mkdir -p "$work/generated" +"$ziran" build --target=c --define PLATFORM_DESKTOP --root "$root/tests" \ + --module-path "$root/src" \ + --module-path "$root/build/packages/kryon/src/ui" \ + --module-path "$root/build/packages/kryon/src/kss" \ + --module-path "$root/build/packages/kryon/src/backend" \ + --module-path "$root/build/packages/game2d/src" \ + --module-path "$root/build/packages/ziran/std" \ + --module-path "$root/build/packages/daochi-client" \ + --entry habit_sessions_behavior:Check \ + -o "$work/generated" "$root/tests/habit_sessions_behavior.zi" \ + "$root/tests/sync_test_host.zi" +cat > "$work/generated/main.c" <<'C' +#include "habit_sessions_behavior.h" +#include +int main(void) +{ + int result = Check(); + if (result != 0) fprintf(stderr, "check failed with code %d\n", result); + return result == 0 ? 0 : 1; +} +C +"${CC:-cc}" -std=c11 -O0 -ffunction-sections -fdata-sections \ + -I"$include" -I"$work/generated" -I"$root/vendor-builds/sqlite" \ + -I"$root/vendor-builds/linux/x86_64/inbe-liboqs/include" \ + "$work/generated"/*.c "$root/vendor-builds/sqlite/sqlite3.c" "$liboqs" \ + -Wl,--gc-sections -ldl -lpthread -lz -lm -o "$work/test" +# Storage must never open the real data directory. +APP_DATA_ROOT=/tmp/inbe-habit-sessions-zi-test/data +export APP_DATA_ROOT +env -u DISPLAY -u WAYLAND_DISPLAY "$work/test" +rm -rf /tmp/inbe-habit-sessions-zi-test diff --git a/tests/storage_habits_behavior.zi b/tests/storage_habits_behavior.zi index 69c5e723a..b4d074b16 100644 --- a/tests/storage_habits_behavior.zi +++ b/tests/storage_habits_behavior.zi @@ -489,6 +489,24 @@ test_existing_sessions_materialize :: () { storage_close() } +// External meditation logs count towards the profile streak and average; a +// log for a session that exists is not counted twice. +test_meditation_logs_feed_profile_stats :: () { + root := make_root("meditation-log-stats") + check_true("init db", storage_init(root) != 0) + storage_close() + raw_exec(root, "INSERT INTO sessions(id,user_id,started_at,local_date,topic,activity,source,imported_at,rounds_hash,deleted_at,updated_at) VALUES('med-session-1',(SELECT id FROM users LIMIT 1),strftime('%s','2026-07-15T00:00:00Z'),20260715,0,1,'sync','1','101',0,strftime('%s','2026-07-15T00:00:00Z'));INSERT INTO session_rounds(session_id,round_index,seconds) VALUES('med-session-1',0,600);INSERT INTO meditation_logs(id,user_id,session_id,duration_seconds,completed_at,updated_at) VALUES('med-log-external',(SELECT id FROM users LIMIT 1),'external-log-session',1200,strftime('%s','2026-07-14T00:00:00Z'),1),('med-log-duplicate',(SELECT id FROM users LIMIT 1),'med-session-1',3000,strftime('%s','2026-07-15T00:00:00Z'),1);") + check_true("reopen db", storage_init(root) != 0) + streak: s32 = -1 + average: s64 = -1 + check_true("stats call", storage_profile_activity_stats(1, 20260715, *streak, *average) != 0) + check_int("streak counts the external log day", streak, 2) + check_int("average counts each session once", cast(s32)average, 900) + check_true("stale day stats call", storage_profile_activity_stats(1, 20260716, *streak, *average) != 0) + check_int("streak resets on a stale day", streak, 0) + storage_close() +} + #program_export Check :: () -> s32 { guard := support_begin("/tmp/inbe-storage-habits-zi-test/") @@ -504,5 +522,6 @@ Check :: () -> s32 { test_profile_week_stats() test_linked_counts_materialize() test_existing_sessions_materialize() + test_meditation_logs_feed_profile_stats() return failures } diff --git a/tests/storage_more_behavior.zi b/tests/storage_more_behavior.zi new file mode 100644 index 000000000..544494158 --- /dev/null +++ b/tests/storage_more_behavior.zi @@ -0,0 +1,408 @@ +#import "byte_text_linux" +#import "drawing_props" +#import "zip" +#import, file "storage_test_support.zi"; +#import, file "../src/app/text_buffers.zi"; +#import, file "../src/storage/data.zi"; +#import, file "../src/storage/state.zi"; +#import, file "../src/storage/db.zi"; +#import, file "../src/storage/import.zi"; +#import, file "../src/storage/session_mood.zi"; +#import, file "../src/storage/storage_core.zi"; +#import, file "../src/storage/storage_sessions.zi"; +#import, file "../src/storage/storage_elist.zi"; +#import, file "../src/screens/elist_types.zi"; +#import, file "../src/habits/habit_types.zi"; +#import, file "../src/habits/habit_memory.zi"; +#import, file "../src/storage/storage_habits.zi"; +#import, file "../src/habits/habit_model.zi"; + +c :: #system_library "c"; +zip_open :: (path: *u8, mode: *u8) -> *void #foreign c "fopen"; +zip_close :: (file: *void) -> s32 #foreign c "fclose"; +zip_write :: (data: *void, size: usize, count: usize, file: *void) -> usize #foreign c "fwrite"; +zip_allocate :: (size: usize) -> *void #foreign c "malloc"; +zip_release :: (memory: *void) #foreign c "free"; +run_command :: (command: *u8) -> s32 #foreign c "system"; +read_file :: (path: *u8, size: *s32) -> *u8 #foreign c "LoadFileData"; +using StorageImportMode; + +habits_a: Habits; +habits_b: Habits; +elists: EListState; + +ascii_lower :: (byte: u8) -> u8 { + if byte >= cast(u8)65 && byte <= cast(u8)90 { return byte + cast(u8)32 } + return byte +} + +find_habit :: (habits: *Habits, name: string) -> *Habit { + index: s32 = 0 + while index < habits.count { + text := TextFromCString(*habits.items[index].name[0]) + if text.count == name.count { + same: bool = true + position: s64 = 0 + while position < text.count { + if ascii_lower(text[position]) != ascii_lower(name[position]) { same = false } + position += 1 + } + if same { return *habits.items[index] } + } + index += 1 + } + return null +} + +has_day :: (habit: *Habit, day: s32) -> bool { + return habit != null && habit_completed_day(habit, day) != 0 +} + +day_count_of :: (habit: *Habit, day: s32) -> s32 { + index := habit_find_day(habit, day) + if index < 0 { return -1 } + return habit.days[index].count +} + +Meditation :: () -> Color { + return Color.{99, 196, 165, 255} +} + +// A source database with one session and default habits (meditation done on +// 20260613), like the one the import tests start from. +write_source_database :: (root: string) { + rounds: [3]s32 = .[45, 60, 75] + check_true("init source db", storage_init(root) != 0) + check_true("save source session", storage_save_session_for_activity(*rounds[0], 3, 0, 0, null, 0) != 0) + habits_a = Habits.{} + habits_add_default_set(*habits_a) + habit_set_day(*habits_a, 0, 20260613, 1) + habits_save(*habits_a) + habits_free(*habits_a) + check_int("source sessions", storage_session_count(), 1) + storage_close() +} + +assert_imported_database :: (root: string) { + check_true("init imported db", storage_init(root) != 0) + check_int("imported sessions", storage_session_count(), 1) + habits_b = Habits.{} + check_true("imported habits load", storage_habits_load(cast(*void)*habits_b) != 0) + check_int("imported habit count", habits_b.count, 2) + check_true("imported meditation day", has_day(find_habit(*habits_b, "Meditation"), 20260613)) + check_true("imported yoga", find_habit(*habits_b, "Yoga") != null) + habits_free(*habits_b) + storage_close() +} + +// Writes a stored ZIP holding `count` entries (up to 2). +write_zip :: (path: string, first_name: string, first: *u8, first_size: s64, + second_name: string, second: *u8, second_size: s64) { + total: s64 = cast(s64)first_name.count + first_size + cast(s64)second_name.count + second_size + input: []u8 = BytesFromPointer(cast(*u8)zip_allocate(cast(usize)total), cast(u64)total) + items: [2]ZipWriteItem + at: s64 = 0 + index: s64 = 0 + while index < cast(s64)first_name.count { + input[at] = first_name[index] + at += 1 + index += 1 + } + items[0] = ZipWriteItem.{cast(u64)0, cast(u64)first_name.count, cast(u64)at, cast(u64)first_size} + index = 0 + while index < first_size { + input[at] = first[index] + at += 1 + index += 1 + } + count: s32 = 1 + if second_name.count > 0 { + name_at: s64 = at + index = 0 + while index < cast(s64)second_name.count { + input[at] = second_name[index] + at += 1 + index += 1 + } + items[1] = ZipWriteItem.{cast(u64)name_at, cast(u64)second_name.count, cast(u64)at, cast(u64)second_size} + index = 0 + while index < second_size { + input[at] = second[index] + at += 1 + index += 1 + } + count = 2 + } + size: u64 = StoredZipSize(input, items[0:count]) + output: []u8 = BytesFromPointer(cast(*u8)zip_allocate(cast(usize)size), size) + written: u64 = WriteStoredZip(output, input, items[0:count]) + check_true("zip written", written == size && size > 0) + file_path: TextBuffer + append(*file_path, path) + mode: [3]u8 = .[119, 98, 0] + file := zip_open(*file_path.bytes[0], *mode[0]) + if file != null { + unused zip_write(cast(*void)*output[0], 1, cast(usize)size, file) + unused zip_close(file) + } else { + check_true("open zip for writing", false) + } + zip_release(cast(*void)*input[0]) + zip_release(cast(*void)*output[0]) +} + +test_previous_and_current_archive_entries :: () { + source := make_root("archive-source") + write_source_database(source) + database: TextBuffer + append(*database, source) + append(*database, "/inbe.db") + size: s32 = 0 + bytes := read_file(*database.bytes[0], *size) + check_true("read source database", bytes != null && size > 0) + names: [2]string = .["inbe-data/inbe.db", "breathing-data/breathing.db"] + labels: [2]string = .["current", "previous"] + which: s32 = 0 + while which < 2 { + dest := make_root(join("archive-dest-", labels[which])) + archive: TextBuffer + append(*archive, source) + append(*archive, "/") + append(*archive, labels[which]) + append(*archive, ".zip") + write_zip(TextFromCString(*archive.bytes[0]), names[which], bytes, cast(s64)size, "", null, 0) + check_true("init import destination", storage_init(dest) != 0) + check_true(join("import ", join(labels[which], " archive entry")), + storage_import_zip(TextFromCString(*archive.bytes[0])) != 0) + storage_close() + assert_imported_database(dest) + which += 1 + } +} + +// Historical archives hold session text files rather than a database. They +// import their sessions, and importing again adds nothing. +test_legacy_file_session_zip :: () { + source := make_root("legacy-zip-source") + dest := make_root("legacy-zip-dest") + archive: TextBuffer + append(*archive, source) + append(*archive, "/legacy.zip") + metadata: string = "Legacy BreathSession export\n" + rounds: string = "31\n35\n39\n27\n" + write_zip(TextFromCString(*archive.bytes[0]), "lotus-data/metadata.txt", pointer_of(metadata), + cast(s64)metadata.count, "custom-root/sessions/2026/06/13/breathing-010203", + pointer_of(rounds), cast(s64)rounds.count) + path := TextFromCString(*archive.bytes[0]) + check_true("init destination", storage_init(dest) != 0) + info: StorageImportInfo + check_true("inspection accepts the archive", storage_inspect_import(path, *info) != 0) + check_true("inspection sees sessions", info.valid != 0 && info.has_sessions != 0) + check_int("inspection counts the session", info.session_count, 1) + check_true("import", storage_import_zip(path) != 0) + check_int("session imported", storage_session_count(), 1) + check_true("import again", storage_import_zip(path) != 0) + check_int("repeat import adds nothing", storage_session_count(), 1) + storage_close() +} + +test_checkin_backup_restore :: () { + source := make_root("checkin-backup") + target := make_root("checkin-restored") + archive: TextBuffer + append(*archive, source) + append(*archive, "/backup.zip") + archive_path := TextFromCString(*archive.bytes[0]) + id: [128]u8 + duration: [1]s32 = .[60] + saved: SessionMoodCheckin + loaded: SessionMoodCheckin + check_true("init source", storage_init(source) != 0) + check_true("save session", storage_save_session_for_activity(*duration[0], 1, 0, 1, *id[0], 128) != 0) + saved.mood_before = 2 + saved.mood_after = 4 + saved.energy = 3 + saved.stress = 1 + unused AppCopyText("Quiet morning", saved.note[:]) + unused AppCopyText("morning,home", saved.tags[:]) + session := TextFromCString(*id[0]) + check_true("save check-in", storage_save_session_checkin(session, *saved) != 0) + check_true("export", storage_export_zip(archive_path) != 0) + storage_close() + check_true("init target", storage_init(target) != 0) + check_true("import", storage_import_zip(archive_path) != 0) + check_true("load restored check-in", storage_load_session_checkin(session, *loaded) != 0) + check_int("restored mood before", loaded.mood_before, 2) + check_int("restored mood after", loaded.mood_after, 4) + check_int("restored energy", loaded.energy, 3) + check_int("restored stress", loaded.stress, 1) + check_true("restored note", TextFromCString(*loaded.note[0]) == "Quiet morning") + check_true("restored tags", TextFromCString(*loaded.tags[0]) == "morning,home") + saved.mood_after = 5 + check_true("edit restored check-in", storage_save_session_checkin(session, *saved) != 0) + check_true("re-import duplicate", storage_import_zip(archive_path) != 0) + check_true("load retained check-in", storage_load_session_checkin(session, *loaded) != 0) + check_int("duplicate keeps the local mood", loaded.mood_after, 5) + check_int("duplicate adds no session", storage_session_count(), 1) + storage_close() +} + +test_historical_file_sessions :: () { + root := make_root("legacy-files") + nested: TextBuffer + append(*nested, "mkdir -p ") + append(*nested, root) + append(*nested, "/2026/06/13") + unused run_command(*nested.bytes[0]) + session_path: TextBuffer + append(*session_path, root) + append(*session_path, "/2026/06/13/breathing-010203") + historical: TextBuffer = joined_text("31\n35\n39\n27\n") + check_true("write historical session", write_text_file(*session_path.bytes[0], *historical)) + check_true("init with historical file sessions", storage_init(root) != 0) + check_int("historical session imported", storage_session_count(), 1) + check_true("historical source file retained", file_holds(*session_path.bytes[0], "31\n35\n39\n27\n")) + storage_close() + check_true("reopen after file import", storage_init(root) != 0) + check_int("historical session not duplicated", storage_session_count(), 1) + storage_close() +} + +joined_text :: (text: string) -> TextBuffer { + buffer: TextBuffer + append(*buffer, text) + return buffer +} + +test_deleted_list_defaults_stay_deleted :: () { + root := make_root("elist-defaults") + check_true("init db", storage_init(root) != 0) + elists = EListState.{} + check_true("load initial lists", storage_elist_load(cast(*void)*elists) != 0) + check_int("initial list count", elists.list_count, 1) + check_int("initial task count", elists.item_count, 3) + index: s32 = 0 + while index < elists.item_count { + check_true("delete starter task", storage_elist_delete_item(TextFromCString(*elists.items[index].id[0])) != 0) + index += 1 + } + check_true("reload empty list", storage_elist_load(cast(*void)*elists) != 0) + check_int("deleted tasks stay deleted", elists.item_count, 0) + check_true("delete last list", storage_elist_delete_list(TextFromCString(*elists.lists[0].id[0])) != 0) + // An installation from before the initialization marker existed. + storage_set_setting_int("elist_initialized", 0) + storage_close() + check_true("reopen db", storage_init(root) != 0) + check_true("reload deleted lists", storage_elist_load(cast(*void)*elists) != 0) + check_int("deleted lists stay deleted after restart", elists.list_count, 0) + check_int("deleted tasks stay deleted after restart", elists.item_count, 0) + storage_close() +} + +test_onelist_import :: () { + root := make_root("onelist") + path: TextBuffer + append(*path, root) + append(*path, "/tasks.1list") + onelist_text: TextBuffer = joined_text("{\"title\":\"Inbox\",\"items\":[{\"title\":\"Open\",\"comment\":\"Details\",\"done\":false,\"id\":1},{\"title\":\"Finished\",\"comment\":\"\",\"done\":true,\"id\":2}]}") + check_true("write OneList file", write_text_file(*path.bytes[0], *onelist_text)) + check_true("init db", storage_init(root) != 0) + key: [5121]u8 + index: s32 = 0 + while index < 5120 { + if index % 2 == 0 { key[index] = cast(u8)52 } else { key[index] = cast(u8)50 } + index += 1 + } + key[5120] = cast(u8)0 + storage_set_setting_text("sync_private_key", TextFromCString(*key[0])) + check_true("import OneList file", storage_elist_import_onelist(TextFromCString(*path.bytes[0])) != 0) + elists = EListState.{} + check_true("load imported lists", storage_elist_load(cast(*void)*elists) != 0) + check_int("list count", elists.list_count, 1) + check_int("item count", elists.item_count, 2) + check_true("list title", TextFromCString(*elists.lists[0].title[0]) == "Inbox") + check_true("item comment", TextFromCString(*elists.items[0].comment[0]) == "Details") + check_int("done item", elists.items[1].done, 1) + payload := storage_build_sync_payload_json("test-public-id", "test-public-key") + check_true("payload builds", payload != null) + if payload != null { + text := TextFromCString(payload) + check_true("list collection", contains(text, "private.inbe.v1.elist-lists")) + check_true("item collection", contains(text, "private.inbe.v1.elist-items")) + storage_free_sync_payload_json(payload) + } + storage_close() +} + +write_tickmate_database :: (path: string) { + file_exec(path, "CREATE TABLE tracks(_id integer primary key autoincrement,name text not null,description text not null,icon text not null,enabled integer not null,multiple_entries_per_day integer DEFAULT 0,color integer DEFAULT 0,\"order\" integer DEFAULT -1);CREATE TABLE ticks(_id integer primary key autoincrement,_track_id integer,year integer,month integer,day integer,hour integer,minute integer,second integer,has_time_info integer DEFAULT 0);INSERT INTO tracks(_id,name,description,icon,enabled,multiple_entries_per_day,color,\"order\") VALUES(1,'Meditation','Silenced my mind','',1,1,8925,0);") + file_exec(path, "INSERT INTO ticks(_track_id,year,month,day,hour,minute,second,has_time_info) VALUES(1,2026,0,1,0,0,0,0),(1,2026,1,2,0,0,0,0),(1,2026,2,3,0,0,0,0),(1,2026,3,4,0,0,0,0),(1,2026,4,5,0,0,0,0),(1,2026,5,6,0,0,0,0),(1,2026,6,7,0,0,0,0),(1,2026,7,8,0,0,0,0),(1,2026,8,9,0,0,0,0),(1,2026,9,10,0,0,0,0),(1,2026,10,11,0,0,0,0),(1,2026,11,12,0,0,0,0),(1,2025,0,1,0,0,0,0),(1,2025,0,1,0,0,0,0);") + // Thousands more, one per day from 2025-01-01, to check large imports. + file_exec(path, "WITH RECURSIVE n(i) AS (SELECT 0 UNION ALL SELECT i+1 FROM n WHERE i<11999) INSERT INTO ticks(_track_id,year,month,day,hour,minute,second,has_time_info) SELECT 1,CAST(strftime('%Y',date('2025-01-01','+'||i||' day')) AS INTEGER),CAST(strftime('%m',date('2025-01-01','+'||i||' day')) AS INTEGER)-1,CAST(strftime('%d',date('2025-01-01','+'||i||' day')) AS INTEGER),0,0,0,0 FROM n;") +} + +test_tickmate_import :: () { + source := make_root("tickmate-source") + dest := make_root("tickmate-dest") + database: TextBuffer + append(*database, source) + append(*database, "/tickmate.db") + write_tickmate_database(TextFromCString(*database.bytes[0])) + check_true("init destination", storage_init(dest) != 0) + check_true("tickmate import", storage_import_zip(TextFromCString(*database.bytes[0])) != 0) + habits_b = Habits.{} + check_true("load habits", storage_habits_load(cast(*void)*habits_b) != 0) + check_int("habit count", habits_b.count, 1) + habit := *habits_b.items[0] + days: [12]s32 = .[20260101, 20260202, 20260303, 20260404, 20260505, 20260606, + 20260707, 20260808, 20260909, 20261010, 20261111, 20261212] + index: s32 = 0 + while index < 12 { + check_true("tickmate month day", has_day(habit, days[index])) + index += 1 + } + check_true("loads thousands of days", has_day(habit, 20571108)) + check_true("habit name", TextFromCString(*habit.name[0]) == "Meditation") + check_int("counter habit enabled", habit.counter_enabled, 1) + check_int("imports the count", day_count_of(habit, 20250101), 3) + habits_free(*habits_b) + storage_close() +} + +test_tickmate_reimport_recovers_counts :: () { + source := make_root("tickmate-reimport-source") + dest := make_root("tickmate-reimport-dest") + database: TextBuffer + append(*database, source) + append(*database, "/tickmate.db") + write_tickmate_database(TextFromCString(*database.bytes[0])) + check_true("init destination", storage_init(dest) != 0) + habits_a = Habits.{} + check_int("add old boolean meditation", habits_add_custom(*habits_a, "Meditation", Meditation(), 0, 0), 0) + habit_set_day(*habits_a, 0, 20250101, 1) + habits_save(*habits_a) + habits_free(*habits_a) + check_true("tickmate reimport", storage_import_zip(TextFromCString(*database.bytes[0])) != 0) + habits_b = Habits.{} + check_true("reload", storage_habits_load(cast(*void)*habits_b) != 0) + check_int("habit count", habits_b.count, 1) + check_int("counter enabled", habits_b.items[0].counter_enabled, 1) + check_int("restores the count", day_count_of(*habits_b.items[0], 20250101), 3) + habits_free(*habits_b) + storage_close() +} + +#program_export +Check :: () -> s32 { + guard := support_begin("/tmp/inbe-storage-more-zi-test/") + if guard != 0 { return guard } + test_previous_and_current_archive_entries() + test_legacy_file_session_zip() + test_checkin_backup_restore() + test_historical_file_sessions() + test_deleted_list_defaults_stay_deleted() + test_onelist_import() + test_tickmate_import() + test_tickmate_reimport_recovers_counts() + return failures +} diff --git a/tests/storage_more_zi_test.sh b/tests/storage_more_zi_test.sh new file mode 100755 index 000000000..08a9fb47d --- /dev/null +++ b/tests/storage_more_zi_test.sh @@ -0,0 +1,44 @@ +#!/bin/sh +set -eu + +# Storage import/export and migration behaviour, run against a real +# SQLite database in a temporary directory. +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +ziran=${1:-"$root/build/ziran-toolchain/bin/ziran"} +liboqs=${2:-"$root/vendor-builds/linux/x86_64/inbe-liboqs/lib/liboqs.a"} +work=$root/build/storage-more-zi-test +include=$root/build/packages/ziran/include + +rm -rf "$work" +mkdir -p "$work/generated" +"$ziran" build --target=c --define PLATFORM_DESKTOP --root "$root/tests" \ + --module-path "$root/src" \ + --module-path "$root/build/packages/kryon/src/ui" \ + --module-path "$root/build/packages/kryon/src/kss" \ + --module-path "$root/build/packages/kryon/src/backend" \ + --module-path "$root/build/packages/game2d/src" \ + --module-path "$root/build/packages/ziran/std" \ + --module-path "$root/build/packages/daochi-client" \ + --entry storage_more_behavior:Check \ + -o "$work/generated" "$root/tests/storage_more_behavior.zi" \ + "$root/tests/sync_test_host.zi" +cat > "$work/generated/main.c" <<'C' +#include "storage_more_behavior.h" +#include +int main(void) +{ + int result = Check(); + if (result != 0) fprintf(stderr, "check failed with code %d\n", result); + return result == 0 ? 0 : 1; +} +C +"${CC:-cc}" -std=c11 -O0 -ffunction-sections -fdata-sections \ + -I"$include" -I"$work/generated" -I"$root/vendor-builds/sqlite" \ + -I"$root/vendor-builds/linux/x86_64/inbe-liboqs/include" \ + "$work/generated"/*.c "$root/vendor-builds/sqlite/sqlite3.c" "$liboqs" \ + -Wl,--gc-sections -ldl -lpthread -lz -lm -o "$work/test" +# Storage must never open the real data directory. +APP_DATA_ROOT=/tmp/inbe-storage-more-zi-test/data +export APP_DATA_ROOT +env -u DISPLAY -u WAYLAND_DISPLAY "$work/test" +rm -rf /tmp/inbe-storage-more-zi-test diff --git a/tests/storage_sync_behavior.zi b/tests/storage_sync_behavior.zi index 0f7a4bca3..292baa6ef 100644 --- a/tests/storage_sync_behavior.zi +++ b/tests/storage_sync_behavior.zi @@ -471,6 +471,188 @@ test_queued_edit_beats_equal_time_remote :: () { check_int("queued local edit kept", raw_count(second, "SELECT count FROM habit_days WHERE local_date=20260619"), 9) } +// Two devices that already share `habit` (a habit named "Counter" with one +// day), each in its own root. Returns to the caller with neither open. +share_counter_habit :: (first: string, second: string) { + check_true("init device a", storage_init(first) != 0) + set_account() + habits_a = Habits.{} + check_true("add habit", habits_add_custom(*habits_a, "Counter", Green(), 0, 0) == 0) + habit_set_day_count(*habits_a, 0, 20260619, 4) + habits_save(*habits_a) + habits_free(*habits_a) + storage_close() + check_true("init device b", storage_init(second) != 0) + set_account() + storage_close() + check_true("ship habit", ship_to(first, second, 1)) +} + +test_counter_enabled_follows_remote :: () { + first := make_root("sync-toggle-a") + second := make_root("sync-toggle-b") + share_counter_habit(first, second) + raw_exec(first, "UPDATE habits SET counter_enabled=1,updated_at=1781903000;DELETE FROM sync_outbox;INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'habit',id,0,1781903000 FROM habits;") + raw_exec(second, "UPDATE habits SET counter_enabled=0,updated_at=1781902800;DELETE FROM sync_outbox;") + check_true("ship enable", ship_to(first, second, 2)) + check_int("remote enables the counter", raw_count(second, "SELECT counter_enabled FROM habits"), 1) + raw_exec(first, "UPDATE habits SET counter_enabled=0,updated_at=1781903100;DELETE FROM sync_outbox;INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'habit',id,0,1781903100 FROM habits;") + check_true("ship disable", ship_to(first, second, 3)) + check_int("remote disables the counter", raw_count(second, "SELECT counter_enabled FROM habits"), 0) +} + +test_queued_counter_enabled_survives_equal_remote :: () { + first := make_root("sync-queued-toggle-a") + second := make_root("sync-queued-toggle-b") + share_counter_habit(first, second) + raw_exec(first, "UPDATE habits SET counter_enabled=0,updated_at=1781902800;DELETE FROM sync_outbox;INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'habit',id,0,1781902800 FROM habits;") + raw_exec(second, "UPDATE habits SET counter_enabled=1,updated_at=1781902800;DELETE FROM sync_outbox;INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'habit',id,0,1781902800 FROM habits;") + check_true("ship equal-time habit", ship_to(first, second, 2)) + check_int("queued local counter setting kept", raw_count(second, "SELECT counter_enabled FROM habits"), 1) + check_true("reopen device b", storage_init(second) != 0) + check_true("still queued for upload", build_payload() && record_count() > 0) + storage_close() +} + +test_stale_habit_save_keeps_remote_habits :: () { + first := make_root("sync-stale-a") + second := make_root("sync-stale-b") + check_true("init device a", storage_init(first) != 0) + set_account() + habits_a = Habits.{} + check_true("add push ups", habits_add_custom(*habits_a, "Push ups", Green(), 0, 0) == 0) + check_true("add cold shower", habits_add_custom(*habits_a, "Cold Shower", Green(), 0, 0) == 1) + habit_set_day(*habits_a, 0, 20260619, 1) + habit_set_day(*habits_a, 1, 20260619, 1) + habits_save(*habits_a) + habits_free(*habits_a) + check_true("device a payload", build_payload()) + records := records_array() + kept: TextBuffer + append(*kept, records) + storage_close() + + check_true("init device b", storage_init(second) != 0) + set_account() + // Device b's screen holds only the default habits. + habits_a = Habits.{} + habits_add_default_set(*habits_a) + check_true("apply remote habits behind the stale screen", + storage_apply_sync_response_json(response_with(1, TextFromCString(*kept.bytes[0]))) != 0) + habits_save(*habits_a) + habits_b = Habits.{} + check_true("load habits", storage_habits_load(cast(*void)*habits_b) != 0) + check_int("stale save keeps the remote habits", habits_b.count, 4) + check_true("push ups survived", find_habit(*habits_b, "Push ups") != null) + check_true("cold shower survived", find_habit(*habits_b, "Cold Shower") != null) + check_true("default yoga survived", find_habit(*habits_b, "Yoga") != null) + habits_free(*habits_a) + habits_free(*habits_b) + storage_close() +} + +test_duplicate_named_habits_merge :: () { + first := make_root("sync-merge-a") + second := make_root("sync-merge-b") + check_true("init device a", storage_init(first) != 0) + set_account() + storage_close() + raw_exec(first, "INSERT INTO habits(id,user_id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,sort_order,deleted_at,updated_at) VALUES('habit-1',(SELECT id FROM users LIMIT 1),'New Habit',99,196,165,0,0,0,0,0,1781902800),('habit-2',(SELECT id FROM users LIMIT 1),'New Habit',99,196,165,0,0,0,1,0,1781902860),('meditation',(SELECT id FROM users LIMIT 1),'Meditation',126,183,230,1,3,0,2,0,1781902920);INSERT INTO habit_days(habit_id,local_date,completed,count,updated_at) VALUES('habit-1',20260617,1,1,1781902800),('habit-2',20260618,1,1,1781902860),('meditation',20260619,1,1,1781902920);DELETE FROM sync_outbox;INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'habit',id,0,1781902800 FROM habits;INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'habit_day',habit_id,local_date,1781902800 FROM habit_days;") + check_true("init device b", storage_init(second) != 0) + set_account() + storage_close() + check_true("ship duplicates", ship_to(first, second, 1)) + check_true("reopen device b", storage_init(second) != 0) + habits_b = Habits.{} + check_true("load merged habits", storage_habits_load(cast(*void)*habits_b) != 0) + check_int("duplicate habit names collapse to one", habits_b.count, 2) + merged := find_habit(*habits_b, "New Habit") + check_true("merged habit visible", merged != null) + check_true("first duplicate day kept", merged != null && habit_completed_day(merged, 20260617) != 0) + check_true("second duplicate day moved", merged != null && habit_completed_day(merged, 20260618) != 0) + check_true("meditation remains", find_habit(*habits_b, "Meditation") != null) + habits_free(*habits_b) + storage_close() +} + +test_session_last_write_wins :: () { + first := make_root("sync-session-a") + second := make_root("sync-session-b") + session_sql: string = "INSERT INTO sessions(id,user_id,started_at,local_date,topic,activity,source,imported_at,rounds_hash,deleted_at,updated_at) VALUES('session-equal-time',(SELECT id FROM users LIMIT 1),1781902800,20260619,0,1,'local',1781902800,'111',0,1781902800);" + check_true("init device a", storage_init(first) != 0) + set_account() + storage_close() + check_true("init device b", storage_init(second) != 0) + set_account() + storage_close() + raw_exec(first, session_sql) + raw_exec(first, "INSERT INTO session_rounds(session_id,round_index,seconds) VALUES('session-equal-time',0,45);DELETE FROM sync_outbox;INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) VALUES('session','session-equal-time',0,1781902800);") + raw_exec(second, session_sql) + raw_exec(second, "INSERT INTO session_rounds(session_id,round_index,seconds) VALUES('session-equal-time',0,60);DELETE FROM sync_outbox;") + check_true("ship equal-time session", ship_to(first, second, 1)) + check_int("equal-time remote update replaces rounds", + raw_count(second, "SELECT seconds FROM session_rounds WHERE session_id='session-equal-time' AND round_index=0"), 45) + // The same again with a queued local edit: it keeps its own rounds. + raw_exec(second, "UPDATE sessions SET rounds_hash='111',updated_at=1781902800;DELETE FROM session_rounds WHERE session_id='session-equal-time';INSERT INTO session_rounds(session_id,round_index,seconds) VALUES('session-equal-time',0,60);INSERT OR REPLACE INTO sync_outbox(entity_type,entity_id,local_date,queued_at) VALUES('session','session-equal-time',0,1781902800);") + raw_exec(first, "DELETE FROM sync_outbox;INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) VALUES('session','session-equal-time',0,1781902800);") + check_true("ship equal-time session again", ship_to(first, second, 2)) + check_int("queued local rounds are kept", + raw_count(second, "SELECT seconds FROM session_rounds WHERE session_id='session-equal-time' AND round_index=0"), 60) +} + +test_linked_session_delete_syncs :: () { + first := make_root("sync-linked-a") + second := make_root("sync-linked-b") + rounds: [1]s32 = .[60] + id: [44]u8 + today := habits_today_index() + check_true("init device a", storage_init(first) != 0) + set_account() + habits_a = Habits.{} + habits_add_default_set(*habits_a) + habits_save(*habits_a) + check_true("save linked session", storage_save_session_for_activity(*rounds[0], 1, 0, 1, *id[0], 44) != 0) + habits_free(*habits_a) + storage_close() + check_true("init device b", storage_init(second) != 0) + set_account() + storage_close() + check_true("ship linked session and habit day", ship_to(first, second, 1)) + check_int("device b has the session", raw_count(second, "SELECT COUNT(*) FROM sessions WHERE deleted_at=0"), 1) + check_int("device b has the linked day", raw_count(second, "SELECT COUNT(*) FROM habit_days WHERE count>0"), 1) + + check_true("reopen device a", storage_init(first) != 0) + check_true("delete the linked session", storage_delete_session(TextFromCString(*id[0])) != 0) + check_true("deletion payload builds", build_payload()) + check_true("session tombstone uploaded", contains(payload(), "private.inbe.v1.sessions") && contains(payload(), "\"deleted_at\":")) + check_true("linked habit day is cleared remotely too", contains(payload(), "private.inbe.v1.habit-days")) + storage_close() + check_true("ship deletion", ship_to(first, second, 2)) + check_int("device b lost the session", raw_count(second, "SELECT COUNT(*) FROM sessions WHERE deleted_at=0"), 0) + check_int("device b cleared the linked day", raw_count(second, "SELECT COUNT(*) FROM habit_days WHERE count>0"), 0) + unused today +} + +test_fresh_account_bootstraps_without_tombstones :: () { + root := make_root("sync-fresh-account") + check_true("init db", storage_init(root) != 0) + habits_a = Habits.{} + check_true("add habit", habits_add_custom(*habits_a, "Work out", Green(), 0, 0) == 0) + habit_set_day(*habits_a, 0, 20260618, 1) + habits_save(*habits_a) + deleted := storage_delete_all_sessions() + check_true("local reset deleted rows", deleted >= cast(s64)2) + check_int("no active habits", storage_habit_count(), 0) + habits_free(*habits_a) + set_account() + storage_reset_sync_state() + check_true("payload builds", build_payload()) + check_true("fresh account sends a bootstrap", contains(payload(), "\"since_server_version\":0") && + contains(payload(), "\"bootstrap\":true")) + check_int("no stale tombstones or clears", record_count(), 0) + storage_close() +} + #program_export Check :: () -> s32 { guard := support_begin("/tmp/inbe-storage-sync-zi-test/") @@ -490,5 +672,12 @@ Check :: () -> s32 { test_deletion_round_trip() test_counter_counts_apply() test_queued_edit_beats_equal_time_remote() + test_counter_enabled_follows_remote() + test_queued_counter_enabled_survives_equal_remote() + test_stale_habit_save_keeps_remote_habits() + test_duplicate_named_habits_merge() + test_session_last_write_wins() + test_linked_session_delete_syncs() + test_fresh_account_bootstraps_without_tombstones() return failures } diff --git a/tests/storage_test_support.zi b/tests/storage_test_support.zi index 089bf798e..d8a2cff46 100644 --- a/tests/storage_test_support.zi +++ b/tests/storage_test_support.zi @@ -396,3 +396,22 @@ file_holds :: (path: *u8, text: string) -> bool { if data == null { return false } return cast(s64)size == cast(s64)text.count && TextFromCString(data) == text } + +// Runs SQL against any SQLite file. +file_exec :: (path: string, sql: string) { + file_path: TextBuffer + append(*file_path, path) + db: *void = null + error: *u8 = null + if TestSqliteOpen(*file_path.bytes[0], *db) != 0 || db == null { + check_true("open sqlite file", false) + return + } + copy: TextBuffer + append(*copy, sql) + if TestSqliteExec(db, *copy.bytes[0], null, null, *error) != 0 { + check_true(join("sql failed: ", sql), false) + if error != null { TestSqliteFree(cast(*void)error) } + } + TestSqliteClose(db) +} diff --git a/tests/sync_test_host.zi b/tests/sync_test_host.zi index 2b4cddbf2..be0c526c6 100644 --- a/tests/sync_test_host.zi +++ b/tests/sync_test_host.zi @@ -69,27 +69,107 @@ host_unload_file_data :: (data: *u8) { HostRelease(cast(*void)data) } -// Directory listing for legacy text sessions: there are none in a test root. -EmptyPaths :: struct { +// Directory listing for legacy text sessions, as raylib's FilePathList. +PathList :: struct { + capacity: u32 count: u32 paths: **u8 } +HostPipeOpen :: (command: *u8, mode: *u8) -> *void #foreign c "popen"; +HostPipeClose :: (pipe: *void) -> s32 #foreign c "pclose"; +HostLine :: (buffer: *u8, size: s32, pipe: *void) -> *u8 #foreign c "fgets"; +HostCopy :: (destination: *u8, source: *u8, size: usize) -> *u8 #foreign c "strncpy"; + +command_bytes: [1200]u8; +line_bytes: [1100]u8; +pipe_mode: [2]u8; + +// Lists the regular files under `root` (recursively), one path each. #program_export "LoadDirectoryFilesEx" -host_load_directory_files :: (root: *u8, filter: *u8, recursive: bool) -> EmptyPaths { - unused root +host_load_directory_files :: (root: *u8, filter: *u8, recursive: bool) -> PathList { unused filter unused recursive - return EmptyPaths.{0, null} + list: PathList = PathList.{0, 0, null} + if root == null { return list } + prefix: string = "find \"" + index: s64 = 0 + while index < prefix.count { + command_bytes[index] = prefix[index] + index += 1 + } + position: s64 = 0 + while root[position] != cast(u8)0 && index < 1100 { + command_bytes[index] = root[position] + index += 1 + position += 1 + } + tail: string = "\" -type f 2>/dev/null" + position = 0 + while position < tail.count { + command_bytes[index] = tail[position] + index += 1 + position += 1 + } + command_bytes[index] = cast(u8)0 + pipe_mode[0] = cast(u8)114 + pipe_mode[1] = cast(u8)0 + pipe := HostPipeOpen(*command_bytes[0], *pipe_mode[0]) + if pipe == null { return list } + capacity: usize = 4096 + list.paths = cast(**u8)HostAllocate(capacity * cast(usize)8) + if list.paths == null { + HostPipeClose(pipe) + return list + } + list.capacity = cast(u32)capacity + while HostLine(*line_bytes[0], 1100, pipe) != null && cast(usize)list.count < capacity { + length: s32 = 0 + while line_bytes[length] != cast(u8)0 && line_bytes[length] != cast(u8)10 { length += 1 } + line_bytes[length] = cast(u8)0 + copy := cast(*u8)HostAllocate(cast(usize)length + 1) + if copy == null { break } + unused HostCopy(copy, *line_bytes[0], cast(usize)length + 1) + list.paths[list.count] = copy + list.count += 1 + } + HostPipeClose(pipe) + return list } #program_export "UnloadDirectoryFiles" -host_unload_directory_files :: (paths: EmptyPaths) { - unused paths +host_unload_directory_files :: (paths: PathList) { + index: u32 = 0 + while index < paths.count { + HostRelease(cast(*void)paths.paths[index]) + index += 1 + } + if paths.paths != null { HostRelease(cast(*void)paths.paths) } } #program_export "IsPathFile" host_is_path_file :: (path: *u8) -> bool { - unused path - return false + return path != null +} + +// Application-level hooks the route and modal code calls; tests that reach +// them do not need their effects. +#program_export "app_leave_practice_config" +host_leave_practice_config :: (app: *void) { + unused app +} + +#program_export "profile_social_load_friends_cache" +host_load_friends_cache :: (app: *void) { + unused app +} + +#program_export "profile_social_load_leaderboard_cache" +host_load_leaderboard_cache :: (app: *void) { + unused app +} + +#program_export "app_request_social_refresh" +host_request_social_refresh :: (app: *void) { + unused app }