From 049d82227e935230f687a6624815923c8b9bcb52 Mon Sep 17 00:00:00 2001 From: Waozi Date: Mon, 28 Sep 2026 19:35:02 -0300 Subject: [PATCH] Port habit form, session results and sync server tests to Ziran --- scripts/sync-server-test.mjs | 7 +- tests/app_hooks_host.zi | 23 ++ tests/clock_host.zi | 2 + tests/habit_form_behavior.zi | 110 +++++++++ tests/habit_form_zi_test.sh | 44 ++++ tests/habit_sessions_zi_test.sh | 3 +- tests/session_results_behavior.zi | 175 +++++++++++---- tests/session_results_zi_test.sh | 70 +++--- tests/storage_habits_behavior.zi | 21 ++ tests/storage_sync_behavior.zi | 228 +++++++++++++++++++ tests/sync_server_behavior.zi | 355 ++++++++++++++++++++++++++++++ tests/sync_server_zi_test.sh | 47 ++++ tests/sync_test_host.zi | 22 -- 13 files changed, 1011 insertions(+), 96 deletions(-) create mode 100644 tests/app_hooks_host.zi create mode 100644 tests/clock_host.zi create mode 100644 tests/habit_form_behavior.zi create mode 100755 tests/habit_form_zi_test.sh mode change 100644 => 100755 tests/session_results_zi_test.sh create mode 100644 tests/sync_server_behavior.zi create mode 100755 tests/sync_server_zi_test.sh diff --git a/scripts/sync-server-test.mjs b/scripts/sync-server-test.mjs index f24aea072..ee03647cc 100644 --- a/scripts/sync-server-test.mjs +++ b/scripts/sync-server-test.mjs @@ -57,8 +57,11 @@ try { http_proxy: '', https_proxy: '', all_proxy: '', NO_PROXY: '127.0.0.1,localhost', no_proxy: '127.0.0.1,localhost', }; - const client = spawn(resolve('build/bin/tests/sync_server_test'), [url, root, faultUrl], { - stdio: 'inherit', env: clientEnv, + // The client is the Ziran program built by tests/sync_server_zi_test.sh. + const clientBinary = process.env.SYNC_SERVER_TEST_BIN || resolve('build/sync-server-zi-test/test'); + const client = spawn(clientBinary, [], { + stdio: 'inherit', + env: { ...clientEnv, SYNC_TEST_URL: url, SYNC_TEST_FAULT_URL: faultUrl, APP_DATA_ROOT: root }, }); const status = await new Promise((resolve, reject) => { client.on('error', reject); client.on('exit', resolve); diff --git a/tests/app_hooks_host.zi b/tests/app_hooks_host.zi new file mode 100644 index 000000000..569f0f623 --- /dev/null +++ b/tests/app_hooks_host.zi @@ -0,0 +1,23 @@ +// Application-level hooks the route and modal code calls; tests that reach +// them do not need their effects. Built as a separate root so no generated +// header declares them twice. + +#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 +} diff --git a/tests/clock_host.zi b/tests/clock_host.zi new file mode 100644 index 000000000..191c75c29 --- /dev/null +++ b/tests/clock_host.zi @@ -0,0 +1,2 @@ +// The clock the date and time helpers read, from the application host. +#import, file "../src/app/app_clock_host.zi"; diff --git a/tests/habit_form_behavior.zi b/tests/habit_form_behavior.zi new file mode 100644 index 000000000..ba8b5a66b --- /dev/null +++ b/tests/habit_form_behavior.zi @@ -0,0 +1,110 @@ +#import "byte_text_linux" +#import "drawing_props" +#import, file "storage_test_support.zi"; +#import, file "../src/app/text_buffers.zi"; +#import, file "../src/app/app_types.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_habits.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/core/types.zi"; +#import, file "../src/screens/habits/edit.zi"; + +using HabitSyncMode; + +app_state: InnerBreeze; +syncs: s32; + +// Application hooks the form calls when it saves. +#program_export "app_auto_sync" +host_auto_sync :: (app: *InnerBreeze) -> s32 { + unused app + syncs += 1 + return 0 +} + +#program_export "save_settings" +host_save_settings :: (app: *InnerBreeze) { + unused app +} + +set_text :: (target: []u8, text: string) { + unused AppCopyText(text, target) +} + +#program_export +Check :: () -> s32 { + guard := support_begin("/tmp/inbe-habit-form-zi-test/") + if guard != 0 { return guard } + root := make_root("habit-form") + check_true("init db", storage_init(root) != 0) + app_state = InnerBreeze.{} + app := *app_state + + habit_edit_begin_new(app) + check_int("new habit opens the form", app.breathing.screen, ScreenHabitEdit) + check_true("the name starts empty", app.habit_edit.text[0] == cast(u8)0) + check_int("no reminder by default", app.habit_edit.reminder_hour, -1) + check_int("no schedule by default", app.habit_edit.weekdays, HABIT_SCHEDULE_OFF) + check_true("first section open", app.habit_edit.sections[0] != 0) + check_true("only the routine sections are open by default", + app.habit_edit.sections[1] == 0 && app.habit_edit.sections[2] != 0) + + habit_edit_commit(app) + check_true("an empty name keeps the form open", app.habit_edit.active != 0 && app.habit_edit.name_error == 1) + check_int("nothing was added", app.habits.count, 0) + check_int("nothing was stored", storage_habit_count(), 0) + + set_text(app.habit_edit.text[:], " \t ") + habit_edit_commit(app) + check_true("a blank name keeps the form open", app.habit_edit.active != 0 && app.habits.count == 0) + + set_text(app.habit_edit.text[:], "Test counter") + set_text(app.habit_edit.description[:], "Only for testing") + app.habit_edit.counter_enabled = 1 + app.habit_edit.sync_activity = 3 + app.habit_edit.weekdays = 31 + app.habit_edit.reminder_hour = 9 + habit_edit_commit(app) + check_true("a valid habit is added and the form closes", app.habits.count == 1 && app.habit_edit.active == 0) + check_int("the habit is stored", storage_habit_count(), 1) + check_int("sync ran once", syncs, 1) + check_int("counter enabled", app.habits.items[0].counter_enabled, 1) + check_int("linked activities", app.habits.items[0].sync_activity, 3) + check_int("linking is independent of the counter", app.habits.items[0].sync_mode, 1) + check_int("weekdays", app.habits.items[0].weekdays, 31) + check_int("reminder", app.habits.items[0].reminder_hour, 9) + check_true("description", TextFromCString(*app.habits.items[0].description[0]) == "Only for testing") + + habit_edit_begin_new(app) + set_text(app.habit_edit.text[:], "Test counter") + habit_edit_commit(app) + check_true("a duplicate name is refused", app.habit_edit.active != 0 && app.habit_edit.name_error == 2 && app.habits.count == 1) + habit_edit_cancel(app) + check_int("cancelling stores nothing", storage_habit_count(), 1) + check_int("cancelling returns to the overview", app.habits.screen_mode, HABITS_SCREEN_OVERVIEW) + + habit_edit_begin(app, 0) + check_true("editing opens the form for the habit", app.breathing.screen == ScreenHabitEdit && app.habit_edit.is_new == 0) + check_true("the form shows the habit's settings", app.habit_edit.counter_enabled != 0 && app.habit_edit.sync_activity == 3) + set_text(app.habit_edit.text[:], "Unsaved edit") + habit_edit_cancel(app) + check_true("cancelling an edit keeps the habit", TextFromCString(*app.habits.items[0].name[0]) == "Test counter") + + habit_edit_begin(app, 0) + app.habit_edit.counter_enabled = 0 + app.habit_edit.weekdays = 0 + app.habit_edit.reminder_hour = -1 + habit_edit_commit(app) + check_true("turning the counter off leaves the linking alone", + app.habits.items[0].counter_enabled == 0 && app.habits.items[0].sync_activity == 3) + check_true("the schedule and reminder are cleared", + app.habits.items[0].weekdays == 0 && app.habits.items[0].reminder_hour == -1) + check_int("sync ran for the edit", syncs, 2) + habits_free(*app.habits) + storage_close() + return failures +} diff --git a/tests/habit_form_zi_test.sh b/tests/habit_form_zi_test.sh new file mode 100755 index 000000000..602433f68 --- /dev/null +++ b/tests/habit_form_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-form-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_form_behavior:Check \ + -o "$work/generated" "$root/tests/habit_form_behavior.zi" \ + "$root/tests/sync_test_host.zi" +cat > "$work/generated/main.c" <<'C' +#include "habit_form_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-form-zi-test/data +export APP_DATA_ROOT +env -u DISPLAY -u WAYLAND_DISPLAY "$work/test" +rm -rf /tmp/inbe-habit-form-zi-test diff --git a/tests/habit_sessions_zi_test.sh b/tests/habit_sessions_zi_test.sh index 29695c493..e68ea5d81 100755 --- a/tests/habit_sessions_zi_test.sh +++ b/tests/habit_sessions_zi_test.sh @@ -21,7 +21,8 @@ mkdir -p "$work/generated" --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" + "$root/tests/sync_test_host.zi" \ + "$root/tests/app_hooks_host.zi" cat > "$work/generated/main.c" <<'C' #include "habit_sessions_behavior.h" #include diff --git a/tests/session_results_behavior.zi b/tests/session_results_behavior.zi index e3226c03e..d278b570d 100644 --- a/tests/session_results_behavior.zi +++ b/tests/session_results_behavior.zi @@ -1,44 +1,143 @@ +#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/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/storage/session_mood.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/core/types.zi"; +#import, file "../src/app/audio_meter_host.zi"; +#import, file "../src/app/music_library_host.zi"; +#import, file "../src/platform/notification_host.zi"; #import, file "../src/practices/session_results.zi"; +#import, file "../src/practices/meditation/meditation_practice.zi"; +#import, file "../src/practices/meditation/meditation_session.zi"; -using ExerciseType; +c :: #system_library "c"; +pause_microseconds :: (microseconds: u32) -> s32 #foreign c "usleep"; + +app_state: InnerBreeze; + +// Effects outside the session-result rules; finishing a meditation asks for +// a sync directly. +#program_export "app_auto_sync" +host_auto_sync :: (app: *InnerBreeze) -> s32 { + unused app + return 1 +} +#program_export "save_settings" +host_save_settings :: (app: *InnerBreeze) { + unused app +} +#program_export "app_play_bell_cue" +host_play_bell_cue :: (app: *InnerBreeze, volume: float32) { + unused app + unused volume +} +#program_export "meditation_music_start_session" +host_music_start :: (app: *InnerBreeze) { + unused app +} +#program_export "meditation_music_stop" +host_music_stop :: (app: *InnerBreeze) { + unused app +} +#program_export "meditation_music_fade_out" +host_music_fade :: (app: *InnerBreeze) { + unused app +} +#program_export "practice_background_start" +host_background_start :: (app: *InnerBreeze, id: s32) { + unused app + unused id +} +#program_export "practice_active_background_stop" +host_background_stop :: (app: *InnerBreeze) { + unused app +} +#program_export "app_notifications_send_session_complete" +host_notify_complete :: (app: *InnerBreeze) { + unused app +} #program_export -Answer :: () -> s32 { - app: InnerBreeze - app.results_scroll = 81 - detail: [4]u8 = .{97, 98, 99, 0} - path: [5]u8 = .{115, 97, 118, 101, 0} - rounds: [14]s32 - index: s32 = 0 - while index < 14 { - rounds[index] = index + 1 - index += 1 - } - app_prepare_session_results(*app, EXERCISE_PATTERNS, 72, 3, - *detail[0], *rounds[0], 14, *path[0]) - if app.session_result.active != 1 || - app.session_result.activity != EXERCISE_PATTERNS || - app.session_result.primary_value != 72 || - app.session_result.secondary_value != 3 || - app.session_result.round_count != 12 || - app.session_result.round_values[11] != 12 || - app.session_result.detail[2] != 99 || - app.session_result.saved != 1 || - app.session_result.path[3] != 101 || - app.results_scroll != 0 { - return 1 - } - app.session_result.write_failed = 1 - app_prepare_session_results(*app, 99, 0, 0, null, null, 0, null) - if app.session_result.activity != EXERCISE_WIM_HOF || - app.session_result.saved != 0 || - app.session_result.write_failed != 0 || - app.session_result.round_count != 0 || - app.session_result.detail[0] != 0 || - app.session_result.path[0] != 0 { - return 2 - } - return 42 +Check :: () -> s32 { + guard := support_begin("/tmp/inbe-session-results-zi-test/") + if guard != 0 { return guard } + root := make_root("session-results") + rounds: [1]s32 = .[60] + id: [64]u8 + check_true("init db", storage_init(root) != 0) + app_state = InnerBreeze.{} + app := *app_state + + check_true("save the session", storage_save_session_for_activity(*rounds[0], 1, 0, 1, *id[0], 64) != 0) + app_prepare_session_results(app, 1, 60, 0, null, null, 0, *id[0]) + app.session_result.mood = 4 + app_state.breathing.screen = ScreenResults + // With storage unavailable the write fails and the results stay open. + storage_close() + session_result_done(app) + check_true("a failed write keeps the results open", + app.session_result.active != 0 && app.session_result.write_failed != 0) + check_true("the mood is kept and nothing else happens", + app.session_result.mood == 4 && app.breathing.screen != ScreenStart && !app.ui.sync_requested) + check_true("reopen db", storage_init(root) != 0) + session_result_done(app) + check_true("done closes the results, leaves and asks for a sync", + app.session_result.active == 0 && app.breathing.screen == ScreenStart && app.ui.sync_requested) + app.ui.sync_requested = false + session_result_done(app) + check_true("done again does nothing", !app.ui.sync_requested) + + app_prepare_session_results(app, 2, 3, 0, null, null, 0, *id[0]) + storage_close() + session_result_discard(app) + check_true("a failed discard keeps the results open", + app.session_result.active != 0 && app.session_result.write_failed != 0) + check_true("reopen db again", storage_init(root) != 0) + app_state.breathing.screen = ScreenResults + session_result_discard(app) + check_true("discard closes the results, leaves and asks for a sync", + app.session_result.active == 0 && app.breathing.screen == ScreenStart && app.ui.sync_requested) + check_int("the discarded session is gone", storage_session_count(), 0) + app.ui.sync_requested = false + session_result_discard(app) + check_true("discard again does nothing", !app.ui.sync_requested) + + app_prepare_session_results(app, 0, 60, 0, null, null, 0, null) + session_result_done(app) + check_true("results without a saved session close", app.session_result.active == 0) + + // A timed meditation saves once when it ends. Session ids come from the + // start time and rounds, so wait out the second the discarded one used. + unused pause_microseconds(1100000) + // A timed meditation saves once when it ends. + app.meditation.duration_mode = 5 + app.meditation.custom_minutes = 1 + meditation_start_configured(app) + check_int("configured length", app.meditation.remaining_seconds, 60) + meditation_advance_elapsed(app, 1500) + check_int("time passes", app.meditation.remaining_seconds, 59) + app.session_paused = 1 + meditation_advance_elapsed(app, 30000) + check_int("paused time does not count", app.meditation.remaining_seconds, 59) + app.session_paused = 0 + meditation_advance_elapsed(app, 59000) + check_true("finishing shows the results", app.breathing.screen == ScreenResults) + check_int("the session was saved", storage_session_count(), 1) + check_true("results record the saved session", + app.session_result.saved != 0 && app.session_result.primary_value == 60) + meditation_advance_elapsed(app, 60000) + check_int("nothing more is saved", storage_session_count(), 1) + app.session_result.mood = 4 + session_result_done(app) + check_true("done returns to the start", app.breathing.screen == ScreenStart && app.session_result.active == 0) + storage_close() + return failures } diff --git a/tests/session_results_zi_test.sh b/tests/session_results_zi_test.sh old mode 100644 new mode 100755 index 6d1ede5d8..c66d7b706 --- a/tests/session_results_zi_test.sh +++ b/tests/session_results_zi_test.sh @@ -1,41 +1,45 @@ #!/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) -bin=${1:-"$root/build/ziran-toolchain/bin"} -work=$(mktemp -d "$root/build/session-results-test.XXXXXX") -trap 'rm -rf "$work"' EXIT HUP INT TERM -source=$root/tests/session_results_behavior.zi +ziran=${1:-"$root/build/ziran-toolchain/bin/ziran"} +liboqs=${2:-"$root/vendor-builds/linux/x86_64/inbe-liboqs/lib/liboqs.a"} +work=$root/build/session-results-zi-test +include=$root/build/packages/ziran/include -"$bin/zi2zir" --check-only --root "$root/tests" \ - --module-path "$root/src" --module-path "$root/build/packages/kryon/src/ui" \ - --module-path "$root/build/packages/ziran/std" "$source" -"$bin/zi2c" --no-main --root "$root/tests" \ - --module-path "$root/src" --module-path "$root/build/packages/kryon/src/ui" \ - --module-path "$root/build/packages/ziran/std" -o "$work/c" "$source" -cat > "$work/c/main.c" <<'C' +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 session_results_behavior:Check \ + -o "$work/generated" "$root/tests/session_results_behavior.zi" \ + "$root/tests/app_hooks_host.zi" "$root/tests/clock_host.zi" +cat > "$work/generated/main.c" <<'C' #include "session_results_behavior.h" -int main(void) { return Answer() == 42 ? 0 : 1; } +#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 -ffunction-sections -fdata-sections \ - -Wl,--gc-sections -I"$root/build/packages/ziran/include" \ - -I"$work/c" "$work/c"/*.c -o "$work/test" +"${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" \ + "$root/vendor-builds/linux/x86_64/raylib/libraylib.a" \ + -Wl,--gc-sections -ldl -lpthread -lz -lm -latomic -o "$work/test" +# Storage must never open the real data directory. +APP_DATA_ROOT=/tmp/inbe-session-results-zi-test/data +export APP_DATA_ROOT env -u DISPLAY -u WAYLAND_DISPLAY "$work/test" - -flow=$root/tests/session_results_flow_behavior.zi -"$bin/zi2zir" --check-only --root "$root/tests" \ - --module-path "$root/src" --module-path "$root/build/packages/kryon/src/ui" \ - --module-path "$root/build/packages/ziran/std" "$flow" -"$bin/zi2c" --no-main --root "$root/tests" \ - --module-path "$root/src" --module-path "$root/build/packages/kryon/src/ui" \ - --module-path "$root/build/packages/ziran/std" -o "$work/flow" "$flow" -cat > "$work/flow/main.c" <<'C' -#include "session_results_flow_behavior.h" -int main(void) { return Answer() == 42 ? 0 : 1; } -C -"${CC:-cc}" -std=c11 -ffunction-sections -fdata-sections \ - -Wl,--gc-sections -I"$root/build/packages/ziran/include" \ - -I"$work/flow" "$work/flow"/*.c \ - "$root/tests/session_results_flow_host.c" -o "$work/flow-test" -env -u DISPLAY -u WAYLAND_DISPLAY "$work/flow-test" -echo "Session results Ziran test passed" +rm -rf /tmp/inbe-session-results-zi-test diff --git a/tests/storage_habits_behavior.zi b/tests/storage_habits_behavior.zi index b4d074b16..a2f0576ff 100644 --- a/tests/storage_habits_behavior.zi +++ b/tests/storage_habits_behavior.zi @@ -507,6 +507,26 @@ test_meditation_logs_feed_profile_stats :: () { storage_close() } +// Habit ids that are full UUIDs load intact, with their days. +test_uuid_habit_ids_load_days :: () { + root := make_root("uuid-habit-load") + check_true("init db", storage_init(root) != 0) + storage_close() + raw_exec(root, "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('940dd8b7-0d60-48ce-9c8f-433b9170b6b1',(SELECT id FROM users LIMIT 1),'Meditation',1,2,3,0,0,1,0,0,1782200000);INSERT INTO habit_days(habit_id,local_date,completed,count,session_count,updated_at) VALUES('940dd8b7-0d60-48ce-9c8f-433b9170b6b1',20260629,1,1,0,1782200000);") + check_true("reopen db", storage_init(root) != 0) + habits_b = Habits.{} + check_true("load habits", storage_habits_load(cast(*void)*habits_b) != 0) + check_int("habit count", habits_b.count, 1) + check_true("uuid id is not truncated", + TextFromCString(*habits_b.items[0].id[0]) == "940dd8b7-0d60-48ce-9c8f-433b9170b6b1") + check_int("habit day loaded", habits_b.items[0].day_count, 1) + if habits_b.items[0].day_count > 0 { + check_int("habit day date", habits_b.items[0].days[0].day_index, 20260629) + } + habits_free(*habits_b) + storage_close() +} + #program_export Check :: () -> s32 { guard := support_begin("/tmp/inbe-storage-habits-zi-test/") @@ -523,5 +543,6 @@ Check :: () -> s32 { test_linked_counts_materialize() test_existing_sessions_materialize() test_meditation_logs_feed_profile_stats() + test_uuid_habit_ids_load_days() return failures } diff --git a/tests/storage_sync_behavior.zi b/tests/storage_sync_behavior.zi index 292baa6ef..11ba14551 100644 --- a/tests/storage_sync_behavior.zi +++ b/tests/storage_sync_behavior.zi @@ -12,6 +12,7 @@ #import, file "../src/habits/habit_types.zi"; #import, file "../src/habits/habit_memory.zi"; #import, file "../src/storage/storage_habits.zi"; +#import, file "../src/storage/sync_review.zi"; #import, file "../src/habits/habit_model.zi"; c :: #system_library "c"; @@ -653,6 +654,223 @@ test_fresh_account_bootstraps_without_tombstones :: () { storage_close() } +// ---- Full snapshots and the review flow ---------------------------------- + +remote_records_text: TextBuffer; + +// The records a remote device would send: its own database seeded with `sql` +// and every row queued for upload. +remote_records :: (name: string, sql: string) { + root := make_root(name) + check_true("init remote device", storage_init(root) != 0) + set_account() + storage_close() + raw_exec(root, sql) + raw_exec(root, "DELETE FROM sync_outbox;INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'habit',id,0,1782300000 FROM habits;INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'habit_day',habit_id,local_date,1782300000 FROM habit_days;INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'session',id,0,1782300000 FROM sessions;") + check_true("reopen remote device", storage_init(root) != 0) + check_true("remote payload builds", build_payload()) + remote_records_text = TextBuffer.{} + append(*remote_records_text, records_array()) + storage_close() +} + +snapshot_buffer: TextBuffer; + +// A server response asking the client to take a full snapshot. +snapshot_response :: (version: s32, hash: string) -> string { + part: [24]u8 + snapshot_buffer = TextBuffer.{} + append(*snapshot_buffer, "{\"protocol_version\":6,\"status\":\"ok\",\"server_version\":") + append(*snapshot_buffer, FormatInteger(cast(s64)version, part[:])) + append(*snapshot_buffer, ",\"server_state_hash\":\"") + append(*snapshot_buffer, hash) + append(*snapshot_buffer, "\",\"full_snapshot_required\":true,\"changes_complete\":false,\"changes\":{\"encrypted_records\":") + append(*snapshot_buffer, TextFromCString(*remote_records_text.bytes[0])) + append(*snapshot_buffer, "}}") + return TextFromCString(*snapshot_buffer.bytes[0]) +} + +REMOTE_SQL :: "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('remote-habit',(SELECT id FROM users LIMIT 1),'Remote Breath',90,80,70,0,0,1,1,0,1782290000);INSERT INTO habit_days(habit_id,local_date,completed,count,session_count,updated_at) VALUES('remote-habit',20260624,1,7,0,1782290000);INSERT INTO sessions(id,user_id,started_at,local_date,topic,activity,source,imported_at,rounds_hash,deleted_at,updated_at) VALUES('remote-session',(SELECT id FROM users LIMIT 1),1782290000,20260624,2,2,'sync-test',1782290000,'202',0,1782290000);INSERT INTO session_rounds(session_id,round_index,seconds) VALUES('remote-session',0,55);" + +LOCAL_SQL :: "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('local-habit',(SELECT id FROM users LIMIT 1),'Local Breath',10,20,30,0,0,1,1,0,1782300000);INSERT INTO habit_days(habit_id,local_date,completed,count,session_count,updated_at) VALUES('local-habit',20260624,1,4,0,1782300000);INSERT INTO sessions(id,user_id,started_at,local_date,topic,activity,source,imported_at,rounds_hash,deleted_at,updated_at) VALUES('local-session',(SELECT id FROM users LIMIT 1),1782300000,20260624,1,1,'test',1782300000,'101',0,1782300000);INSERT INTO session_rounds(session_id,round_index,seconds) VALUES('local-session',0,40);" + +LOCAL_PENDING_SQL :: "INSERT OR REPLACE INTO sync_outbox(entity_type,entity_id,local_date,queued_at) VALUES('habit','local-habit',0,1782300000);INSERT OR REPLACE INTO sync_outbox(entity_type,entity_id,local_date,queued_at) VALUES('habit_day','local-habit',20260624,1782300000);INSERT OR REPLACE INTO sync_outbox(entity_type,entity_id,local_date,queued_at) VALUES('session','local-session',0,1782300000);" + +// A local device with its own data and (optionally) everything queued. +local_device :: (name: string, seed: string, pending: string) -> string { + root := make_root(name) + check_true("init local device", storage_init(root) != 0) + set_account() + storage_close() + raw_exec(root, seed) + if pending.count > 0 { raw_exec(root, pending) } + check_true("reopen local device", storage_init(root) != 0) + return root +} + +// Starts an upload, so the pending changes are "in flight" when the server +// answers. +mark_pending_payload_in_flight :: () { + check_true("pending payload builds", build_payload()) +} + +count_of :: (root: string, sql: string) -> s32 { + return read_db_count(sql) +} + +test_snapshot_with_pending_local_edits_merges :: () { + remote_records("review-remote-1", REMOTE_SQL) + root := local_device("review-pending", LOCAL_SQL, LOCAL_PENDING_SQL) + mark_pending_payload_in_flight() + check_true("apply the snapshot", storage_apply_sync_response_json(snapshot_response(12, "remote-hash-001")) != 0) + check_true("review is not pending for local edits", storage_sync_review_pending() == 0) + check_int("local session kept", count_of(root, "SELECT COUNT(*) FROM sessions WHERE id='local-session'"), 1) + check_int("remote session merged", count_of(root, "SELECT COUNT(*) FROM sessions WHERE id='remote-session'"), 1) + check_int("local habit kept", count_of(root, "SELECT COUNT(*) FROM habits WHERE id='local-habit'"), 1) + check_int("remote habit merged", count_of(root, "SELECT COUNT(*) FROM habits WHERE id='remote-habit'"), 1) + check_int("pending edits cleared after the accepted sync", count_of(root, "SELECT COUNT(*) FROM sync_outbox"), 0) + storage_close() +} + +test_tiny_pending_snapshot_merges :: () { + remote_records("review-remote-tiny", "INSERT INTO sessions(id,user_id,started_at,local_date,topic,activity,source,imported_at,rounds_hash,deleted_at,updated_at) VALUES('tiny-remote-session',(SELECT id FROM users LIMIT 1),1782290300,20260624,1,1,'sync-test',1782290300,'404',0,1782290300);INSERT INTO session_rounds(session_id,round_index,seconds) VALUES('tiny-remote-session',0,55);") + root := local_device("review-tiny", "INSERT INTO sessions(id,user_id,started_at,local_date,topic,activity,source,imported_at,rounds_hash,deleted_at,updated_at) VALUES('tiny-local-session',(SELECT id FROM users LIMIT 1),1782300000,20260624,1,1,'test',1782300000,'101',0,1782300000);INSERT INTO session_rounds(session_id,round_index,seconds) VALUES('tiny-local-session',0,40);", "INSERT OR REPLACE INTO sync_outbox(entity_type,entity_id,local_date,queued_at) VALUES('session','tiny-local-session',0,1782300000);") + mark_pending_payload_in_flight() + check_true("apply the snapshot", storage_apply_sync_response_json(snapshot_response(15, "remote-hash-tiny-session")) != 0) + check_true("review is not pending", storage_sync_review_pending() == 0) + check_int("local session kept", count_of(root, "SELECT COUNT(*) FROM sessions WHERE id='tiny-local-session'"), 1) + check_int("remote session merged", count_of(root, "SELECT COUNT(*) FROM sessions WHERE id='tiny-remote-session'"), 1) + check_int("outbox cleared", count_of(root, "SELECT COUNT(*) FROM sync_outbox"), 0) + storage_close() +} + +test_local_habit_without_activity_does_not_force_review :: () { + remote_records("review-remote-2", REMOTE_SQL) + root := local_device("review-empty-habit", "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('empty-local-habit',(SELECT id FROM users LIMIT 1),'Empty Habit',10,20,30,0,0,1,1,0,1782300000);", "INSERT OR REPLACE INTO sync_outbox(entity_type,entity_id,local_date,queued_at) VALUES('habit','empty-local-habit',0,1782300000);") + mark_pending_payload_in_flight() + check_true("apply the snapshot", storage_apply_sync_response_json(snapshot_response(12, "remote-hash-001")) != 0) + check_true("review is not pending", storage_sync_review_pending() == 0) + check_int("remote session applied", count_of(root, "SELECT COUNT(*) FROM sessions WHERE id='remote-session'"), 1) + check_int("remote habit applied", count_of(root, "SELECT COUNT(*) FROM habits WHERE id='remote-habit'"), 1) + check_int("outbox cleared", count_of(root, "SELECT COUNT(*) FROM sync_outbox"), 0) + storage_close() +} + +// The review works on the visible differences of a snapshot; rows the +// server marks deleted are not among them. +test_review_ignores_deleted_remote_rows :: () { + root := make_root("review-deleted") + check_true("init db", storage_init(root) != 0) + deleted: string = "{\"server_version\":13,\"server_state_hash\":\"remote-hash-deleted\",\"full_snapshot_required\":true,\"changes_complete\":false,\"changes\":{\"habits\":[],\"habit_days\":[],\"sessions\":[{\"id\":\"deleted-session\",\"started_at\":\"2026-06-24T10:00:00Z\",\"local_date\":20260624,\"topic\":2,\"activity\":3,\"source\":\"sync-test\",\"rounds_hash\":202,\"deleted_at\":1782300000,\"updated_at\":\"2026-06-24T10:00:00Z\",\"rounds\":[{\"round_index\":0,\"hold_seconds\":55}]}],\"meditation_logs\":[]}}" + check_true("no visible diff", storage_sync_review_json_has_visible_diff(deleted) == 0) + check_true("review not pending", storage_sync_review_pending() == 0) + storage_close() +} + +test_remote_additions_apply_without_review :: () { + remote_records("review-remote-yoga", "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('yoga',(SELECT id FROM users LIMIT 1),'Yoga',239,178,102,1,4,0,1,0,1782290000);INSERT INTO habit_days(habit_id,local_date,completed,count,session_count,updated_at) VALUES('yoga',20260624,1,1,0,1782290000);INSERT INTO sessions(id,user_id,started_at,local_date,topic,activity,source,imported_at,rounds_hash,deleted_at,updated_at) VALUES('sun-session',(SELECT id FROM users LIMIT 1),1782290000,20260624,0,2,'test',1782290000,'303',0,1782290000);INSERT INTO session_rounds(session_id,round_index,seconds) VALUES('sun-session',0,1);") + root := make_root("review-additive") + check_true("init db", storage_init(root) != 0) + set_account() + check_true("apply additions", storage_apply_sync_response_json(snapshot_response(14, "remote-hash-yoga")) != 0) + check_true("review not pending", storage_sync_review_pending() == 0) + check_int("sun session applied", count_of(root, "SELECT COUNT(*) FROM sessions WHERE id='sun-session'"), 1) + check_int("yoga habit applied", count_of(root, "SELECT COUNT(*) FROM habits WHERE id='yoga' AND counter_enabled=0"), 1) + check_int("yoga day applied", count_of(root, "SELECT COUNT(*) FROM habit_days WHERE habit_id='yoga' AND count=1"), 1) + storage_close() +} + +test_apply_inside_an_outer_transaction :: () { + remote_records("review-remote-clean", "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('clean-habit',(SELECT id FROM users LIMIT 1),'Clean Breath',12,34,56,0,0,1,3,0,1782290000);INSERT INTO habit_days(habit_id,local_date,completed,count,session_count,updated_at) VALUES('clean-habit',20260624,1,5,0,1782290000);INSERT INTO sessions(id,user_id,started_at,local_date,topic,activity,source,imported_at,rounds_hash,deleted_at,updated_at) VALUES('clean-session',(SELECT id FROM users LIMIT 1),1782290000,20260624,2,2,'sync-test',1782290000,'505',0,1782290000);INSERT INTO session_rounds(session_id,round_index,seconds) VALUES('clean-session',0,44);") + clean := TextBuffer.{} + append(*clean, TextFromCString(*remote_records_text.bytes[0])) + root := make_root("review-nested") + check_true("init db", storage_init(root) != 0) + set_account() + check_true("begin outer transaction", exec_sql("BEGIN IMMEDIATE") != 0) + check_true("apply inside it", storage_apply_sync_response_json(response_with(21, TextFromCString(*clean.bytes[0]))) != 0) + check_true("commit outer transaction", exec_sql("COMMIT") != 0) + check_int("habit applied", count_of(root, "SELECT COUNT(*) FROM habits WHERE id='clean-habit'"), 1) + check_int("day applied", count_of(root, "SELECT COUNT(*) FROM habit_days WHERE habit_id='clean-habit' AND count=5"), 1) + check_int("session applied", count_of(root, "SELECT COUNT(*) FROM sessions WHERE id='clean-session'"), 1) + check_int("rounds applied", count_of(root, "SELECT COUNT(*) FROM session_rounds WHERE session_id='clean-session' AND seconds=44"), 1) + storage_close() + + // A local habit with the same name but another id is replaced by the + // remote one, keeping its days. + second := make_root("review-id-repair") + check_true("init repair db", storage_init(second) != 0) + set_account() + storage_close() + raw_exec(second, "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('local-clean-id',(SELECT id FROM users LIMIT 1),'Clean Breath',9,9,9,0,0,1,3,0,1782200000);INSERT INTO habit_days(habit_id,local_date,completed,count,session_count,updated_at) VALUES('local-clean-id',20260623,1,2,0,1782200000);DELETE FROM sync_outbox;") + check_true("reopen repair db", storage_init(second) != 0) + check_true("apply the remote habit", storage_apply_sync_response_json(response_with(22, TextFromCString(*clean.bytes[0]))) != 0) + check_int("local duplicate id removed", count_of(second, "SELECT COUNT(*) FROM habits WHERE id='local-clean-id'"), 0) + check_int("canonical remote id present", count_of(second, "SELECT COUNT(*) FROM habits WHERE id='clean-habit'"), 1) + check_int("local day moved to the canonical id", count_of(second, "SELECT COUNT(*) FROM habit_days WHERE habit_id='clean-habit' AND local_date=20260623 AND count=2"), 1) + check_int("remote day still applied", count_of(second, "SELECT COUNT(*) FROM habit_days WHERE habit_id='clean-habit' AND local_date=20260624 AND count=5"), 1) + storage_close() +} + +YOGA_SQL :: "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('yoga',(SELECT id FROM users LIMIT 1),'Yoga',239,178,102,1,4,0,1,0,1782300000);INSERT INTO habit_days(habit_id,local_date,completed,count,session_count,updated_at) VALUES('yoga',20260624,1,2,0,1782300000);" + +test_snapshot_removes_absent_local_yoga :: () { + remote_records("review-remote-none", "DELETE FROM habits;") + root := local_device("review-removes-yoga", YOGA_SQL, "DELETE FROM sync_outbox;") + check_true("apply the snapshot", storage_apply_sync_response_json(snapshot_response(13, "remote-hash-deleted")) != 0) + check_true("review not pending", storage_sync_review_pending() == 0) + check_int("yoga habit removed", count_of(root, "SELECT COUNT(*) FROM habits WHERE id='yoga'"), 0) + check_int("yoga day removed", count_of(root, "SELECT COUNT(*) FROM habit_days WHERE habit_id='yoga'"), 0) + storage_close() +} + +test_snapshot_keeps_pending_yoga :: () { + remote_records("review-remote-none-2", "DELETE FROM habits;") + root := local_device("review-keeps-yoga", YOGA_SQL, "INSERT OR REPLACE INTO sync_outbox(entity_type,entity_id,local_date,queued_at) VALUES('habit','yoga',0,1782300000);") + mark_pending_payload_in_flight() + check_true("apply the snapshot", storage_apply_sync_response_json(snapshot_response(13, "remote-hash-deleted")) != 0) + check_true("review not pending", storage_sync_review_pending() == 0) + check_int("pending yoga still local after the merge", count_of(root, "SELECT COUNT(*) FROM habits WHERE id='yoga'"), 1) + storage_close() +} + +test_normal_response_records_server_hash :: () { + root := make_root("review-normal") + status: StorageSyncStatus + check_true("init db", storage_init(root) != 0) + check_true("apply a normal response", storage_apply_sync_response_json( + "{\"protocol_version\":6,\"server_version\":5,\"server_clock\":77,\"server_state_hash\":\"normal-hash-001\",\"account_alias\":\"waozi\",\"changes\":{\"encrypted_records\":[]}}") != 0) + check_true("no review", storage_sync_review_pending() == 0) + check_true("alias saved", storage_get_setting_text("sync_account_alias") == "waozi") + check_true("status loads", storage_sync_status(*status) != 0) + check_int("server version recorded", cast(s32)status.server_version, 5) + check_int("server clock recorded", cast(s32)status.server_clock, 77) + set_account() + check_true("payload builds", build_payload()) + check_true("hash in the next payload", contains(payload(), "\"last_server_state_hash\":\"normal-hash-001\"")) + check_true("clock in the next payload", contains(payload(), "\"client_clock\":77")) + check_true("no full replace requested", !contains(payload(), "full_sync_requested")) + storage_close() +} + +test_social_cache_is_server_authored :: () { + root := make_root("review-social") + cached: [512]u8 + check_true("init db", storage_init(root) != 0) + check_true("store a local social cache", storage_set_social_cache_json("friends.list", + "{\"friends\":[{\"user_id_hash\":\"local-edit\"}]}") != 0) + check_true("a social cache alone is not local syncable data", storage_has_local_syncable_data() == 0) + set_account() + check_true("payload builds", build_payload()) + check_true("social cache is not uploaded", !contains(payload(), "social_cache") && !contains(payload(), "friends.list")) + check_true("apply the server's social cache", storage_apply_sync_response_json( + "{\"protocol_version\":6,\"server_version\":9,\"server_clock\":9,\"server_state_hash\":\"social-hash-001\",\"changes\":{\"encrypted_records\":[],\"social_cache\":[{\"kind\":\"friends.list\",\"json\":{\"friends\":[{\"user_id_hash\":\"server-friend\"}]},\"updated_at\":\"2026-06-28T00:00:00Z\"}]}}") != 0) + check_true("load the cache", storage_get_social_cache_json("friends.list", *cached[0], 512) != 0) + text := TextFromCString(*cached[0]) + check_true("the server's cache replaces the local edit", contains(text, "server-friend") && !contains(text, "local-edit")) + storage_close() +} + #program_export Check :: () -> s32 { guard := support_begin("/tmp/inbe-storage-sync-zi-test/") @@ -679,5 +897,15 @@ Check :: () -> s32 { test_session_last_write_wins() test_linked_session_delete_syncs() test_fresh_account_bootstraps_without_tombstones() + test_snapshot_with_pending_local_edits_merges() + test_tiny_pending_snapshot_merges() + test_local_habit_without_activity_does_not_force_review() + test_review_ignores_deleted_remote_rows() + test_remote_additions_apply_without_review() + test_apply_inside_an_outer_transaction() + test_snapshot_removes_absent_local_yoga() + test_snapshot_keeps_pending_yoga() + test_normal_response_records_server_hash() + test_social_cache_is_server_authored() return failures } diff --git a/tests/sync_server_behavior.zi b/tests/sync_server_behavior.zi new file mode 100644 index 000000000..a9ca09018 --- /dev/null +++ b/tests/sync_server_behavior.zi @@ -0,0 +1,355 @@ +#import "byte_text_linux" +#import "drawing_props" +#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/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/storage/sync_review.zi"; +#import, file "../src/storage/import.zi"; +#import, file "../src/storage/sync_account.zi"; +#import, file "../src/storage/sync_account_host.zi"; +#import, file "../src/storage/sync_runtime.zi"; +#import, file "../src/storage/account_types.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"; + +// Two clients, a friend, and fresh installs syncing through a real Daochi +// server (with a proxy that drops one response), from the first upload to +// backup restore and deletion. The runner passes the server address in +// SYNC_TEST_URL and the faulty proxy's in SYNC_TEST_FAULT_URL, and points +// APP_DATA_ROOT at a disposable directory. + +c :: #system_library "c"; +get_environment :: (name: *u8) -> *u8 #foreign c "getenv"; +pause_microseconds :: (microseconds: u32) -> s32 #foreign c "usleep"; + +habits_a: Habits; +elists: EListState; +requests_text: [8192]u8; +friends_text: [8192]u8; + +environment_text :: (name: string) -> string { + buffer: TextBuffer + append(*buffer, name) + value := get_environment(*buffer.bytes[0]) + if value == null { return "" } + return TextFromCString(value) +} + +AlbumHabitId :: () -> string { return "00000000-0000-4000-8000-000000000042" } + +sub_root :: (root: string, name: string) -> string { + return make_root(join(join("sync-server-", name), "")) +} + +open_client :: (root: string) { + storage_close() + check_true("open client storage", storage_init(root) != 0) +} + +expect_habit :: (id: string, name: string, date: s32) { + habits_a = Habits.{} + check_true("load habits", storage_habits_load(cast(*void)*habits_a) != 0) + found: *Habit = null + index: s32 = 0 + while index < habits_a.count { + if TextFromCString(*habits_a.items[index].id[0]) == id { found = *habits_a.items[index] } + index += 1 + } + check_true(join("habit exists: ", id), found != null) + if found != null { + check_true("habit name", TextFromCString(*found.name[0]) == name) + check_int("habit has one day", found.day_count, 1) + if found.day_count > 0 { + check_int("habit day date", found.days[0].day_index, date) + check_true("habit day completed", found.days[0].completed != 0) + check_int("habit day count", found.days[0].count, 1) + } + } + habits_free(*habits_a) +} + +seed_default_habits :: () { + habits_a = Habits.{} + habits_a.count = 2 + unused AppCopyText("meditation", habits_a.items[0].id[:]) + unused AppCopyText("Meditation", habits_a.items[0].name[:]) + unused AppCopyText("yoga", habits_a.items[1].id[:]) + unused AppCopyText("Yoga", habits_a.items[1].name[:]) + index: s32 = 0 + while index < 2 { + habits_a.items[index].color = Color.{126, 183, 230, 255} + habits_a.items[index].counter_target = 1 + habits_a.items[index].reminder_hour = -1 + index += 1 + } + storage_habits_save(cast(*void)*habits_a) + check_int("defaults seeded", storage_habit_count(), 2) + habits_free(*habits_a) +} + +expect_list :: (list_id: string, item_id: string, title: string, comment: string, done: s32) { + elists = EListState.{} + check_true("load lists", storage_elist_load(cast(*void)*elists) != 0) + lists: s32 = 0 + items: s32 = 0 + storage_elist_counts(*lists, *items) + check_true("lists and items exist", lists > 0 && items > 0) + found_list: bool = false + found_item: bool = false + index: s32 = 0 + while index < elists.list_count { + if TextFromCString(*elists.lists[index].id[0]) == list_id && + TextFromCString(*elists.lists[index].title[0]) == title { found_list = true } + index += 1 + } + index = 0 + while index < elists.item_count { + if TextFromCString(*elists.items[index].id[0]) == item_id && + TextFromCString(*elists.items[index].list_id[0]) == list_id && + TextFromCString(*elists.items[index].comment[0]) == comment && + elists.items[index].done == done { found_item = true } + index += 1 + } + check_true(join("list ", title), found_list) + check_true(join("item in ", title), found_item) +} + +// Syncs until nothing is left queued, retrying transient failures. +synchronize :: (url: string) { + attempt: s32 = 0 + while attempt < 8 { + result: s32 = SyncStoredAccount(url) + if result != 0 { + check_int("sync attempt result", result, 0) + unused pause_microseconds(2000000) + attempt += 1 + continue + } + if storage_sync_review_pending() != 0 { + check_true("apply remote when local is empty", + storage_sync_review_apply_remote_if_local_empty() != 0) + check_true("review cleared", storage_sync_review_pending() == 0) + } + status: StorageSyncStatus + check_true("status", storage_sync_status(*status) != 0) + if status.queued_changes == 0 { return } + attempt += 1 + } + check_true("sync drained the queued changes", false) +} + +mood_is :: (id: string, want: s32) -> bool { + loaded: SessionMoodCheckin + return storage_load_session_checkin(id, *loaded) != 0 && loaded.mood_after == want +} + +#program_export +Check :: () -> s32 { + url := environment_text("SYNC_TEST_URL") + fault := environment_text("SYNC_TEST_FAULT_URL") + if url.count == 0 || fault.count == 0 { return 90 } + guard := support_begin("/tmp/inbe-sync-server-") + if guard != 0 { return guard } + // Keep the URLs, which point into the environment, across storage calls. + server: TextBuffer + append(*server, url) + proxy: TextBuffer + append(*proxy, fault) + url = TextFromCString(*server.bytes[0]) + fault = TextFromCString(*proxy.bytes[0]) + + ask := SyncAccountLocalDataChoice.SYNC_ACCOUNT_LOCAL_DATA_ASK + ok := SyncAccountSaveResult.SYNC_ACCOUNT_SAVE_OK + a := make_root("a") + b := make_root("b") + restored := make_root("restored") + friend_root := make_root("friend") + defaults_root := make_root("restored_defaults") + key_path: TextBuffer + append(*key_path, data_root()) + append(*key_path, "/account.key") + backup: TextBuffer + append(*backup, data_root()) + append(*backup, "/backup.zip") + alias: string = "restore_test" + friend_alias: string = "friend_test" + account: SyncAccount + friend_account: SyncAccount + restored_account: SyncAccount + default_account: SyncAccount + id: [256]u8 + other_id: [256]u8 + duration: [1]s32 = .[60] + checkin: SessionMoodCheckin + + open_client(a) + check_true("generate account", sync_account_generate(*account) != 0) + check_true("save account", sync_account_save(*account, ask) == ok) + habit_name: string = "Recovery meditation" + habits_a = Habits.{} + habits_a.count = 1 + unused AppCopyText(AlbumHabitId(), habits_a.items[0].id[:]) + unused AppCopyText(habit_name, habits_a.items[0].name[:]) + habits_a.items[0].color = Color.{82, 119, 193, 255} + habits_a.items[0].counter_target = 1 + habits_a.items[0].reminder_hour = -1 + storage_habits_save(cast(*void)*habits_a) + habits_free(*habits_a) + check_true("save habit day", storage_habit_day_save(AlbumHabitId(), 20260919, 1, 1) != 0) + expect_habit(AlbumHabitId(), habit_name, 20260919) + check_true("save session", storage_save_session_for_activity(*duration[0], 1, 0, 1, *id[0], 256) != 0) + checkin.mood_after = 4 + session := TextFromCString(*id[0]) + check_true("save check-in", storage_save_session_checkin(session, *checkin) != 0) + check_true("syncing offline fails", SyncStoredAccount("http://127.0.0.1:1") != 0) + check_int("an offline failure keeps local work", storage_session_count(), 1) + open_client(a) + check_true("check-in survives the failure", mood_is(session, 4)) + // The server commits the upload, but the proxy drops its response. + check_true("interrupted upload fails", SyncStoredAccount(fault) != 0) + open_client(a) + synchronize(url) + storage_set_setting_text("sync_server_url", url) + storage_set_sync_enabled(1) + check_int("register alias", RegisterAliasStored(url, alias), 0) + list_id: [37]u8 + item_id: [37]u8 + check_true("create list", storage_elist_create_list("Travel", *list_id[0]) != 0) + list_text := TextFromCString(*list_id[0]) + check_true("create item", storage_elist_create_item(list_text, "Pack bag", "Passport", *item_id[0]) != 0) + item_text := TextFromCString(*item_id[0]) + synchronize(url) + + open_client(b) + check_true("second device joins", sync_account_save(*account, ask) == ok) + synchronize(url) + check_true("alias reaches the second device", storage_get_setting_text("sync_account_alias") == alias) + check_int("session reaches the second device", storage_session_count(), 1) + expect_habit(AlbumHabitId(), habit_name, 20260919) + expect_list(list_text, item_text, "Travel", "Passport", 0) + check_true("complete the item", storage_elist_update_item(item_text, "Pack bag", "Passport", 1, 0) != 0) + synchronize(url) + open_client(a) + synchronize(url) + expect_list(list_text, item_text, "Travel", "Passport", 1) + open_client(b) + check_true("b sees the check-in", mood_is(session, 4)) + checkin.mood_after = 2 + check_true("b edits the check-in", storage_save_session_checkin(session, *checkin) != 0) + synchronize(url) + open_client(a) + synchronize(url) + check_true("a sees the edit", mood_is(session, 2)) + synchronize(url) + check_int("retrying an acknowledged upload is idempotent", storage_session_count(), 1) + + // Both clients edit offline; a's second edit is newer. + open_client(b) + checkin.mood_after = 1 + check_true("b offline edit", storage_save_session_checkin(session, *checkin) != 0) + open_client(a) + checkin.mood_after = 3 + check_true("a first offline edit", storage_save_session_checkin(session, *checkin) != 0) + checkin.mood_after = 4 + check_true("a second offline edit", storage_save_session_checkin(session, *checkin) != 0) + open_client(b) + synchronize(url) + open_client(a) + synchronize(url) + open_client(b) + synchronize(url) + check_true("the newer edit wins", mood_is(session, 4)) + + // A friend, then restoring the same key on fresh installs. + check_true("export the account key", + sync_account_export_private_key(*account, *key_path.bytes[0]) != 0) + storage_set_setting_text("sync_server_url", url) + storage_set_sync_enabled(1) + open_client(friend_root) + check_true("generate the friend's account", sync_account_generate(*friend_account) != 0) + check_true("save the friend's account", sync_account_save(*friend_account, ask) == ok) + storage_set_setting_text("sync_server_url", url) + storage_set_sync_enabled(1) + synchronize(url) + check_int("friend registers an alias", RegisterAliasStored(url, friend_alias), 0) + check_int("friend sends a request", + SendFriendRequestStored(url, TextFromCString(*account.public_id[0])), 0) + open_client(b) + check_int("b fetches requests", FetchFriendRequests(url, requests_text[:]), 0) + request_id: [128]u8 + check_true("request id", storage_json_array_object_text(TextFromCString(*requests_text[0]), + "$.incoming", 0, "id", *request_id[0], 128) != 0) + check_int("b accepts the request", AcceptFriendRequestStored(url, TextFromCString(*request_id[0])), 0) + + open_client(restored) + check_true("read the key back", sync_account_import_private_key_preview(*restored_account, + *key_path.bytes[0]) != 0) + check_true("same account id", TextFromCString(*restored_account.public_id[0]) == + TextFromCString(*account.public_id[0])) + check_true("restore the key", sync_account_save(*restored_account, ask) == ok) + storage_set_setting_text("sync_server_url", url) + storage_set_sync_enabled(1) + synchronize(url) + check_true("alias restored", storage_get_setting_text("sync_account_alias") == alias) + check_int("friends fetch", FetchFriends(url, friends_text[:]), 0) + check_true("friendship recovered", contains(TextFromCString(*friends_text[0]), + TextFromCString(*friend_account.public_id[0]))) + check_int("session restored", storage_session_count(), 1) + check_true("check-in restored", mood_is(session, 4)) + expect_habit(AlbumHabitId(), habit_name, 20260919) + expect_list(list_text, item_text, "Travel", "Passport", 1) + + // A new install may seed the default habits before the key is restored. + open_client(defaults_root) + seed_default_habits() + check_true("read the key for the new install", + sync_account_import_private_key_preview(*default_account, *key_path.bytes[0]) != 0) + check_true("restore on the new install", sync_account_save(*default_account, ask) == ok) + storage_set_setting_text("sync_server_url", url) + storage_set_sync_enabled(1) + synchronize(url) + check_true("alias on the new install", storage_get_setting_text("sync_account_alias") == alias) + check_int("session on the new install", storage_session_count(), 1) + expect_habit(AlbumHabitId(), habit_name, 20260919) + expect_list(list_text, item_text, "Travel", "Passport", 1) + check_int("friends on the new install", FetchFriends(url, friends_text[:]), 0) + check_true("friendship on the new install", contains(TextFromCString(*friends_text[0]), + TextFromCString(*friend_account.public_id[0]))) + + // Backup and restore. + open_client(b) + check_true("export a backup", storage_export_zip(TextFromCString(*backup.bytes[0])) != 0) + open_client(restored) + check_true("import the backup", storage_import_zip(TextFromCString(*backup.bytes[0])) != 0) + check_int("backup session", storage_session_count(), 1) + check_true("backup check-in", mood_is(session, 4)) + + // Deleting one session leaves the unrelated upload alone. + open_client(b) + duration[0] = 90 + check_true("save another session", storage_save_session_for_activity(*duration[0], 1, 0, 1, *other_id[0], 256) != 0) + check_true("delete the first session", storage_delete_session(session) != 0) + synchronize(url) + open_client(a) + synchronize(url) + check_int("deletion preserves the unrelated upload", storage_session_count(), 1) + other := TextFromCString(*other_id[0]) + loaded: SessionMoodCheckin + check_true("the other session loads", storage_load_session_checkin(other, *loaded) != 0) + check_true("delete the other session", storage_delete_session(other) != 0) + synchronize(url) + open_client(b) + synchronize(url) + check_int("both deletions reached the second device", storage_session_count(), 0) + storage_close() + return failures +} diff --git a/tests/sync_server_zi_test.sh b/tests/sync_server_zi_test.sh new file mode 100755 index 000000000..20a137f1c --- /dev/null +++ b/tests/sync_server_zi_test.sh @@ -0,0 +1,47 @@ +#!/bin/sh +set -eu + +# Builds the two-client sync scenario as a Ziran program. It runs against a +# real Daochi server through scripts/sync-server-test.mjs, which needs +# DAOCHI_BIN (a built Daochi server) and node. +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/sync-server-zi-test +include=$root/build/packages/ziran/include +# The system library, linked by name where there is no development symlink. +curl=${CURL_LIBRARY:-$(ls /usr/lib/x86_64-linux-gnu/libcurl.so.4 2>/dev/null || echo -lcurl)} + +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 sync_server_behavior:Check \ + -o "$work/generated" "$root/tests/sync_server_behavior.zi" \ + "$root/tests/sync_test_host.zi" +cat > "$work/generated/main.c" <<'C' +#include +#include "sync_server_behavior.h" +int main(void) +{ + int result = Check(); + if (result != 0) fprintf(stderr, "sync server check failed with code %d\n", result); + if (result == 0) puts("PASS two-client sync, habit/session/list/alias/friend recovery, offline retry, conflict, backup restore, deletion"); + 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" \ + -I"$root/build/packages/monocypher/src" -I"$root/build/packages/monocypher/src/optional" \ + "$work/generated"/*.c "$root/vendor-builds/sqlite/sqlite3.c" "$liboqs" \ + "$root/build/packages/monocypher/src/monocypher.c" \ + "$root/build/packages/monocypher/src/optional/monocypher-ed25519.c" \ + -Wl,--gc-sections -ldl -lpthread -lz -lm "$curl" -o "$work/test" +echo "$work/test" diff --git a/tests/sync_test_host.zi b/tests/sync_test_host.zi index be0c526c6..770c5a8d4 100644 --- a/tests/sync_test_host.zi +++ b/tests/sync_test_host.zi @@ -151,25 +151,3 @@ host_unload_directory_files :: (paths: PathList) { host_is_path_file :: (path: *u8) -> bool { 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 -}