redisKey($session->session_id); try { $current = Redis::get($key); if ($current === null) { $seed = $this->seedFromDatabase($session); Redis::setnx($key, $seed); } elseif ((int) $current < $session->last_seq) { Redis::set($key, (string) $session->last_seq); } return (int) Redis::incr($key); } catch (\Throwable) { return $session->last_seq + 1; } } public function syncToAtLeast(string $sessionId, int $seq): void { $key = $this->redisKey($sessionId); try { $current = Redis::get($key); if ($current === null || (int) $current < $seq) { Redis::set($key, (string) $seq); } } catch (\Throwable) { return; } } private function seedFromDatabase(ChatSession $session): int { $maxPersistedSeq = (int) (Message::query() ->where('session_id', $session->session_id) ->max('seq') ?? 0); return max($session->last_seq, $maxPersistedSeq); } private function redisKey(string $sessionId): string { return "chat_session:{$sessionId}:seq"; } }