Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 44 additions & 18 deletions rust/crates/lk-agents-storage/src/backends/agentdb/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,20 +29,23 @@ use lk_agents_abi::storage::agentdb_error::ErrorCode;
// big frames does not spend its answer's wait being written. A dropped socket is redialed only
// while a request waits for it, so the redial lives exactly as long as a caller's deadline; those
// in flight fail `Disconnected` (outcome unknown). The server ends a socket with a notice on
// request id 0, as HTTP/2's GOAWAY does: `wrong_shard_server` (the database moved or is draining:
// redialed at once) or `idle_evicted` (redialed when next needed).
// The server answered every request it read before its notice, so each one still unanswered
// applied nothing: like gRPC's transparent retry, it is sent again on the next socket within its
// deadline, and its caller sees only the answer. A request answered `wrong_shard_server` applied
// nothing either: it is sent again the same way, while its socket retires: it takes no request
// more, a new socket is dialed at once for the next ones, and the retiring one ends once the
// requests still in flight on it are answered. Any other frame on request id 0 is a protocol error
// that ends the socket. A frame the socket fails to send is not sent. Socket-less, the connection
// is dormant, which no pool takes back. The read loop never waits on a caller: each request's
// answers queue in a channel sized for every answer its window allows, and a request whose
// answers overrun it is cancelled. Outgoing frames queue for the socket's writer, which sends them
// in order; a request's caller waits until its own frame is sent, a credit or cancel is queued and
// forgotten.
// request id 0, as HTTP/2's GOAWAY does, having answered every request it read before it, so each
// one still unanswered applied nothing:
// - `wrong_shard_server`: the database moved or is draining; redialed at once.
// - `idle_evicted`: redialed when next needed.
// - `not_found`: the database was deleted; final. Each request unanswered there fails with it, as
// does every later call, and the connection closes without a redial.
// After the first two, like gRPC's transparent retry, each unanswered request is sent again on the
// next socket within its deadline, and its caller sees only the answer. A request answered
// `wrong_shard_server` applied nothing either: it is sent again the same way, while its socket
// retires: it takes no request more, a new socket is dialed at once for the next ones, and the
// retiring one ends once the requests still in flight on it are answered. Any other frame on
// request id 0 is a protocol error that ends the socket. A frame the socket fails to send is not
// sent. Socket-less, the connection is dormant, which no pool takes back. The read loop never
// waits on a caller: each request's answers queue in a channel sized for every answer its window
// allows, and a request whose answers overrun it is cancelled. Outgoing frames queue for the
// socket's writer, which sends them in order; a request's caller waits until its own frame is
// sent, a credit or cancel is queued and forgotten.

type WsRead = futures_util::stream::SplitStream<RawWebSocket>;
type WsSink = futures_util::stream::SplitSink<RawWebSocket, Message>;
Expand Down Expand Up @@ -126,7 +129,9 @@ const CLIENT_VERSION: &str = concat!("lk-agents/", env!("CARGO_PKG_VERSION"));

/// The codes the server ends a socket with, on request id 0.
fn is_notice(code: ErrorCode) -> bool {
code == ErrorCode::IDLE_EVICTED || code == ErrorCode::WRONG_SHARD_SERVER
code == ErrorCode::IDLE_EVICTED
|| code == ErrorCode::WRONG_SHARD_SERVER
|| code == ErrorCode::NOT_FOUND
}

/// A frame for the socket writer, and who learns that the socket took all of it.
Expand Down Expand Up @@ -690,7 +695,7 @@ impl Conn {
}

/// Hands a response to the request awaiting it on this socket, never waiting on its caller;
/// a pong only proves the socket is alive. The server's drain notice ends the socket, as any
/// a pong only proves the socket is alive. The server's notice ends the socket, as any
/// other frame on request id 0 does; a request answered `wrong_shard_server` alone is drained,
/// and the socket retires. The live socket's gate closes first, so a request registering
/// meanwhile waits for the next socket.
Expand All @@ -708,8 +713,12 @@ impl Conn {
if let Some(ready) = ready {
ready.set(false);
}
self.drain(generation, None);
Err(WsdbError::server(e.clone()))
let notice = WsdbError::server(e.clone());
match ErrorCode(e.code) {
ErrorCode::NOT_FOUND => self.gone(generation, &resp, &notice),
_ => self.drain(generation, None),
}
Err(notice)
}
(message, 0) => {
Err(WsdbError::Protocol(format!("unexpected frame on request id 0: {message:?}")))
Expand Down Expand Up @@ -776,6 +785,23 @@ impl Conn {
self.settle(&mut st, generation);
}

/// The server's `not_found` notice on socket `generation`: the database was deleted. Each
/// request still unanswered there applied nothing and fails with the notice; every later call
/// fails with it too, and the connection closes without a redial.
fn gone(&self, generation: u64, frame: &pb::ServerMessage, notice: &WsdbError) {
{
let mut st = self.0.state.lock();
st.fatal = Some(notice.clone());
for pending in st.pending.values().filter(|p| p.socket == Some(generation)) {
if pending.answers.try_send(Answer::Frame(frame.clone())).is_err() {
log::trace!(target: lk_agents_abi::LOG_TARGET, "agentdb request dropped meanwhile");
}
}
Comment on lines +794 to +799

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 False refusal for other-socket writes

When another socket still holds an unanswered write, gone makes that write fail NotFound too. After closure, wait returns the connection-wide fatal error for its empty channel. The notice does not establish that other socket's write outcome, so a committed write can be reported as unapplied.

Learn more

A connection can retain an old socket with unanswered requests while using a replacement socket; Supervisor::run starts a separate reader for that old socket. A deletion notice guarantees that unanswered requests on its own socket applied nothing, but says nothing about requests on the other socket. Inner::close clears every pending request and cancels every reader. Requests on other generations receive no queued error here, so Conn::wait substitutes the connection-wide fatal error when their channels empty. The write-error conversion treats that NOT_FOUND as proof that nothing applied, losing the distinction between refusal and unknown outcome.

Example: Socket A commits an INSERT but has not delivered its answer. A different request receives wrong_shard_server, retiring A and opening socket B. B receives a deletion notice before A delivers its INSERT answer. Closing the connection makes the INSERT return NotFound, although only B's unanswered requests were proven unapplied.

Recommended fix: Before closing, queue a Disconnected terminal result for pending requests bound to other socket generations, while preserving already queued answers. Keep NOT_FOUND for the notifying generation and later unsent calls. Add a two-socket regression covering a retiring write whose answer remains outstanding when the replacement socket receives the deletion notice.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

}
log::info!(target: lk_agents_abi::LOG_TARGET, databaseId = self.0.opts.database_id.as_str(); "agentdb database deleted: connection closed");
self.close();
}

/// A retiring socket with nothing in flight on it is settled: its read ends.
fn settle(&self, st: &mut State, generation: u64) {
let retiring = st.live != Some(generation) && st.writers.contains_key(&generation);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1042,6 +1042,27 @@ async fn an_unexpected_frame_on_request_id_0_ends_the_socket() {
conn.close();
}

/// Catches: the server's `not_found` on request id 0 (the database deleted with the socket open)
/// read as a protocol error: the write in flight failed `Disconnected` (outcome unknown) and the
/// next call redialed. The write applied nothing and fails not found; so does every later call,
/// unsent, with no redial.
#[tokio::test]
async fn a_database_deleted_with_the_socket_open_fails_not_found_for_good() {
let (url, log) = serve_draining(ErrorCode::NOT_FOUND, is_exec, false).await;
let conn = dial(&url, "DB_1").await.unwrap();
let err = conn.exec(&st("INSERT", vec![]), conn.deadline()).await.err().unwrap();
assert!(
matches!(&err, WriteError::Sent(WsdbError::Server { code: ErrorCode::NOT_FOUND, .. })),
"{err}"
);
assert!(matches!(StorageError::from(err), StorageError::NotFound(_)), "applied nothing");
let err = conn.query_all(&st("SELECT", vec![]), conn.deadline()).await.err().unwrap();
assert!(matches!(&err, WsdbError::Server { code: ErrorCode::NOT_FOUND, .. }), "{err}");
assert_eq!(sent(&log, is_exec).len(), 1, "never sent again");
assert!(sent(&log, is_query).is_empty(), "a later call is not sent");
assert_eq!(hellos(&log), 1, "no redial");
}

/// Catches: new requests waiting for a socket refused `wrong_shard_server` to finish its
/// requests in flight. As with HTTP/2's GOAWAY, the next socket opens at once: the refused query
/// and a later exec are served there while the first socket still holds a write, which then
Expand Down
Loading