Skip to content

Add ask_sync() / post_sync() bridge for sync handlers #33

@DaviddeBest-TNO

Description

@DaviddeBest-TNO

Parent

#27

What to build

Add sync convenience methods that allow sync handlers (running in asyncio.to_thread()) to make outgoing KI calls without understanding event loop mechanics.

Bridge methods: Add ask_sync() and post_sync() methods to KnowledgeBase. They accept the same parameters as ask() and post() respectively. Internally, they use asyncio.run_coroutine_threadsafe() to schedule the async ask()/post() coroutine on the event loop stored during start_handling_loop(), then call .result() to block the current thread until the result is ready.

Guard: If no event loop reference is stored (i.e. the handling loop is not running), raise a clear error explaining that ask_sync()/post_sync() are only available from within a sync handler running inside the handling loop.

Use case: A sync handler registered with @kb.react_ki(...) needs to query the KE network before responding:

@kb.react_ki(name="...", argument_graph_pattern="...", result_graph_pattern="...")
def my_handler(binding_set, info):
    # This runs in a thread pool — cannot await
    results = kb.ask_sync([{}], ki_name="my-ask-ki")
    return process(results)

Acceptance criteria

  • ask_sync() method added to KnowledgeBase
  • post_sync() method added to KnowledgeBase
  • Both use asyncio.run_coroutine_threadsafe() on the stored event loop
  • Both block the calling thread until the result is ready
  • Clear error raised if called outside the handling loop context (no stored event loop)
  • Test: sync handler calls ask_sync() during handling loop and receives correct result
  • Test: sync handler calls post_sync() during handling loop and receives correct result
  • Test: calling ask_sync() outside handling loop raises descriptive error
  • uv run ruff check . passes

Blocked by

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestready-for-agentIssue is ready for agent implementation

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions