yield-injections

tursodatabase/turso

Для работы с механизмами инъекции yield и синтетических сбоев в Turso на безопасных границах конечных автоматов: YieldInjector, FailureInjector, YieldPointMarker и макросы inject_*.

Звёзды25 286
Авторtursodatabase
Установок41

Установка

SKILL.md

Yield Injection Guide

Yield injection is test-only infrastructure for forcing cooperative-yield or failure boundaries in resumable state machines. The implementation currently lives under core/mvcc/, but the mechanism is not MVCC semantics.

Key Files

  • core/mvcc/yield_points.rs: injector traits and macros.
  • core/mvcc/yield_hooks.rs: YieldPointMarker, YieldContext, ProvidesYieldContext.
  • core/connection.rs: per-connection injector slots and yield_instance_id_counter.
  • core/mvcc/database/mod.rs: commit points and commit cleanup.
  • core/mvcc/database/checkpoint_state_machine.rs: checkpoint points.
  • core/mvcc/cursor.rs: cursor points.
  • core/mvcc/database/tests.rs: fixed test injectors and regression examples.
  • testing/concurrent-simulator/yield_injection.rs: simulator injector.

All hooks are behind cfg(any(test, injected_yields)); injected_yields means test_helper or simulator.

Core Model

YieldPoint { ordinal, point_count } identifies one hook in one point family. Families are #[repr(u8)] enums implementing YieldPointMarker; ordinal is source-order self as u8, and point_count comes from EnumCount.

Do not reorder existing yield-point variants. Simulator plans store raw ordinals, not names.

Why reordering matters: ordinal is self as u8, so source order is part of the deterministic schedule. If a seed planned "yield at ordinal 2", reordering can silently retarget that same seed from one conceptual hook to another. This makes CI seeds, bisects, and simulator coverage hard to reproduce. Appending a variant still changes point_count and can perturb future plans, but it preserves the meaning of existing ordinals.

Each yield-capable live object has:

  • instance_id: distinguishes simultaneous state machines/cursors.
  • selection_key: stable logical-operation key used by deterministic plans.
  • active connection injectors: yield_injector() and failure_injector().

Hook Macros

  • inject_transition_yield!(self, Point): for StateTransition returning TransitionResult<T>.
  • inject_io_yield!(self, Point): for cursor/helper functions returning IOResult<T>.
  • inject_transition_failure!(self, Point): returns Err(LimboError) from StateTransition.

There is no inject_io_failure! today; failure injection only works for TransitionResult state machines.

Injected yields return Completion::new_yield(). It is already finished, but is_explicit_yield() is true, so the VDBE surfaces it as StepResult::Yield instead of continuing immediately.

New Yield-Capable Type

For a new state machine/cursor family, add all of this behind cfg(any(test, injected_yields)):

yield_instance_id: u64,

Initialize it from the connection:

yield_instance_id: connection.next_yield_instance_id(),

Implement ProvidesYieldContext:

impl ProvidesYieldContext for MyStateMachine {
    fn yield_context(&self) -> YieldContext {
        YieldContext::new(
            self.connection.yield_injector(),
            self.connection.failure_injector(),
            self.yield_instance_id,
            my_yield_key(self.logical_operation_id),
        )
    }
}

Add a family-specific *_yield_key(...) -> u64 helper. Mix stable logical identity, such as tx id/table id, with a family tag so simulator plans do not collide across families. Do not use wall-clock time, random values, allocation addresses, or incidental counters unrelated to the logical operation.

Adding A Point

Before adding a hook, prove re-entry is safe. A synthetic yield returns StepResult::Yield; the same statement/state machine may be stepped again immediately later. On re-entry, it must resume from an explicit state, not repeat non-idempotent work.

Rules:

  • Mutate the state machine into the resumable state before yielding.
  • Do not put a hook before a push, insert, counter increment, lock acquisition, or cleanup action unless repeating that action is harmless or explicitly guarded by state.
  • If a lock/guard is held across the yield, test both resume and drop-at-yield paths.
  • For abandonment tests, dropping the statement at the yield must restore invariants through Drop/abort cleanup.
  • When adding a new yield point, always add it at the last position in the enum to preserve existing ordinals.
  • Do not reorder variants in existing YieldPointMarker enums, unless absolutely required. Reordering changes the meaning of existing ordinals and can break reproducibility of CI seeds and bisects.

Checklist:

  1. Append a variant to the appropriate *YieldPoint enum. Do not reorder.
  2. Place the macro after the transition that makes resume safe, or before a lock acquisition when explicitly testing lock interleavings.
  3. Avoid calling macros while borrowing &mut self.state; they need self.yield_context().
  4. Add a deterministic test with FixedYieldInjector or FixedFailureInjector.
  5. If testing abandoned work, drop the statement at the yield and assert cleanup invariants.

For deeper re-entry/state-machine rules, also use async-io-model.

Fixed Unit-Test Injectors

Use fixed injectors in targeted tests:

use crate::mvcc::yield_hooks::YieldPointMarker;

conn.set_yield_injector(Some(FixedYieldInjector::new([
    CommitYieldPoint::LogRecordPrepared.point(),
])));

FixedYieldInjector stores a HashSet<YieldPoint>, ignores instance_id/selection_key, and consumes each configured point once total. If two simultaneous instances hit the same point, the first one consumes it.

FixedFailureInjector behaves similarly but maps one point to one LimboError.

Clear injectors when reusing the same connection:

conn.set_yield_injector(None);
conn.set_failure_injector(None);

Common Test Targets

  • Commit LogRecordPrepared: leave commit in Preparing, interleave another writer/checkpoint, or drop the statement.
  • Commit BeforeCommittedTimestampWatermarkUpdate: test out-of-order completion and monotonic watermarks.
  • Commit BeforeFinishCommittedTx: test abandonment after committed state but before final cleanup.
  • Commit AfterRemoveTx failure: verify tx maps, connection tx slots, locks, and exclusive tx atomics are not stranded.
  • Checkpoint BeforeAcquireLock: interleave before checkpoint boundary sampling.
  • Checkpoint AfterDurableBoundaryAdvanced failure: test retry/recovery after durable state advanced.
  • Cursor NextStart or SeekStart: test cursor re-entry and dropped-statement cleanup, especially rowid allocator locks.

Abandoned commit tests rely on cleanup paths: CommitStateMachine::drop calls cleanup_unfinished_commit, and abort-side cleanup runs through cleanup_abandoned_mvcc_commit.

Simulator Use

The concurrent simulator owns randomized deterministic injection. Do not install FixedYieldInjector from simulator code.

Runtime:

  • Each fiber owns an Arc<SimulatorYieldInjector> for the current operation.
  • Operation init replaces it with SimulatorYieldInjector::new(fiber_yield_seed(seed, fiber_idx)).
  • Every stmt.step() goes through step_stmt_with_injected_yield, which installs the injector, steps once, then clears it via RAII.

Planning:

  • Plans are keyed by (instance_id, selection_key, point_count).
  • MAX_YIELDS = 20.
  • For each key, the simulator chooses a random count in 0..=MAX_YIELDS; zero injected yields is valid.
  • It fills that many slots with random ordinals in 0..point_count.
  • Matching slots are consumed once; duplicate ordinals let the same hook fire multiple times.

Simulator reproducibility:

  • Same top-level seed and fiber count are required to reproduce a schedule.
  • Reordering variants changes ordinal meaning.
  • Adding variants changes point_count, which can perturb future schedules for the same seed.
  • Changing hook placement or fiber assignment can make the same seed explore a different schedule.

Gotchas

  • Do not add test-only ad hoc Completion::new_yield() if a yield point can express the interleaving. Runtime lock-contention yields are fine when semantics require them.
  • Do not place a hook before state is updated to the resumable state.
  • set_yield_injector(Some(...)) asserts the slot is empty; set_yield_injector(None) asserts it is installed.
  • Do not rely on exact simulator yield counts outside SimulatorYieldInjector tests.

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: yield-injections](https://darkplay.ru/ai/skills/tursodatabase-turso-yield-injections)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

lseganthropics · Оценка облигаций, анализ кривых доходности, оценка carry-сделок по FX, оценка опционов и…
186 комп.
lseganthropics · Оценка облигаций, анализ кривых доходности, оценка FX carry-сделок, оценка опционов и…
233 комп.
barker-stablecoin-skillsanthropics · Навыки ИИ-агента для анализа доходности стейблкоинов: APY в реальном времени от 500+…
38 комп.
docvetanthropics · Диагностика качества Python-докстрингов в реальном времени через LSP с инлайн-подсказками.
38 комп.
lotlyticsanthropics · Аналитика рынка недвижимости — инвестиционные оценки, доходность аренды и рыночные данные…
38 комп.
vector-md-context-injectoranthropics · Vector-md-plugin автоматически подставляет контекстные файлы поддерева при чтении файла…
38 комп.
defi-yield-optimizerjeremylongshore · Оптимизация DeFi-стратегий доходного фермерства с учётом APY и рисков
2 926 ★
Macro Economistjeremylongshore · Переводит макроданные (ВВП, CPI, политика ФРС) в рекомендации по классам активов и…
2 470 ★
Optimize Yieldjeremylongshore · Найти и оптимизировать возможности yield farming в DeFi
2 470 ★
lulosendaifun · Lulo: агрегатор кредитования с автоматической оптимизацией доходности через Kamino…
129 ★

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации изображений

Генерация изображений

Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты

MagviMagvi
По запросу
5.0
DALL-E 3OpenAI
По подписке
5.0
SupaLabSupalab
По запросу
5.0
Freestyling.aiFreestyling
Есть бесплатный тариф
4.9
ArtGeneration.meArtgeneration
Есть бесплатный тариф
4.9
BigjpgBigjpg
По запросу
4.9
Художник от VKVK
Бесплатно
4.9
Wonderink — ИИ-книги
Есть бесплатный тариф
4.8
Avato AI12ai
По запросу
4.8
Virton AIVirton
По запросу
4.8