Skip to content

Commit 5f23f30

Browse files
gongna-ausisyphus-dev-ai
andcommitted
feat(server): implement LATENCY command set (Redis 7.0+)
Implement LATENCY HISTOGRAM, LATENCY RESET and LATENCY HELP subcommands compatible with Redis 7.0 protocol. Skip commands with zero calls in histogram output. Add Go integration tests covering all subcommands, error handling, histogram output structure, filtering and zero-calls exclusion. Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
1 parent 2520bda commit 5f23f30

2 files changed

Lines changed: 299 additions & 1 deletion

File tree

src/commands/cmd_server.cc

Lines changed: 98 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1627,6 +1627,102 @@ class CommandFlushBlockCache : public Commander {
16271627
}
16281628
};
16291629

1630+
class CommandLatency : public Commander {
1631+
public:
1632+
Status Execute([[maybe_unused]] engine::Context &ctx, Server *srv, Connection *conn, std::string *output) override {
1633+
if (args_.size() < 2) {
1634+
return {Status::RedisParseErr, errWrongNumOfArguments};
1635+
}
1636+
1637+
std::string subcommand = util::ToLower(args_[1]);
1638+
if (subcommand == "histogram") {
1639+
return GetHistogram(srv, conn, output);
1640+
} else if (subcommand == "reset") {
1641+
*output = redis::Integer(0);
1642+
return Status::OK();
1643+
} else if (subcommand == "help") {
1644+
std::vector<std::string> help = {
1645+
"HELP",
1646+
" Print this help message.",
1647+
"HISTOGRAM [command ...]",
1648+
" Return a cumulative distribution of latencies in the format of a histogram for the specified "
1649+
"command(s).",
1650+
" If no commands are specified, all commands with latency statistics are returned.",
1651+
"RESET [event ...]",
1652+
" Return the number of reset event classes (Kvrocks has no spike-sampling infrastructure, always returns "
1653+
"0)."};
1654+
*output = ArrayOfBulkStrings(help);
1655+
return Status::OK();
1656+
}
1657+
1658+
return {Status::RedisParseErr, "Unknown LATENCY subcommand or wrong number of arguments"};
1659+
}
1660+
1661+
private:
1662+
Status GetHistogram(Server *srv, Connection *conn, std::string *output) {
1663+
if (srv->stats.bucket_boundaries.empty()) {
1664+
*output = conn->HeaderOfMap(0);
1665+
return Status::OK();
1666+
}
1667+
1668+
std::vector<const std::pair<const std::string, CommandHistogram> *> target_histograms;
1669+
if (args_.size() > 2) {
1670+
for (size_t i = 2; i < args_.size(); i++) {
1671+
auto it = srv->stats.commands_histogram.find(util::ToLower(args_[i]));
1672+
if (it != srv->stats.commands_histogram.end() && it->second.calls > 0) {
1673+
target_histograms.push_back(&(*it));
1674+
}
1675+
}
1676+
} else {
1677+
for (const auto &iter : srv->stats.commands_histogram) {
1678+
if (iter.second.calls > 0) {
1679+
target_histograms.push_back(&iter);
1680+
}
1681+
}
1682+
}
1683+
1684+
*output = conn->HeaderOfMap(target_histograms.size());
1685+
for (const auto *pair_ptr : target_histograms) {
1686+
const auto &cmd_name = pair_ptr->first;
1687+
const auto &hist = pair_ptr->second;
1688+
1689+
std::vector<std::pair<int64_t, uint64_t>> cumulative_buckets;
1690+
uint64_t cumulative = 0;
1691+
for (size_t i = 0; i < hist.buckets.size(); i++) {
1692+
cumulative += hist.buckets[i]->load(std::memory_order_relaxed);
1693+
if (cumulative == 0) continue;
1694+
1695+
int64_t boundary;
1696+
if (i < srv->stats.bucket_boundaries.size()) {
1697+
boundary = static_cast<int64_t>(srv->stats.bucket_boundaries[i]);
1698+
} else {
1699+
boundary = -1;
1700+
}
1701+
cumulative_buckets.emplace_back(boundary, cumulative);
1702+
}
1703+
1704+
*output += redis::BulkString(cmd_name);
1705+
*output += conn->HeaderOfMap(2);
1706+
1707+
*output += redis::BulkString("calls");
1708+
*output += redis::Integer(hist.calls.load(std::memory_order_relaxed));
1709+
1710+
*output += redis::BulkString("histogram_usec");
1711+
*output += conn->HeaderOfMap(cumulative_buckets.size());
1712+
for (const auto &[boundary, count] : cumulative_buckets) {
1713+
if (boundary < 0) {
1714+
*output += redis::BulkString("inf");
1715+
} else {
1716+
*output += redis::Integer(boundary);
1717+
}
1718+
*output += redis::Integer(count);
1719+
}
1720+
}
1721+
1722+
return Status::OK();
1723+
}
1724+
};
1725+
16301726
REDIS_REGISTER_COMMANDS(
16311727
Server, MakeCmdAttr<CommandAuth>("auth", 2, "read-only ok-loading auth", NO_KEY),
16321728
MakeCmdAttr<CommandPing>("ping", -1, "read-only", NO_KEY),
@@ -1670,5 +1766,6 @@ REDIS_REGISTER_COMMANDS(
16701766
MakeCmdAttr<CommandPollUpdates>("pollupdates", -2, "read-only admin", NO_KEY),
16711767
MakeCmdAttr<CommandSST>("sst", -3, "write exclusive admin", 1, 1, 1),
16721768
MakeCmdAttr<CommandFlushMemTable>("flushmemtable", -1, "exclusive write", NO_KEY),
1673-
MakeCmdAttr<CommandFlushBlockCache>("flushblockcache", 1, "exclusive write", NO_KEY), )
1769+
MakeCmdAttr<CommandFlushBlockCache>("flushblockcache", 1, "exclusive write", NO_KEY),
1770+
MakeCmdAttr<CommandLatency>("latency", -2, "read-only admin", NO_KEY), )
16741771
} // namespace redis
Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one
3+
* or more contributor license agreements. See the NOTICE file
4+
* distributed with this work for additional information
5+
* regarding copyright ownership. The ASF licenses this file
6+
* to you under the Apache License, Version 2.0 (the
7+
* "License"); you may not use this file except in compliance
8+
* with the License. You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
20+
package latency
21+
22+
import (
23+
"context"
24+
"fmt"
25+
"testing"
26+
27+
"github.com/apache/kvrocks/tests/gocase/util"
28+
"github.com/stretchr/testify/require"
29+
)
30+
31+
func TestLatencyHelp(t *testing.T) {
32+
srv := util.StartServer(t, map[string]string{})
33+
defer srv.Close()
34+
35+
ctx := context.Background()
36+
rdb := srv.NewClient()
37+
defer func() { require.NoError(t, rdb.Close()) }()
38+
39+
t.Run("LATENCY HELP returns help text", func(t *testing.T) {
40+
result, err := rdb.Do(ctx, "LATENCY", "HELP").StringSlice()
41+
require.NoError(t, err)
42+
require.NotEmpty(t, result)
43+
require.Contains(t, result[0], "HELP")
44+
})
45+
46+
t.Run("LATENCY HELP is case-insensitive", func(t *testing.T) {
47+
result, err := rdb.Do(ctx, "latency", "help").StringSlice()
48+
require.NoError(t, err)
49+
require.NotEmpty(t, result)
50+
})
51+
}
52+
53+
func TestLatencyReset(t *testing.T) {
54+
srv := util.StartServer(t, map[string]string{})
55+
defer srv.Close()
56+
57+
ctx := context.Background()
58+
rdb := srv.NewClient()
59+
defer func() { require.NoError(t, rdb.Close()) }()
60+
61+
t.Run("LATENCY RESET always returns 0", func(t *testing.T) {
62+
val, err := rdb.Do(ctx, "LATENCY", "RESET").Int64()
63+
require.NoError(t, err)
64+
require.EqualValues(t, 0, val)
65+
})
66+
67+
t.Run("LATENCY RESET with event arguments still returns 0", func(t *testing.T) {
68+
val, err := rdb.Do(ctx, "LATENCY", "RESET", "event1", "event2").Int64()
69+
require.NoError(t, err)
70+
require.EqualValues(t, 0, val)
71+
})
72+
}
73+
74+
func TestLatencyErrors(t *testing.T) {
75+
srv := util.StartServer(t, map[string]string{})
76+
defer srv.Close()
77+
78+
ctx := context.Background()
79+
rdb := srv.NewClient()
80+
defer func() { require.NoError(t, rdb.Close()) }()
81+
82+
t.Run("LATENCY without subcommand returns error", func(t *testing.T) {
83+
err := rdb.Do(ctx, "LATENCY").Err()
84+
require.Error(t, err)
85+
})
86+
87+
t.Run("LATENCY with unknown subcommand returns error", func(t *testing.T) {
88+
err := rdb.Do(ctx, "LATENCY", "UNKNOWN").Err()
89+
require.Error(t, err)
90+
require.Contains(t, err.Error(), "Unknown LATENCY subcommand")
91+
})
92+
}
93+
94+
func TestLatencyHistogramWithoutBuckets(t *testing.T) {
95+
srv := util.StartServer(t, map[string]string{})
96+
defer srv.Close()
97+
98+
ctx := context.Background()
99+
rdb := srv.NewClient()
100+
defer func() { require.NoError(t, rdb.Close()) }()
101+
102+
t.Run("LATENCY HISTOGRAM returns empty when histogram-bucket-boundaries is not set", func(t *testing.T) {
103+
result, err := rdb.Do(ctx, "LATENCY", "HISTOGRAM").Slice()
104+
require.NoError(t, err)
105+
require.Empty(t, result)
106+
})
107+
}
108+
109+
func TestLatencyHistogram(t *testing.T) {
110+
srv := util.StartServer(t, map[string]string{
111+
"histogram-bucket-boundaries": "10,20,30,50,100,200,500,1000",
112+
})
113+
defer srv.Close()
114+
115+
ctx := context.Background()
116+
rdb := srv.NewClient()
117+
defer func() { require.NoError(t, rdb.Close()) }()
118+
119+
t.Run("LATENCY HISTOGRAM returns data after running commands", func(t *testing.T) {
120+
for i := 0; i < 10; i++ {
121+
require.NoError(t, rdb.Set(ctx, fmt.Sprintf("key-%d", i), "value", 0).Err())
122+
}
123+
for i := 0; i < 10; i++ {
124+
require.NoError(t, rdb.Get(ctx, fmt.Sprintf("key-%d", i)).Err())
125+
}
126+
127+
result, err := rdb.Do(ctx, "LATENCY", "HISTOGRAM").Slice()
128+
require.NoError(t, err)
129+
require.NotEmpty(t, result)
130+
})
131+
132+
t.Run("LATENCY HISTOGRAM filters by command name", func(t *testing.T) {
133+
for i := 0; i < 5; i++ {
134+
require.NoError(t, rdb.Set(ctx, fmt.Sprintf("filter-key-%d", i), "value", 0).Err())
135+
}
136+
137+
result, err := rdb.Do(ctx, "LATENCY", "HISTOGRAM", "set").Slice()
138+
require.NoError(t, err)
139+
require.NotEmpty(t, result)
140+
141+
cmdName, ok := result[0].(string)
142+
require.True(t, ok)
143+
require.Equal(t, "set", cmdName)
144+
})
145+
146+
t.Run("LATENCY HISTOGRAM for nonexistent command returns empty", func(t *testing.T) {
147+
result, err := rdb.Do(ctx, "LATENCY", "HISTOGRAM", "nonexistent_command").Slice()
148+
require.NoError(t, err)
149+
require.Empty(t, result)
150+
})
151+
152+
t.Run("LATENCY HISTOGRAM skips commands with zero calls", func(t *testing.T) {
153+
// hset has never been called in this test, so it should have calls==0
154+
result, err := rdb.Do(ctx, "LATENCY", "HISTOGRAM", "hset").Slice()
155+
require.NoError(t, err)
156+
require.Empty(t, result)
157+
})
158+
159+
t.Run("LATENCY HISTOGRAM is case-insensitive for command names", func(t *testing.T) {
160+
resultLower, err := rdb.Do(ctx, "LATENCY", "HISTOGRAM", "set").Slice()
161+
require.NoError(t, err)
162+
163+
resultUpper, err := rdb.Do(ctx, "LATENCY", "HISTOGRAM", "SET").Slice()
164+
require.NoError(t, err)
165+
166+
require.Equal(t, len(resultLower), len(resultUpper))
167+
})
168+
169+
t.Run("LATENCY HISTOGRAM with multiple command filters", func(t *testing.T) {
170+
require.NoError(t, rdb.Set(ctx, "multi-key", "value", 0).Err())
171+
_, err := rdb.Get(ctx, "multi-key").Result()
172+
require.NoError(t, err)
173+
174+
result, err := rdb.Do(ctx, "LATENCY", "HISTOGRAM", "set", "get").Slice()
175+
require.NoError(t, err)
176+
// RESP2 flattened map: [cmd1, data1, cmd2, data2, ...]
177+
require.GreaterOrEqual(t, len(result), 4)
178+
})
179+
180+
t.Run("LATENCY HISTOGRAM contains calls and histogram_usec fields", func(t *testing.T) {
181+
require.NoError(t, rdb.Set(ctx, "field-check-key", "value", 0).Err())
182+
183+
result, err := rdb.Do(ctx, "LATENCY", "HISTOGRAM", "set").Slice()
184+
require.NoError(t, err)
185+
require.GreaterOrEqual(t, len(result), 2)
186+
187+
innerSlice, ok := result[1].([]interface{})
188+
require.True(t, ok, "expected inner result to be a slice")
189+
require.GreaterOrEqual(t, len(innerSlice), 4)
190+
191+
require.Equal(t, "calls", innerSlice[0])
192+
calls, ok := innerSlice[1].(int64)
193+
require.True(t, ok)
194+
require.Greater(t, calls, int64(0))
195+
196+
require.Equal(t, "histogram_usec", innerSlice[2])
197+
histSlice, ok := innerSlice[3].([]interface{})
198+
require.True(t, ok, "expected histogram_usec value to be a slice")
199+
require.NotEmpty(t, histSlice)
200+
})
201+
}

0 commit comments

Comments
 (0)