| 560 | } |
| 561 | |
| 562 | static bool frontend_enqueue(frontend_state_t *state, char *message, bool content_length_framed) { |
| 563 | size_t length = strlen(message); |
| 564 | bool has_id = false; |
| 565 | int64_t id = 0; |
| 566 | char *id_str = NULL; |
| 567 | cbm_jsonrpc_request_t request = {0}; |
| 568 | if (cbm_jsonrpc_parse(message, &request) == 0) { |
| 569 | has_id = request.has_id; |
| 570 | id = request.id; |
| 571 | if (request.id_str) { |
| 572 | id_str = cbm_strdup(request.id_str); |
| 573 | } |
| 574 | bool identity_copied = !request.id_str || id_str; |
| 575 | cbm_jsonrpc_request_free(&request); |
| 576 | if (!identity_copied) { |
| 577 | return false; |
| 578 | } |
| 579 | } |
| 580 | /* A frame that exceeds the whole byte budget can never be admitted no |
| 581 | * matter how long we wait; only that case is a hard failure. */ |
| 582 | if (length > FRONTEND_QUEUE_BYTES_MAX) { |
| 583 | cbm_mutex_lock(&state->mutex); |
| 584 | if (!state->stopping && !state->failed) { |
| 585 | state->failed = true; |
| 586 | state->stopping = true; |
| 587 | } |
| 588 | cbm_mutex_unlock(&state->mutex); |
| 589 | free(id_str); |
| 590 | return false; |
| 591 | } |
| 592 | /* A full queue is BACKPRESSURE, not failure. This runs on the stdin reader |
| 593 | * thread, so blocking here stops further reads and lets the kernel pipe |
| 594 | * absorb the client's burst — a pipelining client is a client going fast, |
| 595 | * not a client going wrong. The old code failed the whole session at frame |
| 596 | * capacity+1, killing it with every buffered response unwritten: any 7+ |
| 597 | * pipelined requests (e.g. an agent issuing parallel tool calls) died with |
| 598 | * rc=1 and zero output (#1522 follow-up). Waits are bounded only by the |
| 599 | * stop/fail flags, which every teardown path already sets — the same |
| 600 | * condition the polling worker and watchdogs key on. */ |
| 601 | for (;;) { |
| 602 | cbm_mutex_lock(&state->mutex); |
| 603 | bool stopped = state->stopping || state->failed; |
| 604 | if (stopped) { |
| 605 | cbm_mutex_unlock(&state->mutex); |
| 606 | free(id_str); |
| 607 | return false; |
| 608 | } |
| 609 | bool capacity = state->count < FRONTEND_QUEUE_CAPACITY && |
| 610 | state->queued_bytes <= FRONTEND_QUEUE_BYTES_MAX && |
| 611 | length <= FRONTEND_QUEUE_BYTES_MAX - state->queued_bytes; |
| 612 | if (capacity) { |
| 613 | size_t tail = (state->head + state->count) % FRONTEND_QUEUE_CAPACITY; |
| 614 | state->queue[tail] = (frontend_item_t){ |
| 615 | .message = message, |
| 616 | .length = length, |
| 617 | .content_length_framed = content_length_framed, |
| 618 | .has_id = has_id, |
| 619 | .id = id, |
no test coverage detected