Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix streams with new redis, stream debugger, better queries (#1556)

Eric Hayes2627593f3eaa
diff --git a/js/app/packages/block-chat/component/Chat.tsx b/js/app/packages/block-chat/component/Chat.tsx
index f849919d64..3e1bd87d5d 100644
--- a/js/app/packages/block-chat/component/Chat.tsx
+++ b/js/app/packages/block-chat/component/Chat.tsx
@@ -37,6 +37,7 @@ import { invalidateUserQuota } from '@queries/auth';
import { createCallback } from '@solid-primitives/rootless';
import { ChatInput } from 'core/component/AI/component/input/ChatInput';
import type { LexicalEditor } from 'lexical';
+import { DEV_MODE_ENV } from '@core/constant/featureFlags';
import { createEffect, createSignal, Show } from 'solid-js';
import { pendingLocationParamsSignal } from '../signal/pendingLocationParams';
@@ -71,6 +72,7 @@ function ChatInner(props: {
const { navigatedFromJK } = useNavigatedFromJK();
const [chatEditor, setChatEditor] = createSignal<LexicalEditor>();
const [scrollRef, setScrollRef] = createSignal<HTMLElement>();
+ const [showStreamDebug, setShowStreamDebug] = createSignal(false);
const chatMarkdownArea = useChatMarkdownArea({
initialValue: props.loadedInputText,
@@ -203,6 +205,28 @@ function ChatInner(props: {
isEntityDraggingOver={isDraggingOver}
>
<TopBar />
+ <Show when={DEV_MODE_ENV}>
+ <button
+ class="text-xs px-2 py-0.5 text-secondary hover:text-ink"
+ onClick={() => setShowStreamDebug((p) => !p)}
+ >
+ {showStreamDebug() ? 'Hide' : 'Show'} Stream Debug
+ </button>
+ </Show>
+ <Show when={showStreamDebug()}>
+ <div class="px-2 py-1 bg-menu border-b border-edge text-ink font-mono text-sm">
+ <Show when={chat.stream()} fallback={<div>No active stream</div>}>
+ {(stream) => (
+ <div class="flex gap-x-4">
+ <span>chunks: {stream().data().length}</span>
+ <span>isDone: {String(stream().isDone())}</span>
+ <span>model: {stream().model}</span>
+ <span>streamId: {stream().streamId ?? 'none'}</span>
+ </div>
+ )}
+ </Show>
+ </div>
+ </Show>
<div class="size-full flex-1 min-h-0 p-2 relative">
<div class="absolute inset-0 pointer-events-none" use:droppable />
<div
diff --git a/js/app/packages/core/component/AI/component/debug/Component.tsx b/js/app/packages/core/component/AI/component/debug/Component.tsx
index 9f41e21a0c..c105ac2431 100644
--- a/js/app/packages/core/component/AI/component/debug/Component.tsx
+++ b/js/app/packages/core/component/AI/component/debug/Component.tsx
@@ -1,5 +1,5 @@
-import { DEFAULT_MODEL } from '@core/component/AI/constant';
import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';
+import { DEFAULT_MODEL } from '@core/component/AI/constant';
import type { ChatMessageStream, Model } from '@core/component/AI/types';
import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';
import { isErr } from '@core/util/maybeResult';
@@ -29,6 +29,7 @@ function toChat(stream: MessageStream): ChatMessageStream {
streamId: stream.request.stream_id,
};
}
+
import {
blockDone,
createStream,
@@ -165,7 +166,6 @@ function ChatInputBoxConnectedInner() {
return;
}
const [, { stream_id, chat_id }] = response;
- console.log('created chat', chat_id);
const connectionStream = subscribe('chat', chat_id, stream_id);
if (!connectionStream) {
console.log('no connection stream');
diff --git a/js/app/packages/core/component/AI/context/ChatContext.tsx b/js/app/packages/core/component/AI/context/ChatContext.tsx
index 737d7eabe1..cbae19fcf2 100644
--- a/js/app/packages/core/component/AI/context/ChatContext.tsx
+++ b/js/app/packages/core/component/AI/context/ChatContext.tsx
@@ -164,13 +164,24 @@ export function ChatProvider(
// Uses untrack for stream/messages to only fire on new WS streams or chatId change.
createEffect(() => {
const activeStreams = getEntityStreams('chat', props.chatId)();
+ const currentStream = untrack(stream);
for (const s of activeStreams) {
const sid = s.id()?.stream_id;
- if (!sid || s.isDone()) continue;
+ if (!sid) {
+ console.warn('reject chat stream: no id');
+ continue;
+ }
+ if (currentStream?.isDone() && currentStream?.streamId === sid) {
+ console.warn('reject chat stream: duplicate stream');
+ continue;
+ }
const isInMessages = untrack(() => messages().some((m) => m.id === sid));
- if (isInMessages) continue;
+ if (isInMessages) {
+ console.warn('reject chat stream: already has message');
+ continue;
+ }
setStream({
data: s.data,
diff --git a/rust/cloud-storage/stream/src/domain/ext.rs b/rust/cloud-storage/stream/src/domain/ext.rs
index fc046dd2d8..e1d0a39dbb 100644
--- a/rust/cloud-storage/stream/src/domain/ext.rs
+++ b/rust/cloud-storage/stream/src/domain/ext.rs
@@ -43,7 +43,7 @@ where
while let Some(payload) = stream.next().await {
if let Err(e) = writer.append(&writer_id, payload).await {
tracing::error!(error=?e, "failed to append to stream");
- return;
+ break;
}
}
})
diff --git a/rust/cloud-storage/stream/src/domain/types.rs b/rust/cloud-storage/stream/src/domain/types.rs
index fc9f42434c..21407ff8d3 100644
--- a/rust/cloud-storage/stream/src/domain/types.rs
+++ b/rust/cloud-storage/stream/src/domain/types.rs
@@ -36,3 +36,9 @@ impl From<serde_json::error::Error> for StreamServiceError {
Self::SerdeError(value)
}
}
+
+impl From<sqlx::Error> for StreamServiceError {
+ fn from(value: sqlx::Error) -> Self {
+ Self::StorageError(value.to_string())
+ }
+}
diff --git a/rust/cloud-storage/stream/src/outbound/redis_pg/queries/mod.rs b/rust/cloud-storage/stream/src/outbound/redis_pg/queries/mod.rs
index e373cacdd0..42a64d29ee 100644
--- a/rust/cloud-storage/stream/src/outbound/redis_pg/queries/mod.rs
+++ b/rust/cloud-storage/stream/src/outbound/redis_pg/queries/mod.rs
@@ -1,19 +1,19 @@
#[cfg(test)]
mod test;
+use crate::domain::StreamId;
use sqlx::PgPool;
/// Insert a new active stream entry, ignoring conflicts.
pub(crate) async fn insert_active_stream(
pool: &PgPool,
- entity_id: &str,
- stream_key: &str,
+ stream_id: &StreamId,
) -> Result<(), sqlx::Error> {
sqlx::query(
"INSERT INTO active_streams (entity_id, stream_key) VALUES ($1, $2) ON CONFLICT DO NOTHING",
)
- .bind(entity_id)
- .bind(stream_key)
+ .bind(&stream_id.entity_id)
+ .bind(stream_id.to_string())
.execute(pool)
.await?;
Ok(())
@@ -22,12 +22,11 @@ pub(crate) async fn insert_active_stream(
/// Delete an active stream entry.
pub(crate) async fn delete_active_stream(
pool: &PgPool,
- entity_id: &str,
- stream_key: &str,
+ stream_id: &StreamId,
) -> Result<(), sqlx::Error> {
sqlx::query("DELETE FROM active_streams WHERE entity_id = $1 AND stream_key = $2")
- .bind(entity_id)
- .bind(stream_key)
+ .bind(&stream_id.entity_id)
+ .bind(stream_id.to_string())
.execute(pool)
.await?;
Ok(())
diff --git a/rust/cloud-storage/stream/src/outbound/redis_pg/queries/test.rs b/rust/cloud-storage/stream/src/outbound/redis_pg/queries/test.rs
index e398beb9e1..4019823753 100644
--- a/rust/cloud-storage/stream/src/outbound/redis_pg/queries/test.rs
+++ b/rust/cloud-storage/stream/src/outbound/redis_pg/queries/test.rs
@@ -1,30 +1,36 @@
use super::*;
+use model_entity::EntityType;
use sqlx::PgPool;
+fn stream_id(entity_id: &str, stream: &str) -> StreamId {
+ StreamId {
+ entity_type: EntityType::Chat,
+ entity_id: entity_id.to_string(),
+ stream_id: stream.to_string(),
+ }
+}
+
#[sqlx::test(migrations = "../macro_db_client/migrations")]
async fn test_insert_and_get(pool: PgPool) {
- insert_active_stream(&pool, "entity_1", "stream_a")
- .await
- .unwrap();
- insert_active_stream(&pool, "entity_1", "stream_b")
- .await
- .unwrap();
+ let id_a = stream_id("entity_1", "stream_a");
+ let id_b = stream_id("entity_1", "stream_b");
+
+ insert_active_stream(&pool, &id_a).await.unwrap();
+ insert_active_stream(&pool, &id_b).await.unwrap();
let keys = get_active_stream_keys(&pool, "entity_1").await.unwrap();
assert_eq!(keys.len(), 2);
- assert!(keys.contains(&"stream_a".to_string()));
- assert!(keys.contains(&"stream_b".to_string()));
+ assert!(keys.contains(&id_a.to_string()));
+ assert!(keys.contains(&id_b.to_string()));
}
#[sqlx::test(migrations = "../macro_db_client/migrations")]
async fn test_insert_conflict_is_noop(pool: PgPool) {
- insert_active_stream(&pool, "entity_1", "stream_a")
- .await
- .unwrap();
+ let id = stream_id("entity_1", "stream_a");
+
+ insert_active_stream(&pool, &id).await.unwrap();
// Duplicate insert should succeed (ON CONFLICT DO NOTHING)
- insert_active_stream(&pool, "entity_1", "stream_a")
- .await
- .unwrap();
+ insert_active_stream(&pool, &id).await.unwrap();
let keys = get_active_stream_keys(&pool, "entity_1").await.unwrap();
assert_eq!(keys.len(), 1);
@@ -32,26 +38,22 @@ async fn test_insert_conflict_is_noop(pool: PgPool) {
#[sqlx::test(migrations = "../macro_db_client/migrations")]
async fn test_delete(pool: PgPool) {
- insert_active_stream(&pool, "entity_1", "stream_a")
- .await
- .unwrap();
- insert_active_stream(&pool, "entity_1", "stream_b")
- .await
- .unwrap();
+ let id_a = stream_id("entity_1", "stream_a");
+ let id_b = stream_id("entity_1", "stream_b");
- delete_active_stream(&pool, "entity_1", "stream_a")
- .await
- .unwrap();
+ insert_active_stream(&pool, &id_a).await.unwrap();
+ insert_active_stream(&pool, &id_b).await.unwrap();
+
+ delete_active_stream(&pool, &id_a).await.unwrap();
let keys = get_active_stream_keys(&pool, "entity_1").await.unwrap();
- assert_eq!(keys, vec!["stream_b".to_string()]);
+ assert_eq!(keys, vec![id_b.to_string()]);
}
#[sqlx::test(migrations = "../macro_db_client/migrations")]
async fn test_delete_nonexistent_is_noop(pool: PgPool) {
- delete_active_stream(&pool, "entity_1", "does_not_exist")
- .await
- .unwrap();
+ let id = stream_id("entity_1", "does_not_exist");
+ delete_active_stream(&pool, &id).await.unwrap();
}
#[sqlx::test(migrations = "../macro_db_client/migrations")]
@@ -64,49 +66,43 @@ async fn test_get_empty(pool: PgPool) {
#[sqlx::test(migrations = "../macro_db_client/migrations")]
async fn test_get_filters_by_entity(pool: PgPool) {
- insert_active_stream(&pool, "entity_1", "stream_a")
- .await
- .unwrap();
- insert_active_stream(&pool, "entity_2", "stream_b")
- .await
- .unwrap();
+ let id_1 = stream_id("entity_1", "stream_a");
+ let id_2 = stream_id("entity_2", "stream_b");
+
+ insert_active_stream(&pool, &id_1).await.unwrap();
+ insert_active_stream(&pool, &id_2).await.unwrap();
let keys_1 = get_active_stream_keys(&pool, "entity_1").await.unwrap();
- assert_eq!(keys_1, vec!["stream_a".to_string()]);
+ assert_eq!(keys_1, vec![id_1.to_string()]);
let keys_2 = get_active_stream_keys(&pool, "entity_2").await.unwrap();
- assert_eq!(keys_2, vec!["stream_b".to_string()]);
+ assert_eq!(keys_2, vec![id_2.to_string()]);
}
#[sqlx::test(migrations = "../macro_db_client/migrations")]
async fn test_full_lifecycle(pool: PgPool) {
+ let id_a = stream_id("entity_1", "stream_a");
+ let id_b = stream_id("entity_1", "stream_b");
+
// Start empty
let keys = get_active_stream_keys(&pool, "entity_1").await.unwrap();
assert!(keys.is_empty());
// Insert two streams
- insert_active_stream(&pool, "entity_1", "stream_a")
- .await
- .unwrap();
- insert_active_stream(&pool, "entity_1", "stream_b")
- .await
- .unwrap();
+ insert_active_stream(&pool, &id_a).await.unwrap();
+ insert_active_stream(&pool, &id_b).await.unwrap();
let keys = get_active_stream_keys(&pool, "entity_1").await.unwrap();
assert_eq!(keys.len(), 2);
// Close one stream
- delete_active_stream(&pool, "entity_1", "stream_a")
- .await
- .unwrap();
+ delete_active_stream(&pool, &id_a).await.unwrap();
let keys = get_active_stream_keys(&pool, "entity_1").await.unwrap();
- assert_eq!(keys, vec!["stream_b".to_string()]);
+ assert_eq!(keys, vec![id_b.to_string()]);
// Close the other
- delete_active_stream(&pool, "entity_1", "stream_b")
- .await
- .unwrap();
+ delete_active_stream(&pool, &id_b).await.unwrap();
let keys = get_active_stream_keys(&pool, "entity_1").await.unwrap();
assert!(keys.is_empty());
diff --git a/rust/cloud-storage/stream/src/outbound/redis_pg/repo.rs b/rust/cloud-storage/stream/src/outbound/redis_pg/repo.rs
index d321219808..e1fcf99055 100644
--- a/rust/cloud-storage/stream/src/outbound/redis_pg/repo.rs
+++ b/rust/cloud-storage/stream/src/outbound/redis_pg/repo.rs
@@ -2,7 +2,9 @@ use crate::domain::*;
use async_stream::stream;
use async_trait::async_trait;
use futures::StreamExt;
-use redis::{AsyncCommands, Client, RedisResult, Value, streams::StreamReadReply};
+use redis::{
+ AsyncCommands, AsyncConnectionConfig, Client, RedisResult, Value, streams::StreamReadReply,
+};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::sync::OnceCell;
@@ -125,7 +127,7 @@ impl RedisPostgresStreamRepo {
.map_err(|e| StreamServiceError::StorageError(e.to_string()))?;
// Also clean up PostgreSQL entry
- let _ = super::queries::delete_active_stream(&self.pg_pool, &id.entity_id, &id.to_string())
+ let _ = super::queries::delete_active_stream(&self.pg_pool, id)
.await
.inspect_err(|e| tracing::error!(error=?e, "failed to clean stream from postgres"));
@@ -172,19 +174,22 @@ impl StreamRepo for RedisPostgresStreamRepo {
.inspect_err(|e| tracing::error!(error=?e, "failed to publish new channel"));
// Track in PostgreSQL
- let _ =
- super::queries::insert_active_stream(&self.pg_pool, &id.entity_id, &id.to_string())
- .await
- .inspect_err(
- |e| tracing::error!(error=?e, "failed to track stream in postgres"),
- );
+ let _ = super::queries::insert_active_stream(&self.pg_pool, id)
+ .await
+ .inspect_err(|e| tracing::error!(error=?e, "failed to track stream in postgres"));
}
Ok(item_id)
}
async fn stream_from_beginning(&self, id: &StreamId) -> Result<ItemStream> {
- let mut connection = self.redis_client.get_multiplexed_async_connection().await?;
+ // Use no response timeout for blocking XREAD — the default 500ms from redis 1.0
+ // kills the connection before the block period expires.
+ let config = AsyncConnectionConfig::new().set_response_timeout(None);
+ let mut connection = self
+ .redis_client
+ .get_multiplexed_async_connection_with_config(&config)
+ .await?;
let stream_key = id.to_string();
let stream_id_for_item = id.clone();
@@ -253,7 +258,7 @@ impl StreamRepo for RedisPostgresStreamRepo {
.inspect_err(|e| tracing::error!(error=?e, "failed to set closed stream TTL"));
// Remove from PostgreSQL tracking
- let _ = super::queries::delete_active_stream(&self.pg_pool, &id.entity_id, &id.to_string())
+ let _ = super::queries::delete_active_stream(&self.pg_pool, id)
.await
.inspect_err(|e| tracing::error!(error=?e, "failed to remove stream from postgres"));