Browse documentation
Python API
View Markdown
On this page

gvn.testing

The public test kit: an in-memory fake for every port, and the contract suites every implementation of a port must pass. Import it from tests only.

The ideas behind it are explained in Testing your harness. This page is generated from the source, so it lists every public name with its signature and docstring. Python API has the other packages and an index of every name.

Modules

Module What it holds Names
gvn.testing.contracts Contract suites: the tests every implementation of a port must pass JournalContract, ClockContract, OutputContract, ModelContract, LeasesContract, MemoryContract, EmbedderContract, ToolContract, ThrottleContract
gvn.testing.eval_contracts Contract suite for the evals ports: the tests every Results implementation must pass ResultsContract
gvn.testing.eval_fakes Fakes for the evals ports: deterministic, in memory, no I/O, no real time MemoryResults, FixedEnvironments, ScriptedStandIn, FixedSubject
gvn.testing.fakes Fakes for every port answer_reply, ScriptExhausted, ScriptedModel, FunctionModel, HeldModel, ManualClock, MemoryJournal, MemoryLeases, Crash, CrashingJournal, ListMemory, HashingEmbedder, RecordingOutput, StubTool, measuring_tool
gvn.testing.postgres A throwaway PostgreSQL server in a Docker container, for integration tests DockerUnavailable, ThrowawayPostgres

gvn.testing.contracts

Contract suites: the tests every implementation of a port must pass.

Each suite is a plain class of test methods with one factory method to override. To test an implementation, subclass the suite in a test module with a name pytest collects, and implement the factory:

class TestMemoryJournal(JournalContract):
    def make_journal(self):
        return MemoryJournal()

Test methods are synchronous and run coroutines with asyncio.run, so no pytest plugin is needed. Suites must hold for fakes and real adapters alike, so they assert only what the port's docstring promises.

Constants: ASSISTANT, SIGNAL_KINDS.

JournalContract

from gvn.testing.contracts import JournalContract
JournalContract()

JournalContract.make_journal

make_journal() -> Journal

A fresh, empty Journal.

JournalContract.test_an_unknown_run_reads_as_empty

test_an_unknown_run_reads_as_empty() -> None

JournalContract.test_appended_records_come_back_in_order

test_appended_records_come_back_in_order() -> None

JournalContract.test_runs_are_isolated_from_each_other

test_runs_are_isolated_from_each_other() -> None

JournalContract.test_returned_records_are_copies

test_returned_records_are_copies() -> None

JournalContract.test_mutating_a_record_after_appending_changes_nothing

test_mutating_a_record_after_appending_changes_nothing() -> None

JournalContract.test_many_appends_keep_their_order

test_many_appends_keep_their_order() -> None

JournalContract.test_nested_plain_json_survives_intact

test_nested_plain_json_survives_intact() -> None

JournalContract.reopen

reopen(journal: Journal) -> Journal

A journal over the same storage as journal, as if the process had restarted.

The default returns the same object, which suits in-memory journals.

JournalContract.test_records_survive_a_reopen

test_records_survive_a_reopen() -> None

JournalContract.test_the_latest_snapshot_survives_a_reopen

test_the_latest_snapshot_survives_a_reopen() -> None

JournalContract.test_a_reopened_journal_keeps_appending_after_the_old_records

test_a_reopened_journal_keeps_appending_after_the_old_records() -> None

JournalContract.test_read_from_zero_returns_everything

test_read_from_zero_returns_everything() -> None

JournalContract.test_read_from_the_middle_returns_the_tail

test_read_from_the_middle_returns_the_tail() -> None

JournalContract.test_read_from_the_last_position_returns_one_record

test_read_from_the_last_position_returns_one_record() -> None

JournalContract.test_read_at_the_end_is_empty

test_read_at_the_end_is_empty() -> None

JournalContract.test_read_past_the_end_is_empty

test_read_past_the_end_is_empty() -> None

JournalContract.test_read_with_start_on_an_unknown_run_is_empty

test_read_with_start_on_an_unknown_run_is_empty() -> None

JournalContract.test_read_start_defaults_to_zero

test_read_start_defaults_to_zero() -> None

JournalContract.test_read_with_start_returns_copies

test_read_with_start_returns_copies() -> None

JournalContract.test_the_length_of_an_unknown_run_is_zero

test_the_length_of_an_unknown_run_is_zero() -> None

JournalContract.test_the_length_grows_with_each_append

test_the_length_grows_with_each_append() -> None

JournalContract.test_lengths_of_different_runs_are_independent

test_lengths_of_different_runs_are_independent() -> None

JournalContract.test_the_length_equals_the_number_of_records_read

test_the_length_equals_the_number_of_records_read() -> None

JournalContract.test_an_empty_journal_holds_no_runs

test_an_empty_journal_holds_no_runs() -> None

JournalContract.test_runs_come_back_as_a_tuple_of_strings

test_runs_come_back_as_a_tuple_of_strings() -> None

JournalContract.test_a_run_with_only_records_is_held

test_a_run_with_only_records_is_held() -> None

JournalContract.test_a_run_with_only_a_snapshot_is_held

test_a_run_with_only_a_snapshot_is_held() -> None

JournalContract.test_a_run_begun_with_begin_is_held

test_a_run_begun_with_begin_is_held() -> None

JournalContract.test_a_run_is_listed_once_however_many_records_and_snapshots_it_has

test_a_run_is_listed_once_however_many_records_and_snapshots_it_has() -> None

JournalContract.test_runs_come_back_in_ascending_code_point_order

test_runs_come_back_in_ascending_code_point_order() -> None

JournalContract.test_the_order_does_not_depend_on_the_order_of_writing

test_the_order_does_not_depend_on_the_order_of_writing() -> None

JournalContract.test_after_leaves_out_every_run_that_is_not_greater

test_after_leaves_out_every_run_that_is_not_greater() -> None

JournalContract.test_after_may_name_a_run_the_journal_does_not_hold

test_after_may_name_a_run_the_journal_does_not_hold() -> None

JournalContract.test_after_compares_by_code_point

test_after_compares_by_code_point() -> None

JournalContract.test_after_past_the_last_run_leaves_nothing

test_after_past_the_last_run_leaves_nothing() -> None

JournalContract.test_limit_keeps_the_lowest_runs

test_limit_keeps_the_lowest_runs() -> None

JournalContract.test_a_limit_larger_than_the_list_keeps_them_all

test_a_limit_larger_than_the_list_keeps_them_all() -> None

JournalContract.test_after_and_limit_together_walk_the_whole_list_page_by_page

test_after_and_limit_together_walk_the_whole_list_page_by_page() -> None

JournalContract.test_limit_applies_after_after

test_limit_applies_after_after() -> None

JournalContract.test_runs_listed_are_not_changed_by_what_the_caller_does_with_them

test_runs_listed_are_not_changed_by_what_the_caller_does_with_them() -> None

JournalContract.test_a_run_written_after_a_listing_shows_in_the_next_one

test_a_run_written_after_a_listing_shows_in_the_next_one() -> None

JournalContract.test_the_runs_survive_a_reopen

test_the_runs_survive_a_reopen() -> None

JournalContract.test_another_object_on_the_same_storage_sees_the_runs

test_another_object_on_the_same_storage_sees_the_runs() -> None

JournalContract.test_after_must_be_a_str_or_none

test_after_must_be_a_str_or_none() -> None

JournalContract.test_limit_must_be_an_int_or_none

test_limit_must_be_an_int_or_none() -> None

JournalContract.test_limit_below_one_is_refused

test_limit_below_one_is_refused() -> None

JournalContract.test_there_is_no_snapshot_before_one_is_saved

test_there_is_no_snapshot_before_one_is_saved() -> None

JournalContract.test_the_first_snapshot_is_kept_whatever_is_saved_later

test_the_first_snapshot_is_kept_whatever_is_saved_later() -> None

JournalContract.test_a_returned_first_snapshot_is_a_copy

test_a_returned_first_snapshot_is_a_copy() -> None

JournalContract.test_the_first_snapshot_survives_a_reopen

test_the_first_snapshot_survives_a_reopen() -> None

JournalContract.test_a_snapshot_round_trips_nested_plain_json

test_a_snapshot_round_trips_nested_plain_json() -> None

JournalContract.test_a_snapshot_at_sequence_zero_is_kept

test_a_snapshot_at_sequence_zero_is_kept() -> None

JournalContract.test_the_highest_sequence_wins_when_saved_in_ascending_order

test_the_highest_sequence_wins_when_saved_in_ascending_order() -> None

JournalContract.test_the_highest_sequence_wins_when_saved_in_descending_order

test_the_highest_sequence_wins_when_saved_in_descending_order() -> None

JournalContract.test_saving_the_same_sequence_again_replaces_the_state

test_saving_the_same_sequence_again_replaces_the_state() -> None

JournalContract.test_snapshots_of_different_runs_are_isolated

test_snapshots_of_different_runs_are_isolated() -> None

JournalContract.test_a_returned_snapshot_state_is_a_copy

test_a_returned_snapshot_state_is_a_copy() -> None

JournalContract.test_mutating_a_state_after_saving_it_changes_nothing

test_mutating_a_state_after_saving_it_changes_nothing() -> None

JournalContract.test_snapshots_do_not_show_up_as_records

test_snapshots_do_not_show_up_as_records() -> None

JournalContract.test_records_do_not_disturb_the_snapshot

test_records_do_not_disturb_the_snapshot() -> None

JournalContract.test_a_snapshot_can_be_saved_for_a_run_with_no_records

test_a_snapshot_can_be_saved_for_a_run_with_no_records() -> None

JournalContract.another

another(journal: Journal) -> Journal

A second journal object over the same storage as journal, both in use at once (another connection, another process's view). The default returns the same object, which suits in-memory journals.

JournalContract.test_concurrent_appends_from_many_tasks_lose_nothing_and_keep_each_tasks_order

test_concurrent_appends_from_many_tasks_lose_nothing_and_keep_each_tasks_order() -> None

JournalContract.test_concurrent_appends_to_different_runs_keep_each_run_contiguous

test_concurrent_appends_to_different_runs_keep_each_run_contiguous() -> None

JournalContract.test_another_object_on_the_same_storage_sees_every_write

test_another_object_on_the_same_storage_sees_every_write() -> None

JournalContract.test_a_bad_run_is_refused

test_a_bad_run_is_refused() -> None

JournalContract.test_a_record_that_is_not_a_plain_json_dict_is_refused_and_nothing_is_written

test_a_record_that_is_not_a_plain_json_dict_is_refused_and_nothing_is_written() -> None

JournalContract.test_a_bad_start_is_refused

test_a_bad_start_is_refused() -> None

JournalContract.test_a_bad_sequence_is_refused_and_nothing_is_saved

test_a_bad_sequence_is_refused_and_nothing_is_saved() -> None

JournalContract.test_a_state_that_is_not_a_plain_json_dict_is_refused_and_nothing_is_saved

test_a_state_that_is_not_a_plain_json_dict_is_refused_and_nothing_is_saved() -> None

JournalContract.test_a_huge_start_reads_as_empty

test_a_huge_start_reads_as_empty() -> None

JournalContract.test_a_fenced_write_with_no_lease_is_refused_and_nothing_is_written

test_a_fenced_write_with_no_lease_is_refused_and_nothing_is_written() -> None

JournalContract.test_a_bad_fence_is_refused

test_a_bad_fence_is_refused() -> None

JournalContract.test_begin_keeps_the_birth_snapshot_and_the_opening_record_together

test_begin_keeps_the_birth_snapshot_and_the_opening_record_together() -> None

JournalContract.test_a_begun_run_survives_a_reopen

test_a_begun_run_survives_a_reopen() -> None

JournalContract.test_a_begun_run_goes_on_with_appends

test_a_begun_run_goes_on_with_appends() -> None

JournalContract.test_beginning_a_begun_run_is_refused_and_changes_nothing

test_beginning_a_begun_run_is_refused_and_changes_nothing() -> None

JournalContract.test_beginning_a_run_with_records_is_refused_and_changes_nothing

test_beginning_a_run_with_records_is_refused_and_changes_nothing() -> None

JournalContract.test_beginning_a_run_holding_only_a_snapshot_is_refused_and_changes_nothing

test_beginning_a_run_holding_only_a_snapshot_is_refused_and_changes_nothing() -> None

JournalContract.test_beginning_a_run_holding_only_a_later_snapshot_is_refused

test_beginning_a_run_holding_only_a_later_snapshot_is_refused() -> None

JournalContract.test_beginning_one_run_leaves_the_others_alone

test_beginning_one_run_leaves_the_others_alone() -> None

JournalContract.test_an_append_at_the_end_it_names_is_written

test_an_append_at_the_end_it_names_is_written() -> None

JournalContract.test_an_append_naming_another_place_is_refused_and_changes_nothing

test_an_append_naming_another_place_is_refused_and_changes_nothing() -> None

JournalContract.test_an_append_naming_a_place_in_an_unknown_run_is_refused

test_an_append_naming_a_place_in_an_unknown_run_is_refused() -> None

JournalContract.test_of_writers_naming_one_place_exactly_one_is_written

test_of_writers_naming_one_place_exactly_one_is_written() -> None

JournalContract.test_of_writers_beginning_one_run_exactly_one_begins_it

test_of_writers_beginning_one_run_exactly_one_begins_it() -> None

JournalContract.test_begin_refuses_what_is_not_a_run_a_state_or_a_record

test_begin_refuses_what_is_not_a_run_a_state_or_a_record() -> None

JournalContract.test_a_bad_position_is_refused

test_a_bad_position_is_refused() -> None

JournalContract.test_a_fenced_begin_or_placed_append_with_no_lease_is_refused

test_a_fenced_begin_or_placed_append_with_no_lease_is_refused() -> None

JournalContract.test_the_fence_is_checked_before_the_place

test_the_fence_is_checked_before_the_place() -> None

ClockContract

from gvn.testing.contracts import ClockContract
ClockContract()

ClockContract.make_clock

make_clock() -> Clock

A fresh Clock.

ClockContract.let_pass

let_pass(clock: Clock, seconds: float) -> None

Make seconds pass on clock (advance a fake; a real clock needs nothing).

ClockContract.short_duration

short_duration() -> float

A small positive duration, in seconds, to sleep in tests.

ClockContract.test_now_is_a_float

test_now_is_a_float() -> None

ClockContract.test_now_never_goes_backwards

test_now_never_goes_backwards() -> None

ClockContract.test_sleeping_zero_seconds_returns

test_sleeping_zero_seconds_returns() -> None

ClockContract.test_a_pending_sleep_completes_once_the_time_has_passed

test_a_pending_sleep_completes_once_the_time_has_passed() -> None

OutputContract

from gvn.testing.contracts import OutputContract
OutputContract()

OutputContract.make_output

make_output() -> Output

A fresh Output.

OutputContract.test_every_kind_of_signal_is_accepted

test_every_kind_of_signal_is_accepted() -> None

OutputContract.test_many_emits_in_a_row_are_accepted

test_many_emits_in_a_row_are_accepted() -> None

ModelContract

from gvn.testing.contracts import ModelContract
ModelContract()

ModelContract.make_model

make_model(text: str) -> Model

A Model whose next reply to any exchange is an assistant message with text.

ModelContract.make_failing_model

make_failing_model() -> Model

A Model whose next call fails.

ModelContract.make_held_model

make_held_model() -> Model | None

A Model whose next call blocks until cancelled, or None if it cannot be held.

ModelContract.test_generate_returns_an_assistant_reply_with_the_requested_text

test_generate_returns_an_assistant_reply_with_the_requested_text() -> None

ModelContract.test_reported_fragments_concatenate_to_the_reply_text

test_reported_fragments_concatenate_to_the_reply_text() -> None

ModelContract.test_the_context_window_is_unknown_or_a_positive_int

test_the_context_window_is_unknown_or_a_positive_int() -> None

ModelContract.test_the_context_window_is_the_same_on_every_call

test_the_context_window_is_the_same_on_every_call() -> None

ModelContract.test_a_failing_model_raises_model_failure

test_a_failing_model_raises_model_failure() -> None

ModelContract.test_a_cancelled_call_raises_cancelled_error_promptly

test_a_cancelled_call_raises_cancelled_error_promptly() -> None

LeasesContract

from gvn.testing.contracts import LeasesContract
LeasesContract()

What every Leases store, with the Journal sharing its storage, must do.

Override make_store (and another for a store reached over a second connection). Times are plain numbers: the store reads no clock.

LeasesContract.make_store

make_store() -> tuple[Journal, Leases]

A fresh, empty (journal, leases) pair over one storage.

LeasesContract.another

another(journal: Journal, leases: Leases) -> tuple[Journal, Leases]

A second (journal, leases) pair over the same storage (another connection, another process's view). The default returns the same objects.

LeasesContract.test_the_first_acquisition_of_a_run_has_fence_one

test_the_first_acquisition_of_a_run_has_fence_one() -> None

LeasesContract.test_a_held_run_cannot_be_acquired_by_anyone_else_or_by_its_holder

test_a_held_run_cannot_be_acquired_by_anyone_else_or_by_its_holder() -> None

LeasesContract.test_an_expired_lease_is_taken_over_with_a_higher_fence

test_an_expired_lease_is_taken_over_with_a_higher_fence() -> None

LeasesContract.test_every_acquisition_grows_the_fence_by_one

test_every_acquisition_grows_the_fence_by_one() -> None

LeasesContract.test_runs_have_independent_leases

test_runs_have_independent_leases() -> None

LeasesContract.test_acquire_refuses_bad_arguments

test_acquire_refuses_bad_arguments() -> None

LeasesContract.test_only_one_of_many_concurrent_acquirers_gets_the_run

test_only_one_of_many_concurrent_acquirers_gets_the_run() -> None

LeasesContract.test_renew_moves_until_and_keeps_the_fence

test_renew_moves_until_and_keeps_the_fence() -> None

LeasesContract.test_an_expired_lease_nobody_took_can_be_renewed

test_an_expired_lease_nobody_took_can_be_renewed() -> None

LeasesContract.test_a_lease_taken_over_cannot_be_renewed_or_released

test_a_lease_taken_over_cannot_be_renewed_or_released() -> None

LeasesContract.test_release_frees_the_run_once

test_release_frees_the_run_once() -> None

LeasesContract.test_a_released_run_can_be_acquired_again_at_once

test_a_released_run_can_be_acquired_again_at_once() -> None

LeasesContract.test_the_holder_of_an_expired_lease_is_still_reported

test_the_holder_of_an_expired_lease_is_still_reported() -> None

LeasesContract.test_renew_and_release_refuse_what_is_not_a_lease

test_renew_and_release_refuse_what_is_not_a_lease() -> None

LeasesContract.test_a_run_parked_with_a_due_time_is_claimable_from_then

test_a_run_parked_with_a_due_time_is_claimable_from_then() -> None

LeasesContract.test_a_run_released_with_no_due_is_never_claimable

test_a_run_released_with_no_due_is_never_claimable() -> None

LeasesContract.test_claimable_runs_come_earliest_first_up_to_the_limit

test_claimable_runs_come_earliest_first_up_to_the_limit() -> None

LeasesContract.test_pools_are_scheduled_apart

test_pools_are_scheduled_apart() -> None

LeasesContract.test_a_held_run_is_claimable_only_once_its_lease_expires

test_a_held_run_is_claimable_only_once_its_lease_expires() -> None

LeasesContract.test_due_refuses_a_bad_limit

test_due_refuses_a_bad_limit() -> None

LeasesContract.test_the_current_lease_writes_under_its_fence

test_the_current_lease_writes_under_its_fence() -> None

LeasesContract.test_the_current_lease_begins_and_appends_at_a_place_under_its_fence

test_the_current_lease_begins_and_appends_at_a_place_under_its_fence() -> None

LeasesContract.test_a_lease_taken_over_cannot_begin_the_run

test_a_lease_taken_over_cannot_begin_the_run() -> None

LeasesContract.test_the_current_lease_is_still_refused_a_place_already_taken

test_the_current_lease_is_still_refused_a_place_already_taken() -> None

LeasesContract.test_an_expired_lease_nobody_took_still_writes

test_an_expired_lease_nobody_took_still_writes() -> None

LeasesContract.test_a_lease_taken_over_writes_nothing

test_a_lease_taken_over_writes_nothing() -> None

LeasesContract.test_a_released_lease_writes_nothing

test_a_released_lease_writes_nothing() -> None

LeasesContract.test_a_fence_the_run_never_had_writes_nothing

test_a_fence_the_run_never_had_writes_nothing() -> None

LeasesContract.test_a_fence_of_another_run_writes_nothing

test_a_fence_of_another_run_writes_nothing() -> None

LeasesContract.test_a_takeover_through_another_connection_fences_the_old_holder

test_a_takeover_through_another_connection_fences_the_old_holder() -> None

MemoryContract

from gvn.testing.contracts import MemoryContract
MemoryContract()

What every Memory must do (gvn.harness.ports.Memory).

Override make_memory; reopen for a durable memory; another for a memory reached over a second connection; fail and mend when the implementation can be made to fail on demand. What "match" means is the implementation's, so the suite asks only what any memory (keywords, vectors) does: an entry is found by its own words, an entry identical to the query comes before entries that share no word with it, and a scope that holds nothing recalls nothing.

MemoryContract.make_memory

make_memory() -> Memory

A fresh, empty Memory.

MemoryContract.reopen

reopen(memory: Memory) -> Memory

A memory over the same storage as memory, as if the process had restarted. The default returns the same object, which suits in-memory memories.

MemoryContract.another

another(memory: Memory) -> Memory

A second memory object over the same storage, both in use at once. The default returns the same object.

MemoryContract.fail

fail(memory: Memory) -> bool

Make every later call on memory raise MemoryFailure; return True, or False when this implementation cannot be made to (the default).

MemoryContract.mend

mend(memory: Memory) -> None

Undo fail.

MemoryContract.test_remember_returns_a_non_empty_str_id

test_remember_returns_a_non_empty_str_id() -> None

MemoryContract.test_a_remembered_text_is_recalled_by_its_own_words

test_a_remembered_text_is_recalled_by_its_own_words() -> None

MemoryContract.test_text_comes_back_exactly

test_text_comes_back_exactly() -> None

MemoryContract.test_the_same_key_again_keeps_nothing_new_and_returns_the_first_id

test_the_same_key_again_keeps_nothing_new_and_returns_the_first_id() -> None

MemoryContract.test_different_keys_keep_different_entries_even_for_the_same_text

test_different_keys_keep_different_entries_even_for_the_same_text() -> None

MemoryContract.test_the_same_key_in_two_scopes_is_two_entries

test_the_same_key_in_two_scopes_is_two_entries() -> None

MemoryContract.test_nothing_is_recalled_across_scopes

test_nothing_is_recalled_across_scopes() -> None

MemoryContract.test_a_scope_that_holds_nothing_recalls_nothing

test_a_scope_that_holds_nothing_recalls_nothing() -> None

MemoryContract.test_recall_returns_at_most_limit_entries

test_recall_returns_at_most_limit_entries() -> None

MemoryContract.test_an_entry_identical_to_the_query_comes_first

test_an_entry_identical_to_the_query_comes_first() -> None

MemoryContract.test_every_entry_is_an_id_and_a_text

test_every_entry_is_an_id_and_a_text() -> None

MemoryContract.test_recall_returns_fresh_copies

test_recall_returns_fresh_copies() -> None

MemoryContract.test_an_empty_query_is_accepted

test_an_empty_query_is_accepted() -> None

MemoryContract.test_remember_refuses_bad_arguments_and_keeps_nothing

test_remember_refuses_bad_arguments_and_keeps_nothing() -> None

MemoryContract.test_recall_refuses_bad_arguments

test_recall_refuses_bad_arguments() -> None

MemoryContract.test_the_memory_keeps_working_after_a_refused_call

test_the_memory_keeps_working_after_a_refused_call() -> None

MemoryContract.test_a_failing_memory_raises_memory_failure_and_recovers_with_its_entries

test_a_failing_memory_raises_memory_failure_and_recovers_with_its_entries() -> None

MemoryContract.test_a_cancelled_call_raises_cancelled_error_and_leaves_the_memory_working

test_a_cancelled_call_raises_cancelled_error_and_leaves_the_memory_working() -> None

MemoryContract.test_entries_and_keys_survive_a_reopen

test_entries_and_keys_survive_a_reopen() -> None

MemoryContract.test_concurrent_remembering_of_one_key_keeps_one_entry

test_concurrent_remembering_of_one_key_keeps_one_entry() -> None

MemoryContract.test_concurrent_remembering_of_different_keys_keeps_every_entry

test_concurrent_remembering_of_different_keys_keeps_every_entry() -> None

MemoryContract.test_forget_removes_an_entry_once_and_says_so

test_forget_removes_an_entry_once_and_says_so() -> None

MemoryContract.test_a_forgotten_entry_is_never_recalled_again

test_a_forgotten_entry_is_never_recalled_again() -> None

MemoryContract.test_forgetting_an_id_of_another_scope_removes_nothing

test_forgetting_an_id_of_another_scope_removes_nothing() -> None

MemoryContract.test_forgetting_an_id_nobody_gave_returns_false

test_forgetting_an_id_nobody_gave_returns_false() -> None

MemoryContract.test_forget_all_returns_how_many_it_removed_and_leaves_other_scopes_whole

test_forget_all_returns_how_many_it_removed_and_leaves_other_scopes_whole() -> None

MemoryContract.test_after_forgetting_the_same_key_keeps_a_new_entry

test_after_forgetting_the_same_key_keeps_a_new_entry() -> None

MemoryContract.test_after_forgetting_everything_a_key_of_the_scope_keeps_a_new_entry

test_after_forgetting_everything_a_key_of_the_scope_keeps_a_new_entry() -> None

MemoryContract.test_ids_are_not_reused_after_forgetting

test_ids_are_not_reused_after_forgetting() -> None

MemoryContract.test_forgetting_leaves_the_other_entries_and_their_keys_alone

test_forgetting_leaves_the_other_entries_and_their_keys_alone() -> None

MemoryContract.test_forget_refuses_bad_arguments_and_removes_nothing

test_forget_refuses_bad_arguments_and_removes_nothing() -> None

MemoryContract.test_forget_all_refuses_bad_arguments_and_removes_nothing

test_forget_all_refuses_bad_arguments_and_removes_nothing() -> None

MemoryContract.test_a_failing_memory_cannot_forget_and_keeps_its_entries

test_a_failing_memory_cannot_forget_and_keeps_its_entries() -> None

MemoryContract.test_a_cancelled_forget_raises_cancelled_error_and_leaves_the_memory_working

test_a_cancelled_forget_raises_cancelled_error_and_leaves_the_memory_working() -> None

MemoryContract.test_a_removal_survives_a_reopen_and_ids_stay_unique

test_a_removal_survives_a_reopen_and_ids_stay_unique() -> None

MemoryContract.test_two_handles_forgetting_one_entry_see_exactly_one_removal

test_two_handles_forgetting_one_entry_see_exactly_one_removal() -> None

EmbedderContract

from gvn.testing.contracts import EmbedderContract
EmbedderContract()

What every Embedder must do (gvn.runtime.memory.Embedder).

Override make_embedder; make_held_embedder when the implementation can be made to block until cancelled. The suite asks nothing about which texts are close: that is the embedding's, and no test can know it for every embedder.

EmbedderContract.make_embedder

make_embedder() -> Embedder

A fresh Embedder, working.

EmbedderContract.make_held_embedder

make_held_embedder() -> Embedder | None

An Embedder whose next embed blocks until cancelled, or None if it cannot be held (the default).

EmbedderContract.test_the_name_is_a_non_empty_str_and_the_same_every_time

test_the_name_is_a_non_empty_str_and_the_same_every_time() -> None

EmbedderContract.test_one_vector_per_text_in_order

test_one_vector_per_text_in_order() -> None

EmbedderContract.test_every_vector_is_a_list_of_finite_floats_of_one_length_and_not_all_zeros

test_every_vector_is_a_list_of_finite_floats_of_one_length_and_not_all_zeros() -> None

EmbedderContract.test_the_same_text_gives_the_same_vector

test_the_same_text_gives_the_same_vector() -> None

EmbedderContract.test_every_call_returns_a_fresh_list

test_every_call_returns_a_fresh_list() -> None

EmbedderContract.test_the_texts_given_are_left_alone

test_the_texts_given_are_left_alone() -> None

EmbedderContract.test_a_call_cancelled_before_it_runs_raises_cancelled_error

test_a_call_cancelled_before_it_runs_raises_cancelled_error() -> None

EmbedderContract.test_a_held_call_cancelled_raises_cancelled_error_promptly

test_a_held_call_cancelled_raises_cancelled_error_promptly() -> None

ToolContract

from gvn.testing.contracts import ToolContract
ToolContract()

What every Tool promises before it is run: the names and the description it gives the model, and the identity everything else matches it by. make_tool returns one configured as it would be deployed; running it is the tool's own tests' business.

ToolContract.make_tool

make_tool() -> Tool

A Tool, as it would be deployed.

ToolContract.test_it_is_a_tool

test_it_is_a_tool() -> None

ToolContract.test_its_name_is_a_valid_short_name

test_its_name_is_a_valid_short_name() -> None

ToolContract.test_its_namespace_is_a_dotted_identifier

test_its_namespace_is_a_dotted_identifier() -> None

ToolContract.test_its_identity_is_its_namespace_and_name_joined_by_a_dot

test_its_identity_is_its_namespace_and_name_joined_by_a_dot() -> None

ToolContract.test_its_identity_is_the_same_on_every_call_and_every_build

test_its_identity_is_the_same_on_every_call_and_every_build() -> None

ToolContract.test_it_describes_itself_to_the_model

test_it_describes_itself_to_the_model() -> None

ToolContract.test_it_says_whether_it_is_independent_and_how_it_retries

test_it_says_whether_it_is_independent_and_how_it_retries() -> None

ToolContract.test_it_says_whether_its_results_are_untrusted_the_same_every_time

test_it_says_whether_its_results_are_untrusted_the_same_every_time() -> None

ToolContract.test_a_toolbox_finds_it_by_its_identity

test_a_toolbox_finds_it_by_its_identity() -> None

ThrottleContract

from gvn.testing.contracts import ThrottleContract
ThrottleContract()

What every Throttle promises (gvn.harness.ports.Throttle): an admitted call is released, waiting can be cancelled without holding anything, and hold_off checks what it is told.

make_throttle returns a fresh Throttle that admits at least two calls at once without its clock moving, and at least CYCLES calls one after another (each released before the next) without its clock moving: a rate limit is built with a calls of at least that many, or on a clock that moves by itself.

ThrottleContract.make_throttle

make_throttle() -> Throttle

A fresh Throttle, as the class docstring says.

ThrottleContract.test_it_is_a_throttle

test_it_is_a_throttle() -> None

ThrottleContract.test_an_acquire_then_a_release_completes

test_an_acquire_then_a_release_completes() -> None

ThrottleContract.test_two_calls_are_admitted_at_once

test_two_calls_are_admitted_at_once() -> None

ThrottleContract.test_many_acquire_and_release_cycles_in_a_row_complete

test_many_acquire_and_release_cycles_in_a_row_complete() -> None

ThrottleContract.test_hold_off_refuses_what_is_not_a_number_of_seconds

test_hold_off_refuses_what_is_not_a_number_of_seconds() -> None

ThrottleContract.test_hold_off_accepts_zero_and_the_throttle_still_admits

test_hold_off_accepts_zero_and_the_throttle_still_admits() -> None

ThrottleContract.test_an_acquire_cancelled_before_it_ran_leaves_the_throttle_usable

test_an_acquire_cancelled_before_it_ran_leaves_the_throttle_usable() -> None

ThrottleContract.test_an_acquire_cancelled_while_two_calls_are_held_leaves_the_throttle_usable

test_an_acquire_cancelled_while_two_calls_are_held_leaves_the_throttle_usable() -> None

gvn.testing.eval_contracts

Contract suite for the evals ports: the tests every Results implementation must pass.

Same shape as gvn.testing.contracts: a plain class of synchronous test methods with one factory method to override, coroutines run with asyncio.run::

class TestMemoryResults(ResultsContract):
    def make_results(self):
        return MemoryResults()

Each test calls make_results() once, so every test starts on an empty store.

ResultsContract

from gvn.testing.eval_contracts import ResultsContract
ResultsContract()

ResultsContract.make_results

make_results() -> Results

A fresh, empty Results.

ResultsContract.test_an_unknown_run_has_no_manifest

test_an_unknown_run_has_no_manifest() -> None

ResultsContract.test_a_new_store_has_no_runs

test_a_new_store_has_no_runs() -> None

ResultsContract.test_an_opened_run_keeps_its_manifest

test_an_opened_run_keeps_its_manifest() -> None

ResultsContract.test_opening_with_an_equal_manifest_changes_nothing

test_opening_with_an_equal_manifest_changes_nothing() -> None

ResultsContract.test_opening_with_a_different_manifest_names_the_differing_keys

test_opening_with_a_different_manifest_names_the_differing_keys() -> None

ResultsContract.test_a_mismatch_writes_nothing

test_a_mismatch_writes_nothing() -> None

ResultsContract.test_a_mismatch_is_a_value_error

test_a_mismatch_is_a_value_error() -> None

ResultsContract.test_runs_come_back_oldest_first

test_runs_come_back_oldest_first() -> None

ResultsContract.test_saving_a_trial_before_opening_the_run_is_a_lookup_error

test_saving_a_trial_before_opening_the_run_is_a_lookup_error() -> None

ResultsContract.test_trials_of_an_unknown_run_are_empty

test_trials_of_an_unknown_run_are_empty() -> None

ResultsContract.test_trials_of_an_opened_run_without_trials_are_empty

test_trials_of_an_opened_run_without_trials_are_empty() -> None

ResultsContract.test_trials_come_back_in_the_order_first_saved

test_trials_come_back_in_the_order_first_saved() -> None

ResultsContract.test_saving_a_trial_again_replaces_it_and_keeps_its_place

test_saving_a_trial_again_replaces_it_and_keeps_its_place() -> None

ResultsContract.test_the_same_case_and_trial_in_two_runs_are_two_trials

test_the_same_case_and_trial_in_two_runs_are_two_trials() -> None

ResultsContract.test_a_case_id_and_a_trial_number_make_one_trial_each

test_a_case_id_and_a_trial_number_make_one_trial_each() -> None

ResultsContract.test_returned_manifests_are_copies

test_returned_manifests_are_copies() -> None

ResultsContract.test_a_manifest_changed_after_opening_changes_nothing

test_a_manifest_changed_after_opening_changes_nothing() -> None

ResultsContract.test_returned_trials_are_copies

test_returned_trials_are_copies() -> None

ResultsContract.test_a_record_changed_after_saving_changes_nothing

test_a_record_changed_after_saving_changes_nothing() -> None

ResultsContract.test_records_keep_json_shaped_nesting

test_records_keep_json_shaped_nesting() -> None

ResultsContract.test_a_record_that_is_not_plain_json_is_refused_and_nothing_is_saved

test_a_record_that_is_not_plain_json_is_refused_and_nothing_is_saved() -> None

ResultsContract.test_a_manifest_that_is_not_plain_json_is_refused_and_nothing_is_written

test_a_manifest_that_is_not_plain_json_is_refused_and_nothing_is_written() -> None

ResultsContract.test_amending_replaces_the_manifest

test_amending_replaces_the_manifest() -> None

ResultsContract.test_an_amended_run_is_continued_under_its_new_manifest_only

test_an_amended_run_is_continued_under_its_new_manifest_only() -> None

ResultsContract.test_amending_an_unknown_run_is_a_lookup_error_and_begins_nothing

test_amending_an_unknown_run_is_a_lookup_error_and_begins_nothing() -> None

ResultsContract.test_amending_leaves_the_trials_as_they_are

test_amending_leaves_the_trials_as_they_are() -> None

ResultsContract.test_a_manifest_changed_after_amending_changes_nothing

test_a_manifest_changed_after_amending_changes_nothing() -> None

ResultsContract.test_amending_with_what_is_not_plain_json_is_refused_and_changes_nothing

test_amending_with_what_is_not_plain_json_is_refused_and_changes_nothing() -> None

ResultsContract.test_a_bad_run_name_is_refused

test_a_bad_run_name_is_refused() -> None

ResultsContract.test_a_bad_case_id_is_refused_and_nothing_is_saved

test_a_bad_case_id_is_refused_and_nothing_is_saved() -> None

ResultsContract.test_a_bad_trial_number_is_refused_and_nothing_is_saved

test_a_bad_trial_number_is_refused_and_nothing_is_saved() -> None

ResultsContract.test_an_unclaimed_trial_is_claimed

test_an_unclaimed_trial_is_claimed() -> None

ResultsContract.test_a_live_claim_keeps_another_owner_out_and_stays_as_it_was

test_a_live_claim_keeps_another_owner_out_and_stays_as_it_was() -> None

ResultsContract.test_an_owner_renews_its_own_claim

test_an_owner_renews_its_own_claim() -> None

ResultsContract.test_a_claim_that_ran_out_goes_to_the_next_owner

test_a_claim_that_ran_out_goes_to_the_next_owner() -> None

ResultsContract.test_of_two_owners_claiming_at_once_exactly_one_gets_the_trial

test_of_two_owners_claiming_at_once_exactly_one_gets_the_trial() -> None

ResultsContract.test_releasing_frees_the_trial_and_only_the_owner_can

test_releasing_frees_the_trial_and_only_the_owner_can() -> None

ResultsContract.test_claims_are_per_run_case_and_trial_and_come_back_in_order

test_claims_are_per_run_case_and_trial_and_come_back_in_order() -> None

ResultsContract.test_claiming_in_a_run_that_was_not_opened_is_a_lookup_error

test_claiming_in_a_run_that_was_not_opened_is_a_lookup_error() -> None

ResultsContract.test_a_claim_and_a_saved_trial_do_not_disturb_each_other

test_a_claim_and_a_saved_trial_do_not_disturb_each_other() -> None

ResultsContract.test_a_bad_claim_is_refused_and_nothing_is_claimed

test_a_bad_claim_is_refused_and_nothing_is_claimed() -> None

gvn.testing.eval_fakes

Fakes for the evals ports: deterministic, in memory, no I/O, no real time.

MemoryResults passes gvn.testing.eval_contracts.ResultsContract. The others are small scripted stand-ins for tests of the evals layer: FixedSubject (a Subject from one function), FixedEnvironments (an Environment per trial, counting how many were opened and closed), ScriptedStandIn (answers from one function).

Constants: VERDICTS.

MemoryResults

from gvn.testing.eval_fakes import MemoryResults
MemoryResults() -> None

Results kept in memory. Passes ResultsContract.

MemoryResults.open

async def open(run_name: str, manifest: dict[str, typing.Any]) -> None

Begin the eval run run_name with manifest, or continue it: opening a name that exists with an equal manifest changes nothing; with a different one it raises ManifestMismatch naming the keys that differ, and writes nothing.

MemoryResults.amend

async def amend(run_name: str, manifest: dict[str, typing.Any]) -> None

Replace the manifest of the eval run run_name, in one step. LookupError when there is no such run. For scoring a recorded run again under changed criteria; open remains the only way to begin a run.

MemoryResults.manifest

async def manifest(run_name: str) -> dict[str, typing.Any] | None

The manifest of run_name, or None when there is no such eval run.

MemoryResults.runs

async def runs() -> tuple[str, ...]

The names of every eval run, oldest first.

MemoryResults.save_trial

async def save_trial(
    run_name: str,
    case_id: str,
    trial: int,
    record: dict[str, typing.Any],
) -> None

Keep record as trial trial of case_id, replacing an earlier record of that trial. LookupError for an eval run that was not opened.

MemoryResults.trials

async def trials(run_name: str) -> tuple[dict[str, typing.Any], ...]

Every trial record of run_name, ordered by the order in which each (case, trial) was first saved. Empty for an unknown run.

MemoryResults.claim

async def claim(
    run_name: str,
    case_id: str,
    trial: int,
    owner: str,
    now: float,
    until: float,
) -> bool

Take, or renew, owner's claim on trial trial of case_id until until: True when the trial was unclaimed, its claim had run out (its until <= now) or was owner's already; False when another owner's claim is still live, and then nothing changes. One step: of two owners claiming at once, exactly one gets True. owner: a non-empty str; now and until: finite numbers with until > now (ValueError otherwise). LookupError for an eval run that was not opened.

MemoryResults.release

async def release(run_name: str, case_id: str, trial: int, owner: str) -> None

Give up owner's claim on that trial. Changes nothing when owner holds none there (it ran out and another took it, or it was never taken).

MemoryResults.claims

async def claims(run_name: str, now: float) -> tuple[tuple[str, int, str], ...]

The claims of run_name still live at now, each (case_id, trial, owner), ordered by case id then trial. Empty for an unknown run.

FixedEnvironments

from gvn.testing.eval_fakes import FixedEnvironments
FixedEnvironments(
    name: str,
    tools: Callable[[Case, int], Toolbox] | Iterable[Tool],
    policy: Decision | None = None,
    observe: Callable[[Case, int, Toolbox], dict[str, typing.Any]] | None = None,
    failing: Mapping[tuple[str, int], int] | None = None,
) -> None

An Environments whose every Environment holds a toolbox from one function.

name: what name() answers. tools: a function (case, trial) -> Toolbox (called once per environment, so each trial can get its own world), or an iterable of Tool (every environment then gets a Toolbox of those same tools). policy: a Decision over gvn.harness.tools.VERDICTS; default clears every call. observe: None (the environment reports {}), or a function (case, trial, toolbox) -> dict, sync or async, giving what observe() reports. failing: None, or a mapping (case_id, trial) -> n: open raises RuntimeError the first n times it is asked for that pair, then succeeds.

opened() counts the environments opened, closed() the close calls made on them, so tests can check isolation and cleanup.

FixedEnvironments.name

name() -> str

Recorded with every eval run.

FixedEnvironments.opened

opened() -> int

How many environments were opened (an open that raised is not counted).

FixedEnvironments.closed

closed() -> int

How many close calls the opened environments received.

FixedEnvironments.open

async def open(case: Case, trial: int) -> Environment

A fresh Environment for trial number trial (0-based) of case, prepared from the case (its brief and expect).

ScriptedStandIn

from gvn.testing.eval_fakes import ScriptedStandIn
ScriptedStandIn(name: str, answer: Callable[[Request, Case], Event | None]) -> None

A StandIn answering from one function (request, case) -> Event | None (sync or async); None leaves the request unanswered. name: what name() answers.

ScriptedStandIn.name

name() -> str

Recorded with every eval run.

ScriptedStandIn.answer

async def answer(request: Request, case: Case) -> Event | None

The Event answering request (an external request the run is waiting on), or None to leave it unanswered (the trial then ends parked). Asked again for a request re-issued after a crash, so the same request should get an equal answer where it can.

FixedSubject

from gvn.testing.eval_fakes import FixedSubject
FixedSubject(
    name: str,
    fingerprint: str,
    actor_class: type[Actor],
    start: Callable[[str, dict[str, typing.Any]], tuple[Actor, Event]],
) -> None

A Subject from one function.

name, fingerprint: what the methods answer. actor_class: a subclass of gvn.harness.actor.Actor. start: (run_id, brief) -> (Actor, Event).

FixedSubject.name

name() -> str

What reports call this version ("baseline", "shorter-prompt").

FixedSubject.fingerprint

fingerprint() -> str

A str that changes whenever this version would behave differently: its definition's fingerprint together with its settings' (and the instructions and anything else its builder varies). Recorded with every eval run.

FixedSubject.actor_class

actor_class() -> type[Actor]

The Actor subclass of its runs (what Replay and Recovery rebuild).

FixedSubject.start

start(run_id: str, brief: dict[str, typing.Any]) -> tuple[Actor, Event]

(actor, event): a fresh actor named run_id and the Event that starts it. Deterministic. ValueError for a brief it does not admit.

gvn.testing.fakes

Fakes for every port. Deterministic, in-memory, no I/O, no real time.

They pass the same contract suites (gvn.testing.contracts) as real adapters.

answer_reply

from gvn.testing.fakes import answer_reply
answer_reply(data: typing.Any, input_tokens: int = 0, output_tokens: int = 0) -> Reply

A Reply whose text is data (plain JSON) written as compact JSON, as a vendor's structured output returns an answer: for a ScriptedModel or FunctionModel standing in for a model asked for a structured answer (Agent(..., answer=...), a Choice).

It is only text: a fake model constrains nothing, so a test can as easily script a reply that does not match the schema and watch the actor's own check refuse it. TypeError when data is not plain JSON.

ScriptExhausted

from gvn.testing.fakes import ScriptExhausted

A ScriptedModel was asked for more replies than it was given.

ScriptedModel

from gvn.testing.fakes import ScriptedModel
ScriptedModel(
    script: Iterable[object],
    context_window: int | None = None,
    name: str | None = None,
) -> None

Answers from a script, one entry per generate call, in order.

Each entry is one of: * a Reply: its message text is reported to progress as one fragment (if non-empty), then it is returned * a (fragments, Reply) tuple: each fragment (str) is reported, then the Reply returned * a ModelFailure instance: raised * an asyncio.Event-like object with an awaitable wait(): awaited (so a test can hold the model mid-call), then the next entry is used Raises ScriptExhausted when the script runs out.

name: None, or the non-empty str name() returns (Model.name).

ScriptedModel.generate

async def generate(exchange: Exchange, progress: Progress) -> Reply

Run one model call and return the complete Reply.

Text fragments are reported to progress as they arrive; their concatenation equals the reply message's text. Raises ModelFailure for any failure. Must honour cancellation (asyncio.CancelledError) promptly.

ScriptedModel.name

name() -> str | None

What to call this model in the record of what it cost: a non-empty str (an adapter gives the vendor's model id), or None when it has none (the default). Constant for the object's life. The ModelFulfiller journals it with every answer whose Reply does not name its own model (Reply.model()).

ScriptedModel.context_window

context_window() -> int | None

How many tokens one call to this model can hold (its context window): an int >= 1, or None when unknown (the default). A fact about the model, constant for the object's life. The ModelFulfiller journals it with every reply, which is how an actor's ContextBudget learns it (gvn.harness.context_window).

ScriptedModel.exchanges

exchanges() -> tuple[Exchange, ...]

Tuple of every Exchange received, in order.

ScriptedModel.remaining

remaining() -> int

How many script entries are unused.

FunctionModel

from gvn.testing.fakes import FunctionModel
FunctionModel(
    respond: Callable[[Exchange], Reply],
    context_window: int | None = None,
    name: str | None = None,
) -> None

A Model whose reply is a function of the exchange: the same question always gets the same answer, which is what crash-recovery tests need.

respond is a synchronous callable taking the Exchange and returning a Reply (its text is reported to progress as one fragment when non-empty) or raising ModelFailure. Records every Exchange received. name: None, or the non-empty str name() returns (Model.name).

FunctionModel.name

name() -> str | None

What to call this model in the record of what it cost: a non-empty str (an adapter gives the vendor's model id), or None when it has none (the default). Constant for the object's life. The ModelFulfiller journals it with every answer whose Reply does not name its own model (Reply.model()).

FunctionModel.context_window

context_window() -> int | None

How many tokens one call to this model can hold (its context window): an int >= 1, or None when unknown (the default). A fact about the model, constant for the object's life. The ModelFulfiller journals it with every reply, which is how an actor's ContextBudget learns it (gvn.harness.context_window).

FunctionModel.generate

async def generate(exchange: Exchange, progress: Progress) -> Reply

Run one model call and return the complete Reply.

Text fragments are reported to progress as they arrive; their concatenation equals the reply message's text. Raises ModelFailure for any failure. Must honour cancellation (asyncio.CancelledError) promptly.

FunctionModel.exchanges

exchanges() -> tuple[Exchange, ...]

Tuple of every Exchange received, in order.

HeldModel

from gvn.testing.fakes import HeldModel
HeldModel(
    respond: Callable[[Exchange], Reply],
    context_window: int | None = None,
    name: str | None = None,
) -> None

Like FunctionModel, but every generate call waits until it is released.

respond is a synchronous callable taking the Exchange and returning a Reply (or raising ModelFailure); it is called only once the call is let through. A held call that is cancelled raises CancelledError and is no longer held.

model = HeldModel(respond)
task = asyncio.create_task(governor.deliver(agent, start))
await model.held(1)          # the run is now mid-flight, inside the model
governor.interrupt("helper") # or model.release(), or task.cancel()
result = await task

waiting() counts the calls held now; await held(n) returns once at least n are held (no polling); release() lets every held call and every later call through; release_one() lets the oldest through. name: None, or the non-empty str name() returns (Model.name).

HeldModel.name

name() -> str | None

What to call this model in the record of what it cost: a non-empty str (an adapter gives the vendor's model id), or None when it has none (the default). Constant for the object's life. The ModelFulfiller journals it with every answer whose Reply does not name its own model (Reply.model()).

HeldModel.context_window

context_window() -> int | None

How many tokens one call to this model can hold (its context window): an int >= 1, or None when unknown (the default). A fact about the model, constant for the object's life. The ModelFulfiller journals it with every reply, which is how an actor's ContextBudget learns it (gvn.harness.context_window).

HeldModel.generate

async def generate(exchange: Exchange, progress: Progress) -> Reply

Run one model call and return the complete Reply.

Text fragments are reported to progress as they arrive; their concatenation equals the reply message's text. Raises ModelFailure for any failure. Must honour cancellation (asyncio.CancelledError) promptly.

HeldModel.waiting

waiting() -> int

How many calls are held right now.

HeldModel.held

async def held(n: int = 1) -> None

Return once at least n (an int >= 0) calls are held at the same time.

HeldModel.release

release() -> None

Let every held call through, and every later call pass without waiting.

HeldModel.release_one

release_one() -> bool

Let the oldest held call through. Returns False when none is held.

HeldModel.exchanges

exchanges() -> tuple[Exchange, ...]

Tuple of every Exchange received, in order (held ones included).

ManualClock

from gvn.testing.fakes import ManualClock
ManualClock(start: float = 0.0) -> None

Time moves only when advance is called.

await sleeping(n) returns once at least n sleep calls are waiting (no polling), and earliest() says when the first of them is due, so a test can advance time exactly while a run is being driven.

ManualClock.now

now() -> float

Seconds since the epoch, as a float. Never goes backwards.

ManualClock.sleep

async def sleep(seconds: float) -> None

Returns once advance has moved time at least seconds past now.

sleep(0) returns without waiting. ValueError for a negative duration.

ManualClock.advance

advance(seconds: float) -> None

Move time forward (ValueError if negative) and wake every sleeper now due.

ManualClock.sleepers

sleepers() -> int

How many sleep calls are currently waiting.

ManualClock.earliest

earliest() -> float | None

The earliest time (a float) any waiting sleep call is due to wake, or None when nothing sleeps: advance(clock.earliest() - clock.now()) wakes it.

ManualClock.sleeping

async def sleeping(n: int = 1) -> None

Return once at least n (an int >= 0) sleep calls are waiting at once.

MemoryJournal

from gvn.testing.fakes import MemoryJournal
MemoryJournal(leases: MemoryLeases | None = None) -> None

A Journal in memory.

leases: None, or the MemoryLeases this journal shares its storage with: fenced writes are checked against it (Journal's docstring). Without one, every fenced write raises LeaseLost.

MemoryJournal.begin

async def begin(
    run_id: str,
    state: dict[str, typing.Any],
    record: dict[str, typing.Any],
    fence: int | None = None,
) -> None

Durably begin run_id, as one atomic step: keep state as its snapshot taken after 0 records (its first snapshot and its latest) and add record at position 0 (fenced as the class says).

Made only if the run has no record and no snapshot at that moment; otherwise PositionTaken is raised and nothing is written. So a run is never left with a birth snapshot and no opening record, and of several callers beginning one run exactly one succeeds while the others change nothing.

MemoryJournal.append

async def append(
    run_id: str,
    record: dict[str, typing.Any],
    fence: int | None = None,
    position: int | None = None,
) -> None

Durably add record at the end of run_id (fenced as the class says).

position: None (the default) adds at the end wherever that is. An int >= 0 (TypeError / ValueError otherwise) is where the caller believes the end is: the record is added only if the run has exactly position records at the moment of the write (the check and the write are one atomic step); otherwise PositionTaken is raised and nothing is written.

MemoryJournal.read

async def read(run_id: str, start: int = 0) -> tuple[dict[str, typing.Any], ...]

Tuple of the records of run_id from position start (an int >= 0), in order.

Empty for an unknown run or a start at or past the end.

MemoryJournal.length

async def length(run_id: str) -> int

How many records run_id has; 0 for an unknown run.

MemoryJournal.runs

async def runs(after: str | None = None, limit: int | None = None) -> tuple[str, ...]

The ids of the runs this journal holds, as a tuple in ascending order.

A run is held once it has a record or a snapshot. The order is that of Python's str comparison (by code point) on every storage, so a caller can read a long list in pages: after (None, or a str, which need not be a run the journal holds) leaves out every id that is not greater than it, and limit (None, or an int >= 1) keeps at most that many of the ids that are left, the lowest ones. TypeError for an after that is neither None nor a str or a limit that is neither None nor an int (a bool is not an int here); ValueError for a limit below 1. Empty when no run fits.

MemoryJournal.save_snapshot

async def save_snapshot(
    run_id: str,
    sequence: int,
    state: dict[str, typing.Any],
    fence: int | None = None,
) -> None

Durably keep state as the snapshot of run_id taken after sequence records (fenced as the class says).

sequence is an int >= 0: the state reflects exactly the records at positions below it. Two snapshots are kept per run: the first one ever saved, and the one with the highest sequence; saving a lower one than is already held changes nothing (beyond becoming the first, if it is).

MemoryJournal.latest_snapshot

async def latest_snapshot(run_id: str) -> tuple[int, dict[str, typing.Any]] | None

(sequence, state) for the highest-sequence snapshot of run_id, or None.

MemoryJournal.first_snapshot

async def first_snapshot(run_id: str) -> tuple[int, dict[str, typing.Any]] | None

(sequence, state) for the first snapshot ever saved for run_id, or None.

The first snapshot is kept for good (later saves never replace it), so a run can always be replayed from its beginning.

MemoryLeases

from gvn.testing.fakes import MemoryLeases
MemoryLeases() -> None

Leases in memory. Pair it with a journal: MemoryJournal(leases=leases).

The schedule is scanned rather than indexed: a fake for tests, not for scale.

MemoryLeases.acquire

async def acquire(
    run_id: str,
    pool: str,
    holder: str,
    now: float,
    until: float,
) -> Lease | None

Take run_id for holder until until (> now), or None.

Succeeds only when the run has no lease or an expired one (the same holder included: a lease is never taken twice). On success the run's fence grows by one (1 for a run never leased), its pool becomes pool, its due becomes now, and the new Lease is returned. On failure nothing changes. TypeError / ValueError for bad arguments.

MemoryLeases.renew

async def renew(lease: Lease, until: float) -> Lease | None

Extend lease to until: the renewed Lease (same fence), or None when the lease is no longer the run's current one (taken over or released). An expired lease nobody took is renewed.

MemoryLeases.release

async def release(lease: Lease, due: float | None = None) -> bool

Give lease back and set the run's due (None or a finite number).

True if released; False, with nothing changed, when it was no longer the run's current lease. The fence is kept: the next acquire makes a higher one, and a released lease writes nothing more.

MemoryLeases.holder

async def holder(run_id: str) -> Lease | None

The run's current Lease (taken and not released; expired or not), or None.

MemoryLeases.due

async def due(pool: str, now: float, limit: int) -> tuple[str, ...]

Tuple of up to limit (an int >= 1) run ids claimable by pool at now, earliest due first (ties by run id). Answered from an index: it does not read every run.

MemoryLeases.earliest

async def earliest(pool: str) -> float | None

The earliest time at which some run of pool with a due becomes claimable (max(due, until) for a leased run), or None if no run of the pool has a due. A time already past means some run is claimable now.

Crash

from gvn.testing.fakes import Crash

Raised by CrashingJournal to simulate the process dying.

CrashingJournal

from gvn.testing.fakes import CrashingJournal
CrashingJournal(journal: Journal, at_append: int, after: bool = False) -> None

Wraps another Journal and dies at a chosen append.

Appends are counted from 0 per wrapper instance, across all runs: only the appends made through this wrapper count, so at_append=1 is the second append made through this wrapper, not the second record of a run (records already in journal, or written through another wrapper, are not counted). A begin counts as one append: it writes a run's birth snapshot and opening record together, so a crash at it leaves both (after True) or neither. At append number at_append it raises Crash: before writing when after is False (the record is lost), after writing when after is True (the record is kept). Later calls keep working normally. Every other method passes straight through to journal.

CrashingJournal.begin

async def begin(
    run_id: str,
    state: dict[str, typing.Any],
    record: dict[str, typing.Any],
    fence: int | None = None,
) -> None

Durably begin run_id, as one atomic step: keep state as its snapshot taken after 0 records (its first snapshot and its latest) and add record at position 0 (fenced as the class says).

Made only if the run has no record and no snapshot at that moment; otherwise PositionTaken is raised and nothing is written. So a run is never left with a birth snapshot and no opening record, and of several callers beginning one run exactly one succeeds while the others change nothing.

CrashingJournal.append

async def append(
    run_id: str,
    record: dict[str, typing.Any],
    fence: int | None = None,
    position: int | None = None,
) -> None

Durably add record at the end of run_id (fenced as the class says).

position: None (the default) adds at the end wherever that is. An int >= 0 (TypeError / ValueError otherwise) is where the caller believes the end is: the record is added only if the run has exactly position records at the moment of the write (the check and the write are one atomic step); otherwise PositionTaken is raised and nothing is written.

CrashingJournal.read

async def read(run_id: str, start: int = 0) -> tuple[dict[str, typing.Any], ...]

Tuple of the records of run_id from position start (an int >= 0), in order.

Empty for an unknown run or a start at or past the end.

CrashingJournal.length

async def length(run_id: str) -> int

How many records run_id has; 0 for an unknown run.

CrashingJournal.runs

async def runs(after: str | None = None, limit: int | None = None) -> tuple[str, ...]

The ids of the runs this journal holds, as a tuple in ascending order.

A run is held once it has a record or a snapshot. The order is that of Python's str comparison (by code point) on every storage, so a caller can read a long list in pages: after (None, or a str, which need not be a run the journal holds) leaves out every id that is not greater than it, and limit (None, or an int >= 1) keeps at most that many of the ids that are left, the lowest ones. TypeError for an after that is neither None nor a str or a limit that is neither None nor an int (a bool is not an int here); ValueError for a limit below 1. Empty when no run fits.

CrashingJournal.save_snapshot

async def save_snapshot(
    run_id: str,
    sequence: int,
    state: dict[str, typing.Any],
    fence: int | None = None,
) -> None

Durably keep state as the snapshot of run_id taken after sequence records (fenced as the class says).

sequence is an int >= 0: the state reflects exactly the records at positions below it. Two snapshots are kept per run: the first one ever saved, and the one with the highest sequence; saving a lower one than is already held changes nothing (beyond becoming the first, if it is).

CrashingJournal.latest_snapshot

async def latest_snapshot(run_id: str) -> tuple[int, dict[str, typing.Any]] | None

(sequence, state) for the highest-sequence snapshot of run_id, or None.

CrashingJournal.first_snapshot

async def first_snapshot(run_id: str) -> tuple[int, dict[str, typing.Any]] | None

(sequence, state) for the first snapshot ever saved for run_id, or None.

The first snapshot is kept for good (later saves never replace it), so a run can always be replayed from its beginning.

CrashingJournal.crashed

crashed() -> bool

True once the crash has happened.

CrashingJournal.journal

journal() -> Journal

The Journal this one wraps (to inspect or close it after the crash).

ListMemory

from gvn.testing.fakes import ListMemory
ListMemory(embedder: Embedder | None = None, *, least_similarity: float = 0.0) -> None

A Memory in a list, for tests.

Without an embedder (the default), an entry matches a query when they share a word (runs of letters, digits and _, compared case-insensitively); entries are ranked by how many distinct words they share with the query, then oldest first.

With an embedder (ListMemory(embedder=...), a gvn.runtime.memory.Embedder), it recalls by meaning as well as by words. remember embeds the text of a key the scope does not hold yet and keeps the entry with its vector; a key already held keeps nothing new and asks the embedder nothing. recall embeds the query and fuses two rankings with gvn.runtime.memory.fused_ranking: by words (as above) and by meaning (every entry of the scope, by cosine_similarity with the query's vector, highest first, then oldest first, leaving out entries whose similarity is below least_similarity). A query with no words recalls nothing and asks the embedder nothing. An EmbedderFailure is raised as MemoryFailure with the same reason, and nothing is kept; so is a vector whose length differs from the vectors already kept. least_similarity (keyword-only, a finite number in [-1, 1], default 0.0) is the floor of the ranking by meaning: with a real embedder most texts are somewhat similar to each other, so a deployment that wants a query about nothing relevant to recall nothing raises it.

Ids are "entry-<n>", counting from 1 in the order remembered, across scopes; an id is never given twice, even after the entry was forgotten (forget, forget_all).

held(scope) shows what a scope holds (never the vectors); embedder() gives the embedder or None; fail(reason) makes every later call raise MemoryFailure (checked arguments are checked first) until mend(). TypeError/ValueError at construction.

ListMemory.embedder

embedder() -> Embedder | None

The Embedder this memory was built with, or None.

ListMemory.fail

fail(reason: str = 'the memory is down') -> None

Make every call raise MemoryFailure(reason) until mend().

ListMemory.mend

mend() -> None

Stop failing.

ListMemory.held

held(scope: str) -> tuple[dict[str, str], ...]

Tuple of {"id", "key", "text"} for every entry of scope, in the order remembered (fresh copies; empty for a scope never used).

ListMemory.scopes

scopes() -> tuple[str, ...]

Tuple of the scopes that hold something, in the order first used.

ListMemory.remember

async def remember(scope: str, text: str, key: str) -> str

Keep text (a non-empty str) under scope and return the entry's id (a non-empty str, unique within the scope).

key is a non-empty str that identifies this act of remembering: work is delivered at least once, so the same scope and key may arrive again after a crash. Then nothing new is kept and the first entry's id is returned (whatever the text). Once the method returns, the entry survives the process. Raises MemoryFailure when it cannot keep the text, which includes a memory that is read-only. Must honour cancellation promptly.

ListMemory.forget

async def forget(scope: str, entry: str) -> bool

Remove the entry whose id is entry (a non-empty str, as remember and recall give it) from scope (a non-empty str). True when an entry was removed; False, with nothing changed, when scope holds no entry with that id (an id that belongs to another scope included: scopes are kept apart here too).

Once the method returns, the removal survives the process and the entry is never recalled again. Ids are never reused within a scope: a later remember gets a new id. The entry's idempotency key goes with it, so remember with the same scope and key afterwards keeps a NEW entry (a new id, the new text). Forgetting twice is safe: the second call returns False. Raises MemoryFailure when it cannot remove, which includes a memory that is read-only. Must honour cancellation promptly.

ListMemory.forget_all

async def forget_all(scope: str) -> int

Remove every entry of scope (a non-empty str) and return how many were removed (0 for a scope that holds nothing). No other scope is touched.

Once the method returns, the removal survives the process and none of those entries is recalled again. Ids are never reused within a scope, and the entries' idempotency keys go with them: remember with a key the scope used before keeps a NEW entry. Raises MemoryFailure when it cannot remove, which includes a memory that is read-only. Must honour cancellation promptly.

ListMemory.recall

async def recall(scope: str, query: str, limit: int) -> list[dict[str, str]]

The entries under scope that best match query (a str; what "match" means is the implementation's), best first, at most limit (an int >= 1): a list of {"id": str, "text": str}, a fresh copy, empty when nothing matches. Raises MemoryFailure when it cannot search. Must honour cancellation promptly.

HashingEmbedder

from gvn.testing.fakes import HashingEmbedder
HashingEmbedder(dimensions: int = 64, name: str = 'hashing') -> None

An Embedder for tests: deterministic, in memory, no network. A stand-in that knows words, not meaning.

A text's vector has dimensions + 1 components: its words (casefolded runs of letters, digits and _) counted into dimensions buckets by zlib.crc32 of their UTF-8 bytes (stable across processes, unlike hash), then one fixed component (0.5), so no vector is all zeros. The same text always gives the same vector; texts that share words have a positive cosine (so does any pair of texts, through the fixed component), and texts with more words in common a higher one.

dimensions: an int >= 1. name: a non-empty str, the embedding's name (name()); give two objects different names to keep their vectors apart. fail(reason) makes every later embed raise EmbedderFailure until mend(); asked() is the tuple of the text lists embed was given (fresh lists), in order, failed calls included. embed refuses anything but a non-empty list of non-empty str (TypeError/ValueError) and yields to the event loop once, so it can be cancelled. TypeError/ValueError at construction.

HashingEmbedder.name

name() -> str

A non-empty str naming this embedding: the same for every object whose vectors may be compared with each other (the same model with the same settings), and different otherwise. Constant for the object's life; no I/O.

HashingEmbedder.fail

fail(reason: str = 'the embedder is down') -> None

Make every embed raise EmbedderFailure(reason) until mend().

HashingEmbedder.mend

mend() -> None

Stop failing.

HashingEmbedder.asked

asked() -> tuple[list[str], ...]

Tuple of the text lists embed was given, oldest first (fresh lists).

HashingEmbedder.embed

async def embed(texts: list[str]) -> list[list[float]]

The vectors of texts (a non-empty list of non-empty str), one per text, in the same order: a list of lists of float, each finite, every vector of the same length (>= 1) on every call, none all zeros. A fresh list. The same text gives the same vector, or one close enough that nothing depends on the difference.

Raises EmbedderFailure when it cannot (the service is unreachable, refuses, or answers with something that is not such a list). Must honour cancellation promptly.

RecordingOutput

from gvn.testing.fakes import RecordingOutput
RecordingOutput() -> None

Receives every Signal. Structured logs, tracing and user streams implement this.

RecordingOutput.emit

emit(signal: Signal) -> None

Take one Signal. Synchronous; must return promptly and must not block on I/O.

The Governor swallows and counts any exception raised here: an observer can never break a run.

RecordingOutput.signals

signals() -> tuple[Signal, ...]

Tuple of every Signal received, in order.

RecordingOutput.kinds

kinds() -> tuple[str, ...]

Tuple of the signals' kinds, in order.

RecordingOutput.text

text() -> str

Every delta's text, concatenated in order.

StubTool

from gvn.testing.fakes import StubTool
StubTool(
    name: str,
    arguments: Record,
    result: object = None,
    description: str = 'A stub tool.',
    retry: Retry | None = None,
    namespace: str | None = None,
    independent: bool = False,
    untrusted: bool = False,
) -> None

A Tool for tests.

result is either plain JSON to return, an Exception instance to raise, or a callable taking the arguments dict (sync or async) whose return value is returned. Every arguments dict received is recorded, and so is every Invocation (invocations()) and its key (keys()). retry is what retry() returns: None (one attempt) or a gvn.harness.ports.Retry (TypeError otherwise). namespace: None ("gvn.testing.fakes", so the identity is "gvn.testing.fakes.<name>") or a dotted identifier; give two stubs of one name different namespaces to stand for two tools that share a short name. independent: what independent() returns (a bool). untrusted: what untrusted() returns (a bool, TypeError otherwise): True stands for a tool whose results come from outside the deployment (a web page, an issue), which an actor records in its exposure.

StubTool.name

name() -> str

The short name the model sees and calls. Matches [A-Za-z][A-Za-z0-9_-]*. Unique among the tools one actor is offered; a Toolbox may hold same-named tools of different identities.

StubTool.namespace

namespace() -> str

Where the tool comes from, a dotted identifier: the module that defines the tool's class (type(self).__module__) unless a tool overrides it. A tool class that backs many tools (one per configuration) takes a namespace at construction, so tools of one class configured apart have different identities.

StubTool.description

description() -> str

What the tool does, written for the model.

StubTool.arguments

arguments() -> Record

A gvn.kernel.schema.Record describing the arguments dict.

StubTool.independent

independent() -> bool

True when a call to this tool neither depends on nor affects any other call in the same reply (a pure read). Independent calls next to each other may run at the same time; everything else runs in the order the model asked.

False unless a tool overrides it. Must return a bool (the Toolbox checks).

StubTool.untrusted

untrusted() -> bool

True when what this tool returns may hold text written by someone the deployer does not control: a web page, an issue or a ticket, an email, a record in another system, the answer of a server reached over a protocol. Such text may be written to steer the model that reads it, so gvn tracks it: an actor that hands a result of this tool to its model records the tool's identity in its exposure, and every later consult_policy and request_approval of that actor carries the exposure, so a policy and an approver judge a call knowing what the model had read when it made it (Consultation.exposure()).

False unless a tool overrides it. Constant for the tool's life. Must return a bool (the Toolbox and the actors check).

StubTool.retry

retry() -> Retry | None

How a call of this tool is tried again when it fails retryably: None (one attempt) or a gvn.harness.ports.Retry (how many attempts in all, how long to wait between them). Constant for the tool's life.

The retry belongs to the tool because only the tool knows whether repeating a call is safe. Every attempt carries the same Invocation, so the same idempotency key: a tool should declare a Retry only when a repeat under that key is harmless (a pure read, or a service that honours the key). A search may deserve five attempts and a payment none. Only a ToolFailure with retryable=True is ever retried.

None unless a tool overrides it. The ToolFulfiller checks what it returns: anything other than None or a Retry is a TypeError naming the tool (a broken tool definition, not a failed call).

StubTool.run

async def run(arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any

Do the work. arguments already satisfies arguments(). Returns plain JSON, or a ToolOutput when the model should also see images or documents (a screenshot): its content is the result's JSON and its attachments go to the model after it.

invocation is the Invocation: which run asked (invocation.origin()), with what trusted data (invocation.context()), under which idempotency key (invocation.key()). A tool that must stay within the run's data (only this alert's hosts, only this customer) checks invocation.context() and raises rather than act outside it.

invocation.key() is a non-empty str that identifies this call: it is the same every time the same call of the same run is (re)issued, and different for every other call. Work is delivered at least once, so after a crash the same call may run again with the same key. A tool with side effects should use the key to make repeats harmless, for example by passing it to the service it calls as that service's idempotency key, or by remembering the keys it has completed (in storage that outlives the process) and not repeating them.

What the key does not cover. An Agent that is interrupted after a tool acted, and then resumed, asks its model again: the next call is a new call with a new key, even when it asks for the same thing. (An Errand's batch is fixed, so its keys stay the same across interrupt and resume.) An effect that must happen at most once whatever happens to the run (a payment, a deployment, a signature) should therefore be keyed by what it is, built from the trusted invocation.context() (for example "promote:<service>:<version>"), not by invocation.key() alone.

Failure. A tool that understands why a call failed raises ToolFailure: retryable=True when the service could not be reached or asked to wait (an outage, a timeout, a rate limit; pass its retry_after when it gave one), retryable=False (the default) when it answered and refused (not found, not permitted, invalid for the service, a business rule). The runtime turns it into a failed ToolResult of kind tool_rejected or tool_unavailable, and may run a retryable call again under the same invocation.key() (when the tool declares a retry()), which a tool already tolerates. Any other exception is reported as tool_raised: a defect in the tool, never retried. See TOOL_ERRORS.

StubTool.calls

calls() -> tuple[dict[str, typing.Any], ...]

Tuple of every arguments dict received, in order.

StubTool.keys

keys() -> tuple[str, ...]

Tuple of every key received, in order (one per call, matching calls()).

StubTool.invocations

invocations() -> tuple[Invocation, ...]

Tuple of every Invocation received, in order (matching calls()).

measuring_tool

from gvn.testing.fakes import measuring_tool
measuring_tool(
    name: str,
    readings: Sequence[object],
    arguments: Record | None = None,
    namespace: str | None = None,
) -> StubTool

A StubTool that stands for a sensor's measuring tool (gvn.harness.sensors).

readings: a non-empty sequence of what the tool returns, one per call, in order; the last is returned again for every later call. Each is a reading ({"clean": bool, "text": str}), or anything else a test wants the tool to return (an Exception instance is raised, as by StubTool). arguments: the Record of its arguments (Record({}) when None). namespace: as StubTool's. The stub records its calls (calls(), keys()) as StubTool does. TypeError/ValueError otherwise.

gvn.testing.postgres

A throwaway PostgreSQL server in a Docker container, for integration tests.

with ThrowawayPostgres() as server:
    conninfo = server.database()        # a fresh, empty database on it
    journal = PostgresJournal(conninfo=conninfo)

The container listens on 127.0.0.1 only, on a port Docker picks, with a password made up at start; it is removed when the block ends (or the process exits normally). DockerUnavailable is raised at start when Docker cannot run it, so a test fixture can skip. Needs psycopg (the postgres extra) to create databases.

DockerUnavailable

from gvn.testing.postgres import DockerUnavailable

Docker is not installed, not running, or could not start the container.

ThrowawayPostgres

from gvn.testing.postgres import ThrowawayPostgres
ThrowawayPostgres(image: str = 'postgres:16') -> None

One PostgreSQL container for the life of a with block.

ThrowawayPostgres.conninfo

conninfo(database: str = 'postgres') -> str

The connection string of database on this server.

ThrowawayPostgres.database

database() -> str

The connection string of a new, empty database on this server.